echarts.common.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963
  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: (Simplified) Chinese.
  22319. */
  22320. var lang = {
  22321. legend: {
  22322. selector: {
  22323. all: '全选',
  22324. inverse: '反选'
  22325. }
  22326. },
  22327. toolbox: {
  22328. brush: {
  22329. title: {
  22330. rect: '矩形选择',
  22331. polygon: '圈选',
  22332. lineX: '横向选择',
  22333. lineY: '纵向选择',
  22334. keep: '保持选择',
  22335. clear: '清除选择'
  22336. }
  22337. },
  22338. dataView: {
  22339. title: '数据视图',
  22340. lang: ['数据视图', '关闭', '刷新']
  22341. },
  22342. dataZoom: {
  22343. title: {
  22344. zoom: '区域缩放',
  22345. back: '区域缩放还原'
  22346. }
  22347. },
  22348. magicType: {
  22349. title: {
  22350. line: '切换为折线图',
  22351. bar: '切换为柱状图',
  22352. stack: '切换为堆叠',
  22353. tiled: '切换为平铺'
  22354. }
  22355. },
  22356. restore: {
  22357. title: '还原'
  22358. },
  22359. saveAsImage: {
  22360. title: '保存为图片',
  22361. lang: ['右键另存为图片']
  22362. }
  22363. },
  22364. series: {
  22365. typeNames: {
  22366. pie: '饼图',
  22367. bar: '柱状图',
  22368. line: '折线图',
  22369. scatter: '散点图',
  22370. effectScatter: '涟漪散点图',
  22371. radar: '雷达图',
  22372. tree: '树图',
  22373. treemap: '矩形树图',
  22374. boxplot: '箱型图',
  22375. candlestick: 'K线图',
  22376. k: 'K线图',
  22377. heatmap: '热力图',
  22378. map: '地图',
  22379. parallel: '平行坐标图',
  22380. lines: '线图',
  22381. graph: '关系图',
  22382. sankey: '桑基图',
  22383. funnel: '漏斗图',
  22384. gauge: '仪表盘图',
  22385. pictorialBar: '象形柱图',
  22386. themeRiver: '主题河流图',
  22387. sunburst: '旭日图'
  22388. }
  22389. },
  22390. aria: {
  22391. general: {
  22392. withTitle: '这是一个关于“{title}”的图表。',
  22393. withoutTitle: '这是一个图表,'
  22394. },
  22395. series: {
  22396. single: {
  22397. prefix: '',
  22398. withName: '图表类型是{seriesType},表示{seriesName}。',
  22399. withoutName: '图表类型是{seriesType}。'
  22400. },
  22401. multiple: {
  22402. prefix: '它由{seriesCount}个图表系列组成。',
  22403. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  22404. withoutName: '第{seriesId}个系列是一个{seriesType},',
  22405. separator: {
  22406. middle: ';',
  22407. end: '。'
  22408. }
  22409. }
  22410. },
  22411. data: {
  22412. allData: '其数据是——',
  22413. partialData: '其中,前{displayCnt}项是——',
  22414. withName: '{name}的数据是{value}',
  22415. withoutName: '{value}',
  22416. separator: {
  22417. middle: ',',
  22418. end: ''
  22419. }
  22420. }
  22421. }
  22422. };
  22423. /*
  22424. * Licensed to the Apache Software Foundation (ASF) under one
  22425. * or more contributor license agreements. See the NOTICE file
  22426. * distributed with this work for additional information
  22427. * regarding copyright ownership. The ASF licenses this file
  22428. * to you under the Apache License, Version 2.0 (the
  22429. * "License"); you may not use this file except in compliance
  22430. * with the License. You may obtain a copy of the License at
  22431. *
  22432. * http://www.apache.org/licenses/LICENSE-2.0
  22433. *
  22434. * Unless required by applicable law or agreed to in writing,
  22435. * software distributed under the License is distributed on an
  22436. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22437. * KIND, either express or implied. See the License for the
  22438. * specific language governing permissions and limitations
  22439. * under the License.
  22440. */
  22441. var aria = function (dom, ecModel) {
  22442. var ariaModel = ecModel.getModel('aria');
  22443. if (!ariaModel.get('show')) {
  22444. return;
  22445. }
  22446. else if (ariaModel.get('description')) {
  22447. dom.setAttribute('aria-label', ariaModel.get('description'));
  22448. return;
  22449. }
  22450. var seriesCnt = 0;
  22451. ecModel.eachSeries(function (seriesModel, idx) {
  22452. ++seriesCnt;
  22453. }, this);
  22454. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22455. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22456. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22457. var ariaLabel;
  22458. if (seriesCnt < 1) {
  22459. // No series, no aria label
  22460. return;
  22461. }
  22462. else {
  22463. var title = getTitle();
  22464. if (title) {
  22465. ariaLabel = replace(getConfig('general.withTitle'), {
  22466. title: title
  22467. });
  22468. }
  22469. else {
  22470. ariaLabel = getConfig('general.withoutTitle');
  22471. }
  22472. var seriesLabels = [];
  22473. var prefix = seriesCnt > 1
  22474. ? 'series.multiple.prefix'
  22475. : 'series.single.prefix';
  22476. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22477. ecModel.eachSeries(function (seriesModel, idx) {
  22478. if (idx < displaySeriesCnt) {
  22479. var seriesLabel;
  22480. var seriesName = seriesModel.get('name');
  22481. var seriesTpl = 'series.'
  22482. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22483. seriesLabel = getConfig(seriesName
  22484. ? seriesTpl + 'withName'
  22485. : seriesTpl + 'withoutName');
  22486. seriesLabel = replace(seriesLabel, {
  22487. seriesId: seriesModel.seriesIndex,
  22488. seriesName: seriesModel.get('name'),
  22489. seriesType: getSeriesTypeName(seriesModel.subType)
  22490. });
  22491. var data = seriesModel.getData();
  22492. window.data = data;
  22493. if (data.count() > maxDataCnt) {
  22494. // Show part of data
  22495. seriesLabel += replace(getConfig('data.partialData'), {
  22496. displayCnt: maxDataCnt
  22497. });
  22498. }
  22499. else {
  22500. seriesLabel += getConfig('data.allData');
  22501. }
  22502. var dataLabels = [];
  22503. for (var i = 0; i < data.count(); i++) {
  22504. if (i < maxDataCnt) {
  22505. var name = data.getName(i);
  22506. var value = retrieveRawValue(data, i);
  22507. dataLabels.push(
  22508. replace(
  22509. name
  22510. ? getConfig('data.withName')
  22511. : getConfig('data.withoutName'),
  22512. {
  22513. name: name,
  22514. value: value
  22515. }
  22516. )
  22517. );
  22518. }
  22519. }
  22520. seriesLabel += dataLabels
  22521. .join(getConfig('data.separator.middle'))
  22522. + getConfig('data.separator.end');
  22523. seriesLabels.push(seriesLabel);
  22524. }
  22525. });
  22526. ariaLabel += seriesLabels
  22527. .join(getConfig('series.multiple.separator.middle'))
  22528. + getConfig('series.multiple.separator.end');
  22529. dom.setAttribute('aria-label', ariaLabel);
  22530. }
  22531. function replace(str, keyValues) {
  22532. if (typeof str !== 'string') {
  22533. return str;
  22534. }
  22535. var result = str;
  22536. each$1(keyValues, function (value, key) {
  22537. result = result.replace(
  22538. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22539. value
  22540. );
  22541. });
  22542. return result;
  22543. }
  22544. function getConfig(path) {
  22545. var userConfig = ariaModel.get(path);
  22546. if (userConfig == null) {
  22547. var pathArr = path.split('.');
  22548. var result = lang.aria;
  22549. for (var i = 0; i < pathArr.length; ++i) {
  22550. result = result[pathArr[i]];
  22551. }
  22552. return result;
  22553. }
  22554. else {
  22555. return userConfig;
  22556. }
  22557. }
  22558. function getTitle() {
  22559. var title = ecModel.getModel('title').option;
  22560. if (title && title.length) {
  22561. title = title[0];
  22562. }
  22563. return title && title.text;
  22564. }
  22565. function getSeriesTypeName(type) {
  22566. return lang.series.typeNames[type] || '自定义图';
  22567. }
  22568. };
  22569. /*
  22570. * Licensed to the Apache Software Foundation (ASF) under one
  22571. * or more contributor license agreements. See the NOTICE file
  22572. * distributed with this work for additional information
  22573. * regarding copyright ownership. The ASF licenses this file
  22574. * to you under the Apache License, Version 2.0 (the
  22575. * "License"); you may not use this file except in compliance
  22576. * with the License. You may obtain a copy of the License at
  22577. *
  22578. * http://www.apache.org/licenses/LICENSE-2.0
  22579. *
  22580. * Unless required by applicable law or agreed to in writing,
  22581. * software distributed under the License is distributed on an
  22582. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22583. * KIND, either express or implied. See the License for the
  22584. * specific language governing permissions and limitations
  22585. * under the License.
  22586. */
  22587. var PI$1 = Math.PI;
  22588. /**
  22589. * @param {module:echarts/ExtensionAPI} api
  22590. * @param {Object} [opts]
  22591. * @param {string} [opts.text]
  22592. * @param {string} [opts.color]
  22593. * @param {string} [opts.textColor]
  22594. * @return {module:zrender/Element}
  22595. */
  22596. var loadingDefault = function (api, opts) {
  22597. opts = opts || {};
  22598. defaults(opts, {
  22599. text: 'loading',
  22600. color: '#c23531',
  22601. textColor: '#000',
  22602. maskColor: 'rgba(255, 255, 255, 0.8)',
  22603. zlevel: 0
  22604. });
  22605. var mask = new Rect({
  22606. style: {
  22607. fill: opts.maskColor
  22608. },
  22609. zlevel: opts.zlevel,
  22610. z: 10000
  22611. });
  22612. var arc = new Arc({
  22613. shape: {
  22614. startAngle: -PI$1 / 2,
  22615. endAngle: -PI$1 / 2 + 0.1,
  22616. r: 10
  22617. },
  22618. style: {
  22619. stroke: opts.color,
  22620. lineCap: 'round',
  22621. lineWidth: 5
  22622. },
  22623. zlevel: opts.zlevel,
  22624. z: 10001
  22625. });
  22626. var labelRect = new Rect({
  22627. style: {
  22628. fill: 'none',
  22629. text: opts.text,
  22630. textPosition: 'right',
  22631. textDistance: 10,
  22632. textFill: opts.textColor
  22633. },
  22634. zlevel: opts.zlevel,
  22635. z: 10001
  22636. });
  22637. arc.animateShape(true)
  22638. .when(1000, {
  22639. endAngle: PI$1 * 3 / 2
  22640. })
  22641. .start('circularInOut');
  22642. arc.animateShape(true)
  22643. .when(1000, {
  22644. startAngle: PI$1 * 3 / 2
  22645. })
  22646. .delay(300)
  22647. .start('circularInOut');
  22648. var group = new Group();
  22649. group.add(arc);
  22650. group.add(labelRect);
  22651. group.add(mask);
  22652. // Inject resize
  22653. group.resize = function () {
  22654. var cx = api.getWidth() / 2;
  22655. var cy = api.getHeight() / 2;
  22656. arc.setShape({
  22657. cx: cx,
  22658. cy: cy
  22659. });
  22660. var r = arc.shape.r;
  22661. labelRect.setShape({
  22662. x: cx - r,
  22663. y: cy - r,
  22664. width: r * 2,
  22665. height: r * 2
  22666. });
  22667. mask.setShape({
  22668. x: 0,
  22669. y: 0,
  22670. width: api.getWidth(),
  22671. height: api.getHeight()
  22672. });
  22673. };
  22674. group.resize();
  22675. return group;
  22676. };
  22677. /*
  22678. * Licensed to the Apache Software Foundation (ASF) under one
  22679. * or more contributor license agreements. See the NOTICE file
  22680. * distributed with this work for additional information
  22681. * regarding copyright ownership. The ASF licenses this file
  22682. * to you under the Apache License, Version 2.0 (the
  22683. * "License"); you may not use this file except in compliance
  22684. * with the License. You may obtain a copy of the License at
  22685. *
  22686. * http://www.apache.org/licenses/LICENSE-2.0
  22687. *
  22688. * Unless required by applicable law or agreed to in writing,
  22689. * software distributed under the License is distributed on an
  22690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22691. * KIND, either express or implied. See the License for the
  22692. * specific language governing permissions and limitations
  22693. * under the License.
  22694. */
  22695. /**
  22696. * @module echarts/stream/Scheduler
  22697. */
  22698. /**
  22699. * @constructor
  22700. */
  22701. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22702. this.ecInstance = ecInstance;
  22703. this.api = api;
  22704. this.unfinished;
  22705. // Fix current processors in case that in some rear cases that
  22706. // processors might be registered after echarts instance created.
  22707. // Register processors incrementally for a echarts instance is
  22708. // not supported by this stream architecture.
  22709. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22710. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22711. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22712. /**
  22713. * @private
  22714. * @type {
  22715. * [handlerUID: string]: {
  22716. * seriesTaskMap?: {
  22717. * [seriesUID: string]: Task
  22718. * },
  22719. * overallTask?: Task
  22720. * }
  22721. * }
  22722. */
  22723. this._stageTaskMap = createHashMap();
  22724. }
  22725. var proto = Scheduler.prototype;
  22726. /**
  22727. * @param {module:echarts/model/Global} ecModel
  22728. * @param {Object} payload
  22729. */
  22730. proto.restoreData = function (ecModel, payload) {
  22731. // TODO: Only restroe needed series and components, but not all components.
  22732. // Currently `restoreData` of all of the series and component will be called.
  22733. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22734. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22735. // and some components like coordinate system, axes, dataZoom, visualMap only
  22736. // need their target series refresh.
  22737. // (1) If we are implementing this feature some day, we should consider these cases:
  22738. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22739. // on the settings of `dataZoom`), it should be re-performed if the component
  22740. // is modified by `setOption`.
  22741. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22742. // it should be re-performed when the result array of `getTargetSeries` changed.
  22743. // We use `dependencies` to cover these issues.
  22744. // (3) How to update target series when coordinate system related components modified.
  22745. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22746. // and this case all of the tasks will be set as dirty.
  22747. ecModel.restoreData(payload);
  22748. // Theoretically an overall task not only depends on each of its target series, but also
  22749. // depends on all of the series.
  22750. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22751. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22752. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22753. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22754. // probably cause state chaos (consider `dataZoomProcessor`).
  22755. this._stageTaskMap.each(function (taskRecord) {
  22756. var overallTask = taskRecord.overallTask;
  22757. overallTask && overallTask.dirty();
  22758. });
  22759. };
  22760. // If seriesModel provided, incremental threshold is check by series data.
  22761. proto.getPerformArgs = function (task, isBlock) {
  22762. // For overall task
  22763. if (!task.__pipeline) {
  22764. return;
  22765. }
  22766. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22767. var pCtx = pipeline.context;
  22768. var incremental = !isBlock
  22769. && pipeline.progressiveEnabled
  22770. && (!pCtx || pCtx.progressiveRender)
  22771. && task.__idxInPipeline > pipeline.blockIndex;
  22772. var step = incremental ? pipeline.step : null;
  22773. var modDataCount = pCtx && pCtx.modDataCount;
  22774. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22775. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22776. };
  22777. proto.getPipeline = function (pipelineId) {
  22778. return this._pipelineMap.get(pipelineId);
  22779. };
  22780. /**
  22781. * Current, progressive rendering starts from visual and layout.
  22782. * Always detect render mode in the same stage, avoiding that incorrect
  22783. * detection caused by data filtering.
  22784. * Caution:
  22785. * `updateStreamModes` use `seriesModel.getData()`.
  22786. */
  22787. proto.updateStreamModes = function (seriesModel, view) {
  22788. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22789. var data = seriesModel.getData();
  22790. var dataLen = data.count();
  22791. // `progressiveRender` means that can render progressively in each
  22792. // animation frame. Note that some types of series do not provide
  22793. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22794. // use the term `incremental` but not `progressive` to describe the
  22795. // case that `chart.appendData`.
  22796. var progressiveRender = pipeline.progressiveEnabled
  22797. && view.incrementalPrepareRender
  22798. && dataLen >= pipeline.threshold;
  22799. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22800. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22801. // see `test/candlestick-large3.html`
  22802. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22803. seriesModel.pipelineContext = pipeline.context = {
  22804. progressiveRender: progressiveRender,
  22805. modDataCount: modDataCount,
  22806. large: large
  22807. };
  22808. };
  22809. proto.restorePipelines = function (ecModel) {
  22810. var scheduler = this;
  22811. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22812. ecModel.eachSeries(function (seriesModel) {
  22813. var progressive = seriesModel.getProgressive();
  22814. var pipelineId = seriesModel.uid;
  22815. pipelineMap.set(pipelineId, {
  22816. id: pipelineId,
  22817. head: null,
  22818. tail: null,
  22819. threshold: seriesModel.getProgressiveThreshold(),
  22820. progressiveEnabled: progressive
  22821. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22822. blockIndex: -1,
  22823. step: Math.round(progressive || 700),
  22824. count: 0
  22825. });
  22826. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22827. });
  22828. };
  22829. proto.prepareStageTasks = function () {
  22830. var stageTaskMap = this._stageTaskMap;
  22831. var ecModel = this.ecInstance.getModel();
  22832. var api = this.api;
  22833. each$1(this._allHandlers, function (handler) {
  22834. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22835. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22836. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22837. }, this);
  22838. };
  22839. proto.prepareView = function (view, model, ecModel, api) {
  22840. var renderTask = view.renderTask;
  22841. var context = renderTask.context;
  22842. context.model = model;
  22843. context.ecModel = ecModel;
  22844. context.api = api;
  22845. renderTask.__block = !view.incrementalPrepareRender;
  22846. pipe(this, model, renderTask);
  22847. };
  22848. proto.performDataProcessorTasks = function (ecModel, payload) {
  22849. // If we do not use `block` here, it should be considered when to update modes.
  22850. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22851. };
  22852. // opt
  22853. // opt.visualType: 'visual' or 'layout'
  22854. // opt.setDirty
  22855. proto.performVisualTasks = function (ecModel, payload, opt) {
  22856. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22857. };
  22858. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22859. opt = opt || {};
  22860. var unfinished;
  22861. each$1(stageHandlers, function (stageHandler, idx) {
  22862. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22863. return;
  22864. }
  22865. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22866. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22867. var overallTask = stageHandlerRecord.overallTask;
  22868. if (overallTask) {
  22869. var overallNeedDirty;
  22870. var agentStubMap = overallTask.agentStubMap;
  22871. agentStubMap.each(function (stub) {
  22872. if (needSetDirty(opt, stub)) {
  22873. stub.dirty();
  22874. overallNeedDirty = true;
  22875. }
  22876. });
  22877. overallNeedDirty && overallTask.dirty();
  22878. updatePayload(overallTask, payload);
  22879. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22880. // Execute stubs firstly, which may set the overall task dirty,
  22881. // then execute the overall task. And stub will call seriesModel.setData,
  22882. // which ensures that in the overallTask seriesModel.getData() will not
  22883. // return incorrect data.
  22884. agentStubMap.each(function (stub) {
  22885. stub.perform(performArgs);
  22886. });
  22887. unfinished |= overallTask.perform(performArgs);
  22888. }
  22889. else if (seriesTaskMap) {
  22890. seriesTaskMap.each(function (task, pipelineId) {
  22891. if (needSetDirty(opt, task)) {
  22892. task.dirty();
  22893. }
  22894. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22895. performArgs.skip = !stageHandler.performRawSeries
  22896. && ecModel.isSeriesFiltered(task.context.model);
  22897. updatePayload(task, payload);
  22898. unfinished |= task.perform(performArgs);
  22899. });
  22900. }
  22901. });
  22902. function needSetDirty(opt, task) {
  22903. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22904. }
  22905. scheduler.unfinished |= unfinished;
  22906. }
  22907. proto.performSeriesTasks = function (ecModel) {
  22908. var unfinished;
  22909. ecModel.eachSeries(function (seriesModel) {
  22910. // Progress to the end for dataInit and dataRestore.
  22911. unfinished |= seriesModel.dataTask.perform();
  22912. });
  22913. this.unfinished |= unfinished;
  22914. };
  22915. proto.plan = function () {
  22916. // Travel pipelines, check block.
  22917. this._pipelineMap.each(function (pipeline) {
  22918. var task = pipeline.tail;
  22919. do {
  22920. if (task.__block) {
  22921. pipeline.blockIndex = task.__idxInPipeline;
  22922. break;
  22923. }
  22924. task = task.getUpstream();
  22925. }
  22926. while (task);
  22927. });
  22928. };
  22929. var updatePayload = proto.updatePayload = function (task, payload) {
  22930. payload !== 'remain' && (task.context.payload = payload);
  22931. };
  22932. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22933. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22934. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22935. var seriesType = stageHandler.seriesType;
  22936. var getTargetSeries = stageHandler.getTargetSeries;
  22937. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22938. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22939. // it works but it may cause other irrelevant charts blocked.
  22940. if (stageHandler.createOnAllSeries) {
  22941. ecModel.eachRawSeries(create);
  22942. }
  22943. else if (seriesType) {
  22944. ecModel.eachRawSeriesByType(seriesType, create);
  22945. }
  22946. else if (getTargetSeries) {
  22947. getTargetSeries(ecModel, api).each(create);
  22948. }
  22949. function create(seriesModel) {
  22950. var pipelineId = seriesModel.uid;
  22951. // Init tasks for each seriesModel only once.
  22952. // Reuse original task instance.
  22953. var task = seriesTaskMap.get(pipelineId)
  22954. || seriesTaskMap.set(pipelineId, createTask({
  22955. plan: seriesTaskPlan,
  22956. reset: seriesTaskReset,
  22957. count: seriesTaskCount
  22958. }));
  22959. task.context = {
  22960. model: seriesModel,
  22961. ecModel: ecModel,
  22962. api: api,
  22963. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22964. plan: stageHandler.plan,
  22965. reset: stageHandler.reset,
  22966. scheduler: scheduler
  22967. };
  22968. pipe(scheduler, seriesModel, task);
  22969. }
  22970. // Clear unused series tasks.
  22971. var pipelineMap = scheduler._pipelineMap;
  22972. seriesTaskMap.each(function (task, pipelineId) {
  22973. if (!pipelineMap.get(pipelineId)) {
  22974. task.dispose();
  22975. seriesTaskMap.removeKey(pipelineId);
  22976. }
  22977. });
  22978. }
  22979. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22980. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22981. // For overall task, the function only be called on reset stage.
  22982. || createTask({reset: overallTaskReset});
  22983. overallTask.context = {
  22984. ecModel: ecModel,
  22985. api: api,
  22986. overallReset: stageHandler.overallReset,
  22987. scheduler: scheduler
  22988. };
  22989. // Reuse orignal stubs.
  22990. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22991. var seriesType = stageHandler.seriesType;
  22992. var getTargetSeries = stageHandler.getTargetSeries;
  22993. var overallProgress = true;
  22994. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22995. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22996. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22997. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22998. // we set the pipeline block.
  22999. if (seriesType) {
  23000. ecModel.eachRawSeriesByType(seriesType, createStub);
  23001. }
  23002. else if (getTargetSeries) {
  23003. getTargetSeries(ecModel, api).each(createStub);
  23004. }
  23005. // Otherwise, (usually it is legancy case), the overall task will only be
  23006. // executed when upstream dirty. Otherwise the progressive rendering of all
  23007. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23008. // dirty info from upsteam.
  23009. else {
  23010. overallProgress = false;
  23011. each$1(ecModel.getSeries(), createStub);
  23012. }
  23013. function createStub(seriesModel) {
  23014. var pipelineId = seriesModel.uid;
  23015. var stub = agentStubMap.get(pipelineId);
  23016. if (!stub) {
  23017. stub = agentStubMap.set(pipelineId, createTask(
  23018. {reset: stubReset, onDirty: stubOnDirty}
  23019. ));
  23020. // When the result of `getTargetSeries` changed, the overallTask
  23021. // should be set as dirty and re-performed.
  23022. overallTask.dirty();
  23023. }
  23024. stub.context = {
  23025. model: seriesModel,
  23026. overallProgress: overallProgress,
  23027. modifyOutputEnd: modifyOutputEnd
  23028. };
  23029. stub.agent = overallTask;
  23030. stub.__block = overallProgress;
  23031. pipe(scheduler, seriesModel, stub);
  23032. }
  23033. // Clear unused stubs.
  23034. var pipelineMap = scheduler._pipelineMap;
  23035. agentStubMap.each(function (stub, pipelineId) {
  23036. if (!pipelineMap.get(pipelineId)) {
  23037. stub.dispose();
  23038. // When the result of `getTargetSeries` changed, the overallTask
  23039. // should be set as dirty and re-performed.
  23040. overallTask.dirty();
  23041. agentStubMap.removeKey(pipelineId);
  23042. }
  23043. });
  23044. }
  23045. function overallTaskReset(context) {
  23046. context.overallReset(
  23047. context.ecModel, context.api, context.payload
  23048. );
  23049. }
  23050. function stubReset(context, upstreamContext) {
  23051. return context.overallProgress && stubProgress;
  23052. }
  23053. function stubProgress() {
  23054. this.agent.dirty();
  23055. this.getDownstream().dirty();
  23056. }
  23057. function stubOnDirty() {
  23058. this.agent && this.agent.dirty();
  23059. }
  23060. function seriesTaskPlan(context) {
  23061. return context.plan && context.plan(
  23062. context.model, context.ecModel, context.api, context.payload
  23063. );
  23064. }
  23065. function seriesTaskReset(context) {
  23066. if (context.useClearVisual) {
  23067. context.data.clearAllVisual();
  23068. }
  23069. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23070. context.model, context.ecModel, context.api, context.payload
  23071. ));
  23072. return resetDefines.length > 1
  23073. ? map(resetDefines, function (v, idx) {
  23074. return makeSeriesTaskProgress(idx);
  23075. })
  23076. : singleSeriesTaskProgress;
  23077. }
  23078. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23079. function makeSeriesTaskProgress(resetDefineIdx) {
  23080. return function (params, context) {
  23081. var data = context.data;
  23082. var resetDefine = context.resetDefines[resetDefineIdx];
  23083. if (resetDefine && resetDefine.dataEach) {
  23084. for (var i = params.start; i < params.end; i++) {
  23085. resetDefine.dataEach(data, i);
  23086. }
  23087. }
  23088. else if (resetDefine && resetDefine.progress) {
  23089. resetDefine.progress(params, data);
  23090. }
  23091. };
  23092. }
  23093. function seriesTaskCount(context) {
  23094. return context.data.count();
  23095. }
  23096. function pipe(scheduler, seriesModel, task) {
  23097. var pipelineId = seriesModel.uid;
  23098. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23099. !pipeline.head && (pipeline.head = task);
  23100. pipeline.tail && pipeline.tail.pipe(task);
  23101. pipeline.tail = task;
  23102. task.__idxInPipeline = pipeline.count++;
  23103. task.__pipeline = pipeline;
  23104. }
  23105. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23106. if (isFunction$1(stageHandler)) {
  23107. stageHandler = {
  23108. overallReset: stageHandler,
  23109. seriesType: detectSeriseType(stageHandler)
  23110. };
  23111. }
  23112. stageHandler.uid = getUID('stageHandler');
  23113. visualType && (stageHandler.visualType = visualType);
  23114. return stageHandler;
  23115. };
  23116. /**
  23117. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23118. * To ensure that they can work normally, they should work in block mode, that is,
  23119. * they should not be started util the previous tasks finished. So they cause the
  23120. * progressive rendering disabled. We try to detect the series type, to narrow down
  23121. * the block range to only the series type they concern, but not all series.
  23122. */
  23123. function detectSeriseType(legacyFunc) {
  23124. seriesType = null;
  23125. try {
  23126. // Assume there is no async when calling `eachSeriesByType`.
  23127. legacyFunc(ecModelMock, apiMock);
  23128. }
  23129. catch (e) {
  23130. }
  23131. return seriesType;
  23132. }
  23133. var ecModelMock = {};
  23134. var apiMock = {};
  23135. var seriesType;
  23136. mockMethods(ecModelMock, GlobalModel);
  23137. mockMethods(apiMock, ExtensionAPI);
  23138. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23139. seriesType = type;
  23140. };
  23141. ecModelMock.eachComponent = function (cond) {
  23142. if (cond.mainType === 'series' && cond.subType) {
  23143. seriesType = cond.subType;
  23144. }
  23145. };
  23146. function mockMethods(target, Clz) {
  23147. /* eslint-disable */
  23148. for (var name in Clz.prototype) {
  23149. // Do not use hasOwnProperty
  23150. target[name] = noop;
  23151. }
  23152. /* eslint-enable */
  23153. }
  23154. /*
  23155. * Licensed to the Apache Software Foundation (ASF) under one
  23156. * or more contributor license agreements. See the NOTICE file
  23157. * distributed with this work for additional information
  23158. * regarding copyright ownership. The ASF licenses this file
  23159. * to you under the Apache License, Version 2.0 (the
  23160. * "License"); you may not use this file except in compliance
  23161. * with the License. You may obtain a copy of the License at
  23162. *
  23163. * http://www.apache.org/licenses/LICENSE-2.0
  23164. *
  23165. * Unless required by applicable law or agreed to in writing,
  23166. * software distributed under the License is distributed on an
  23167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23168. * KIND, either express or implied. See the License for the
  23169. * specific language governing permissions and limitations
  23170. * under the License.
  23171. */
  23172. var colorAll = [
  23173. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23174. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23175. ];
  23176. var lightTheme = {
  23177. color: colorAll,
  23178. colorLayer: [
  23179. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23180. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23181. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23182. colorAll
  23183. ]
  23184. };
  23185. /*
  23186. * Licensed to the Apache Software Foundation (ASF) under one
  23187. * or more contributor license agreements. See the NOTICE file
  23188. * distributed with this work for additional information
  23189. * regarding copyright ownership. The ASF licenses this file
  23190. * to you under the Apache License, Version 2.0 (the
  23191. * "License"); you may not use this file except in compliance
  23192. * with the License. You may obtain a copy of the License at
  23193. *
  23194. * http://www.apache.org/licenses/LICENSE-2.0
  23195. *
  23196. * Unless required by applicable law or agreed to in writing,
  23197. * software distributed under the License is distributed on an
  23198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23199. * KIND, either express or implied. See the License for the
  23200. * specific language governing permissions and limitations
  23201. * under the License.
  23202. */
  23203. var contrastColor = '#eee';
  23204. var axisCommon = function () {
  23205. return {
  23206. axisLine: {
  23207. lineStyle: {
  23208. color: contrastColor
  23209. }
  23210. },
  23211. axisTick: {
  23212. lineStyle: {
  23213. color: contrastColor
  23214. }
  23215. },
  23216. axisLabel: {
  23217. textStyle: {
  23218. color: contrastColor
  23219. }
  23220. },
  23221. splitLine: {
  23222. lineStyle: {
  23223. type: 'dashed',
  23224. color: '#aaa'
  23225. }
  23226. },
  23227. splitArea: {
  23228. areaStyle: {
  23229. color: contrastColor
  23230. }
  23231. }
  23232. };
  23233. };
  23234. var colorPalette = [
  23235. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23236. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23237. ];
  23238. var theme = {
  23239. color: colorPalette,
  23240. backgroundColor: '#333',
  23241. tooltip: {
  23242. axisPointer: {
  23243. lineStyle: {
  23244. color: contrastColor
  23245. },
  23246. crossStyle: {
  23247. color: contrastColor
  23248. },
  23249. label: {
  23250. color: '#000'
  23251. }
  23252. }
  23253. },
  23254. legend: {
  23255. textStyle: {
  23256. color: contrastColor
  23257. }
  23258. },
  23259. textStyle: {
  23260. color: contrastColor
  23261. },
  23262. title: {
  23263. textStyle: {
  23264. color: contrastColor
  23265. }
  23266. },
  23267. toolbox: {
  23268. iconStyle: {
  23269. normal: {
  23270. borderColor: contrastColor
  23271. }
  23272. }
  23273. },
  23274. dataZoom: {
  23275. textStyle: {
  23276. color: contrastColor
  23277. }
  23278. },
  23279. visualMap: {
  23280. textStyle: {
  23281. color: contrastColor
  23282. }
  23283. },
  23284. timeline: {
  23285. lineStyle: {
  23286. color: contrastColor
  23287. },
  23288. itemStyle: {
  23289. normal: {
  23290. color: colorPalette[1]
  23291. }
  23292. },
  23293. label: {
  23294. normal: {
  23295. textStyle: {
  23296. color: contrastColor
  23297. }
  23298. }
  23299. },
  23300. controlStyle: {
  23301. normal: {
  23302. color: contrastColor,
  23303. borderColor: contrastColor
  23304. }
  23305. }
  23306. },
  23307. timeAxis: axisCommon(),
  23308. logAxis: axisCommon(),
  23309. valueAxis: axisCommon(),
  23310. categoryAxis: axisCommon(),
  23311. line: {
  23312. symbol: 'circle'
  23313. },
  23314. graph: {
  23315. color: colorPalette
  23316. },
  23317. gauge: {
  23318. title: {
  23319. textStyle: {
  23320. color: contrastColor
  23321. }
  23322. }
  23323. },
  23324. candlestick: {
  23325. itemStyle: {
  23326. normal: {
  23327. color: '#FD1050',
  23328. color0: '#0CF49B',
  23329. borderColor: '#FD1050',
  23330. borderColor0: '#0CF49B'
  23331. }
  23332. }
  23333. }
  23334. };
  23335. theme.categoryAxis.splitLine.show = false;
  23336. /*
  23337. * Licensed to the Apache Software Foundation (ASF) under one
  23338. * or more contributor license agreements. See the NOTICE file
  23339. * distributed with this work for additional information
  23340. * regarding copyright ownership. The ASF licenses this file
  23341. * to you under the Apache License, Version 2.0 (the
  23342. * "License"); you may not use this file except in compliance
  23343. * with the License. You may obtain a copy of the License at
  23344. *
  23345. * http://www.apache.org/licenses/LICENSE-2.0
  23346. *
  23347. * Unless required by applicable law or agreed to in writing,
  23348. * software distributed under the License is distributed on an
  23349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23350. * KIND, either express or implied. See the License for the
  23351. * specific language governing permissions and limitations
  23352. * under the License.
  23353. */
  23354. /**
  23355. * This module is imported by echarts directly.
  23356. *
  23357. * Notice:
  23358. * Always keep this file exists for backward compatibility.
  23359. * Because before 4.1.0, dataset is an optional component,
  23360. * some users may import this module manually.
  23361. */
  23362. ComponentModel.extend({
  23363. type: 'dataset',
  23364. /**
  23365. * @protected
  23366. */
  23367. defaultOption: {
  23368. // 'row', 'column'
  23369. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23370. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23371. sourceHeader: null,
  23372. dimensions: null,
  23373. source: null
  23374. },
  23375. optionUpdated: function () {
  23376. detectSourceFormat(this);
  23377. }
  23378. });
  23379. Component$1.extend({
  23380. type: 'dataset'
  23381. });
  23382. /**
  23383. * 椭圆形状
  23384. * @module zrender/graphic/shape/Ellipse
  23385. */
  23386. var Ellipse = Path.extend({
  23387. type: 'ellipse',
  23388. shape: {
  23389. cx: 0, cy: 0,
  23390. rx: 0, ry: 0
  23391. },
  23392. buildPath: function (ctx, shape) {
  23393. var k = 0.5522848;
  23394. var x = shape.cx;
  23395. var y = shape.cy;
  23396. var a = shape.rx;
  23397. var b = shape.ry;
  23398. var ox = a * k; // 水平控制点偏移量
  23399. var oy = b * k; // 垂直控制点偏移量
  23400. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23401. ctx.moveTo(x - a, y);
  23402. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23403. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23404. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23405. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23406. ctx.closePath();
  23407. }
  23408. });
  23409. // import RadialGradient from '../graphic/RadialGradient';
  23410. // import Pattern from '../graphic/Pattern';
  23411. // import * as vector from '../core/vector';
  23412. // Most of the values can be separated by comma and/or white space.
  23413. var DILIMITER_REG = /[\s,]+/;
  23414. /**
  23415. * For big svg string, this method might be time consuming.
  23416. *
  23417. * @param {string} svg xml string
  23418. * @return {Object} xml root.
  23419. */
  23420. function parseXML(svg) {
  23421. if (isString(svg)) {
  23422. var parser = new DOMParser();
  23423. svg = parser.parseFromString(svg, 'text/xml');
  23424. }
  23425. // Document node. If using $.get, doc node may be input.
  23426. if (svg.nodeType === 9) {
  23427. svg = svg.firstChild;
  23428. }
  23429. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23430. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23431. svg = svg.nextSibling;
  23432. }
  23433. return svg;
  23434. }
  23435. function SVGParser() {
  23436. this._defs = {};
  23437. this._root = null;
  23438. this._isDefine = false;
  23439. this._isText = false;
  23440. }
  23441. SVGParser.prototype.parse = function (xml, opt) {
  23442. opt = opt || {};
  23443. var svg = parseXML(xml);
  23444. if (!svg) {
  23445. throw new Error('Illegal svg');
  23446. }
  23447. var root = new Group();
  23448. this._root = root;
  23449. // parse view port
  23450. var viewBox = svg.getAttribute('viewBox') || '';
  23451. // If width/height not specified, means "100%" of `opt.width/height`.
  23452. // TODO: Other percent value not supported yet.
  23453. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23454. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23455. // If width/height not specified, set as null for output.
  23456. isNaN(width) && (width = null);
  23457. isNaN(height) && (height = null);
  23458. // Apply inline style on svg element.
  23459. parseAttributes(svg, root, null, true);
  23460. var child = svg.firstChild;
  23461. while (child) {
  23462. this._parseNode(child, root);
  23463. child = child.nextSibling;
  23464. }
  23465. var viewBoxRect;
  23466. var viewBoxTransform;
  23467. if (viewBox) {
  23468. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23469. // Some invalid case like viewBox: 'none'.
  23470. if (viewBoxArr.length >= 4) {
  23471. viewBoxRect = {
  23472. x: parseFloat(viewBoxArr[0] || 0),
  23473. y: parseFloat(viewBoxArr[1] || 0),
  23474. width: parseFloat(viewBoxArr[2]),
  23475. height: parseFloat(viewBoxArr[3])
  23476. };
  23477. }
  23478. }
  23479. if (viewBoxRect && width != null && height != null) {
  23480. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23481. if (!opt.ignoreViewBox) {
  23482. // If set transform on the output group, it probably bring trouble when
  23483. // some users only intend to show the clipped content inside the viewBox,
  23484. // but not intend to transform the output group. So we keep the output
  23485. // group no transform. If the user intend to use the viewBox as a
  23486. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23487. // manually according to the viewBox info in the output of this method.
  23488. var elRoot = root;
  23489. root = new Group();
  23490. root.add(elRoot);
  23491. elRoot.scale = viewBoxTransform.scale.slice();
  23492. elRoot.position = viewBoxTransform.position.slice();
  23493. }
  23494. }
  23495. // Some shapes might be overflow the viewport, which should be
  23496. // clipped despite whether the viewBox is used, as the SVG does.
  23497. if (!opt.ignoreRootClip && width != null && height != null) {
  23498. root.setClipPath(new Rect({
  23499. shape: {x: 0, y: 0, width: width, height: height}
  23500. }));
  23501. }
  23502. // Set width/height on group just for output the viewport size.
  23503. return {
  23504. root: root,
  23505. width: width,
  23506. height: height,
  23507. viewBoxRect: viewBoxRect,
  23508. viewBoxTransform: viewBoxTransform
  23509. };
  23510. };
  23511. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23512. var nodeName = xmlNode.nodeName.toLowerCase();
  23513. // TODO
  23514. // support <style>...</style> in svg, where nodeName is 'style',
  23515. // CSS classes is defined globally wherever the style tags are declared.
  23516. if (nodeName === 'defs') {
  23517. // define flag
  23518. this._isDefine = true;
  23519. }
  23520. else if (nodeName === 'text') {
  23521. this._isText = true;
  23522. }
  23523. var el;
  23524. if (this._isDefine) {
  23525. var parser = defineParsers[nodeName];
  23526. if (parser) {
  23527. var def = parser.call(this, xmlNode);
  23528. var id = xmlNode.getAttribute('id');
  23529. if (id) {
  23530. this._defs[id] = def;
  23531. }
  23532. }
  23533. }
  23534. else {
  23535. var parser = nodeParsers[nodeName];
  23536. if (parser) {
  23537. el = parser.call(this, xmlNode, parentGroup);
  23538. parentGroup.add(el);
  23539. }
  23540. }
  23541. var child = xmlNode.firstChild;
  23542. while (child) {
  23543. if (child.nodeType === 1) {
  23544. this._parseNode(child, el);
  23545. }
  23546. // Is text
  23547. if (child.nodeType === 3 && this._isText) {
  23548. this._parseText(child, el);
  23549. }
  23550. child = child.nextSibling;
  23551. }
  23552. // Quit define
  23553. if (nodeName === 'defs') {
  23554. this._isDefine = false;
  23555. }
  23556. else if (nodeName === 'text') {
  23557. this._isText = false;
  23558. }
  23559. };
  23560. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23561. if (xmlNode.nodeType === 1) {
  23562. var dx = xmlNode.getAttribute('dx') || 0;
  23563. var dy = xmlNode.getAttribute('dy') || 0;
  23564. this._textX += parseFloat(dx);
  23565. this._textY += parseFloat(dy);
  23566. }
  23567. var text = new Text({
  23568. style: {
  23569. text: xmlNode.textContent,
  23570. transformText: true
  23571. },
  23572. position: [this._textX || 0, this._textY || 0]
  23573. });
  23574. inheritStyle(parentGroup, text);
  23575. parseAttributes(xmlNode, text, this._defs);
  23576. var fontSize = text.style.fontSize;
  23577. if (fontSize && fontSize < 9) {
  23578. // PENDING
  23579. text.style.fontSize = 9;
  23580. text.scale = text.scale || [1, 1];
  23581. text.scale[0] *= fontSize / 9;
  23582. text.scale[1] *= fontSize / 9;
  23583. }
  23584. var rect = text.getBoundingRect();
  23585. this._textX += rect.width;
  23586. parentGroup.add(text);
  23587. return text;
  23588. };
  23589. var nodeParsers = {
  23590. 'g': function (xmlNode, parentGroup) {
  23591. var g = new Group();
  23592. inheritStyle(parentGroup, g);
  23593. parseAttributes(xmlNode, g, this._defs);
  23594. return g;
  23595. },
  23596. 'rect': function (xmlNode, parentGroup) {
  23597. var rect = new Rect();
  23598. inheritStyle(parentGroup, rect);
  23599. parseAttributes(xmlNode, rect, this._defs);
  23600. rect.setShape({
  23601. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23602. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23603. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23604. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23605. });
  23606. // console.log(xmlNode.getAttribute('transform'));
  23607. // console.log(rect.transform);
  23608. return rect;
  23609. },
  23610. 'circle': function (xmlNode, parentGroup) {
  23611. var circle = new Circle();
  23612. inheritStyle(parentGroup, circle);
  23613. parseAttributes(xmlNode, circle, this._defs);
  23614. circle.setShape({
  23615. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23616. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23617. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23618. });
  23619. return circle;
  23620. },
  23621. 'line': function (xmlNode, parentGroup) {
  23622. var line = new Line();
  23623. inheritStyle(parentGroup, line);
  23624. parseAttributes(xmlNode, line, this._defs);
  23625. line.setShape({
  23626. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23627. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23628. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23629. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23630. });
  23631. return line;
  23632. },
  23633. 'ellipse': function (xmlNode, parentGroup) {
  23634. var ellipse = new Ellipse();
  23635. inheritStyle(parentGroup, ellipse);
  23636. parseAttributes(xmlNode, ellipse, this._defs);
  23637. ellipse.setShape({
  23638. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23639. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23640. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23641. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23642. });
  23643. return ellipse;
  23644. },
  23645. 'polygon': function (xmlNode, parentGroup) {
  23646. var points = xmlNode.getAttribute('points');
  23647. if (points) {
  23648. points = parsePoints(points);
  23649. }
  23650. var polygon = new Polygon({
  23651. shape: {
  23652. points: points || []
  23653. }
  23654. });
  23655. inheritStyle(parentGroup, polygon);
  23656. parseAttributes(xmlNode, polygon, this._defs);
  23657. return polygon;
  23658. },
  23659. 'polyline': function (xmlNode, parentGroup) {
  23660. var path = new Path();
  23661. inheritStyle(parentGroup, path);
  23662. parseAttributes(xmlNode, path, this._defs);
  23663. var points = xmlNode.getAttribute('points');
  23664. if (points) {
  23665. points = parsePoints(points);
  23666. }
  23667. var polyline = new Polyline({
  23668. shape: {
  23669. points: points || []
  23670. }
  23671. });
  23672. return polyline;
  23673. },
  23674. 'image': function (xmlNode, parentGroup) {
  23675. var img = new ZImage();
  23676. inheritStyle(parentGroup, img);
  23677. parseAttributes(xmlNode, img, this._defs);
  23678. img.setStyle({
  23679. image: xmlNode.getAttribute('xlink:href'),
  23680. x: xmlNode.getAttribute('x'),
  23681. y: xmlNode.getAttribute('y'),
  23682. width: xmlNode.getAttribute('width'),
  23683. height: xmlNode.getAttribute('height')
  23684. });
  23685. return img;
  23686. },
  23687. 'text': function (xmlNode, parentGroup) {
  23688. var x = xmlNode.getAttribute('x') || 0;
  23689. var y = xmlNode.getAttribute('y') || 0;
  23690. var dx = xmlNode.getAttribute('dx') || 0;
  23691. var dy = xmlNode.getAttribute('dy') || 0;
  23692. this._textX = parseFloat(x) + parseFloat(dx);
  23693. this._textY = parseFloat(y) + parseFloat(dy);
  23694. var g = new Group();
  23695. inheritStyle(parentGroup, g);
  23696. parseAttributes(xmlNode, g, this._defs);
  23697. return g;
  23698. },
  23699. 'tspan': function (xmlNode, parentGroup) {
  23700. var x = xmlNode.getAttribute('x');
  23701. var y = xmlNode.getAttribute('y');
  23702. if (x != null) {
  23703. // new offset x
  23704. this._textX = parseFloat(x);
  23705. }
  23706. if (y != null) {
  23707. // new offset y
  23708. this._textY = parseFloat(y);
  23709. }
  23710. var dx = xmlNode.getAttribute('dx') || 0;
  23711. var dy = xmlNode.getAttribute('dy') || 0;
  23712. var g = new Group();
  23713. inheritStyle(parentGroup, g);
  23714. parseAttributes(xmlNode, g, this._defs);
  23715. this._textX += dx;
  23716. this._textY += dy;
  23717. return g;
  23718. },
  23719. 'path': function (xmlNode, parentGroup) {
  23720. // TODO svg fill rule
  23721. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23722. // path.style.globalCompositeOperation = 'xor';
  23723. var d = xmlNode.getAttribute('d') || '';
  23724. // Performance sensitive.
  23725. var path = createFromString(d);
  23726. inheritStyle(parentGroup, path);
  23727. parseAttributes(xmlNode, path, this._defs);
  23728. return path;
  23729. }
  23730. };
  23731. var defineParsers = {
  23732. 'lineargradient': function (xmlNode) {
  23733. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23734. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23735. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23736. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23737. var gradient = new LinearGradient(x1, y1, x2, y2);
  23738. _parseGradientColorStops(xmlNode, gradient);
  23739. return gradient;
  23740. },
  23741. 'radialgradient': function (xmlNode) {
  23742. }
  23743. };
  23744. function _parseGradientColorStops(xmlNode, gradient) {
  23745. var stop = xmlNode.firstChild;
  23746. while (stop) {
  23747. if (stop.nodeType === 1) {
  23748. var offset = stop.getAttribute('offset');
  23749. if (offset.indexOf('%') > 0) { // percentage
  23750. offset = parseInt(offset, 10) / 100;
  23751. }
  23752. else if (offset) { // number from 0 to 1
  23753. offset = parseFloat(offset);
  23754. }
  23755. else {
  23756. offset = 0;
  23757. }
  23758. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23759. gradient.addColorStop(offset, stopColor);
  23760. }
  23761. stop = stop.nextSibling;
  23762. }
  23763. }
  23764. function inheritStyle(parent, child) {
  23765. if (parent && parent.__inheritedStyle) {
  23766. if (!child.__inheritedStyle) {
  23767. child.__inheritedStyle = {};
  23768. }
  23769. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23770. }
  23771. }
  23772. function parsePoints(pointsString) {
  23773. var list = trim(pointsString).split(DILIMITER_REG);
  23774. var points = [];
  23775. for (var i = 0; i < list.length; i += 2) {
  23776. var x = parseFloat(list[i]);
  23777. var y = parseFloat(list[i + 1]);
  23778. points.push([x, y]);
  23779. }
  23780. return points;
  23781. }
  23782. var attributesMap = {
  23783. 'fill': 'fill',
  23784. 'stroke': 'stroke',
  23785. 'stroke-width': 'lineWidth',
  23786. 'opacity': 'opacity',
  23787. 'fill-opacity': 'fillOpacity',
  23788. 'stroke-opacity': 'strokeOpacity',
  23789. 'stroke-dasharray': 'lineDash',
  23790. 'stroke-dashoffset': 'lineDashOffset',
  23791. 'stroke-linecap': 'lineCap',
  23792. 'stroke-linejoin': 'lineJoin',
  23793. 'stroke-miterlimit': 'miterLimit',
  23794. 'font-family': 'fontFamily',
  23795. 'font-size': 'fontSize',
  23796. 'font-style': 'fontStyle',
  23797. 'font-weight': 'fontWeight',
  23798. 'text-align': 'textAlign',
  23799. 'alignment-baseline': 'textBaseline'
  23800. };
  23801. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23802. var zrStyle = el.__inheritedStyle || {};
  23803. var isTextEl = el.type === 'text';
  23804. // TODO Shadow
  23805. if (xmlNode.nodeType === 1) {
  23806. parseTransformAttribute(xmlNode, el);
  23807. extend(zrStyle, parseStyleAttribute(xmlNode));
  23808. if (!onlyInlineStyle) {
  23809. for (var svgAttrName in attributesMap) {
  23810. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23811. var attrValue = xmlNode.getAttribute(svgAttrName);
  23812. if (attrValue != null) {
  23813. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23814. }
  23815. }
  23816. }
  23817. }
  23818. }
  23819. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23820. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23821. el.style = el.style || new Style();
  23822. var elStyle = el.style;
  23823. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23824. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23825. each$1([
  23826. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23827. ], function (propName) {
  23828. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23829. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23830. });
  23831. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23832. zrStyle.textBaseline = 'alphabetic';
  23833. }
  23834. if (zrStyle.textBaseline === 'alphabetic') {
  23835. zrStyle.textBaseline = 'bottom';
  23836. }
  23837. if (zrStyle.textAlign === 'start') {
  23838. zrStyle.textAlign = 'left';
  23839. }
  23840. if (zrStyle.textAlign === 'end') {
  23841. zrStyle.textAlign = 'right';
  23842. }
  23843. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23844. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23845. ], function (propName) {
  23846. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23847. });
  23848. if (zrStyle.lineDash) {
  23849. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23850. }
  23851. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23852. // enable stroke
  23853. el[elStrokeProp] = true;
  23854. }
  23855. el.__inheritedStyle = zrStyle;
  23856. }
  23857. var urlRegex = /url\(\s*#(.*?)\)/;
  23858. function getPaint(str, defs) {
  23859. // if (str === 'none') {
  23860. // return;
  23861. // }
  23862. var urlMatch = defs && str && str.match(urlRegex);
  23863. if (urlMatch) {
  23864. var url = trim(urlMatch[1]);
  23865. var def = defs[url];
  23866. return def;
  23867. }
  23868. return str;
  23869. }
  23870. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23871. function parseTransformAttribute(xmlNode, node) {
  23872. var transform = xmlNode.getAttribute('transform');
  23873. if (transform) {
  23874. transform = transform.replace(/,/g, ' ');
  23875. var m = null;
  23876. var transformOps = [];
  23877. transform.replace(transformRegex, function (str, type, value) {
  23878. transformOps.push(type, value);
  23879. });
  23880. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23881. var value = transformOps[i];
  23882. var type = transformOps[i - 1];
  23883. m = m || create$1();
  23884. switch (type) {
  23885. case 'translate':
  23886. value = trim(value).split(DILIMITER_REG);
  23887. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23888. break;
  23889. case 'scale':
  23890. value = trim(value).split(DILIMITER_REG);
  23891. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23892. break;
  23893. case 'rotate':
  23894. value = trim(value).split(DILIMITER_REG);
  23895. rotate(m, m, parseFloat(value[0]));
  23896. break;
  23897. case 'skew':
  23898. value = trim(value).split(DILIMITER_REG);
  23899. console.warn('Skew transform is not supported yet');
  23900. break;
  23901. case 'matrix':
  23902. var value = trim(value).split(DILIMITER_REG);
  23903. m[0] = parseFloat(value[0]);
  23904. m[1] = parseFloat(value[1]);
  23905. m[2] = parseFloat(value[2]);
  23906. m[3] = parseFloat(value[3]);
  23907. m[4] = parseFloat(value[4]);
  23908. m[5] = parseFloat(value[5]);
  23909. break;
  23910. }
  23911. }
  23912. node.setLocalTransform(m);
  23913. }
  23914. }
  23915. // Value may contain space.
  23916. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23917. function parseStyleAttribute(xmlNode) {
  23918. var style = xmlNode.getAttribute('style');
  23919. var result = {};
  23920. if (!style) {
  23921. return result;
  23922. }
  23923. var styleList = {};
  23924. styleRegex.lastIndex = 0;
  23925. var styleRegResult;
  23926. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23927. styleList[styleRegResult[1]] = styleRegResult[2];
  23928. }
  23929. for (var svgAttrName in attributesMap) {
  23930. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23931. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23932. }
  23933. }
  23934. return result;
  23935. }
  23936. /**
  23937. * @param {Array.<number>} viewBoxRect
  23938. * @param {number} width
  23939. * @param {number} height
  23940. * @return {Object} {scale, position}
  23941. */
  23942. function makeViewBoxTransform(viewBoxRect, width, height) {
  23943. var scaleX = width / viewBoxRect.width;
  23944. var scaleY = height / viewBoxRect.height;
  23945. var scale = Math.min(scaleX, scaleY);
  23946. // preserveAspectRatio 'xMidYMid'
  23947. var viewBoxScale = [scale, scale];
  23948. var viewBoxPosition = [
  23949. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23950. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23951. ];
  23952. return {
  23953. scale: viewBoxScale,
  23954. position: viewBoxPosition
  23955. };
  23956. }
  23957. /**
  23958. * @param {string|XMLElement} xml
  23959. * @param {Object} [opt]
  23960. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23961. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23962. * @param {boolean} [opt.ignoreViewBox]
  23963. * @param {boolean} [opt.ignoreRootClip]
  23964. * @return {Object} result:
  23965. * {
  23966. * root: Group, The root of the the result tree of zrender shapes,
  23967. * width: number, the viewport width of the SVG,
  23968. * height: number, the viewport height of the SVG,
  23969. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23970. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23971. * }
  23972. */
  23973. /*
  23974. * Licensed to the Apache Software Foundation (ASF) under one
  23975. * or more contributor license agreements. See the NOTICE file
  23976. * distributed with this work for additional information
  23977. * regarding copyright ownership. The ASF licenses this file
  23978. * to you under the Apache License, Version 2.0 (the
  23979. * "License"); you may not use this file except in compliance
  23980. * with the License. You may obtain a copy of the License at
  23981. *
  23982. * http://www.apache.org/licenses/LICENSE-2.0
  23983. *
  23984. * Unless required by applicable law or agreed to in writing,
  23985. * software distributed under the License is distributed on an
  23986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23987. * KIND, either express or implied. See the License for the
  23988. * specific language governing permissions and limitations
  23989. * under the License.
  23990. */
  23991. var storage = createHashMap();
  23992. // For minimize the code size of common echarts package,
  23993. // do not put too much logic in this module.
  23994. var mapDataStorage = {
  23995. // The format of record: see `echarts.registerMap`.
  23996. // Compatible with previous `echarts.registerMap`.
  23997. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23998. var records;
  23999. if (isArray(rawGeoJson)) {
  24000. records = rawGeoJson;
  24001. }
  24002. else if (rawGeoJson.svg) {
  24003. records = [{
  24004. type: 'svg',
  24005. source: rawGeoJson.svg,
  24006. specialAreas: rawGeoJson.specialAreas
  24007. }];
  24008. }
  24009. else {
  24010. // Backward compatibility.
  24011. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24012. rawSpecialAreas = rawGeoJson.specialAreas;
  24013. rawGeoJson = rawGeoJson.geoJson;
  24014. }
  24015. records = [{
  24016. type: 'geoJSON',
  24017. source: rawGeoJson,
  24018. specialAreas: rawSpecialAreas
  24019. }];
  24020. }
  24021. each$1(records, function (record) {
  24022. var type = record.type;
  24023. type === 'geoJson' && (type = record.type = 'geoJSON');
  24024. var parse = parsers[type];
  24025. if (__DEV__) {
  24026. assert$1(parse, 'Illegal map type: ' + type);
  24027. }
  24028. parse(record);
  24029. });
  24030. return storage.set(mapName, records);
  24031. },
  24032. retrieveMap: function (mapName) {
  24033. return storage.get(mapName);
  24034. }
  24035. };
  24036. var parsers = {
  24037. geoJSON: function (record) {
  24038. var source = record.source;
  24039. record.geoJSON = !isString(source)
  24040. ? source
  24041. : (typeof JSON !== 'undefined' && JSON.parse)
  24042. ? JSON.parse(source)
  24043. : (new Function('return (' + source + ');'))();
  24044. },
  24045. // Only perform parse to XML object here, which might be time
  24046. // consiming for large SVG.
  24047. // Although convert XML to zrender element is also time consiming,
  24048. // if we do it here, the clone of zrender elements has to be
  24049. // required. So we do it once for each geo instance, util real
  24050. // performance issues call for optimizing it.
  24051. svg: function (record) {
  24052. record.svgXML = parseXML(record.source);
  24053. }
  24054. };
  24055. /*
  24056. * Licensed to the Apache Software Foundation (ASF) under one
  24057. * or more contributor license agreements. See the NOTICE file
  24058. * distributed with this work for additional information
  24059. * regarding copyright ownership. The ASF licenses this file
  24060. * to you under the Apache License, Version 2.0 (the
  24061. * "License"); you may not use this file except in compliance
  24062. * with the License. You may obtain a copy of the License at
  24063. *
  24064. * http://www.apache.org/licenses/LICENSE-2.0
  24065. *
  24066. * Unless required by applicable law or agreed to in writing,
  24067. * software distributed under the License is distributed on an
  24068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24069. * KIND, either express or implied. See the License for the
  24070. * specific language governing permissions and limitations
  24071. * under the License.
  24072. */
  24073. var assert = assert$1;
  24074. var each = each$1;
  24075. var isFunction = isFunction$1;
  24076. var isObject = isObject$1;
  24077. var parseClassType = ComponentModel.parseClassType;
  24078. var version = '4.6.0';
  24079. var dependencies = {
  24080. zrender: '4.2.0'
  24081. };
  24082. var TEST_FRAME_REMAIN_TIME = 1;
  24083. var PRIORITY_PROCESSOR_FILTER = 1000;
  24084. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24085. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24086. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24087. var PRIORITY_VISUAL_LAYOUT = 1000;
  24088. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24089. var PRIORITY_VISUAL_GLOBAL = 2000;
  24090. var PRIORITY_VISUAL_CHART = 3000;
  24091. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24092. var PRIORITY_VISUAL_COMPONENT = 4000;
  24093. // FIXME
  24094. // necessary?
  24095. var PRIORITY_VISUAL_BRUSH = 5000;
  24096. var PRIORITY = {
  24097. PROCESSOR: {
  24098. FILTER: PRIORITY_PROCESSOR_FILTER,
  24099. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24100. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24101. },
  24102. VISUAL: {
  24103. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24104. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24105. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24106. CHART: PRIORITY_VISUAL_CHART,
  24107. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24108. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24109. BRUSH: PRIORITY_VISUAL_BRUSH
  24110. }
  24111. };
  24112. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24113. // where they must not be invoked nestedly, except the only case: invoke
  24114. // dispatchAction with updateMethod "none" in main process.
  24115. // This flag is used to carry out this rule.
  24116. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24117. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24118. var OPTION_UPDATED = '__optionUpdated';
  24119. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24120. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24121. return function (eventName, handler, context) {
  24122. if (!ignoreDisposed && this._disposed) {
  24123. disposedWarning(this.id);
  24124. return;
  24125. }
  24126. // Event name is all lowercase
  24127. eventName = eventName && eventName.toLowerCase();
  24128. Eventful.prototype[method].call(this, eventName, handler, context);
  24129. };
  24130. }
  24131. /**
  24132. * @module echarts~MessageCenter
  24133. */
  24134. function MessageCenter() {
  24135. Eventful.call(this);
  24136. }
  24137. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24138. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24139. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24140. mixin(MessageCenter, Eventful);
  24141. /**
  24142. * @module echarts~ECharts
  24143. */
  24144. function ECharts(dom, theme$$1, opts) {
  24145. opts = opts || {};
  24146. // Get theme by name
  24147. if (typeof theme$$1 === 'string') {
  24148. theme$$1 = themeStorage[theme$$1];
  24149. }
  24150. /**
  24151. * @type {string}
  24152. */
  24153. this.id;
  24154. /**
  24155. * Group id
  24156. * @type {string}
  24157. */
  24158. this.group;
  24159. /**
  24160. * @type {HTMLElement}
  24161. * @private
  24162. */
  24163. this._dom = dom;
  24164. var defaultRenderer = 'canvas';
  24165. if (__DEV__) {
  24166. defaultRenderer = (
  24167. typeof window === 'undefined' ? global : window
  24168. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24169. }
  24170. /**
  24171. * @type {module:zrender/ZRender}
  24172. * @private
  24173. */
  24174. var zr = this._zr = init$1(dom, {
  24175. renderer: opts.renderer || defaultRenderer,
  24176. devicePixelRatio: opts.devicePixelRatio,
  24177. width: opts.width,
  24178. height: opts.height
  24179. });
  24180. /**
  24181. * Expect 60 fps.
  24182. * @type {Function}
  24183. * @private
  24184. */
  24185. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24186. var theme$$1 = clone(theme$$1);
  24187. theme$$1 && backwardCompat(theme$$1, true);
  24188. /**
  24189. * @type {Object}
  24190. * @private
  24191. */
  24192. this._theme = theme$$1;
  24193. /**
  24194. * @type {Array.<module:echarts/view/Chart>}
  24195. * @private
  24196. */
  24197. this._chartsViews = [];
  24198. /**
  24199. * @type {Object.<string, module:echarts/view/Chart>}
  24200. * @private
  24201. */
  24202. this._chartsMap = {};
  24203. /**
  24204. * @type {Array.<module:echarts/view/Component>}
  24205. * @private
  24206. */
  24207. this._componentsViews = [];
  24208. /**
  24209. * @type {Object.<string, module:echarts/view/Component>}
  24210. * @private
  24211. */
  24212. this._componentsMap = {};
  24213. /**
  24214. * @type {module:echarts/CoordinateSystem}
  24215. * @private
  24216. */
  24217. this._coordSysMgr = new CoordinateSystemManager();
  24218. /**
  24219. * @type {module:echarts/ExtensionAPI}
  24220. * @private
  24221. */
  24222. var api = this._api = createExtensionAPI(this);
  24223. // Sort on demand
  24224. function prioritySortFunc(a, b) {
  24225. return a.__prio - b.__prio;
  24226. }
  24227. sort(visualFuncs, prioritySortFunc);
  24228. sort(dataProcessorFuncs, prioritySortFunc);
  24229. /**
  24230. * @type {module:echarts/stream/Scheduler}
  24231. */
  24232. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24233. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24234. /**
  24235. * @type {module:echarts~MessageCenter}
  24236. * @private
  24237. */
  24238. this._messageCenter = new MessageCenter();
  24239. // Init mouse events
  24240. this._initEvents();
  24241. // In case some people write `window.onresize = chart.resize`
  24242. this.resize = bind(this.resize, this);
  24243. // Can't dispatch action during rendering procedure
  24244. this._pendingActions = [];
  24245. zr.animation.on('frame', this._onframe, this);
  24246. bindRenderedEvent(zr, this);
  24247. // ECharts instance can be used as value.
  24248. setAsPrimitive(this);
  24249. }
  24250. var echartsProto = ECharts.prototype;
  24251. echartsProto._onframe = function () {
  24252. if (this._disposed) {
  24253. return;
  24254. }
  24255. var scheduler = this._scheduler;
  24256. // Lazy update
  24257. if (this[OPTION_UPDATED]) {
  24258. var silent = this[OPTION_UPDATED].silent;
  24259. this[IN_MAIN_PROCESS] = true;
  24260. prepare(this);
  24261. updateMethods.update.call(this);
  24262. this[IN_MAIN_PROCESS] = false;
  24263. this[OPTION_UPDATED] = false;
  24264. flushPendingActions.call(this, silent);
  24265. triggerUpdatedEvent.call(this, silent);
  24266. }
  24267. // Avoid do both lazy update and progress in one frame.
  24268. else if (scheduler.unfinished) {
  24269. // Stream progress.
  24270. var remainTime = TEST_FRAME_REMAIN_TIME;
  24271. var ecModel = this._model;
  24272. var api = this._api;
  24273. scheduler.unfinished = false;
  24274. do {
  24275. var startTime = +new Date();
  24276. scheduler.performSeriesTasks(ecModel);
  24277. // Currently dataProcessorFuncs do not check threshold.
  24278. scheduler.performDataProcessorTasks(ecModel);
  24279. updateStreamModes(this, ecModel);
  24280. // Do not update coordinate system here. Because that coord system update in
  24281. // each frame is not a good user experience. So we follow the rule that
  24282. // the extent of the coordinate system is determin in the first frame (the
  24283. // frame is executed immedietely after task reset.
  24284. // this._coordSysMgr.update(ecModel, api);
  24285. // console.log('--- ec frame visual ---', remainTime);
  24286. scheduler.performVisualTasks(ecModel);
  24287. renderSeries(this, this._model, api, 'remain');
  24288. remainTime -= (+new Date() - startTime);
  24289. }
  24290. while (remainTime > 0 && scheduler.unfinished);
  24291. // Call flush explicitly for trigger finished event.
  24292. if (!scheduler.unfinished) {
  24293. this._zr.flush();
  24294. }
  24295. // Else, zr flushing be ensue within the same frame,
  24296. // because zr flushing is after onframe event.
  24297. }
  24298. };
  24299. /**
  24300. * @return {HTMLElement}
  24301. */
  24302. echartsProto.getDom = function () {
  24303. return this._dom;
  24304. };
  24305. /**
  24306. * @return {module:zrender~ZRender}
  24307. */
  24308. echartsProto.getZr = function () {
  24309. return this._zr;
  24310. };
  24311. /**
  24312. * Usage:
  24313. * chart.setOption(option, notMerge, lazyUpdate);
  24314. * chart.setOption(option, {
  24315. * notMerge: ...,
  24316. * lazyUpdate: ...,
  24317. * silent: ...
  24318. * });
  24319. *
  24320. * @param {Object} option
  24321. * @param {Object|boolean} [opts] opts or notMerge.
  24322. * @param {boolean} [opts.notMerge=false]
  24323. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24324. */
  24325. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24326. if (__DEV__) {
  24327. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24328. }
  24329. if (this._disposed) {
  24330. disposedWarning(this.id);
  24331. return;
  24332. }
  24333. var silent;
  24334. if (isObject(notMerge)) {
  24335. lazyUpdate = notMerge.lazyUpdate;
  24336. silent = notMerge.silent;
  24337. notMerge = notMerge.notMerge;
  24338. }
  24339. this[IN_MAIN_PROCESS] = true;
  24340. if (!this._model || notMerge) {
  24341. var optionManager = new OptionManager(this._api);
  24342. var theme$$1 = this._theme;
  24343. var ecModel = this._model = new GlobalModel();
  24344. ecModel.scheduler = this._scheduler;
  24345. ecModel.init(null, null, theme$$1, optionManager);
  24346. }
  24347. this._model.setOption(option, optionPreprocessorFuncs);
  24348. if (lazyUpdate) {
  24349. this[OPTION_UPDATED] = {silent: silent};
  24350. this[IN_MAIN_PROCESS] = false;
  24351. }
  24352. else {
  24353. prepare(this);
  24354. updateMethods.update.call(this);
  24355. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24356. // fetched after `setOption`.
  24357. this._zr.flush();
  24358. this[OPTION_UPDATED] = false;
  24359. this[IN_MAIN_PROCESS] = false;
  24360. flushPendingActions.call(this, silent);
  24361. triggerUpdatedEvent.call(this, silent);
  24362. }
  24363. };
  24364. /**
  24365. * @DEPRECATED
  24366. */
  24367. echartsProto.setTheme = function () {
  24368. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24369. };
  24370. /**
  24371. * @return {module:echarts/model/Global}
  24372. */
  24373. echartsProto.getModel = function () {
  24374. return this._model;
  24375. };
  24376. /**
  24377. * @return {Object}
  24378. */
  24379. echartsProto.getOption = function () {
  24380. return this._model && this._model.getOption();
  24381. };
  24382. /**
  24383. * @return {number}
  24384. */
  24385. echartsProto.getWidth = function () {
  24386. return this._zr.getWidth();
  24387. };
  24388. /**
  24389. * @return {number}
  24390. */
  24391. echartsProto.getHeight = function () {
  24392. return this._zr.getHeight();
  24393. };
  24394. /**
  24395. * @return {number}
  24396. */
  24397. echartsProto.getDevicePixelRatio = function () {
  24398. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24399. };
  24400. /**
  24401. * Get canvas which has all thing rendered
  24402. * @param {Object} opts
  24403. * @param {string} [opts.backgroundColor]
  24404. * @return {string}
  24405. */
  24406. echartsProto.getRenderedCanvas = function (opts) {
  24407. if (!env$1.canvasSupported) {
  24408. return;
  24409. }
  24410. opts = opts || {};
  24411. opts.pixelRatio = opts.pixelRatio || 1;
  24412. opts.backgroundColor = opts.backgroundColor
  24413. || this._model.get('backgroundColor');
  24414. var zr = this._zr;
  24415. // var list = zr.storage.getDisplayList();
  24416. // Stop animations
  24417. // Never works before in init animation, so remove it.
  24418. // zrUtil.each(list, function (el) {
  24419. // el.stopAnimation(true);
  24420. // });
  24421. return zr.painter.getRenderedCanvas(opts);
  24422. };
  24423. /**
  24424. * Get svg data url
  24425. * @return {string}
  24426. */
  24427. echartsProto.getSvgDataUrl = function () {
  24428. if (!env$1.svgSupported) {
  24429. return;
  24430. }
  24431. var zr = this._zr;
  24432. var list = zr.storage.getDisplayList();
  24433. // Stop animations
  24434. each$1(list, function (el) {
  24435. el.stopAnimation(true);
  24436. });
  24437. return zr.painter.pathToDataUrl();
  24438. };
  24439. /**
  24440. * @return {string}
  24441. * @param {Object} opts
  24442. * @param {string} [opts.type='png']
  24443. * @param {string} [opts.pixelRatio=1]
  24444. * @param {string} [opts.backgroundColor]
  24445. * @param {string} [opts.excludeComponents]
  24446. */
  24447. echartsProto.getDataURL = function (opts) {
  24448. if (this._disposed) {
  24449. disposedWarning(this.id);
  24450. return;
  24451. }
  24452. opts = opts || {};
  24453. var excludeComponents = opts.excludeComponents;
  24454. var ecModel = this._model;
  24455. var excludesComponentViews = [];
  24456. var self = this;
  24457. each(excludeComponents, function (componentType) {
  24458. ecModel.eachComponent({
  24459. mainType: componentType
  24460. }, function (component) {
  24461. var view = self._componentsMap[component.__viewId];
  24462. if (!view.group.ignore) {
  24463. excludesComponentViews.push(view);
  24464. view.group.ignore = true;
  24465. }
  24466. });
  24467. });
  24468. var url = this._zr.painter.getType() === 'svg'
  24469. ? this.getSvgDataUrl()
  24470. : this.getRenderedCanvas(opts).toDataURL(
  24471. 'image/' + (opts && opts.type || 'png')
  24472. );
  24473. each(excludesComponentViews, function (view) {
  24474. view.group.ignore = false;
  24475. });
  24476. return url;
  24477. };
  24478. /**
  24479. * @return {string}
  24480. * @param {Object} opts
  24481. * @param {string} [opts.type='png']
  24482. * @param {string} [opts.pixelRatio=1]
  24483. * @param {string} [opts.backgroundColor]
  24484. */
  24485. echartsProto.getConnectedDataURL = function (opts) {
  24486. if (this._disposed) {
  24487. disposedWarning(this.id);
  24488. return;
  24489. }
  24490. if (!env$1.canvasSupported) {
  24491. return;
  24492. }
  24493. var groupId = this.group;
  24494. var mathMin = Math.min;
  24495. var mathMax = Math.max;
  24496. var MAX_NUMBER = Infinity;
  24497. if (connectedGroups[groupId]) {
  24498. var left = MAX_NUMBER;
  24499. var top = MAX_NUMBER;
  24500. var right = -MAX_NUMBER;
  24501. var bottom = -MAX_NUMBER;
  24502. var canvasList = [];
  24503. var dpr = (opts && opts.pixelRatio) || 1;
  24504. each$1(instances, function (chart, id) {
  24505. if (chart.group === groupId) {
  24506. var canvas = chart.getRenderedCanvas(
  24507. clone(opts)
  24508. );
  24509. var boundingRect = chart.getDom().getBoundingClientRect();
  24510. left = mathMin(boundingRect.left, left);
  24511. top = mathMin(boundingRect.top, top);
  24512. right = mathMax(boundingRect.right, right);
  24513. bottom = mathMax(boundingRect.bottom, bottom);
  24514. canvasList.push({
  24515. dom: canvas,
  24516. left: boundingRect.left,
  24517. top: boundingRect.top
  24518. });
  24519. }
  24520. });
  24521. left *= dpr;
  24522. top *= dpr;
  24523. right *= dpr;
  24524. bottom *= dpr;
  24525. var width = right - left;
  24526. var height = bottom - top;
  24527. var targetCanvas = createCanvas();
  24528. targetCanvas.width = width;
  24529. targetCanvas.height = height;
  24530. var zr = init$1(targetCanvas);
  24531. // Background between the charts
  24532. if (opts.connectedBackgroundColor) {
  24533. zr.add(new Rect({
  24534. shape: {
  24535. x: 0,
  24536. y: 0,
  24537. width: width,
  24538. height: height
  24539. },
  24540. style: {
  24541. fill: opts.connectedBackgroundColor
  24542. }
  24543. }));
  24544. }
  24545. each(canvasList, function (item) {
  24546. var img = new ZImage({
  24547. style: {
  24548. x: item.left * dpr - left,
  24549. y: item.top * dpr - top,
  24550. image: item.dom
  24551. }
  24552. });
  24553. zr.add(img);
  24554. });
  24555. zr.refreshImmediately();
  24556. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24557. }
  24558. else {
  24559. return this.getDataURL(opts);
  24560. }
  24561. };
  24562. /**
  24563. * Convert from logical coordinate system to pixel coordinate system.
  24564. * See CoordinateSystem#convertToPixel.
  24565. * @param {string|Object} finder
  24566. * If string, e.g., 'geo', means {geoIndex: 0}.
  24567. * If Object, could contain some of these properties below:
  24568. * {
  24569. * seriesIndex / seriesId / seriesName,
  24570. * geoIndex / geoId, geoName,
  24571. * bmapIndex / bmapId / bmapName,
  24572. * xAxisIndex / xAxisId / xAxisName,
  24573. * yAxisIndex / yAxisId / yAxisName,
  24574. * gridIndex / gridId / gridName,
  24575. * ... (can be extended)
  24576. * }
  24577. * @param {Array|number} value
  24578. * @return {Array|number} result
  24579. */
  24580. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24581. /**
  24582. * Convert from pixel coordinate system to logical coordinate system.
  24583. * See CoordinateSystem#convertFromPixel.
  24584. * @param {string|Object} finder
  24585. * If string, e.g., 'geo', means {geoIndex: 0}.
  24586. * If Object, could contain some of these properties below:
  24587. * {
  24588. * seriesIndex / seriesId / seriesName,
  24589. * geoIndex / geoId / geoName,
  24590. * bmapIndex / bmapId / bmapName,
  24591. * xAxisIndex / xAxisId / xAxisName,
  24592. * yAxisIndex / yAxisId / yAxisName
  24593. * gridIndex / gridId / gridName,
  24594. * ... (can be extended)
  24595. * }
  24596. * @param {Array|number} value
  24597. * @return {Array|number} result
  24598. */
  24599. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24600. function doConvertPixel(methodName, finder, value) {
  24601. if (this._disposed) {
  24602. disposedWarning(this.id);
  24603. return;
  24604. }
  24605. var ecModel = this._model;
  24606. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24607. var result;
  24608. finder = parseFinder(ecModel, finder);
  24609. for (var i = 0; i < coordSysList.length; i++) {
  24610. var coordSys = coordSysList[i];
  24611. if (coordSys[methodName]
  24612. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24613. ) {
  24614. return result;
  24615. }
  24616. }
  24617. if (__DEV__) {
  24618. console.warn(
  24619. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24620. );
  24621. }
  24622. }
  24623. /**
  24624. * Is the specified coordinate systems or components contain the given pixel point.
  24625. * @param {string|Object} finder
  24626. * If string, e.g., 'geo', means {geoIndex: 0}.
  24627. * If Object, could contain some of these properties below:
  24628. * {
  24629. * seriesIndex / seriesId / seriesName,
  24630. * geoIndex / geoId / geoName,
  24631. * bmapIndex / bmapId / bmapName,
  24632. * xAxisIndex / xAxisId / xAxisName,
  24633. * yAxisIndex / yAxisId / yAxisName,
  24634. * gridIndex / gridId / gridName,
  24635. * ... (can be extended)
  24636. * }
  24637. * @param {Array|number} value
  24638. * @return {boolean} result
  24639. */
  24640. echartsProto.containPixel = function (finder, value) {
  24641. if (this._disposed) {
  24642. disposedWarning(this.id);
  24643. return;
  24644. }
  24645. var ecModel = this._model;
  24646. var result;
  24647. finder = parseFinder(ecModel, finder);
  24648. each$1(finder, function (models, key) {
  24649. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24650. var coordSys = model.coordinateSystem;
  24651. if (coordSys && coordSys.containPoint) {
  24652. result |= !!coordSys.containPoint(value);
  24653. }
  24654. else if (key === 'seriesModels') {
  24655. var view = this._chartsMap[model.__viewId];
  24656. if (view && view.containPoint) {
  24657. result |= view.containPoint(value, model);
  24658. }
  24659. else {
  24660. if (__DEV__) {
  24661. console.warn(key + ': ' + (view
  24662. ? 'The found component do not support containPoint.'
  24663. : 'No view mapping to the found component.'
  24664. ));
  24665. }
  24666. }
  24667. }
  24668. else {
  24669. if (__DEV__) {
  24670. console.warn(key + ': containPoint is not supported');
  24671. }
  24672. }
  24673. }, this);
  24674. }, this);
  24675. return !!result;
  24676. };
  24677. /**
  24678. * Get visual from series or data.
  24679. * @param {string|Object} finder
  24680. * If string, e.g., 'series', means {seriesIndex: 0}.
  24681. * If Object, could contain some of these properties below:
  24682. * {
  24683. * seriesIndex / seriesId / seriesName,
  24684. * dataIndex / dataIndexInside
  24685. * }
  24686. * If dataIndex is not specified, series visual will be fetched,
  24687. * but not data item visual.
  24688. * If all of seriesIndex, seriesId, seriesName are not specified,
  24689. * visual will be fetched from first series.
  24690. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24691. */
  24692. echartsProto.getVisual = function (finder, visualType) {
  24693. var ecModel = this._model;
  24694. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24695. var seriesModel = finder.seriesModel;
  24696. if (__DEV__) {
  24697. if (!seriesModel) {
  24698. console.warn('There is no specified seires model');
  24699. }
  24700. }
  24701. var data = seriesModel.getData();
  24702. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24703. ? finder.dataIndexInside
  24704. : finder.hasOwnProperty('dataIndex')
  24705. ? data.indexOfRawIndex(finder.dataIndex)
  24706. : null;
  24707. return dataIndexInside != null
  24708. ? data.getItemVisual(dataIndexInside, visualType)
  24709. : data.getVisual(visualType);
  24710. };
  24711. /**
  24712. * Get view of corresponding component model
  24713. * @param {module:echarts/model/Component} componentModel
  24714. * @return {module:echarts/view/Component}
  24715. */
  24716. echartsProto.getViewOfComponentModel = function (componentModel) {
  24717. return this._componentsMap[componentModel.__viewId];
  24718. };
  24719. /**
  24720. * Get view of corresponding series model
  24721. * @param {module:echarts/model/Series} seriesModel
  24722. * @return {module:echarts/view/Chart}
  24723. */
  24724. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24725. return this._chartsMap[seriesModel.__viewId];
  24726. };
  24727. var updateMethods = {
  24728. prepareAndUpdate: function (payload) {
  24729. prepare(this);
  24730. updateMethods.update.call(this, payload);
  24731. },
  24732. /**
  24733. * @param {Object} payload
  24734. * @private
  24735. */
  24736. update: function (payload) {
  24737. // console.profile && console.profile('update');
  24738. var ecModel = this._model;
  24739. var api = this._api;
  24740. var zr = this._zr;
  24741. var coordSysMgr = this._coordSysMgr;
  24742. var scheduler = this._scheduler;
  24743. // update before setOption
  24744. if (!ecModel) {
  24745. return;
  24746. }
  24747. scheduler.restoreData(ecModel, payload);
  24748. scheduler.performSeriesTasks(ecModel);
  24749. // TODO
  24750. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24751. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24752. // Create new coordinate system each update
  24753. // In LineView may save the old coordinate system and use it to get the orignal point
  24754. coordSysMgr.create(ecModel, api);
  24755. scheduler.performDataProcessorTasks(ecModel, payload);
  24756. // Current stream render is not supported in data process. So we can update
  24757. // stream modes after data processing, where the filtered data is used to
  24758. // deteming whether use progressive rendering.
  24759. updateStreamModes(this, ecModel);
  24760. // We update stream modes before coordinate system updated, then the modes info
  24761. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24762. // the drawback is the full coord info can not be fetched. Fortunately this full
  24763. // coord is not requied in stream mode updater currently.
  24764. coordSysMgr.update(ecModel, api);
  24765. clearColorPalette(ecModel);
  24766. scheduler.performVisualTasks(ecModel, payload);
  24767. render(this, ecModel, api, payload);
  24768. // Set background
  24769. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24770. // In IE8
  24771. if (!env$1.canvasSupported) {
  24772. var colorArr = parse(backgroundColor);
  24773. backgroundColor = stringify(colorArr, 'rgb');
  24774. if (colorArr[3] === 0) {
  24775. backgroundColor = 'transparent';
  24776. }
  24777. }
  24778. else {
  24779. zr.setBackgroundColor(backgroundColor);
  24780. }
  24781. performPostUpdateFuncs(ecModel, api);
  24782. // console.profile && console.profileEnd('update');
  24783. },
  24784. /**
  24785. * @param {Object} payload
  24786. * @private
  24787. */
  24788. updateTransform: function (payload) {
  24789. var ecModel = this._model;
  24790. var ecIns = this;
  24791. var api = this._api;
  24792. // update before setOption
  24793. if (!ecModel) {
  24794. return;
  24795. }
  24796. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24797. var componentDirtyList = [];
  24798. ecModel.eachComponent(function (componentType, componentModel) {
  24799. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24800. if (componentView && componentView.__alive) {
  24801. if (componentView.updateTransform) {
  24802. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24803. result && result.update && componentDirtyList.push(componentView);
  24804. }
  24805. else {
  24806. componentDirtyList.push(componentView);
  24807. }
  24808. }
  24809. });
  24810. var seriesDirtyMap = createHashMap();
  24811. ecModel.eachSeries(function (seriesModel) {
  24812. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24813. if (chartView.updateTransform) {
  24814. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24815. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24816. }
  24817. else {
  24818. seriesDirtyMap.set(seriesModel.uid, 1);
  24819. }
  24820. });
  24821. clearColorPalette(ecModel);
  24822. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24823. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24824. this._scheduler.performVisualTasks(
  24825. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24826. );
  24827. // Currently, not call render of components. Geo render cost a lot.
  24828. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24829. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24830. performPostUpdateFuncs(ecModel, this._api);
  24831. },
  24832. /**
  24833. * @param {Object} payload
  24834. * @private
  24835. */
  24836. updateView: function (payload) {
  24837. var ecModel = this._model;
  24838. // update before setOption
  24839. if (!ecModel) {
  24840. return;
  24841. }
  24842. Chart.markUpdateMethod(payload, 'updateView');
  24843. clearColorPalette(ecModel);
  24844. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24845. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24846. render(this, this._model, this._api, payload);
  24847. performPostUpdateFuncs(ecModel, this._api);
  24848. },
  24849. /**
  24850. * @param {Object} payload
  24851. * @private
  24852. */
  24853. updateVisual: function (payload) {
  24854. updateMethods.update.call(this, payload);
  24855. // var ecModel = this._model;
  24856. // // update before setOption
  24857. // if (!ecModel) {
  24858. // return;
  24859. // }
  24860. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24861. // clearColorPalette(ecModel);
  24862. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24863. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24864. // render(this, this._model, this._api, payload);
  24865. // performPostUpdateFuncs(ecModel, this._api);
  24866. },
  24867. /**
  24868. * @param {Object} payload
  24869. * @private
  24870. */
  24871. updateLayout: function (payload) {
  24872. updateMethods.update.call(this, payload);
  24873. // var ecModel = this._model;
  24874. // // update before setOption
  24875. // if (!ecModel) {
  24876. // return;
  24877. // }
  24878. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24879. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24880. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24881. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24882. // render(this, this._model, this._api, payload);
  24883. // performPostUpdateFuncs(ecModel, this._api);
  24884. }
  24885. };
  24886. function prepare(ecIns) {
  24887. var ecModel = ecIns._model;
  24888. var scheduler = ecIns._scheduler;
  24889. scheduler.restorePipelines(ecModel);
  24890. scheduler.prepareStageTasks();
  24891. prepareView(ecIns, 'component', ecModel, scheduler);
  24892. prepareView(ecIns, 'chart', ecModel, scheduler);
  24893. scheduler.plan();
  24894. }
  24895. /**
  24896. * @private
  24897. */
  24898. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24899. var ecModel = ecIns._model;
  24900. // broadcast
  24901. if (!mainType) {
  24902. // FIXME
  24903. // Chart will not be update directly here, except set dirty.
  24904. // But there is no such scenario now.
  24905. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24906. return;
  24907. }
  24908. var query = {};
  24909. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24910. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24911. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24912. var condition = {mainType: mainType, query: query};
  24913. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24914. var excludeSeriesId = payload.excludeSeriesId;
  24915. if (excludeSeriesId != null) {
  24916. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24917. }
  24918. // If dispatchAction before setOption, do nothing.
  24919. ecModel && ecModel.eachComponent(condition, function (model) {
  24920. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24921. callView(ecIns[
  24922. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24923. ][model.__viewId]);
  24924. }
  24925. }, ecIns);
  24926. function callView(view) {
  24927. view && view.__alive && view[method] && view[method](
  24928. view.__model, ecModel, ecIns._api, payload
  24929. );
  24930. }
  24931. }
  24932. /**
  24933. * Resize the chart
  24934. * @param {Object} opts
  24935. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24936. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24937. * @param {boolean} [opts.silent=false]
  24938. */
  24939. echartsProto.resize = function (opts) {
  24940. if (__DEV__) {
  24941. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24942. }
  24943. if (this._disposed) {
  24944. disposedWarning(this.id);
  24945. return;
  24946. }
  24947. this._zr.resize(opts);
  24948. var ecModel = this._model;
  24949. // Resize loading effect
  24950. this._loadingFX && this._loadingFX.resize();
  24951. if (!ecModel) {
  24952. return;
  24953. }
  24954. var optionChanged = ecModel.resetOption('media');
  24955. var silent = opts && opts.silent;
  24956. this[IN_MAIN_PROCESS] = true;
  24957. optionChanged && prepare(this);
  24958. updateMethods.update.call(this);
  24959. this[IN_MAIN_PROCESS] = false;
  24960. flushPendingActions.call(this, silent);
  24961. triggerUpdatedEvent.call(this, silent);
  24962. };
  24963. function updateStreamModes(ecIns, ecModel) {
  24964. var chartsMap = ecIns._chartsMap;
  24965. var scheduler = ecIns._scheduler;
  24966. ecModel.eachSeries(function (seriesModel) {
  24967. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24968. });
  24969. }
  24970. /**
  24971. * Show loading effect
  24972. * @param {string} [name='default']
  24973. * @param {Object} [cfg]
  24974. */
  24975. echartsProto.showLoading = function (name, cfg) {
  24976. if (this._disposed) {
  24977. disposedWarning(this.id);
  24978. return;
  24979. }
  24980. if (isObject(name)) {
  24981. cfg = name;
  24982. name = '';
  24983. }
  24984. name = name || 'default';
  24985. this.hideLoading();
  24986. if (!loadingEffects[name]) {
  24987. if (__DEV__) {
  24988. console.warn('Loading effects ' + name + ' not exists.');
  24989. }
  24990. return;
  24991. }
  24992. var el = loadingEffects[name](this._api, cfg);
  24993. var zr = this._zr;
  24994. this._loadingFX = el;
  24995. zr.add(el);
  24996. };
  24997. /**
  24998. * Hide loading effect
  24999. */
  25000. echartsProto.hideLoading = function () {
  25001. if (this._disposed) {
  25002. disposedWarning(this.id);
  25003. return;
  25004. }
  25005. this._loadingFX && this._zr.remove(this._loadingFX);
  25006. this._loadingFX = null;
  25007. };
  25008. /**
  25009. * @param {Object} eventObj
  25010. * @return {Object}
  25011. */
  25012. echartsProto.makeActionFromEvent = function (eventObj) {
  25013. var payload = extend({}, eventObj);
  25014. payload.type = eventActionMap[eventObj.type];
  25015. return payload;
  25016. };
  25017. /**
  25018. * @pubilc
  25019. * @param {Object} payload
  25020. * @param {string} [payload.type] Action type
  25021. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25022. * @param {boolean} [opt.silent=false] Whether trigger events.
  25023. * @param {boolean} [opt.flush=undefined]
  25024. * true: Flush immediately, and then pixel in canvas can be fetched
  25025. * immediately. Caution: it might affect performance.
  25026. * false: Not flush.
  25027. * undefined: Auto decide whether perform flush.
  25028. */
  25029. echartsProto.dispatchAction = function (payload, opt) {
  25030. if (this._disposed) {
  25031. disposedWarning(this.id);
  25032. return;
  25033. }
  25034. if (!isObject(opt)) {
  25035. opt = {silent: !!opt};
  25036. }
  25037. if (!actions[payload.type]) {
  25038. return;
  25039. }
  25040. // Avoid dispatch action before setOption. Especially in `connect`.
  25041. if (!this._model) {
  25042. return;
  25043. }
  25044. // May dispatchAction in rendering procedure
  25045. if (this[IN_MAIN_PROCESS]) {
  25046. this._pendingActions.push(payload);
  25047. return;
  25048. }
  25049. doDispatchAction.call(this, payload, opt.silent);
  25050. if (opt.flush) {
  25051. this._zr.flush(true);
  25052. }
  25053. else if (opt.flush !== false && env$1.browser.weChat) {
  25054. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25055. // hang when sliding page (on touch event), which cause that zr does not
  25056. // refresh util user interaction finished, which is not expected.
  25057. // But `dispatchAction` may be called too frequently when pan on touch
  25058. // screen, which impacts performance if do not throttle them.
  25059. this._throttledZrFlush();
  25060. }
  25061. flushPendingActions.call(this, opt.silent);
  25062. triggerUpdatedEvent.call(this, opt.silent);
  25063. };
  25064. function doDispatchAction(payload, silent) {
  25065. var payloadType = payload.type;
  25066. var escapeConnect = payload.escapeConnect;
  25067. var actionWrap = actions[payloadType];
  25068. var actionInfo = actionWrap.actionInfo;
  25069. var cptType = (actionInfo.update || 'update').split(':');
  25070. var updateMethod = cptType.pop();
  25071. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25072. this[IN_MAIN_PROCESS] = true;
  25073. var payloads = [payload];
  25074. var batched = false;
  25075. // Batch action
  25076. if (payload.batch) {
  25077. batched = true;
  25078. payloads = map(payload.batch, function (item) {
  25079. item = defaults(extend({}, item), payload);
  25080. item.batch = null;
  25081. return item;
  25082. });
  25083. }
  25084. var eventObjBatch = [];
  25085. var eventObj;
  25086. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25087. each(payloads, function (batchItem) {
  25088. // Action can specify the event by return it.
  25089. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25090. // Emit event outside
  25091. eventObj = eventObj || extend({}, batchItem);
  25092. // Convert type to eventType
  25093. eventObj.type = actionInfo.event || eventObj.type;
  25094. eventObjBatch.push(eventObj);
  25095. // light update does not perform data process, layout and visual.
  25096. if (isHighDown) {
  25097. // method, payload, mainType, subType
  25098. updateDirectly(this, updateMethod, batchItem, 'series');
  25099. }
  25100. else if (cptType) {
  25101. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25102. }
  25103. }, this);
  25104. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25105. // Still dirty
  25106. if (this[OPTION_UPDATED]) {
  25107. // FIXME Pass payload ?
  25108. prepare(this);
  25109. updateMethods.update.call(this, payload);
  25110. this[OPTION_UPDATED] = false;
  25111. }
  25112. else {
  25113. updateMethods[updateMethod].call(this, payload);
  25114. }
  25115. }
  25116. // Follow the rule of action batch
  25117. if (batched) {
  25118. eventObj = {
  25119. type: actionInfo.event || payloadType,
  25120. escapeConnect: escapeConnect,
  25121. batch: eventObjBatch
  25122. };
  25123. }
  25124. else {
  25125. eventObj = eventObjBatch[0];
  25126. }
  25127. this[IN_MAIN_PROCESS] = false;
  25128. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25129. }
  25130. function flushPendingActions(silent) {
  25131. var pendingActions = this._pendingActions;
  25132. while (pendingActions.length) {
  25133. var payload = pendingActions.shift();
  25134. doDispatchAction.call(this, payload, silent);
  25135. }
  25136. }
  25137. function triggerUpdatedEvent(silent) {
  25138. !silent && this.trigger('updated');
  25139. }
  25140. /**
  25141. * Event `rendered` is triggered when zr
  25142. * rendered. It is useful for realtime
  25143. * snapshot (reflect animation).
  25144. *
  25145. * Event `finished` is triggered when:
  25146. * (1) zrender rendering finished.
  25147. * (2) initial animation finished.
  25148. * (3) progressive rendering finished.
  25149. * (4) no pending action.
  25150. * (5) no delayed setOption needs to be processed.
  25151. */
  25152. function bindRenderedEvent(zr, ecIns) {
  25153. zr.on('rendered', function () {
  25154. ecIns.trigger('rendered');
  25155. // The `finished` event should not be triggered repeatly,
  25156. // so it should only be triggered when rendering indeed happend
  25157. // in zrender. (Consider the case that dipatchAction is keep
  25158. // triggering when mouse move).
  25159. if (
  25160. // Although zr is dirty if initial animation is not finished
  25161. // and this checking is called on frame, we also check
  25162. // animation finished for robustness.
  25163. zr.animation.isFinished()
  25164. && !ecIns[OPTION_UPDATED]
  25165. && !ecIns._scheduler.unfinished
  25166. && !ecIns._pendingActions.length
  25167. ) {
  25168. ecIns.trigger('finished');
  25169. }
  25170. });
  25171. }
  25172. /**
  25173. * @param {Object} params
  25174. * @param {number} params.seriesIndex
  25175. * @param {Array|TypedArray} params.data
  25176. */
  25177. echartsProto.appendData = function (params) {
  25178. if (this._disposed) {
  25179. disposedWarning(this.id);
  25180. return;
  25181. }
  25182. var seriesIndex = params.seriesIndex;
  25183. var ecModel = this.getModel();
  25184. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25185. if (__DEV__) {
  25186. assert(params.data && seriesModel);
  25187. }
  25188. seriesModel.appendData(params);
  25189. // Note: `appendData` does not support that update extent of coordinate
  25190. // system, util some scenario require that. In the expected usage of
  25191. // `appendData`, the initial extent of coordinate system should better
  25192. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25193. // the extent changed while `appendData`, the location of the painted
  25194. // graphic elements have to be changed, which make the usage of
  25195. // `appendData` meaningless.
  25196. this._scheduler.unfinished = true;
  25197. };
  25198. /**
  25199. * Register event
  25200. * @method
  25201. */
  25202. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25203. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25204. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25205. /**
  25206. * Prepare view instances of charts and components
  25207. * @param {module:echarts/model/Global} ecModel
  25208. * @private
  25209. */
  25210. function prepareView(ecIns, type, ecModel, scheduler) {
  25211. var isComponent = type === 'component';
  25212. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25213. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25214. var zr = ecIns._zr;
  25215. var api = ecIns._api;
  25216. for (var i = 0; i < viewList.length; i++) {
  25217. viewList[i].__alive = false;
  25218. }
  25219. isComponent
  25220. ? ecModel.eachComponent(function (componentType, model) {
  25221. componentType !== 'series' && doPrepare(model);
  25222. })
  25223. : ecModel.eachSeries(doPrepare);
  25224. function doPrepare(model) {
  25225. // Consider: id same and type changed.
  25226. var viewId = '_ec_' + model.id + '_' + model.type;
  25227. var view = viewMap[viewId];
  25228. if (!view) {
  25229. var classType = parseClassType(model.type);
  25230. var Clazz = isComponent
  25231. ? Component$1.getClass(classType.main, classType.sub)
  25232. : Chart.getClass(classType.sub);
  25233. if (__DEV__) {
  25234. assert(Clazz, classType.sub + ' does not exist.');
  25235. }
  25236. view = new Clazz();
  25237. view.init(ecModel, api);
  25238. viewMap[viewId] = view;
  25239. viewList.push(view);
  25240. zr.add(view.group);
  25241. }
  25242. model.__viewId = view.__id = viewId;
  25243. view.__alive = true;
  25244. view.__model = model;
  25245. view.group.__ecComponentInfo = {
  25246. mainType: model.mainType,
  25247. index: model.componentIndex
  25248. };
  25249. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25250. }
  25251. for (var i = 0; i < viewList.length;) {
  25252. var view = viewList[i];
  25253. if (!view.__alive) {
  25254. !isComponent && view.renderTask.dispose();
  25255. zr.remove(view.group);
  25256. view.dispose(ecModel, api);
  25257. viewList.splice(i, 1);
  25258. delete viewMap[view.__id];
  25259. view.__id = view.group.__ecComponentInfo = null;
  25260. }
  25261. else {
  25262. i++;
  25263. }
  25264. }
  25265. }
  25266. // /**
  25267. // * Encode visual infomation from data after data processing
  25268. // *
  25269. // * @param {module:echarts/model/Global} ecModel
  25270. // * @param {object} layout
  25271. // * @param {boolean} [layoutFilter] `true`: only layout,
  25272. // * `false`: only not layout,
  25273. // * `null`/`undefined`: all.
  25274. // * @param {string} taskBaseTag
  25275. // * @private
  25276. // */
  25277. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25278. // each(visualFuncs, function (visual, index) {
  25279. // var isLayout = visual.isLayout;
  25280. // if (layoutFilter == null
  25281. // || (layoutFilter === false && !isLayout)
  25282. // || (layoutFilter === true && isLayout)
  25283. // ) {
  25284. // visual.func(ecModel, api, payload);
  25285. // }
  25286. // });
  25287. // }
  25288. function clearColorPalette(ecModel) {
  25289. ecModel.clearColorPalette();
  25290. ecModel.eachSeries(function (seriesModel) {
  25291. seriesModel.clearColorPalette();
  25292. });
  25293. }
  25294. function render(ecIns, ecModel, api, payload) {
  25295. renderComponents(ecIns, ecModel, api, payload);
  25296. each(ecIns._chartsViews, function (chart) {
  25297. chart.__alive = false;
  25298. });
  25299. renderSeries(ecIns, ecModel, api, payload);
  25300. // Remove groups of unrendered charts
  25301. each(ecIns._chartsViews, function (chart) {
  25302. if (!chart.__alive) {
  25303. chart.remove(ecModel, api);
  25304. }
  25305. });
  25306. }
  25307. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25308. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25309. var componentModel = componentView.__model;
  25310. componentView.render(componentModel, ecModel, api, payload);
  25311. updateZ(componentModel, componentView);
  25312. });
  25313. }
  25314. /**
  25315. * Render each chart and component
  25316. * @private
  25317. */
  25318. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25319. // Render all charts
  25320. var scheduler = ecIns._scheduler;
  25321. var unfinished;
  25322. ecModel.eachSeries(function (seriesModel) {
  25323. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25324. chartView.__alive = true;
  25325. var renderTask = chartView.renderTask;
  25326. scheduler.updatePayload(renderTask, payload);
  25327. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25328. renderTask.dirty();
  25329. }
  25330. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25331. chartView.group.silent = !!seriesModel.get('silent');
  25332. updateZ(seriesModel, chartView);
  25333. updateBlend(seriesModel, chartView);
  25334. });
  25335. scheduler.unfinished |= unfinished;
  25336. // If use hover layer
  25337. updateHoverLayerStatus(ecIns, ecModel);
  25338. // Add aria
  25339. aria(ecIns._zr.dom, ecModel);
  25340. }
  25341. function performPostUpdateFuncs(ecModel, api) {
  25342. each(postUpdateFuncs, function (func) {
  25343. func(ecModel, api);
  25344. });
  25345. }
  25346. var MOUSE_EVENT_NAMES = [
  25347. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25348. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25349. ];
  25350. /**
  25351. * @private
  25352. */
  25353. echartsProto._initEvents = function () {
  25354. each(MOUSE_EVENT_NAMES, function (eveName) {
  25355. var handler = function (e) {
  25356. var ecModel = this.getModel();
  25357. var el = e.target;
  25358. var params;
  25359. var isGlobalOut = eveName === 'globalout';
  25360. // no e.target when 'globalout'.
  25361. if (isGlobalOut) {
  25362. params = {};
  25363. }
  25364. else if (el && el.dataIndex != null) {
  25365. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25366. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25367. }
  25368. // If element has custom eventData of components
  25369. else if (el && el.eventData) {
  25370. params = extend({}, el.eventData);
  25371. }
  25372. // Contract: if params prepared in mouse event,
  25373. // these properties must be specified:
  25374. // {
  25375. // componentType: string (component main type)
  25376. // componentIndex: number
  25377. // }
  25378. // Otherwise event query can not work.
  25379. if (params) {
  25380. var componentType = params.componentType;
  25381. var componentIndex = params.componentIndex;
  25382. // Special handling for historic reason: when trigger by
  25383. // markLine/markPoint/markArea, the componentType is
  25384. // 'markLine'/'markPoint'/'markArea', but we should better
  25385. // enable them to be queried by seriesIndex, since their
  25386. // option is set in each series.
  25387. if (componentType === 'markLine'
  25388. || componentType === 'markPoint'
  25389. || componentType === 'markArea'
  25390. ) {
  25391. componentType = 'series';
  25392. componentIndex = params.seriesIndex;
  25393. }
  25394. var model = componentType && componentIndex != null
  25395. && ecModel.getComponent(componentType, componentIndex);
  25396. var view = model && this[
  25397. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25398. ][model.__viewId];
  25399. if (__DEV__) {
  25400. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25401. // be missed, otherwise there is no way to distinguish source component.
  25402. // See `dataFormat.getDataParams`.
  25403. if (!isGlobalOut && !(model && view)) {
  25404. console.warn('model or view can not be found by params');
  25405. }
  25406. }
  25407. params.event = e;
  25408. params.type = eveName;
  25409. this._ecEventProcessor.eventInfo = {
  25410. targetEl: el,
  25411. packedEvent: params,
  25412. model: model,
  25413. view: view
  25414. };
  25415. this.trigger(eveName, params);
  25416. }
  25417. };
  25418. // Consider that some component (like tooltip, brush, ...)
  25419. // register zr event handler, but user event handler might
  25420. // do anything, such as call `setOption` or `dispatchAction`,
  25421. // which probably update any of the content and probably
  25422. // cause problem if it is called previous other inner handlers.
  25423. handler.zrEventfulCallAtLast = true;
  25424. this._zr.on(eveName, handler, this);
  25425. }, this);
  25426. each(eventActionMap, function (actionType, eventType) {
  25427. this._messageCenter.on(eventType, function (event) {
  25428. this.trigger(eventType, event);
  25429. }, this);
  25430. }, this);
  25431. };
  25432. /**
  25433. * @return {boolean}
  25434. */
  25435. echartsProto.isDisposed = function () {
  25436. return this._disposed;
  25437. };
  25438. /**
  25439. * Clear
  25440. */
  25441. echartsProto.clear = function () {
  25442. if (this._disposed) {
  25443. disposedWarning(this.id);
  25444. return;
  25445. }
  25446. this.setOption({ series: [] }, true);
  25447. };
  25448. /**
  25449. * Dispose instance
  25450. */
  25451. echartsProto.dispose = function () {
  25452. if (this._disposed) {
  25453. disposedWarning(this.id);
  25454. return;
  25455. }
  25456. this._disposed = true;
  25457. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25458. var api = this._api;
  25459. var ecModel = this._model;
  25460. each(this._componentsViews, function (component) {
  25461. component.dispose(ecModel, api);
  25462. });
  25463. each(this._chartsViews, function (chart) {
  25464. chart.dispose(ecModel, api);
  25465. });
  25466. // Dispose after all views disposed
  25467. this._zr.dispose();
  25468. delete instances[this.id];
  25469. };
  25470. mixin(ECharts, Eventful);
  25471. function disposedWarning(id) {
  25472. if (__DEV__) {
  25473. console.warn('Instance ' + id + ' has been disposed');
  25474. }
  25475. }
  25476. function updateHoverLayerStatus(ecIns, ecModel) {
  25477. var zr = ecIns._zr;
  25478. var storage = zr.storage;
  25479. var elCount = 0;
  25480. storage.traverse(function (el) {
  25481. elCount++;
  25482. });
  25483. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25484. ecModel.eachSeries(function (seriesModel) {
  25485. if (seriesModel.preventUsingHoverLayer) {
  25486. return;
  25487. }
  25488. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25489. if (chartView.__alive) {
  25490. chartView.group.traverse(function (el) {
  25491. // Don't switch back.
  25492. el.useHoverLayer = true;
  25493. });
  25494. }
  25495. });
  25496. }
  25497. }
  25498. /**
  25499. * Update chart progressive and blend.
  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 updateBlend(seriesModel, chartView) {
  25504. var blendMode = seriesModel.get('blendMode') || null;
  25505. if (__DEV__) {
  25506. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25507. console.warn('Only canvas support blendMode');
  25508. }
  25509. }
  25510. chartView.group.traverse(function (el) {
  25511. // FIXME marker and other components
  25512. if (!el.isGroup) {
  25513. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25514. if (el.style.blend !== blendMode) {
  25515. el.setStyle('blend', blendMode);
  25516. }
  25517. }
  25518. if (el.eachPendingDisplayable) {
  25519. el.eachPendingDisplayable(function (displayable) {
  25520. displayable.setStyle('blend', blendMode);
  25521. });
  25522. }
  25523. });
  25524. }
  25525. /**
  25526. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25527. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25528. */
  25529. function updateZ(model, view) {
  25530. var z = model.get('z');
  25531. var zlevel = model.get('zlevel');
  25532. // Set z and zlevel
  25533. view.group.traverse(function (el) {
  25534. if (el.type !== 'group') {
  25535. z != null && (el.z = z);
  25536. zlevel != null && (el.zlevel = zlevel);
  25537. }
  25538. });
  25539. }
  25540. function createExtensionAPI(ecInstance) {
  25541. var coordSysMgr = ecInstance._coordSysMgr;
  25542. return extend(new ExtensionAPI(ecInstance), {
  25543. // Inject methods
  25544. getCoordinateSystems: bind(
  25545. coordSysMgr.getCoordinateSystems, coordSysMgr
  25546. ),
  25547. getComponentByElement: function (el) {
  25548. while (el) {
  25549. var modelInfo = el.__ecComponentInfo;
  25550. if (modelInfo != null) {
  25551. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25552. }
  25553. el = el.parent;
  25554. }
  25555. }
  25556. });
  25557. }
  25558. /**
  25559. * @class
  25560. * Usage of query:
  25561. * `chart.on('click', query, handler);`
  25562. * The `query` can be:
  25563. * + The component type query string, only `mainType` or `mainType.subType`,
  25564. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25565. * + The component query object, like:
  25566. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25567. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25568. * + The data query object, like:
  25569. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25570. * + The other query object (cmponent customized query), like:
  25571. * `{element: 'some'}` (only available in custom series).
  25572. *
  25573. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25574. * same as there is no such prop in the `query` object.
  25575. */
  25576. function EventProcessor() {
  25577. // These info required: targetEl, packedEvent, model, view
  25578. this.eventInfo;
  25579. }
  25580. EventProcessor.prototype = {
  25581. constructor: EventProcessor,
  25582. normalizeQuery: function (query) {
  25583. var cptQuery = {};
  25584. var dataQuery = {};
  25585. var otherQuery = {};
  25586. // `query` is `mainType` or `mainType.subType` of component.
  25587. if (isString(query)) {
  25588. var condCptType = parseClassType(query);
  25589. // `.main` and `.sub` may be ''.
  25590. cptQuery.mainType = condCptType.main || null;
  25591. cptQuery.subType = condCptType.sub || null;
  25592. }
  25593. // `query` is an object, convert to {mainType, index, name, id}.
  25594. else {
  25595. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25596. // can not be used in `compomentModel.filterForExposedEvent`.
  25597. var suffixes = ['Index', 'Name', 'Id'];
  25598. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25599. each$1(query, function (val, key) {
  25600. var reserved = false;
  25601. for (var i = 0; i < suffixes.length; i++) {
  25602. var propSuffix = suffixes[i];
  25603. var suffixPos = key.lastIndexOf(propSuffix);
  25604. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25605. var mainType = key.slice(0, suffixPos);
  25606. // Consider `dataIndex`.
  25607. if (mainType !== 'data') {
  25608. cptQuery.mainType = mainType;
  25609. cptQuery[propSuffix.toLowerCase()] = val;
  25610. reserved = true;
  25611. }
  25612. }
  25613. }
  25614. if (dataKeys.hasOwnProperty(key)) {
  25615. dataQuery[key] = val;
  25616. reserved = true;
  25617. }
  25618. if (!reserved) {
  25619. otherQuery[key] = val;
  25620. }
  25621. });
  25622. }
  25623. return {
  25624. cptQuery: cptQuery,
  25625. dataQuery: dataQuery,
  25626. otherQuery: otherQuery
  25627. };
  25628. },
  25629. filter: function (eventType, query, args) {
  25630. // They should be assigned before each trigger call.
  25631. var eventInfo = this.eventInfo;
  25632. if (!eventInfo) {
  25633. return true;
  25634. }
  25635. var targetEl = eventInfo.targetEl;
  25636. var packedEvent = eventInfo.packedEvent;
  25637. var model = eventInfo.model;
  25638. var view = eventInfo.view;
  25639. // For event like 'globalout'.
  25640. if (!model || !view) {
  25641. return true;
  25642. }
  25643. var cptQuery = query.cptQuery;
  25644. var dataQuery = query.dataQuery;
  25645. return check(cptQuery, model, 'mainType')
  25646. && check(cptQuery, model, 'subType')
  25647. && check(cptQuery, model, 'index', 'componentIndex')
  25648. && check(cptQuery, model, 'name')
  25649. && check(cptQuery, model, 'id')
  25650. && check(dataQuery, packedEvent, 'name')
  25651. && check(dataQuery, packedEvent, 'dataIndex')
  25652. && check(dataQuery, packedEvent, 'dataType')
  25653. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25654. eventType, query.otherQuery, targetEl, packedEvent
  25655. ));
  25656. function check(query, host, prop, propOnHost) {
  25657. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25658. }
  25659. },
  25660. afterTrigger: function () {
  25661. // Make sure the eventInfo wont be used in next trigger.
  25662. this.eventInfo = null;
  25663. }
  25664. };
  25665. /**
  25666. * @type {Object} key: actionType.
  25667. * @inner
  25668. */
  25669. var actions = {};
  25670. /**
  25671. * Map eventType to actionType
  25672. * @type {Object}
  25673. */
  25674. var eventActionMap = {};
  25675. /**
  25676. * Data processor functions of each stage
  25677. * @type {Array.<Object.<string, Function>>}
  25678. * @inner
  25679. */
  25680. var dataProcessorFuncs = [];
  25681. /**
  25682. * @type {Array.<Function>}
  25683. * @inner
  25684. */
  25685. var optionPreprocessorFuncs = [];
  25686. /**
  25687. * @type {Array.<Function>}
  25688. * @inner
  25689. */
  25690. var postUpdateFuncs = [];
  25691. /**
  25692. * Visual encoding functions of each stage
  25693. * @type {Array.<Object.<string, Function>>}
  25694. */
  25695. var visualFuncs = [];
  25696. /**
  25697. * Theme storage
  25698. * @type {Object.<key, Object>}
  25699. */
  25700. var themeStorage = {};
  25701. /**
  25702. * Loading effects
  25703. */
  25704. var loadingEffects = {};
  25705. var instances = {};
  25706. var connectedGroups = {};
  25707. var idBase = new Date() - 0;
  25708. var groupIdBase = new Date() - 0;
  25709. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25710. function enableConnect(chart) {
  25711. var STATUS_PENDING = 0;
  25712. var STATUS_UPDATING = 1;
  25713. var STATUS_UPDATED = 2;
  25714. var STATUS_KEY = '__connectUpdateStatus';
  25715. function updateConnectedChartsStatus(charts, status) {
  25716. for (var i = 0; i < charts.length; i++) {
  25717. var otherChart = charts[i];
  25718. otherChart[STATUS_KEY] = status;
  25719. }
  25720. }
  25721. each(eventActionMap, function (actionType, eventType) {
  25722. chart._messageCenter.on(eventType, function (event) {
  25723. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25724. if (event && event.escapeConnect) {
  25725. return;
  25726. }
  25727. var action = chart.makeActionFromEvent(event);
  25728. var otherCharts = [];
  25729. each(instances, function (otherChart) {
  25730. if (otherChart !== chart && otherChart.group === chart.group) {
  25731. otherCharts.push(otherChart);
  25732. }
  25733. });
  25734. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25735. each(otherCharts, function (otherChart) {
  25736. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25737. otherChart.dispatchAction(action);
  25738. }
  25739. });
  25740. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25741. }
  25742. });
  25743. });
  25744. }
  25745. /**
  25746. * @param {HTMLElement} dom
  25747. * @param {Object} [theme]
  25748. * @param {Object} opts
  25749. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25750. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25751. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25752. * Can be 'auto' (the same as null/undefined)
  25753. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25754. * Can be 'auto' (the same as null/undefined)
  25755. */
  25756. function init(dom, theme$$1, opts) {
  25757. if (__DEV__) {
  25758. // Check version
  25759. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25760. throw new Error(
  25761. 'zrender/src ' + version$1
  25762. + ' is too old for ECharts ' + version
  25763. + '. Current version need ZRender '
  25764. + dependencies.zrender + '+'
  25765. );
  25766. }
  25767. if (!dom) {
  25768. throw new Error('Initialize failed: invalid dom.');
  25769. }
  25770. }
  25771. var existInstance = getInstanceByDom(dom);
  25772. if (existInstance) {
  25773. if (__DEV__) {
  25774. console.warn('There is a chart instance already initialized on the dom.');
  25775. }
  25776. return existInstance;
  25777. }
  25778. if (__DEV__) {
  25779. if (isDom(dom)
  25780. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25781. && (
  25782. (!dom.clientWidth && (!opts || opts.width == null))
  25783. || (!dom.clientHeight && (!opts || opts.height == null))
  25784. )
  25785. ) {
  25786. console.warn('Can\'t get DOM width or height. Please check '
  25787. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25788. + 'For example, you may need to call this in the callback '
  25789. + 'of window.onload.');
  25790. }
  25791. }
  25792. var chart = new ECharts(dom, theme$$1, opts);
  25793. chart.id = 'ec_' + idBase++;
  25794. instances[chart.id] = chart;
  25795. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25796. enableConnect(chart);
  25797. return chart;
  25798. }
  25799. /**
  25800. * @return {string|Array.<module:echarts~ECharts>} groupId
  25801. */
  25802. function connect(groupId) {
  25803. // Is array of charts
  25804. if (isArray(groupId)) {
  25805. var charts = groupId;
  25806. groupId = null;
  25807. // If any chart has group
  25808. each(charts, function (chart) {
  25809. if (chart.group != null) {
  25810. groupId = chart.group;
  25811. }
  25812. });
  25813. groupId = groupId || ('g_' + groupIdBase++);
  25814. each(charts, function (chart) {
  25815. chart.group = groupId;
  25816. });
  25817. }
  25818. connectedGroups[groupId] = true;
  25819. return groupId;
  25820. }
  25821. /**
  25822. * @DEPRECATED
  25823. * @return {string} groupId
  25824. */
  25825. function disConnect(groupId) {
  25826. connectedGroups[groupId] = false;
  25827. }
  25828. /**
  25829. * @return {string} groupId
  25830. */
  25831. var disconnect = disConnect;
  25832. /**
  25833. * Dispose a chart instance
  25834. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25835. */
  25836. function dispose(chart) {
  25837. if (typeof chart === 'string') {
  25838. chart = instances[chart];
  25839. }
  25840. else if (!(chart instanceof ECharts)) {
  25841. // Try to treat as dom
  25842. chart = getInstanceByDom(chart);
  25843. }
  25844. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25845. chart.dispose();
  25846. }
  25847. }
  25848. /**
  25849. * @param {HTMLElement} dom
  25850. * @return {echarts~ECharts}
  25851. */
  25852. function getInstanceByDom(dom) {
  25853. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25854. }
  25855. /**
  25856. * @param {string} key
  25857. * @return {echarts~ECharts}
  25858. */
  25859. function getInstanceById(key) {
  25860. return instances[key];
  25861. }
  25862. /**
  25863. * Register theme
  25864. */
  25865. function registerTheme(name, theme$$1) {
  25866. themeStorage[name] = theme$$1;
  25867. }
  25868. /**
  25869. * Register option preprocessor
  25870. * @param {Function} preprocessorFunc
  25871. */
  25872. function registerPreprocessor(preprocessorFunc) {
  25873. optionPreprocessorFuncs.push(preprocessorFunc);
  25874. }
  25875. /**
  25876. * @param {number} [priority=1000]
  25877. * @param {Object|Function} processor
  25878. */
  25879. function registerProcessor(priority, processor) {
  25880. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25881. }
  25882. /**
  25883. * Register postUpdater
  25884. * @param {Function} postUpdateFunc
  25885. */
  25886. function registerPostUpdate(postUpdateFunc) {
  25887. postUpdateFuncs.push(postUpdateFunc);
  25888. }
  25889. /**
  25890. * Usage:
  25891. * registerAction('someAction', 'someEvent', function () { ... });
  25892. * registerAction('someAction', function () { ... });
  25893. * registerAction(
  25894. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25895. * function () { ... }
  25896. * );
  25897. *
  25898. * @param {(string|Object)} actionInfo
  25899. * @param {string} actionInfo.type
  25900. * @param {string} [actionInfo.event]
  25901. * @param {string} [actionInfo.update]
  25902. * @param {string} [eventName]
  25903. * @param {Function} action
  25904. */
  25905. function registerAction(actionInfo, eventName, action) {
  25906. if (typeof eventName === 'function') {
  25907. action = eventName;
  25908. eventName = '';
  25909. }
  25910. var actionType = isObject(actionInfo)
  25911. ? actionInfo.type
  25912. : ([actionInfo, actionInfo = {
  25913. event: eventName
  25914. }][0]);
  25915. // Event name is all lowercase
  25916. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25917. eventName = actionInfo.event;
  25918. // Validate action type and event name.
  25919. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25920. if (!actions[actionType]) {
  25921. actions[actionType] = {action: action, actionInfo: actionInfo};
  25922. }
  25923. eventActionMap[eventName] = actionType;
  25924. }
  25925. /**
  25926. * @param {string} type
  25927. * @param {*} CoordinateSystem
  25928. */
  25929. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25930. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25931. }
  25932. /**
  25933. * Get dimensions of specified coordinate system.
  25934. * @param {string} type
  25935. * @return {Array.<string|Object>}
  25936. */
  25937. function getCoordinateSystemDimensions(type) {
  25938. var coordSysCreator = CoordinateSystemManager.get(type);
  25939. if (coordSysCreator) {
  25940. return coordSysCreator.getDimensionsInfo
  25941. ? coordSysCreator.getDimensionsInfo()
  25942. : coordSysCreator.dimensions.slice();
  25943. }
  25944. }
  25945. /**
  25946. * Layout is a special stage of visual encoding
  25947. * Most visual encoding like color are common for different chart
  25948. * But each chart has it's own layout algorithm
  25949. *
  25950. * @param {number} [priority=1000]
  25951. * @param {Function} layoutTask
  25952. */
  25953. function registerLayout(priority, layoutTask) {
  25954. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25955. }
  25956. /**
  25957. * @param {number} [priority=3000]
  25958. * @param {module:echarts/stream/Task} visualTask
  25959. */
  25960. function registerVisual(priority, visualTask) {
  25961. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25962. }
  25963. /**
  25964. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25965. */
  25966. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25967. if (isFunction(priority) || isObject(priority)) {
  25968. fn = priority;
  25969. priority = defaultPriority;
  25970. }
  25971. if (__DEV__) {
  25972. if (isNaN(priority) || priority == null) {
  25973. throw new Error('Illegal priority');
  25974. }
  25975. // Check duplicate
  25976. each(targetList, function (wrap) {
  25977. assert(wrap.__raw !== fn);
  25978. });
  25979. }
  25980. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25981. stageHandler.__prio = priority;
  25982. stageHandler.__raw = fn;
  25983. targetList.push(stageHandler);
  25984. return stageHandler;
  25985. }
  25986. /**
  25987. * @param {string} name
  25988. */
  25989. function registerLoading(name, loadingFx) {
  25990. loadingEffects[name] = loadingFx;
  25991. }
  25992. /**
  25993. * @param {Object} opts
  25994. * @param {string} [superClass]
  25995. */
  25996. function extendComponentModel(opts/*, superClass*/) {
  25997. // var Clazz = ComponentModel;
  25998. // if (superClass) {
  25999. // var classType = parseClassType(superClass);
  26000. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26001. // }
  26002. return ComponentModel.extend(opts);
  26003. }
  26004. /**
  26005. * @param {Object} opts
  26006. * @param {string} [superClass]
  26007. */
  26008. function extendComponentView(opts/*, superClass*/) {
  26009. // var Clazz = ComponentView;
  26010. // if (superClass) {
  26011. // var classType = parseClassType(superClass);
  26012. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26013. // }
  26014. return Component$1.extend(opts);
  26015. }
  26016. /**
  26017. * @param {Object} opts
  26018. * @param {string} [superClass]
  26019. */
  26020. function extendSeriesModel(opts/*, superClass*/) {
  26021. // var Clazz = SeriesModel;
  26022. // if (superClass) {
  26023. // superClass = 'series.' + superClass.replace('series.', '');
  26024. // var classType = parseClassType(superClass);
  26025. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26026. // }
  26027. return SeriesModel.extend(opts);
  26028. }
  26029. /**
  26030. * @param {Object} opts
  26031. * @param {string} [superClass]
  26032. */
  26033. function extendChartView(opts/*, superClass*/) {
  26034. // var Clazz = ChartView;
  26035. // if (superClass) {
  26036. // superClass = superClass.replace('series.', '');
  26037. // var classType = parseClassType(superClass);
  26038. // Clazz = ChartView.getClass(classType.main, true);
  26039. // }
  26040. return Chart.extend(opts);
  26041. }
  26042. /**
  26043. * ZRender need a canvas context to do measureText.
  26044. * But in node environment canvas may be created by node-canvas.
  26045. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26046. *
  26047. * Be careful of using it in the browser.
  26048. *
  26049. * @param {Function} creator
  26050. * @example
  26051. * var Canvas = require('canvas');
  26052. * var echarts = require('echarts');
  26053. * echarts.setCanvasCreator(function () {
  26054. * // Small size is enough.
  26055. * return new Canvas(32, 32);
  26056. * });
  26057. */
  26058. function setCanvasCreator(creator) {
  26059. $override('createCanvas', creator);
  26060. }
  26061. /**
  26062. * @param {string} mapName
  26063. * @param {Array.<Object>|Object|string} geoJson
  26064. * @param {Object} [specialAreas]
  26065. *
  26066. * @example GeoJSON
  26067. * $.get('USA.json', function (geoJson) {
  26068. * echarts.registerMap('USA', geoJson);
  26069. * // Or
  26070. * echarts.registerMap('USA', {
  26071. * geoJson: geoJson,
  26072. * specialAreas: {}
  26073. * })
  26074. * });
  26075. *
  26076. * $.get('airport.svg', function (svg) {
  26077. * echarts.registerMap('airport', {
  26078. * svg: svg
  26079. * }
  26080. * });
  26081. *
  26082. * echarts.registerMap('eu', [
  26083. * {svg: eu-topographic.svg},
  26084. * {geoJSON: eu.json}
  26085. * ])
  26086. */
  26087. function registerMap(mapName, geoJson, specialAreas) {
  26088. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26089. }
  26090. /**
  26091. * @param {string} mapName
  26092. * @return {Object}
  26093. */
  26094. function getMap(mapName) {
  26095. // For backward compatibility, only return the first one.
  26096. var records = mapDataStorage.retrieveMap(mapName);
  26097. return records && records[0] && {
  26098. geoJson: records[0].geoJSON,
  26099. specialAreas: records[0].specialAreas
  26100. };
  26101. }
  26102. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26103. registerPreprocessor(backwardCompat);
  26104. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26105. registerLoading('default', loadingDefault);
  26106. // Default actions
  26107. registerAction({
  26108. type: 'highlight',
  26109. event: 'highlight',
  26110. update: 'highlight'
  26111. }, noop);
  26112. registerAction({
  26113. type: 'downplay',
  26114. event: 'downplay',
  26115. update: 'downplay'
  26116. }, noop);
  26117. // Default theme
  26118. registerTheme('light', lightTheme);
  26119. registerTheme('dark', theme);
  26120. // For backward compatibility, where the namespace `dataTool` will
  26121. // be mounted on `echarts` is the extension `dataTool` is imported.
  26122. var dataTool = {};
  26123. /*
  26124. * Licensed to the Apache Software Foundation (ASF) under one
  26125. * or more contributor license agreements. See the NOTICE file
  26126. * distributed with this work for additional information
  26127. * regarding copyright ownership. The ASF licenses this file
  26128. * to you under the Apache License, Version 2.0 (the
  26129. * "License"); you may not use this file except in compliance
  26130. * with the License. You may obtain a copy of the License at
  26131. *
  26132. * http://www.apache.org/licenses/LICENSE-2.0
  26133. *
  26134. * Unless required by applicable law or agreed to in writing,
  26135. * software distributed under the License is distributed on an
  26136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26137. * KIND, either express or implied. See the License for the
  26138. * specific language governing permissions and limitations
  26139. * under the License.
  26140. */
  26141. function defaultKeyGetter(item) {
  26142. return item;
  26143. }
  26144. /**
  26145. * @param {Array} oldArr
  26146. * @param {Array} newArr
  26147. * @param {Function} oldKeyGetter
  26148. * @param {Function} newKeyGetter
  26149. * @param {Object} [context] Can be visited by this.context in callback.
  26150. */
  26151. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26152. this._old = oldArr;
  26153. this._new = newArr;
  26154. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26155. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26156. this.context = context;
  26157. }
  26158. DataDiffer.prototype = {
  26159. constructor: DataDiffer,
  26160. /**
  26161. * Callback function when add a data
  26162. */
  26163. add: function (func) {
  26164. this._add = func;
  26165. return this;
  26166. },
  26167. /**
  26168. * Callback function when update a data
  26169. */
  26170. update: function (func) {
  26171. this._update = func;
  26172. return this;
  26173. },
  26174. /**
  26175. * Callback function when remove a data
  26176. */
  26177. remove: function (func) {
  26178. this._remove = func;
  26179. return this;
  26180. },
  26181. execute: function () {
  26182. var oldArr = this._old;
  26183. var newArr = this._new;
  26184. var oldDataIndexMap = {};
  26185. var newDataIndexMap = {};
  26186. var oldDataKeyArr = [];
  26187. var newDataKeyArr = [];
  26188. var i;
  26189. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26190. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26191. for (i = 0; i < oldArr.length; i++) {
  26192. var key = oldDataKeyArr[i];
  26193. var idx = newDataIndexMap[key];
  26194. // idx can never be empty array here. see 'set null' logic below.
  26195. if (idx != null) {
  26196. // Consider there is duplicate key (for example, use dataItem.name as key).
  26197. // We should make sure every item in newArr and oldArr can be visited.
  26198. var len = idx.length;
  26199. if (len) {
  26200. len === 1 && (newDataIndexMap[key] = null);
  26201. idx = idx.shift();
  26202. }
  26203. else {
  26204. newDataIndexMap[key] = null;
  26205. }
  26206. this._update && this._update(idx, i);
  26207. }
  26208. else {
  26209. this._remove && this._remove(i);
  26210. }
  26211. }
  26212. for (var i = 0; i < newDataKeyArr.length; i++) {
  26213. var key = newDataKeyArr[i];
  26214. if (newDataIndexMap.hasOwnProperty(key)) {
  26215. var idx = newDataIndexMap[key];
  26216. if (idx == null) {
  26217. continue;
  26218. }
  26219. // idx can never be empty array here. see 'set null' logic above.
  26220. if (!idx.length) {
  26221. this._add && this._add(idx);
  26222. }
  26223. else {
  26224. for (var j = 0, len = idx.length; j < len; j++) {
  26225. this._add && this._add(idx[j]);
  26226. }
  26227. }
  26228. }
  26229. }
  26230. }
  26231. };
  26232. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26233. for (var i = 0; i < arr.length; i++) {
  26234. // Add prefix to avoid conflict with Object.prototype.
  26235. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26236. var existence = map[key];
  26237. if (existence == null) {
  26238. keyArr.push(key);
  26239. map[key] = i;
  26240. }
  26241. else {
  26242. if (!existence.length) {
  26243. map[key] = existence = [existence];
  26244. }
  26245. existence.push(i);
  26246. }
  26247. }
  26248. }
  26249. /*
  26250. * Licensed to the Apache Software Foundation (ASF) under one
  26251. * or more contributor license agreements. See the NOTICE file
  26252. * distributed with this work for additional information
  26253. * regarding copyright ownership. The ASF licenses this file
  26254. * to you under the Apache License, Version 2.0 (the
  26255. * "License"); you may not use this file except in compliance
  26256. * with the License. You may obtain a copy of the License at
  26257. *
  26258. * http://www.apache.org/licenses/LICENSE-2.0
  26259. *
  26260. * Unless required by applicable law or agreed to in writing,
  26261. * software distributed under the License is distributed on an
  26262. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26263. * KIND, either express or implied. See the License for the
  26264. * specific language governing permissions and limitations
  26265. * under the License.
  26266. */
  26267. var OTHER_DIMENSIONS = createHashMap([
  26268. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26269. ]);
  26270. function summarizeDimensions(data) {
  26271. var summary = {};
  26272. var encode = summary.encode = {};
  26273. var notExtraCoordDimMap = createHashMap();
  26274. var defaultedLabel = [];
  26275. var defaultedTooltip = [];
  26276. // See the comment of `List.js#userOutput`.
  26277. var userOutput = summary.userOutput = {
  26278. dimensionNames: data.dimensions.slice(),
  26279. encode: {}
  26280. };
  26281. each$1(data.dimensions, function (dimName) {
  26282. var dimItem = data.getDimensionInfo(dimName);
  26283. var coordDim = dimItem.coordDim;
  26284. if (coordDim) {
  26285. if (__DEV__) {
  26286. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26287. }
  26288. var coordDimIndex = dimItem.coordDimIndex;
  26289. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26290. if (!dimItem.isExtraCoord) {
  26291. notExtraCoordDimMap.set(coordDim, 1);
  26292. // Use the last coord dim (and label friendly) as default label,
  26293. // because when dataset is used, it is hard to guess which dimension
  26294. // can be value dimension. If both show x, y on label is not look good,
  26295. // and conventionally y axis is focused more.
  26296. if (mayLabelDimType(dimItem.type)) {
  26297. defaultedLabel[0] = dimName;
  26298. }
  26299. // User output encode do not contain generated coords.
  26300. // And it only has index. User can use index to retrieve value from the raw item array.
  26301. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26302. }
  26303. if (dimItem.defaultTooltip) {
  26304. defaultedTooltip.push(dimName);
  26305. }
  26306. }
  26307. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26308. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26309. var dimIndex = dimItem.otherDims[otherDim];
  26310. if (dimIndex != null && dimIndex !== false) {
  26311. encodeArr[dimIndex] = dimItem.name;
  26312. }
  26313. });
  26314. });
  26315. var dataDimsOnCoord = [];
  26316. var encodeFirstDimNotExtra = {};
  26317. notExtraCoordDimMap.each(function (v, coordDim) {
  26318. var dimArr = encode[coordDim];
  26319. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26320. // But should fix the case that radar axes: simplify the logic
  26321. // of `completeDimension`, remove `extraPrefix`.
  26322. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26323. // Not necessary to remove duplicate, because a data
  26324. // dim canot on more than one coordDim.
  26325. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26326. });
  26327. summary.dataDimsOnCoord = dataDimsOnCoord;
  26328. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26329. var encodeLabel = encode.label;
  26330. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26331. // in this way. Use label.formatter instead. May be remove this approach someday.
  26332. if (encodeLabel && encodeLabel.length) {
  26333. defaultedLabel = encodeLabel.slice();
  26334. }
  26335. var encodeTooltip = encode.tooltip;
  26336. if (encodeTooltip && encodeTooltip.length) {
  26337. defaultedTooltip = encodeTooltip.slice();
  26338. }
  26339. else if (!defaultedTooltip.length) {
  26340. defaultedTooltip = defaultedLabel.slice();
  26341. }
  26342. encode.defaultedLabel = defaultedLabel;
  26343. encode.defaultedTooltip = defaultedTooltip;
  26344. return summary;
  26345. }
  26346. function getOrCreateEncodeArr(encode, dim) {
  26347. if (!encode.hasOwnProperty(dim)) {
  26348. encode[dim] = [];
  26349. }
  26350. return encode[dim];
  26351. }
  26352. function getDimensionTypeByAxis(axisType) {
  26353. return axisType === 'category'
  26354. ? 'ordinal'
  26355. : axisType === 'time'
  26356. ? 'time'
  26357. : 'float';
  26358. }
  26359. function mayLabelDimType(dimType) {
  26360. // In most cases, ordinal and time do not suitable for label.
  26361. // Ordinal info can be displayed on axis. Time is too long.
  26362. return !(dimType === 'ordinal' || dimType === 'time');
  26363. }
  26364. // function findTheLastDimMayLabel(data) {
  26365. // // Get last value dim
  26366. // var dimensions = data.dimensions.slice();
  26367. // var valueType;
  26368. // var valueDim;
  26369. // while (dimensions.length && (
  26370. // valueDim = dimensions.pop(),
  26371. // valueType = data.getDimensionInfo(valueDim).type,
  26372. // valueType === 'ordinal' || valueType === 'time'
  26373. // )) {} // jshint ignore:line
  26374. // return valueDim;
  26375. // }
  26376. /*
  26377. * Licensed to the Apache Software Foundation (ASF) under one
  26378. * or more contributor license agreements. See the NOTICE file
  26379. * distributed with this work for additional information
  26380. * regarding copyright ownership. The ASF licenses this file
  26381. * to you under the Apache License, Version 2.0 (the
  26382. * "License"); you may not use this file except in compliance
  26383. * with the License. You may obtain a copy of the License at
  26384. *
  26385. * http://www.apache.org/licenses/LICENSE-2.0
  26386. *
  26387. * Unless required by applicable law or agreed to in writing,
  26388. * software distributed under the License is distributed on an
  26389. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26390. * KIND, either express or implied. See the License for the
  26391. * specific language governing permissions and limitations
  26392. * under the License.
  26393. */
  26394. /**
  26395. * @class
  26396. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26397. */
  26398. function DataDimensionInfo(opt) {
  26399. if (opt != null) {
  26400. extend(this, opt);
  26401. }
  26402. /**
  26403. * Dimension name.
  26404. * Mandatory.
  26405. * @type {string}
  26406. */
  26407. // this.name;
  26408. /**
  26409. * The origin name in dimsDef, see source helper.
  26410. * If displayName given, the tooltip will displayed vertically.
  26411. * Optional.
  26412. * @type {string}
  26413. */
  26414. // this.displayName;
  26415. /**
  26416. * Which coordSys dimension this dimension mapped to.
  26417. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26418. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26419. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26420. * (That is determined by whether `isExtraCoord` is `true`).
  26421. * Mandatory.
  26422. * @type {string}
  26423. */
  26424. // this.coordDim;
  26425. /**
  26426. * The index of this dimension in `series.encode[coordDim]`.
  26427. * Mandatory.
  26428. * @type {number}
  26429. */
  26430. // this.coordDimIndex;
  26431. /**
  26432. * Dimension type. The enumerable values are the key of
  26433. * `dataCtors` of `data/List`.
  26434. * Optional.
  26435. * @type {string}
  26436. */
  26437. // this.type;
  26438. /**
  26439. * This index of this dimension info in `data/List#_dimensionInfos`.
  26440. * Mandatory after added to `data/List`.
  26441. * @type {number}
  26442. */
  26443. // this.index;
  26444. /**
  26445. * The format of `otherDims` is:
  26446. * ```js
  26447. * {
  26448. * tooltip: number optional,
  26449. * label: number optional,
  26450. * itemName: number optional,
  26451. * seriesName: number optional,
  26452. * }
  26453. * ```
  26454. *
  26455. * A `series.encode` can specified these fields:
  26456. * ```js
  26457. * encode: {
  26458. * // "3, 1, 5" is the index of data dimension.
  26459. * tooltip: [3, 1, 5],
  26460. * label: [0, 3],
  26461. * ...
  26462. * }
  26463. * ```
  26464. * `otherDims` is the parse result of the `series.encode` above, like:
  26465. * ```js
  26466. * // Suppose the index of this data dimension is `3`.
  26467. * this.otherDims = {
  26468. * // `3` is at the index `0` of the `encode.tooltip`
  26469. * tooltip: 0,
  26470. * // `3` is at the index `1` of the `encode.tooltip`
  26471. * label: 1
  26472. * };
  26473. * ```
  26474. *
  26475. * This prop should never be `null`/`undefined` after initialized.
  26476. * @type {Object}
  26477. */
  26478. this.otherDims = {};
  26479. /**
  26480. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26481. * "coordSys" required.
  26482. * Mandatory.
  26483. * @type {boolean}
  26484. */
  26485. // this.isExtraCoord;
  26486. /**
  26487. * @type {module:data/OrdinalMeta}
  26488. */
  26489. // this.ordinalMeta;
  26490. /**
  26491. * Whether to create inverted indices.
  26492. * @type {boolean}
  26493. */
  26494. // this.createInvertedIndices;
  26495. }
  26496. /*
  26497. * Licensed to the Apache Software Foundation (ASF) under one
  26498. * or more contributor license agreements. See the NOTICE file
  26499. * distributed with this work for additional information
  26500. * regarding copyright ownership. The ASF licenses this file
  26501. * to you under the Apache License, Version 2.0 (the
  26502. * "License"); you may not use this file except in compliance
  26503. * with the License. You may obtain a copy of the License at
  26504. *
  26505. * http://www.apache.org/licenses/LICENSE-2.0
  26506. *
  26507. * Unless required by applicable law or agreed to in writing,
  26508. * software distributed under the License is distributed on an
  26509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26510. * KIND, either express or implied. See the License for the
  26511. * specific language governing permissions and limitations
  26512. * under the License.
  26513. */
  26514. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26515. /**
  26516. * List for data storage
  26517. * @module echarts/data/List
  26518. */
  26519. var isObject$4 = isObject$1;
  26520. var UNDEFINED = 'undefined';
  26521. var INDEX_NOT_FOUND = -1;
  26522. // Use prefix to avoid index to be the same as otherIdList[idx],
  26523. // which will cause weird udpate animation.
  26524. var ID_PREFIX = 'e\0\0';
  26525. var dataCtors = {
  26526. 'float': typeof Float64Array === UNDEFINED
  26527. ? Array : Float64Array,
  26528. 'int': typeof Int32Array === UNDEFINED
  26529. ? Array : Int32Array,
  26530. // Ordinal data type can be string or int
  26531. 'ordinal': Array,
  26532. 'number': Array,
  26533. 'time': Array
  26534. };
  26535. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26536. // different from the Ctor of typed array.
  26537. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26538. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26539. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26540. function getIndicesCtor(list) {
  26541. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26542. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26543. }
  26544. function cloneChunk(originalChunk) {
  26545. var Ctor = originalChunk.constructor;
  26546. // Only shallow clone is enough when Array.
  26547. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26548. }
  26549. var TRANSFERABLE_PROPERTIES = [
  26550. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26551. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26552. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26553. ];
  26554. var CLONE_PROPERTIES = [
  26555. '_extent', '_approximateExtent', '_rawExtent'
  26556. ];
  26557. function transferProperties(target, source) {
  26558. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26559. if (source.hasOwnProperty(propName)) {
  26560. target[propName] = source[propName];
  26561. }
  26562. });
  26563. target.__wrappedMethods = source.__wrappedMethods;
  26564. each$1(CLONE_PROPERTIES, function (propName) {
  26565. target[propName] = clone(source[propName]);
  26566. });
  26567. target._calculationInfo = extend(source._calculationInfo);
  26568. }
  26569. /**
  26570. * @constructor
  26571. * @alias module:echarts/data/List
  26572. *
  26573. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26574. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26575. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26576. * @param {module:echarts/model/Model} hostModel
  26577. */
  26578. var List = function (dimensions, hostModel) {
  26579. dimensions = dimensions || ['x', 'y'];
  26580. var dimensionInfos = {};
  26581. var dimensionNames = [];
  26582. var invertedIndicesMap = {};
  26583. for (var i = 0; i < dimensions.length; i++) {
  26584. // Use the original dimensions[i], where other flag props may exists.
  26585. var dimensionInfo = dimensions[i];
  26586. if (isString(dimensionInfo)) {
  26587. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26588. }
  26589. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26590. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26591. }
  26592. var dimensionName = dimensionInfo.name;
  26593. dimensionInfo.type = dimensionInfo.type || 'float';
  26594. if (!dimensionInfo.coordDim) {
  26595. dimensionInfo.coordDim = dimensionName;
  26596. dimensionInfo.coordDimIndex = 0;
  26597. }
  26598. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26599. dimensionNames.push(dimensionName);
  26600. dimensionInfos[dimensionName] = dimensionInfo;
  26601. dimensionInfo.index = i;
  26602. if (dimensionInfo.createInvertedIndices) {
  26603. invertedIndicesMap[dimensionName] = [];
  26604. }
  26605. }
  26606. /**
  26607. * @readOnly
  26608. * @type {Array.<string>}
  26609. */
  26610. this.dimensions = dimensionNames;
  26611. /**
  26612. * Infomation of each data dimension, like data type.
  26613. * @type {Object}
  26614. */
  26615. this._dimensionInfos = dimensionInfos;
  26616. /**
  26617. * @type {module:echarts/model/Model}
  26618. */
  26619. this.hostModel = hostModel;
  26620. /**
  26621. * @type {module:echarts/model/Model}
  26622. */
  26623. this.dataType;
  26624. /**
  26625. * Indices stores the indices of data subset after filtered.
  26626. * This data subset will be used in chart.
  26627. * @type {Array.<number>}
  26628. * @readOnly
  26629. */
  26630. this._indices = null;
  26631. this._count = 0;
  26632. this._rawCount = 0;
  26633. /**
  26634. * Data storage
  26635. * @type {Object.<key, Array.<TypedArray|Array>>}
  26636. * @private
  26637. */
  26638. this._storage = {};
  26639. /**
  26640. * @type {Array.<string>}
  26641. */
  26642. this._nameList = [];
  26643. /**
  26644. * @type {Array.<string>}
  26645. */
  26646. this._idList = [];
  26647. /**
  26648. * Models of data option is stored sparse for optimizing memory cost
  26649. * @type {Array.<module:echarts/model/Model>}
  26650. * @private
  26651. */
  26652. this._optionModels = [];
  26653. /**
  26654. * Global visual properties after visual coding
  26655. * @type {Object}
  26656. * @private
  26657. */
  26658. this._visual = {};
  26659. /**
  26660. * Globel layout properties.
  26661. * @type {Object}
  26662. * @private
  26663. */
  26664. this._layout = {};
  26665. /**
  26666. * Item visual properties after visual coding
  26667. * @type {Array.<Object>}
  26668. * @private
  26669. */
  26670. this._itemVisuals = [];
  26671. /**
  26672. * Key: visual type, Value: boolean
  26673. * @type {Object}
  26674. * @readOnly
  26675. */
  26676. this.hasItemVisual = {};
  26677. /**
  26678. * Item layout properties after layout
  26679. * @type {Array.<Object>}
  26680. * @private
  26681. */
  26682. this._itemLayouts = [];
  26683. /**
  26684. * Graphic elemnents
  26685. * @type {Array.<module:zrender/Element>}
  26686. * @private
  26687. */
  26688. this._graphicEls = [];
  26689. /**
  26690. * Max size of each chunk.
  26691. * @type {number}
  26692. * @private
  26693. */
  26694. this._chunkSize = 1e5;
  26695. /**
  26696. * @type {number}
  26697. * @private
  26698. */
  26699. this._chunkCount = 0;
  26700. /**
  26701. * @type {Array.<Array|Object>}
  26702. * @private
  26703. */
  26704. this._rawData;
  26705. /**
  26706. * Raw extent will not be cloned, but only transfered.
  26707. * It will not be calculated util needed.
  26708. * key: dim,
  26709. * value: {end: number, extent: Array.<number>}
  26710. * @type {Object}
  26711. * @private
  26712. */
  26713. this._rawExtent = {};
  26714. /**
  26715. * @type {Object}
  26716. * @private
  26717. */
  26718. this._extent = {};
  26719. /**
  26720. * key: dim
  26721. * value: extent
  26722. * @type {Object}
  26723. * @private
  26724. */
  26725. this._approximateExtent = {};
  26726. /**
  26727. * Cache summary info for fast visit. See "dimensionHelper".
  26728. * @type {Object}
  26729. * @private
  26730. */
  26731. this._dimensionsSummary = summarizeDimensions(this);
  26732. /**
  26733. * @type {Object.<Array|TypedArray>}
  26734. * @private
  26735. */
  26736. this._invertedIndicesMap = invertedIndicesMap;
  26737. /**
  26738. * @type {Object}
  26739. * @private
  26740. */
  26741. this._calculationInfo = {};
  26742. /**
  26743. * User output info of this data.
  26744. * DO NOT use it in other places!
  26745. *
  26746. * When preparing user params for user callbacks, we have
  26747. * to clone these inner data structures to prevent users
  26748. * from modifying them to effect built-in logic. And for
  26749. * performance consideration we make this `userOutput` to
  26750. * avoid clone them too many times.
  26751. *
  26752. * @type {Object}
  26753. * @readOnly
  26754. */
  26755. this.userOutput = this._dimensionsSummary.userOutput;
  26756. };
  26757. var listProto = List.prototype;
  26758. listProto.type = 'list';
  26759. /**
  26760. * If each data item has it's own option
  26761. * @type {boolean}
  26762. */
  26763. listProto.hasItemOption = true;
  26764. /**
  26765. * The meanings of the input parameter `dim`:
  26766. *
  26767. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26768. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26769. * + If dim is a number-like string (e.g., `"1"`):
  26770. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26771. * + If not, it will be converted to a number, which means the index of the dimension.
  26772. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26773. * dimension setting, although now it seems that it is not a good idea.)
  26774. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26775. * if no dimension name is defined as `"1"`.
  26776. * + If dim is a not-number-like string, it means the concrete dim name.
  26777. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26778. * or customized in `dimensions` property of option like `"age"`.
  26779. *
  26780. * Get dimension name
  26781. * @param {string|number} dim See above.
  26782. * @return {string} Concrete dim name.
  26783. */
  26784. listProto.getDimension = function (dim) {
  26785. if (typeof dim === 'number'
  26786. // If being a number-like string but not being defined a dimension name.
  26787. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26788. ) {
  26789. dim = this.dimensions[dim];
  26790. }
  26791. return dim;
  26792. };
  26793. /**
  26794. * Get type and calculation info of particular dimension
  26795. * @param {string|number} dim
  26796. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26797. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26798. */
  26799. listProto.getDimensionInfo = function (dim) {
  26800. // Do not clone, because there may be categories in dimInfo.
  26801. return this._dimensionInfos[this.getDimension(dim)];
  26802. };
  26803. /**
  26804. * @return {Array.<string>} concrete dimension name list on coord.
  26805. */
  26806. listProto.getDimensionsOnCoord = function () {
  26807. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26808. };
  26809. /**
  26810. * @param {string} coordDim
  26811. * @param {number} [idx] A coordDim may map to more than one data dim.
  26812. * If idx is `true`, return a array of all mapped dims.
  26813. * If idx is not specified, return the first dim not extra.
  26814. * @return {string|Array.<string>} concrete data dim.
  26815. * If idx is number, and not found, return null/undefined.
  26816. * If idx is `true`, and not found, return empty array (always return array).
  26817. */
  26818. listProto.mapDimension = function (coordDim, idx) {
  26819. var dimensionsSummary = this._dimensionsSummary;
  26820. if (idx == null) {
  26821. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26822. }
  26823. var dims = dimensionsSummary.encode[coordDim];
  26824. return idx === true
  26825. // always return array if idx is `true`
  26826. ? (dims || []).slice()
  26827. : (dims && dims[idx]);
  26828. };
  26829. /**
  26830. * Initialize from data
  26831. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26832. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26833. * defualt label/tooltip.
  26834. * A name can be specified in encode.itemName,
  26835. * or dataItem.name (only for series option data),
  26836. * or provided in nameList from outside.
  26837. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26838. */
  26839. listProto.initData = function (data, nameList, dimValueGetter) {
  26840. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26841. if (notProvider) {
  26842. data = new DefaultDataProvider(data, this.dimensions.length);
  26843. }
  26844. if (__DEV__) {
  26845. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26846. throw new Error('Inavlid data provider.');
  26847. }
  26848. }
  26849. this._rawData = data;
  26850. // Clear
  26851. this._storage = {};
  26852. this._indices = null;
  26853. this._nameList = nameList || [];
  26854. this._idList = [];
  26855. this._nameRepeatCount = {};
  26856. if (!dimValueGetter) {
  26857. this.hasItemOption = false;
  26858. }
  26859. /**
  26860. * @readOnly
  26861. */
  26862. this.defaultDimValueGetter = defaultDimValueGetters[
  26863. this._rawData.getSource().sourceFormat
  26864. ];
  26865. // Default dim value getter
  26866. this._dimValueGetter = dimValueGetter = dimValueGetter
  26867. || this.defaultDimValueGetter;
  26868. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26869. // Reset raw extent.
  26870. this._rawExtent = {};
  26871. this._initDataFromProvider(0, data.count());
  26872. // If data has no item option.
  26873. if (data.pure) {
  26874. this.hasItemOption = false;
  26875. }
  26876. };
  26877. listProto.getProvider = function () {
  26878. return this._rawData;
  26879. };
  26880. /**
  26881. * Caution: Can be only called on raw data (before `this._indices` created).
  26882. */
  26883. listProto.appendData = function (data) {
  26884. if (__DEV__) {
  26885. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26886. }
  26887. var rawData = this._rawData;
  26888. var start = this.count();
  26889. rawData.appendData(data);
  26890. var end = rawData.count();
  26891. if (!rawData.persistent) {
  26892. end += start;
  26893. }
  26894. this._initDataFromProvider(start, end);
  26895. };
  26896. /**
  26897. * Caution: Can be only called on raw data (before `this._indices` created).
  26898. * This method does not modify `rawData` (`dataProvider`), but only
  26899. * add values to storage.
  26900. *
  26901. * The final count will be increased by `Math.max(values.length, names.length)`.
  26902. *
  26903. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26904. * [
  26905. * [12, 33, 44],
  26906. * [NaN, 43, 1],
  26907. * ['-', 'asdf', 0]
  26908. * ]
  26909. * Each item is exaclty cooresponding to a dimension.
  26910. * @param {Array.<string>} [names]
  26911. */
  26912. listProto.appendValues = function (values, names) {
  26913. var chunkSize = this._chunkSize;
  26914. var storage = this._storage;
  26915. var dimensions = this.dimensions;
  26916. var dimLen = dimensions.length;
  26917. var rawExtent = this._rawExtent;
  26918. var start = this.count();
  26919. var end = start + Math.max(values.length, names ? names.length : 0);
  26920. var originalChunkCount = this._chunkCount;
  26921. for (var i = 0; i < dimLen; i++) {
  26922. var dim = dimensions[i];
  26923. if (!rawExtent[dim]) {
  26924. rawExtent[dim] = getInitialExtent();
  26925. }
  26926. if (!storage[dim]) {
  26927. storage[dim] = [];
  26928. }
  26929. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26930. this._chunkCount = storage[dim].length;
  26931. }
  26932. var emptyDataItem = new Array(dimLen);
  26933. for (var idx = start; idx < end; idx++) {
  26934. var sourceIdx = idx - start;
  26935. var chunkIndex = Math.floor(idx / chunkSize);
  26936. var chunkOffset = idx % chunkSize;
  26937. // Store the data by dimensions
  26938. for (var k = 0; k < dimLen; k++) {
  26939. var dim = dimensions[k];
  26940. var val = this._dimValueGetterArrayRows(
  26941. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26942. );
  26943. storage[dim][chunkIndex][chunkOffset] = val;
  26944. var dimRawExtent = rawExtent[dim];
  26945. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26946. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26947. }
  26948. if (names) {
  26949. this._nameList[idx] = names[sourceIdx];
  26950. }
  26951. }
  26952. this._rawCount = this._count = end;
  26953. // Reset data extent
  26954. this._extent = {};
  26955. prepareInvertedIndex(this);
  26956. };
  26957. listProto._initDataFromProvider = function (start, end) {
  26958. // Optimize.
  26959. if (start >= end) {
  26960. return;
  26961. }
  26962. var chunkSize = this._chunkSize;
  26963. var rawData = this._rawData;
  26964. var storage = this._storage;
  26965. var dimensions = this.dimensions;
  26966. var dimLen = dimensions.length;
  26967. var dimensionInfoMap = this._dimensionInfos;
  26968. var nameList = this._nameList;
  26969. var idList = this._idList;
  26970. var rawExtent = this._rawExtent;
  26971. var nameRepeatCount = this._nameRepeatCount = {};
  26972. var nameDimIdx;
  26973. var originalChunkCount = this._chunkCount;
  26974. for (var i = 0; i < dimLen; i++) {
  26975. var dim = dimensions[i];
  26976. if (!rawExtent[dim]) {
  26977. rawExtent[dim] = getInitialExtent();
  26978. }
  26979. var dimInfo = dimensionInfoMap[dim];
  26980. if (dimInfo.otherDims.itemName === 0) {
  26981. nameDimIdx = this._nameDimIdx = i;
  26982. }
  26983. if (dimInfo.otherDims.itemId === 0) {
  26984. this._idDimIdx = i;
  26985. }
  26986. if (!storage[dim]) {
  26987. storage[dim] = [];
  26988. }
  26989. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26990. this._chunkCount = storage[dim].length;
  26991. }
  26992. var dataItem = new Array(dimLen);
  26993. for (var idx = start; idx < end; idx++) {
  26994. // NOTICE: Try not to write things into dataItem
  26995. dataItem = rawData.getItem(idx, dataItem);
  26996. // Each data item is value
  26997. // [1, 2]
  26998. // 2
  26999. // Bar chart, line chart which uses category axis
  27000. // only gives the 'y' value. 'x' value is the indices of category
  27001. // Use a tempValue to normalize the value to be a (x, y) value
  27002. var chunkIndex = Math.floor(idx / chunkSize);
  27003. var chunkOffset = idx % chunkSize;
  27004. // Store the data by dimensions
  27005. for (var k = 0; k < dimLen; k++) {
  27006. var dim = dimensions[k];
  27007. var dimStorage = storage[dim][chunkIndex];
  27008. // PENDING NULL is empty or zero
  27009. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27010. dimStorage[chunkOffset] = val;
  27011. var dimRawExtent = rawExtent[dim];
  27012. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27013. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27014. }
  27015. // ??? FIXME not check by pure but sourceFormat?
  27016. // TODO refactor these logic.
  27017. if (!rawData.pure) {
  27018. var name = nameList[idx];
  27019. if (dataItem && name == null) {
  27020. // If dataItem is {name: ...}, it has highest priority.
  27021. // That is appropriate for many common cases.
  27022. if (dataItem.name != null) {
  27023. // There is no other place to persistent dataItem.name,
  27024. // so save it to nameList.
  27025. nameList[idx] = name = dataItem.name;
  27026. }
  27027. else if (nameDimIdx != null) {
  27028. var nameDim = dimensions[nameDimIdx];
  27029. var nameDimChunk = storage[nameDim][chunkIndex];
  27030. if (nameDimChunk) {
  27031. name = nameDimChunk[chunkOffset];
  27032. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27033. if (ordinalMeta && ordinalMeta.categories.length) {
  27034. name = ordinalMeta.categories[name];
  27035. }
  27036. }
  27037. }
  27038. }
  27039. // Try using the id in option
  27040. // id or name is used on dynamical data, mapping old and new items.
  27041. var id = dataItem == null ? null : dataItem.id;
  27042. if (id == null && name != null) {
  27043. // Use name as id and add counter to avoid same name
  27044. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27045. id = name;
  27046. if (nameRepeatCount[name] > 0) {
  27047. id += '__ec__' + nameRepeatCount[name];
  27048. }
  27049. nameRepeatCount[name]++;
  27050. }
  27051. id != null && (idList[idx] = id);
  27052. }
  27053. }
  27054. if (!rawData.persistent && rawData.clean) {
  27055. // Clean unused data if data source is typed array.
  27056. rawData.clean();
  27057. }
  27058. this._rawCount = this._count = end;
  27059. // Reset data extent
  27060. this._extent = {};
  27061. prepareInvertedIndex(this);
  27062. };
  27063. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27064. var DataCtor = dataCtors[dimInfo.type];
  27065. var lastChunkIndex = chunkCount - 1;
  27066. var dim = dimInfo.name;
  27067. var resizeChunkArray = storage[dim][lastChunkIndex];
  27068. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27069. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27070. // The cost of the copy is probably inconsiderable
  27071. // within the initial chunkSize.
  27072. for (var j = 0; j < resizeChunkArray.length; j++) {
  27073. newStore[j] = resizeChunkArray[j];
  27074. }
  27075. storage[dim][lastChunkIndex] = newStore;
  27076. }
  27077. // Create new chunks.
  27078. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27079. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27080. }
  27081. }
  27082. function prepareInvertedIndex(list) {
  27083. var invertedIndicesMap = list._invertedIndicesMap;
  27084. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27085. var dimInfo = list._dimensionInfos[dim];
  27086. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27087. var ordinalMeta = dimInfo.ordinalMeta;
  27088. if (ordinalMeta) {
  27089. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27090. ordinalMeta.categories.length
  27091. );
  27092. // The default value of TypedArray is 0. To avoid miss
  27093. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27094. for (var i = 0; i < invertedIndices.length; i++) {
  27095. invertedIndices[i] = INDEX_NOT_FOUND;
  27096. }
  27097. for (var i = 0; i < list._count; i++) {
  27098. // Only support the case that all values are distinct.
  27099. invertedIndices[list.get(dim, i)] = i;
  27100. }
  27101. }
  27102. });
  27103. }
  27104. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27105. var val;
  27106. if (dimIndex != null) {
  27107. var chunkSize = list._chunkSize;
  27108. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27109. var chunkOffset = rawIndex % chunkSize;
  27110. var dim = list.dimensions[dimIndex];
  27111. var chunk = list._storage[dim][chunkIndex];
  27112. if (chunk) {
  27113. val = chunk[chunkOffset];
  27114. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27115. if (ordinalMeta && ordinalMeta.categories.length) {
  27116. val = ordinalMeta.categories[val];
  27117. }
  27118. }
  27119. }
  27120. return val;
  27121. }
  27122. /**
  27123. * @return {number}
  27124. */
  27125. listProto.count = function () {
  27126. return this._count;
  27127. };
  27128. listProto.getIndices = function () {
  27129. var newIndices;
  27130. var indices = this._indices;
  27131. if (indices) {
  27132. var Ctor = indices.constructor;
  27133. var thisCount = this._count;
  27134. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27135. if (Ctor === Array) {
  27136. newIndices = new Ctor(thisCount);
  27137. for (var i = 0; i < thisCount; i++) {
  27138. newIndices[i] = indices[i];
  27139. }
  27140. }
  27141. else {
  27142. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27143. }
  27144. }
  27145. else {
  27146. var Ctor = getIndicesCtor(this);
  27147. var newIndices = new Ctor(this.count());
  27148. for (var i = 0; i < newIndices.length; i++) {
  27149. newIndices[i] = i;
  27150. }
  27151. }
  27152. return newIndices;
  27153. };
  27154. /**
  27155. * Get value. Return NaN if idx is out of range.
  27156. * @param {string} dim Dim must be concrete name.
  27157. * @param {number} idx
  27158. * @param {boolean} stack
  27159. * @return {number}
  27160. */
  27161. listProto.get = function (dim, idx /*, stack */) {
  27162. if (!(idx >= 0 && idx < this._count)) {
  27163. return NaN;
  27164. }
  27165. var storage = this._storage;
  27166. if (!storage[dim]) {
  27167. // TODO Warn ?
  27168. return NaN;
  27169. }
  27170. idx = this.getRawIndex(idx);
  27171. var chunkIndex = Math.floor(idx / this._chunkSize);
  27172. var chunkOffset = idx % this._chunkSize;
  27173. var chunkStore = storage[dim][chunkIndex];
  27174. var value = chunkStore[chunkOffset];
  27175. // FIXME ordinal data type is not stackable
  27176. // if (stack) {
  27177. // var dimensionInfo = this._dimensionInfos[dim];
  27178. // if (dimensionInfo && dimensionInfo.stackable) {
  27179. // var stackedOn = this.stackedOn;
  27180. // while (stackedOn) {
  27181. // // Get no stacked data of stacked on
  27182. // var stackedValue = stackedOn.get(dim, idx);
  27183. // // Considering positive stack, negative stack and empty data
  27184. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27185. // || (value <= 0 && stackedValue < 0) // Negative stack
  27186. // ) {
  27187. // value += stackedValue;
  27188. // }
  27189. // stackedOn = stackedOn.stackedOn;
  27190. // }
  27191. // }
  27192. // }
  27193. return value;
  27194. };
  27195. /**
  27196. * @param {string} dim concrete dim
  27197. * @param {number} rawIndex
  27198. * @return {number|string}
  27199. */
  27200. listProto.getByRawIndex = function (dim, rawIdx) {
  27201. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27202. return NaN;
  27203. }
  27204. var dimStore = this._storage[dim];
  27205. if (!dimStore) {
  27206. // TODO Warn ?
  27207. return NaN;
  27208. }
  27209. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27210. var chunkOffset = rawIdx % this._chunkSize;
  27211. var chunkStore = dimStore[chunkIndex];
  27212. return chunkStore[chunkOffset];
  27213. };
  27214. /**
  27215. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27216. * Hack a much simpler _getFast
  27217. * @private
  27218. */
  27219. listProto._getFast = function (dim, rawIdx) {
  27220. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27221. var chunkOffset = rawIdx % this._chunkSize;
  27222. var chunkStore = this._storage[dim][chunkIndex];
  27223. return chunkStore[chunkOffset];
  27224. };
  27225. /**
  27226. * Get value for multi dimensions.
  27227. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27228. * @param {number} idx
  27229. * @return {number}
  27230. */
  27231. listProto.getValues = function (dimensions, idx /*, stack */) {
  27232. var values = [];
  27233. if (!isArray(dimensions)) {
  27234. // stack = idx;
  27235. idx = dimensions;
  27236. dimensions = this.dimensions;
  27237. }
  27238. for (var i = 0, len = dimensions.length; i < len; i++) {
  27239. values.push(this.get(dimensions[i], idx /*, stack */));
  27240. }
  27241. return values;
  27242. };
  27243. /**
  27244. * If value is NaN. Inlcuding '-'
  27245. * Only check the coord dimensions.
  27246. * @param {string} dim
  27247. * @param {number} idx
  27248. * @return {number}
  27249. */
  27250. listProto.hasValue = function (idx) {
  27251. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27252. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27253. // Ordinal type originally can be string or number.
  27254. // But when an ordinal type is used on coord, it can
  27255. // not be string but only number. So we can also use isNaN.
  27256. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27257. return false;
  27258. }
  27259. }
  27260. return true;
  27261. };
  27262. /**
  27263. * Get extent of data in one dimension
  27264. * @param {string} dim
  27265. * @param {boolean} stack
  27266. */
  27267. listProto.getDataExtent = function (dim /*, stack */) {
  27268. // Make sure use concrete dim as cache name.
  27269. dim = this.getDimension(dim);
  27270. var dimData = this._storage[dim];
  27271. var initialExtent = getInitialExtent();
  27272. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27273. if (!dimData) {
  27274. return initialExtent;
  27275. }
  27276. // Make more strict checkings to ensure hitting cache.
  27277. var currEnd = this.count();
  27278. // var cacheName = [dim, !!stack].join('_');
  27279. // var cacheName = dim;
  27280. // Consider the most cases when using data zoom, `getDataExtent`
  27281. // happened before filtering. We cache raw extent, which is not
  27282. // necessary to be cleared and recalculated when restore data.
  27283. var useRaw = !this._indices; // && !stack;
  27284. var dimExtent;
  27285. if (useRaw) {
  27286. return this._rawExtent[dim].slice();
  27287. }
  27288. dimExtent = this._extent[dim];
  27289. if (dimExtent) {
  27290. return dimExtent.slice();
  27291. }
  27292. dimExtent = initialExtent;
  27293. var min = dimExtent[0];
  27294. var max = dimExtent[1];
  27295. for (var i = 0; i < currEnd; i++) {
  27296. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27297. var value = this._getFast(dim, this.getRawIndex(i));
  27298. value < min && (min = value);
  27299. value > max && (max = value);
  27300. }
  27301. dimExtent = [min, max];
  27302. this._extent[dim] = dimExtent;
  27303. return dimExtent;
  27304. };
  27305. /**
  27306. * Optimize for the scenario that data is filtered by a given extent.
  27307. * Consider that if data amount is more than hundreds of thousand,
  27308. * extent calculation will cost more than 10ms and the cache will
  27309. * be erased because of the filtering.
  27310. */
  27311. listProto.getApproximateExtent = function (dim /*, stack */) {
  27312. dim = this.getDimension(dim);
  27313. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27314. };
  27315. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27316. dim = this.getDimension(dim);
  27317. this._approximateExtent[dim] = extent.slice();
  27318. };
  27319. /**
  27320. * @param {string} key
  27321. * @return {*}
  27322. */
  27323. listProto.getCalculationInfo = function (key) {
  27324. return this._calculationInfo[key];
  27325. };
  27326. /**
  27327. * @param {string|Object} key or k-v object
  27328. * @param {*} [value]
  27329. */
  27330. listProto.setCalculationInfo = function (key, value) {
  27331. isObject$4(key)
  27332. ? extend(this._calculationInfo, key)
  27333. : (this._calculationInfo[key] = value);
  27334. };
  27335. /**
  27336. * Get sum of data in one dimension
  27337. * @param {string} dim
  27338. */
  27339. listProto.getSum = function (dim /*, stack */) {
  27340. var dimData = this._storage[dim];
  27341. var sum = 0;
  27342. if (dimData) {
  27343. for (var i = 0, len = this.count(); i < len; i++) {
  27344. var value = this.get(dim, i /*, stack */);
  27345. if (!isNaN(value)) {
  27346. sum += value;
  27347. }
  27348. }
  27349. }
  27350. return sum;
  27351. };
  27352. /**
  27353. * Get median of data in one dimension
  27354. * @param {string} dim
  27355. */
  27356. listProto.getMedian = function (dim /*, stack */) {
  27357. var dimDataArray = [];
  27358. // map all data of one dimension
  27359. this.each(dim, function (val, idx) {
  27360. if (!isNaN(val)) {
  27361. dimDataArray.push(val);
  27362. }
  27363. });
  27364. // TODO
  27365. // Use quick select?
  27366. // immutability & sort
  27367. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27368. return a - b;
  27369. });
  27370. var len = this.count();
  27371. // calculate median
  27372. return len === 0
  27373. ? 0
  27374. : len % 2 === 1
  27375. ? sortedDimDataArray[(len - 1) / 2]
  27376. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27377. };
  27378. // /**
  27379. // * Retreive the index with given value
  27380. // * @param {string} dim Concrete dimension.
  27381. // * @param {number} value
  27382. // * @return {number}
  27383. // */
  27384. // Currently incorrect: should return dataIndex but not rawIndex.
  27385. // Do not fix it until this method is to be used somewhere.
  27386. // FIXME Precision of float value
  27387. // listProto.indexOf = function (dim, value) {
  27388. // var storage = this._storage;
  27389. // var dimData = storage[dim];
  27390. // var chunkSize = this._chunkSize;
  27391. // if (dimData) {
  27392. // for (var i = 0, len = this.count(); i < len; i++) {
  27393. // var chunkIndex = Math.floor(i / chunkSize);
  27394. // var chunkOffset = i % chunkSize;
  27395. // if (dimData[chunkIndex][chunkOffset] === value) {
  27396. // return i;
  27397. // }
  27398. // }
  27399. // }
  27400. // return -1;
  27401. // };
  27402. /**
  27403. * Only support the dimension which inverted index created.
  27404. * Do not support other cases until required.
  27405. * @param {string} concrete dim
  27406. * @param {number|string} value
  27407. * @return {number} rawIndex
  27408. */
  27409. listProto.rawIndexOf = function (dim, value) {
  27410. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27411. if (__DEV__) {
  27412. if (!invertedIndices) {
  27413. throw new Error('Do not supported yet');
  27414. }
  27415. }
  27416. var rawIndex = invertedIndices[value];
  27417. if (rawIndex == null || isNaN(rawIndex)) {
  27418. return INDEX_NOT_FOUND;
  27419. }
  27420. return rawIndex;
  27421. };
  27422. /**
  27423. * Retreive the index with given name
  27424. * @param {number} idx
  27425. * @param {number} name
  27426. * @return {number}
  27427. */
  27428. listProto.indexOfName = function (name) {
  27429. for (var i = 0, len = this.count(); i < len; i++) {
  27430. if (this.getName(i) === name) {
  27431. return i;
  27432. }
  27433. }
  27434. return -1;
  27435. };
  27436. /**
  27437. * Retreive the index with given raw data index
  27438. * @param {number} idx
  27439. * @param {number} name
  27440. * @return {number}
  27441. */
  27442. listProto.indexOfRawIndex = function (rawIndex) {
  27443. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27444. return -1;
  27445. }
  27446. if (!this._indices) {
  27447. return rawIndex;
  27448. }
  27449. // Indices are ascending
  27450. var indices = this._indices;
  27451. // If rawIndex === dataIndex
  27452. var rawDataIndex = indices[rawIndex];
  27453. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27454. return rawIndex;
  27455. }
  27456. var left = 0;
  27457. var right = this._count - 1;
  27458. while (left <= right) {
  27459. var mid = (left + right) / 2 | 0;
  27460. if (indices[mid] < rawIndex) {
  27461. left = mid + 1;
  27462. }
  27463. else if (indices[mid] > rawIndex) {
  27464. right = mid - 1;
  27465. }
  27466. else {
  27467. return mid;
  27468. }
  27469. }
  27470. return -1;
  27471. };
  27472. /**
  27473. * Retreive the index of nearest value
  27474. * @param {string} dim
  27475. * @param {number} value
  27476. * @param {number} [maxDistance=Infinity]
  27477. * @return {Array.<number>} If and only if multiple indices has
  27478. * the same value, they are put to the result.
  27479. */
  27480. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27481. var storage = this._storage;
  27482. var dimData = storage[dim];
  27483. var nearestIndices = [];
  27484. if (!dimData) {
  27485. return nearestIndices;
  27486. }
  27487. if (maxDistance == null) {
  27488. maxDistance = Infinity;
  27489. }
  27490. var minDist = Infinity;
  27491. var minDiff = -1;
  27492. var nearestIndicesLen = 0;
  27493. // Check the test case of `test/ut/spec/data/List.js`.
  27494. for (var i = 0, len = this.count(); i < len; i++) {
  27495. var diff = value - this.get(dim, i);
  27496. var dist = Math.abs(diff);
  27497. if (dist <= maxDistance) {
  27498. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27499. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27500. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27501. // So we chose the one that `diff >= 0` in this csae.
  27502. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27503. // should be push to `nearestIndices`.
  27504. if (dist < minDist
  27505. || (dist === minDist && diff >= 0 && minDiff < 0)
  27506. ) {
  27507. minDist = dist;
  27508. minDiff = diff;
  27509. nearestIndicesLen = 0;
  27510. }
  27511. if (diff === minDiff) {
  27512. nearestIndices[nearestIndicesLen++] = i;
  27513. }
  27514. }
  27515. }
  27516. nearestIndices.length = nearestIndicesLen;
  27517. return nearestIndices;
  27518. };
  27519. /**
  27520. * Get raw data index
  27521. * @param {number} idx
  27522. * @return {number}
  27523. */
  27524. listProto.getRawIndex = getRawIndexWithoutIndices;
  27525. function getRawIndexWithoutIndices(idx) {
  27526. return idx;
  27527. }
  27528. function getRawIndexWithIndices(idx) {
  27529. if (idx < this._count && idx >= 0) {
  27530. return this._indices[idx];
  27531. }
  27532. return -1;
  27533. }
  27534. /**
  27535. * Get raw data item
  27536. * @param {number} idx
  27537. * @return {number}
  27538. */
  27539. listProto.getRawDataItem = function (idx) {
  27540. if (!this._rawData.persistent) {
  27541. var val = [];
  27542. for (var i = 0; i < this.dimensions.length; i++) {
  27543. var dim = this.dimensions[i];
  27544. val.push(this.get(dim, idx));
  27545. }
  27546. return val;
  27547. }
  27548. else {
  27549. return this._rawData.getItem(this.getRawIndex(idx));
  27550. }
  27551. };
  27552. /**
  27553. * @param {number} idx
  27554. * @param {boolean} [notDefaultIdx=false]
  27555. * @return {string}
  27556. */
  27557. listProto.getName = function (idx) {
  27558. var rawIndex = this.getRawIndex(idx);
  27559. return this._nameList[rawIndex]
  27560. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27561. || '';
  27562. };
  27563. /**
  27564. * @param {number} idx
  27565. * @param {boolean} [notDefaultIdx=false]
  27566. * @return {string}
  27567. */
  27568. listProto.getId = function (idx) {
  27569. return getId(this, this.getRawIndex(idx));
  27570. };
  27571. function getId(list, rawIndex) {
  27572. var id = list._idList[rawIndex];
  27573. if (id == null) {
  27574. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27575. }
  27576. if (id == null) {
  27577. // FIXME Check the usage in graph, should not use prefix.
  27578. id = ID_PREFIX + rawIndex;
  27579. }
  27580. return id;
  27581. }
  27582. function normalizeDimensions(dimensions) {
  27583. if (!isArray(dimensions)) {
  27584. dimensions = [dimensions];
  27585. }
  27586. return dimensions;
  27587. }
  27588. function validateDimensions(list, dims) {
  27589. for (var i = 0; i < dims.length; i++) {
  27590. // stroage may be empty when no data, so use
  27591. // dimensionInfos to check.
  27592. if (!list._dimensionInfos[dims[i]]) {
  27593. console.error('Unkown dimension ' + dims[i]);
  27594. }
  27595. }
  27596. }
  27597. /**
  27598. * Data iteration
  27599. * @param {string|Array.<string>}
  27600. * @param {Function} cb
  27601. * @param {*} [context=this]
  27602. *
  27603. * @example
  27604. * list.each('x', function (x, idx) {});
  27605. * list.each(['x', 'y'], function (x, y, idx) {});
  27606. * list.each(function (idx) {})
  27607. */
  27608. listProto.each = function (dims, cb, context, contextCompat) {
  27609. 'use strict';
  27610. if (!this._count) {
  27611. return;
  27612. }
  27613. if (typeof dims === 'function') {
  27614. contextCompat = context;
  27615. context = cb;
  27616. cb = dims;
  27617. dims = [];
  27618. }
  27619. // contextCompat just for compat echarts3
  27620. context = context || contextCompat || this;
  27621. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27622. if (__DEV__) {
  27623. validateDimensions(this, dims);
  27624. }
  27625. var dimSize = dims.length;
  27626. for (var i = 0; i < this.count(); i++) {
  27627. // Simple optimization
  27628. switch (dimSize) {
  27629. case 0:
  27630. cb.call(context, i);
  27631. break;
  27632. case 1:
  27633. cb.call(context, this.get(dims[0], i), i);
  27634. break;
  27635. case 2:
  27636. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27637. break;
  27638. default:
  27639. var k = 0;
  27640. var value = [];
  27641. for (; k < dimSize; k++) {
  27642. value[k] = this.get(dims[k], i);
  27643. }
  27644. // Index
  27645. value[k] = i;
  27646. cb.apply(context, value);
  27647. }
  27648. }
  27649. };
  27650. /**
  27651. * Data filter
  27652. * @param {string|Array.<string>}
  27653. * @param {Function} cb
  27654. * @param {*} [context=this]
  27655. */
  27656. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27657. 'use strict';
  27658. if (!this._count) {
  27659. return;
  27660. }
  27661. if (typeof dimensions === 'function') {
  27662. contextCompat = context;
  27663. context = cb;
  27664. cb = dimensions;
  27665. dimensions = [];
  27666. }
  27667. // contextCompat just for compat echarts3
  27668. context = context || contextCompat || this;
  27669. dimensions = map(
  27670. normalizeDimensions(dimensions), this.getDimension, this
  27671. );
  27672. if (__DEV__) {
  27673. validateDimensions(this, dimensions);
  27674. }
  27675. var count = this.count();
  27676. var Ctor = getIndicesCtor(this);
  27677. var newIndices = new Ctor(count);
  27678. var value = [];
  27679. var dimSize = dimensions.length;
  27680. var offset = 0;
  27681. var dim0 = dimensions[0];
  27682. for (var i = 0; i < count; i++) {
  27683. var keep;
  27684. var rawIdx = this.getRawIndex(i);
  27685. // Simple optimization
  27686. if (dimSize === 0) {
  27687. keep = cb.call(context, i);
  27688. }
  27689. else if (dimSize === 1) {
  27690. var val = this._getFast(dim0, rawIdx);
  27691. keep = cb.call(context, val, i);
  27692. }
  27693. else {
  27694. for (var k = 0; k < dimSize; k++) {
  27695. value[k] = this._getFast(dim0, rawIdx);
  27696. }
  27697. value[k] = i;
  27698. keep = cb.apply(context, value);
  27699. }
  27700. if (keep) {
  27701. newIndices[offset++] = rawIdx;
  27702. }
  27703. }
  27704. // Set indices after filtered.
  27705. if (offset < count) {
  27706. this._indices = newIndices;
  27707. }
  27708. this._count = offset;
  27709. // Reset data extent
  27710. this._extent = {};
  27711. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27712. return this;
  27713. };
  27714. /**
  27715. * Select data in range. (For optimization of filter)
  27716. * (Manually inline code, support 5 million data filtering in data zoom.)
  27717. */
  27718. listProto.selectRange = function (range) {
  27719. 'use strict';
  27720. if (!this._count) {
  27721. return;
  27722. }
  27723. var dimensions = [];
  27724. for (var dim in range) {
  27725. if (range.hasOwnProperty(dim)) {
  27726. dimensions.push(dim);
  27727. }
  27728. }
  27729. if (__DEV__) {
  27730. validateDimensions(this, dimensions);
  27731. }
  27732. var dimSize = dimensions.length;
  27733. if (!dimSize) {
  27734. return;
  27735. }
  27736. var originalCount = this.count();
  27737. var Ctor = getIndicesCtor(this);
  27738. var newIndices = new Ctor(originalCount);
  27739. var offset = 0;
  27740. var dim0 = dimensions[0];
  27741. var min = range[dim0][0];
  27742. var max = range[dim0][1];
  27743. var quickFinished = false;
  27744. if (!this._indices) {
  27745. // Extreme optimization for common case. About 2x faster in chrome.
  27746. var idx = 0;
  27747. if (dimSize === 1) {
  27748. var dimStorage = this._storage[dimensions[0]];
  27749. for (var k = 0; k < this._chunkCount; k++) {
  27750. var chunkStorage = dimStorage[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. // NaN will not be filtered. Consider the case, in line chart, empty
  27755. // value indicates the line should be broken. But for the case like
  27756. // scatter plot, a data item with empty value will not be rendered,
  27757. // but the axis extent may be effected if some other dim of the data
  27758. // item has value. Fortunately it is not a significant negative effect.
  27759. if (
  27760. (val >= min && val <= max) || isNaN(val)
  27761. ) {
  27762. newIndices[offset++] = idx;
  27763. }
  27764. idx++;
  27765. }
  27766. }
  27767. quickFinished = true;
  27768. }
  27769. else if (dimSize === 2) {
  27770. var dimStorage = this._storage[dim0];
  27771. var dimStorage2 = this._storage[dimensions[1]];
  27772. var min2 = range[dimensions[1]][0];
  27773. var max2 = range[dimensions[1]][1];
  27774. for (var k = 0; k < this._chunkCount; k++) {
  27775. var chunkStorage = dimStorage[k];
  27776. var chunkStorage2 = dimStorage2[k];
  27777. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27778. for (var i = 0; i < len; i++) {
  27779. var val = chunkStorage[i];
  27780. var val2 = chunkStorage2[i];
  27781. // Do not filter NaN, see comment above.
  27782. if ((
  27783. (val >= min && val <= max) || isNaN(val)
  27784. )
  27785. && (
  27786. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27787. )
  27788. ) {
  27789. newIndices[offset++] = idx;
  27790. }
  27791. idx++;
  27792. }
  27793. }
  27794. quickFinished = true;
  27795. }
  27796. }
  27797. if (!quickFinished) {
  27798. if (dimSize === 1) {
  27799. for (var i = 0; i < originalCount; i++) {
  27800. var rawIndex = this.getRawIndex(i);
  27801. var val = this._getFast(dim0, rawIndex);
  27802. // Do not filter NaN, see comment above.
  27803. if (
  27804. (val >= min && val <= max) || isNaN(val)
  27805. ) {
  27806. newIndices[offset++] = rawIndex;
  27807. }
  27808. }
  27809. }
  27810. else {
  27811. for (var i = 0; i < originalCount; i++) {
  27812. var keep = true;
  27813. var rawIndex = this.getRawIndex(i);
  27814. for (var k = 0; k < dimSize; k++) {
  27815. var dimk = dimensions[k];
  27816. var val = this._getFast(dim, rawIndex);
  27817. // Do not filter NaN, see comment above.
  27818. if (val < range[dimk][0] || val > range[dimk][1]) {
  27819. keep = false;
  27820. }
  27821. }
  27822. if (keep) {
  27823. newIndices[offset++] = this.getRawIndex(i);
  27824. }
  27825. }
  27826. }
  27827. }
  27828. // Set indices after filtered.
  27829. if (offset < originalCount) {
  27830. this._indices = newIndices;
  27831. }
  27832. this._count = offset;
  27833. // Reset data extent
  27834. this._extent = {};
  27835. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27836. return this;
  27837. };
  27838. /**
  27839. * Data mapping to a plain array
  27840. * @param {string|Array.<string>} [dimensions]
  27841. * @param {Function} cb
  27842. * @param {*} [context=this]
  27843. * @return {Array}
  27844. */
  27845. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27846. 'use strict';
  27847. if (typeof dimensions === 'function') {
  27848. contextCompat = context;
  27849. context = cb;
  27850. cb = dimensions;
  27851. dimensions = [];
  27852. }
  27853. // contextCompat just for compat echarts3
  27854. context = context || contextCompat || this;
  27855. var result = [];
  27856. this.each(dimensions, function () {
  27857. result.push(cb && cb.apply(this, arguments));
  27858. }, context);
  27859. return result;
  27860. };
  27861. // Data in excludeDimensions is copied, otherwise transfered.
  27862. function cloneListForMapAndSample(original, excludeDimensions) {
  27863. var allDimensions = original.dimensions;
  27864. var list = new List(
  27865. map(allDimensions, original.getDimensionInfo, original),
  27866. original.hostModel
  27867. );
  27868. // FIXME If needs stackedOn, value may already been stacked
  27869. transferProperties(list, original);
  27870. var storage = list._storage = {};
  27871. var originalStorage = original._storage;
  27872. // Init storage
  27873. for (var i = 0; i < allDimensions.length; i++) {
  27874. var dim = allDimensions[i];
  27875. if (originalStorage[dim]) {
  27876. // Notice that we do not reset invertedIndicesMap here, becuase
  27877. // there is no scenario of mapping or sampling ordinal dimension.
  27878. if (indexOf(excludeDimensions, dim) >= 0) {
  27879. storage[dim] = cloneDimStore(originalStorage[dim]);
  27880. list._rawExtent[dim] = getInitialExtent();
  27881. list._extent[dim] = null;
  27882. }
  27883. else {
  27884. // Direct reference for other dimensions
  27885. storage[dim] = originalStorage[dim];
  27886. }
  27887. }
  27888. }
  27889. return list;
  27890. }
  27891. function cloneDimStore(originalDimStore) {
  27892. var newDimStore = new Array(originalDimStore.length);
  27893. for (var j = 0; j < originalDimStore.length; j++) {
  27894. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27895. }
  27896. return newDimStore;
  27897. }
  27898. function getInitialExtent() {
  27899. return [Infinity, -Infinity];
  27900. }
  27901. /**
  27902. * Data mapping to a new List with given dimensions
  27903. * @param {string|Array.<string>} dimensions
  27904. * @param {Function} cb
  27905. * @param {*} [context=this]
  27906. * @return {Array}
  27907. */
  27908. listProto.map = function (dimensions, cb, context, contextCompat) {
  27909. 'use strict';
  27910. // contextCompat just for compat echarts3
  27911. context = context || contextCompat || this;
  27912. dimensions = map(
  27913. normalizeDimensions(dimensions), this.getDimension, this
  27914. );
  27915. if (__DEV__) {
  27916. validateDimensions(this, dimensions);
  27917. }
  27918. var list = cloneListForMapAndSample(this, dimensions);
  27919. // Following properties are all immutable.
  27920. // So we can reference to the same value
  27921. list._indices = this._indices;
  27922. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27923. var storage = list._storage;
  27924. var tmpRetValue = [];
  27925. var chunkSize = this._chunkSize;
  27926. var dimSize = dimensions.length;
  27927. var dataCount = this.count();
  27928. var values = [];
  27929. var rawExtent = list._rawExtent;
  27930. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27931. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27932. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27933. }
  27934. values[dimSize] = dataIndex;
  27935. var retValue = cb && cb.apply(context, values);
  27936. if (retValue != null) {
  27937. // a number or string (in oridinal dimension)?
  27938. if (typeof retValue !== 'object') {
  27939. tmpRetValue[0] = retValue;
  27940. retValue = tmpRetValue;
  27941. }
  27942. var rawIndex = this.getRawIndex(dataIndex);
  27943. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27944. var chunkOffset = rawIndex % chunkSize;
  27945. for (var i = 0; i < retValue.length; i++) {
  27946. var dim = dimensions[i];
  27947. var val = retValue[i];
  27948. var rawExtentOnDim = rawExtent[dim];
  27949. var dimStore = storage[dim];
  27950. if (dimStore) {
  27951. dimStore[chunkIndex][chunkOffset] = val;
  27952. }
  27953. if (val < rawExtentOnDim[0]) {
  27954. rawExtentOnDim[0] = val;
  27955. }
  27956. if (val > rawExtentOnDim[1]) {
  27957. rawExtentOnDim[1] = val;
  27958. }
  27959. }
  27960. }
  27961. }
  27962. return list;
  27963. };
  27964. /**
  27965. * Large data down sampling on given dimension
  27966. * @param {string} dimension
  27967. * @param {number} rate
  27968. * @param {Function} sampleValue
  27969. * @param {Function} sampleIndex Sample index for name and id
  27970. */
  27971. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27972. var list = cloneListForMapAndSample(this, [dimension]);
  27973. var targetStorage = list._storage;
  27974. var frameValues = [];
  27975. var frameSize = Math.floor(1 / rate);
  27976. var dimStore = targetStorage[dimension];
  27977. var len = this.count();
  27978. var chunkSize = this._chunkSize;
  27979. var rawExtentOnDim = list._rawExtent[dimension];
  27980. var newIndices = new (getIndicesCtor(this))(len);
  27981. var offset = 0;
  27982. for (var i = 0; i < len; i += frameSize) {
  27983. // Last frame
  27984. if (frameSize > len - i) {
  27985. frameSize = len - i;
  27986. frameValues.length = frameSize;
  27987. }
  27988. for (var k = 0; k < frameSize; k++) {
  27989. var dataIdx = this.getRawIndex(i + k);
  27990. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27991. var originalChunkOffset = dataIdx % chunkSize;
  27992. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27993. }
  27994. var value = sampleValue(frameValues);
  27995. var sampleFrameIdx = this.getRawIndex(
  27996. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27997. );
  27998. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27999. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28000. // Only write value on the filtered data
  28001. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28002. if (value < rawExtentOnDim[0]) {
  28003. rawExtentOnDim[0] = value;
  28004. }
  28005. if (value > rawExtentOnDim[1]) {
  28006. rawExtentOnDim[1] = value;
  28007. }
  28008. newIndices[offset++] = sampleFrameIdx;
  28009. }
  28010. list._count = offset;
  28011. list._indices = newIndices;
  28012. list.getRawIndex = getRawIndexWithIndices;
  28013. return list;
  28014. };
  28015. /**
  28016. * Get model of one data item.
  28017. *
  28018. * @param {number} idx
  28019. */
  28020. // FIXME Model proxy ?
  28021. listProto.getItemModel = function (idx) {
  28022. var hostModel = this.hostModel;
  28023. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28024. };
  28025. /**
  28026. * Create a data differ
  28027. * @param {module:echarts/data/List} otherList
  28028. * @return {module:echarts/data/DataDiffer}
  28029. */
  28030. listProto.diff = function (otherList) {
  28031. var thisList = this;
  28032. return new DataDiffer(
  28033. otherList ? otherList.getIndices() : [],
  28034. this.getIndices(),
  28035. function (idx) {
  28036. return getId(otherList, idx);
  28037. },
  28038. function (idx) {
  28039. return getId(thisList, idx);
  28040. }
  28041. );
  28042. };
  28043. /**
  28044. * Get visual property.
  28045. * @param {string} key
  28046. */
  28047. listProto.getVisual = function (key) {
  28048. var visual = this._visual;
  28049. return visual && visual[key];
  28050. };
  28051. /**
  28052. * Set visual property
  28053. * @param {string|Object} key
  28054. * @param {*} [value]
  28055. *
  28056. * @example
  28057. * setVisual('color', color);
  28058. * setVisual({
  28059. * 'color': color
  28060. * });
  28061. */
  28062. listProto.setVisual = function (key, val) {
  28063. if (isObject$4(key)) {
  28064. for (var name in key) {
  28065. if (key.hasOwnProperty(name)) {
  28066. this.setVisual(name, key[name]);
  28067. }
  28068. }
  28069. return;
  28070. }
  28071. this._visual = this._visual || {};
  28072. this._visual[key] = val;
  28073. };
  28074. /**
  28075. * Set layout property.
  28076. * @param {string|Object} key
  28077. * @param {*} [val]
  28078. */
  28079. listProto.setLayout = function (key, val) {
  28080. if (isObject$4(key)) {
  28081. for (var name in key) {
  28082. if (key.hasOwnProperty(name)) {
  28083. this.setLayout(name, key[name]);
  28084. }
  28085. }
  28086. return;
  28087. }
  28088. this._layout[key] = val;
  28089. };
  28090. /**
  28091. * Get layout property.
  28092. * @param {string} key.
  28093. * @return {*}
  28094. */
  28095. listProto.getLayout = function (key) {
  28096. return this._layout[key];
  28097. };
  28098. /**
  28099. * Get layout of single data item
  28100. * @param {number} idx
  28101. */
  28102. listProto.getItemLayout = function (idx) {
  28103. return this._itemLayouts[idx];
  28104. };
  28105. /**
  28106. * Set layout of single data item
  28107. * @param {number} idx
  28108. * @param {Object} layout
  28109. * @param {boolean=} [merge=false]
  28110. */
  28111. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28112. this._itemLayouts[idx] = merge$$1
  28113. ? extend(this._itemLayouts[idx] || {}, layout)
  28114. : layout;
  28115. };
  28116. /**
  28117. * Clear all layout of single data item
  28118. */
  28119. listProto.clearItemLayouts = function () {
  28120. this._itemLayouts.length = 0;
  28121. };
  28122. /**
  28123. * Get visual property of single data item
  28124. * @param {number} idx
  28125. * @param {string} key
  28126. * @param {boolean} [ignoreParent=false]
  28127. */
  28128. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28129. var itemVisual = this._itemVisuals[idx];
  28130. var val = itemVisual && itemVisual[key];
  28131. if (val == null && !ignoreParent) {
  28132. // Use global visual property
  28133. return this.getVisual(key);
  28134. }
  28135. return val;
  28136. };
  28137. /**
  28138. * Set visual property of single data item
  28139. *
  28140. * @param {number} idx
  28141. * @param {string|Object} key
  28142. * @param {*} [value]
  28143. *
  28144. * @example
  28145. * setItemVisual(0, 'color', color);
  28146. * setItemVisual(0, {
  28147. * 'color': color
  28148. * });
  28149. */
  28150. listProto.setItemVisual = function (idx, key, value) {
  28151. var itemVisual = this._itemVisuals[idx] || {};
  28152. var hasItemVisual = this.hasItemVisual;
  28153. this._itemVisuals[idx] = itemVisual;
  28154. if (isObject$4(key)) {
  28155. for (var name in key) {
  28156. if (key.hasOwnProperty(name)) {
  28157. itemVisual[name] = key[name];
  28158. hasItemVisual[name] = true;
  28159. }
  28160. }
  28161. return;
  28162. }
  28163. itemVisual[key] = value;
  28164. hasItemVisual[key] = true;
  28165. };
  28166. /**
  28167. * Clear itemVisuals and list visual.
  28168. */
  28169. listProto.clearAllVisual = function () {
  28170. this._visual = {};
  28171. this._itemVisuals = [];
  28172. this.hasItemVisual = {};
  28173. };
  28174. var setItemDataAndSeriesIndex = function (child) {
  28175. child.seriesIndex = this.seriesIndex;
  28176. child.dataIndex = this.dataIndex;
  28177. child.dataType = this.dataType;
  28178. };
  28179. /**
  28180. * Set graphic element relative to data. It can be set as null
  28181. * @param {number} idx
  28182. * @param {module:zrender/Element} [el]
  28183. */
  28184. listProto.setItemGraphicEl = function (idx, el) {
  28185. var hostModel = this.hostModel;
  28186. if (el) {
  28187. // Add data index and series index for indexing the data by element
  28188. // Useful in tooltip
  28189. el.dataIndex = idx;
  28190. el.dataType = this.dataType;
  28191. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28192. if (el.type === 'group') {
  28193. el.traverse(setItemDataAndSeriesIndex, el);
  28194. }
  28195. }
  28196. this._graphicEls[idx] = el;
  28197. };
  28198. /**
  28199. * @param {number} idx
  28200. * @return {module:zrender/Element}
  28201. */
  28202. listProto.getItemGraphicEl = function (idx) {
  28203. return this._graphicEls[idx];
  28204. };
  28205. /**
  28206. * @param {Function} cb
  28207. * @param {*} context
  28208. */
  28209. listProto.eachItemGraphicEl = function (cb, context) {
  28210. each$1(this._graphicEls, function (el, idx) {
  28211. if (el) {
  28212. cb && cb.call(context, el, idx);
  28213. }
  28214. });
  28215. };
  28216. /**
  28217. * Shallow clone a new list except visual and layout properties, and graph elements.
  28218. * New list only change the indices.
  28219. */
  28220. listProto.cloneShallow = function (list) {
  28221. if (!list) {
  28222. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28223. list = new List(dimensionInfoList, this.hostModel);
  28224. }
  28225. // FIXME
  28226. list._storage = this._storage;
  28227. transferProperties(list, this);
  28228. // Clone will not change the data extent and indices
  28229. if (this._indices) {
  28230. var Ctor = this._indices.constructor;
  28231. list._indices = new Ctor(this._indices);
  28232. }
  28233. else {
  28234. list._indices = null;
  28235. }
  28236. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28237. return list;
  28238. };
  28239. /**
  28240. * Wrap some method to add more feature
  28241. * @param {string} methodName
  28242. * @param {Function} injectFunction
  28243. */
  28244. listProto.wrapMethod = function (methodName, injectFunction) {
  28245. var originalMethod = this[methodName];
  28246. if (typeof originalMethod !== 'function') {
  28247. return;
  28248. }
  28249. this.__wrappedMethods = this.__wrappedMethods || [];
  28250. this.__wrappedMethods.push(methodName);
  28251. this[methodName] = function () {
  28252. var res = originalMethod.apply(this, arguments);
  28253. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28254. };
  28255. };
  28256. // Methods that create a new list based on this list should be listed here.
  28257. // Notice that those method should `RETURN` the new list.
  28258. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28259. // Methods that change indices of this list should be listed here.
  28260. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28261. /*
  28262. * Licensed to the Apache Software Foundation (ASF) under one
  28263. * or more contributor license agreements. See the NOTICE file
  28264. * distributed with this work for additional information
  28265. * regarding copyright ownership. The ASF licenses this file
  28266. * to you under the Apache License, Version 2.0 (the
  28267. * "License"); you may not use this file except in compliance
  28268. * with the License. You may obtain a copy of the License at
  28269. *
  28270. * http://www.apache.org/licenses/LICENSE-2.0
  28271. *
  28272. * Unless required by applicable law or agreed to in writing,
  28273. * software distributed under the License is distributed on an
  28274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28275. * KIND, either express or implied. See the License for the
  28276. * specific language governing permissions and limitations
  28277. * under the License.
  28278. */
  28279. /**
  28280. * @deprecated
  28281. * Use `echarts/data/helper/createDimensions` instead.
  28282. */
  28283. /**
  28284. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28285. *
  28286. * This method builds the relationship between:
  28287. * + "what the coord sys or series requires (see `sysDims`)",
  28288. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28289. * + "what the data source provids (see `source`)".
  28290. *
  28291. * Some guess strategy will be adapted if user does not define something.
  28292. * If no 'value' dimension specified, the first no-named dimension will be
  28293. * named as 'value'.
  28294. *
  28295. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28296. * provides not only dim template, but also default order.
  28297. * properties: 'name', 'type', 'displayName'.
  28298. * `name` of each item provides default coord name.
  28299. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28300. * provide dims count that the sysDim required.
  28301. * [{ordinalMeta}] can be specified.
  28302. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28303. * @param {Object} [opt]
  28304. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28305. * For example: ['asdf', {name, type}, ...].
  28306. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28307. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28308. * If not specified, auto find the next available data dim.
  28309. * param source {module:data/Source}
  28310. * param dimCount {number}
  28311. * return {Object} encode Never be `null/undefined`.
  28312. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28313. * If not specified, extra dim names will be:
  28314. * 'value', 'value0', 'value1', ...
  28315. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28316. * If `generateCoordCount` specified, the generated dim names will be:
  28317. * `generateCoord` + 0, `generateCoord` + 1, ...
  28318. * can be Infinity, indicate that use all of the remain columns.
  28319. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28320. * @return {Array.<module:data/DataDimensionInfo>}
  28321. */
  28322. function completeDimensions(sysDims, source, opt) {
  28323. if (!Source.isInstance(source)) {
  28324. source = Source.seriesDataToSource(source);
  28325. }
  28326. opt = opt || {};
  28327. sysDims = (sysDims || []).slice();
  28328. var dimsDef = (opt.dimsDef || []).slice();
  28329. var dataDimNameMap = createHashMap();
  28330. var coordDimNameMap = createHashMap();
  28331. // var valueCandidate;
  28332. var result = [];
  28333. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28334. // Apply user defined dims (`name` and `type`) and init result.
  28335. for (var i = 0; i < dimCount; i++) {
  28336. var dimDefItem = dimsDef[i] = extend(
  28337. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28338. );
  28339. var userDimName = dimDefItem.name;
  28340. var resultItem = result[i] = new DataDimensionInfo();
  28341. // Name will be applied later for avoiding duplication.
  28342. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28343. // Only if `series.dimensions` is defined in option
  28344. // displayName, will be set, and dimension will be diplayed vertically in
  28345. // tooltip by default.
  28346. resultItem.name = resultItem.displayName = userDimName;
  28347. dataDimNameMap.set(userDimName, i);
  28348. }
  28349. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28350. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28351. }
  28352. var encodeDef = opt.encodeDef;
  28353. if (!encodeDef && opt.encodeDefaulter) {
  28354. encodeDef = opt.encodeDefaulter(source, dimCount);
  28355. }
  28356. encodeDef = createHashMap(encodeDef);
  28357. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28358. encodeDef.each(function (dataDims, coordDim) {
  28359. dataDims = normalizeToArray(dataDims).slice();
  28360. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28361. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28362. // this case.
  28363. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28364. encodeDef.set(coordDim, false);
  28365. return;
  28366. }
  28367. var validDataDims = encodeDef.set(coordDim, []);
  28368. each$1(dataDims, function (resultDimIdx, idx) {
  28369. // The input resultDimIdx can be dim name or index.
  28370. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28371. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28372. validDataDims[idx] = resultDimIdx;
  28373. applyDim(result[resultDimIdx], coordDim, idx);
  28374. }
  28375. });
  28376. });
  28377. // Apply templetes and default order from `sysDims`.
  28378. var availDimIdx = 0;
  28379. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28380. var coordDim;
  28381. var sysDimItem;
  28382. var sysDimItemDimsDef;
  28383. var sysDimItemOtherDims;
  28384. if (isString(sysDimItem)) {
  28385. coordDim = sysDimItem;
  28386. sysDimItem = {};
  28387. }
  28388. else {
  28389. coordDim = sysDimItem.name;
  28390. var ordinalMeta = sysDimItem.ordinalMeta;
  28391. sysDimItem.ordinalMeta = null;
  28392. sysDimItem = clone(sysDimItem);
  28393. sysDimItem.ordinalMeta = ordinalMeta;
  28394. // `coordDimIndex` should not be set directly.
  28395. sysDimItemDimsDef = sysDimItem.dimsDef;
  28396. sysDimItemOtherDims = sysDimItem.otherDims;
  28397. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28398. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28399. }
  28400. var dataDims = encodeDef.get(coordDim);
  28401. // negative resultDimIdx means no need to mapping.
  28402. if (dataDims === false) {
  28403. return;
  28404. }
  28405. var dataDims = normalizeToArray(dataDims);
  28406. // dimensions provides default dim sequences.
  28407. if (!dataDims.length) {
  28408. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28409. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28410. availDimIdx++;
  28411. }
  28412. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28413. }
  28414. }
  28415. // Apply templates.
  28416. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28417. var resultItem = result[resultDimIdx];
  28418. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28419. if (resultItem.name == null && sysDimItemDimsDef) {
  28420. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28421. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28422. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28423. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28424. }
  28425. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28426. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28427. });
  28428. });
  28429. function applyDim(resultItem, coordDim, coordDimIndex) {
  28430. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28431. resultItem.otherDims[coordDim] = coordDimIndex;
  28432. }
  28433. else {
  28434. resultItem.coordDim = coordDim;
  28435. resultItem.coordDimIndex = coordDimIndex;
  28436. coordDimNameMap.set(coordDim, true);
  28437. }
  28438. }
  28439. // Make sure the first extra dim is 'value'.
  28440. var generateCoord = opt.generateCoord;
  28441. var generateCoordCount = opt.generateCoordCount;
  28442. var fromZero = generateCoordCount != null;
  28443. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28444. var extra = generateCoord || 'value';
  28445. // Set dim `name` and other `coordDim` and other props.
  28446. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28447. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28448. var coordDim = resultItem.coordDim;
  28449. if (coordDim == null) {
  28450. resultItem.coordDim = genName(
  28451. extra, coordDimNameMap, fromZero
  28452. );
  28453. resultItem.coordDimIndex = 0;
  28454. if (!generateCoord || generateCoordCount <= 0) {
  28455. resultItem.isExtraCoord = true;
  28456. }
  28457. generateCoordCount--;
  28458. }
  28459. resultItem.name == null && (resultItem.name = genName(
  28460. resultItem.coordDim,
  28461. dataDimNameMap
  28462. ));
  28463. if (resultItem.type == null
  28464. && (
  28465. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28466. // Consider the case:
  28467. // {
  28468. // dataset: {source: [
  28469. // ['2001', 123],
  28470. // ['2002', 456],
  28471. // ...
  28472. // ['The others', 987],
  28473. // ]},
  28474. // series: {type: 'pie'}
  28475. // }
  28476. // The first colum should better be treated as a "ordinal" although it
  28477. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28478. || (resultItem.isExtraCoord
  28479. && (resultItem.otherDims.itemName != null
  28480. || resultItem.otherDims.seriesName != null
  28481. )
  28482. )
  28483. )
  28484. ) {
  28485. resultItem.type = 'ordinal';
  28486. }
  28487. }
  28488. return result;
  28489. }
  28490. // ??? TODO
  28491. // Originally detect dimCount by data[0]. Should we
  28492. // optimize it to only by sysDims and dimensions and encode.
  28493. // So only necessary dims will be initialized.
  28494. // But
  28495. // (1) custom series should be considered. where other dims
  28496. // may be visited.
  28497. // (2) sometimes user need to calcualte bubble size or use visualMap
  28498. // on other dimensions besides coordSys needed.
  28499. // So, dims that is not used by system, should be shared in storage?
  28500. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28501. // Note that the result dimCount should not small than columns count
  28502. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28503. var dimCount = Math.max(
  28504. source.dimensionsDetectCount || 1,
  28505. sysDims.length,
  28506. dimsDef.length,
  28507. optDimCount || 0
  28508. );
  28509. each$1(sysDims, function (sysDimItem) {
  28510. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28511. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28512. });
  28513. return dimCount;
  28514. }
  28515. function genName(name, map$$1, fromZero) {
  28516. if (fromZero || map$$1.get(name) != null) {
  28517. var i = 0;
  28518. while (map$$1.get(name + i) != null) {
  28519. i++;
  28520. }
  28521. name += i;
  28522. }
  28523. map$$1.set(name, true);
  28524. return name;
  28525. }
  28526. /*
  28527. * Licensed to the Apache Software Foundation (ASF) under one
  28528. * or more contributor license agreements. See the NOTICE file
  28529. * distributed with this work for additional information
  28530. * regarding copyright ownership. The ASF licenses this file
  28531. * to you under the Apache License, Version 2.0 (the
  28532. * "License"); you may not use this file except in compliance
  28533. * with the License. You may obtain a copy of the License at
  28534. *
  28535. * http://www.apache.org/licenses/LICENSE-2.0
  28536. *
  28537. * Unless required by applicable law or agreed to in writing,
  28538. * software distributed under the License is distributed on an
  28539. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28540. * KIND, either express or implied. See the License for the
  28541. * specific language governing permissions and limitations
  28542. * under the License.
  28543. */
  28544. /**
  28545. * Substitute `completeDimensions`.
  28546. * `completeDimensions` is to be deprecated.
  28547. */
  28548. /**
  28549. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28550. * @param {Object|Array} [opt]
  28551. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28552. * @param {number} [opt.dimensionsCount]
  28553. * @param {string} [opt.generateCoord]
  28554. * @param {string} [opt.generateCoordCount]
  28555. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28556. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28557. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28558. * @return {Array.<Object>} dimensionsInfo
  28559. */
  28560. var createDimensions = function (source, opt) {
  28561. opt = opt || {};
  28562. return completeDimensions(opt.coordDimensions || [], source, {
  28563. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28564. encodeDef: opt.encodeDefine || source.encodeDefine,
  28565. dimCount: opt.dimensionsCount,
  28566. encodeDefaulter: opt.encodeDefaulter,
  28567. generateCoord: opt.generateCoord,
  28568. generateCoordCount: opt.generateCoordCount
  28569. });
  28570. };
  28571. /*
  28572. * Licensed to the Apache Software Foundation (ASF) under one
  28573. * or more contributor license agreements. See the NOTICE file
  28574. * distributed with this work for additional information
  28575. * regarding copyright ownership. The ASF licenses this file
  28576. * to you under the Apache License, Version 2.0 (the
  28577. * "License"); you may not use this file except in compliance
  28578. * with the License. You may obtain a copy of the License at
  28579. *
  28580. * http://www.apache.org/licenses/LICENSE-2.0
  28581. *
  28582. * Unless required by applicable law or agreed to in writing,
  28583. * software distributed under the License is distributed on an
  28584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28585. * KIND, either express or implied. See the License for the
  28586. * specific language governing permissions and limitations
  28587. * under the License.
  28588. */
  28589. /**
  28590. * Helper for model references.
  28591. * There are many manners to refer axis/coordSys.
  28592. */
  28593. // TODO
  28594. // merge relevant logic to this file?
  28595. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28596. /**
  28597. * @class
  28598. * For example:
  28599. * {
  28600. * coordSysName: 'cartesian2d',
  28601. * coordSysDims: ['x', 'y', ...],
  28602. * axisMap: HashMap({
  28603. * x: xAxisModel,
  28604. * y: yAxisModel
  28605. * }),
  28606. * categoryAxisMap: HashMap({
  28607. * x: xAxisModel,
  28608. * y: undefined
  28609. * }),
  28610. * // The index of the first category axis in `coordSysDims`.
  28611. * // `null/undefined` means no category axis exists.
  28612. * firstCategoryDimIndex: 1,
  28613. * // To replace user specified encode.
  28614. * }
  28615. */
  28616. function CoordSysInfo(coordSysName) {
  28617. /**
  28618. * @type {string}
  28619. */
  28620. this.coordSysName = coordSysName;
  28621. /**
  28622. * @type {Array.<string>}
  28623. */
  28624. this.coordSysDims = [];
  28625. /**
  28626. * @type {module:zrender/core/util#HashMap}
  28627. */
  28628. this.axisMap = createHashMap();
  28629. /**
  28630. * @type {module:zrender/core/util#HashMap}
  28631. */
  28632. this.categoryAxisMap = createHashMap();
  28633. /**
  28634. * @type {number}
  28635. */
  28636. this.firstCategoryDimIndex = null;
  28637. }
  28638. /**
  28639. * @return {module:model/referHelper#CoordSysInfo}
  28640. */
  28641. function getCoordSysInfoBySeries(seriesModel) {
  28642. var coordSysName = seriesModel.get('coordinateSystem');
  28643. var result = new CoordSysInfo(coordSysName);
  28644. var fetch = fetchers[coordSysName];
  28645. if (fetch) {
  28646. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28647. return result;
  28648. }
  28649. }
  28650. var fetchers = {
  28651. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28652. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28653. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28654. if (__DEV__) {
  28655. if (!xAxisModel) {
  28656. throw new Error('xAxis "' + retrieve(
  28657. seriesModel.get('xAxisIndex'),
  28658. seriesModel.get('xAxisId'),
  28659. 0
  28660. ) + '" not found');
  28661. }
  28662. if (!yAxisModel) {
  28663. throw new Error('yAxis "' + retrieve(
  28664. seriesModel.get('xAxisIndex'),
  28665. seriesModel.get('yAxisId'),
  28666. 0
  28667. ) + '" not found');
  28668. }
  28669. }
  28670. result.coordSysDims = ['x', 'y'];
  28671. axisMap.set('x', xAxisModel);
  28672. axisMap.set('y', yAxisModel);
  28673. if (isCategory(xAxisModel)) {
  28674. categoryAxisMap.set('x', xAxisModel);
  28675. result.firstCategoryDimIndex = 0;
  28676. }
  28677. if (isCategory(yAxisModel)) {
  28678. categoryAxisMap.set('y', yAxisModel);
  28679. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28680. }
  28681. },
  28682. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28683. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28684. if (__DEV__) {
  28685. if (!singleAxisModel) {
  28686. throw new Error('singleAxis should be specified.');
  28687. }
  28688. }
  28689. result.coordSysDims = ['single'];
  28690. axisMap.set('single', singleAxisModel);
  28691. if (isCategory(singleAxisModel)) {
  28692. categoryAxisMap.set('single', singleAxisModel);
  28693. result.firstCategoryDimIndex = 0;
  28694. }
  28695. },
  28696. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28697. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28698. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28699. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28700. if (__DEV__) {
  28701. if (!angleAxisModel) {
  28702. throw new Error('angleAxis option not found');
  28703. }
  28704. if (!radiusAxisModel) {
  28705. throw new Error('radiusAxis option not found');
  28706. }
  28707. }
  28708. result.coordSysDims = ['radius', 'angle'];
  28709. axisMap.set('radius', radiusAxisModel);
  28710. axisMap.set('angle', angleAxisModel);
  28711. if (isCategory(radiusAxisModel)) {
  28712. categoryAxisMap.set('radius', radiusAxisModel);
  28713. result.firstCategoryDimIndex = 0;
  28714. }
  28715. if (isCategory(angleAxisModel)) {
  28716. categoryAxisMap.set('angle', angleAxisModel);
  28717. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28718. }
  28719. },
  28720. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28721. result.coordSysDims = ['lng', 'lat'];
  28722. },
  28723. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28724. var ecModel = seriesModel.ecModel;
  28725. var parallelModel = ecModel.getComponent(
  28726. 'parallel', seriesModel.get('parallelIndex')
  28727. );
  28728. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28729. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28730. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28731. var axisDim = coordSysDims[index];
  28732. axisMap.set(axisDim, axisModel);
  28733. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28734. categoryAxisMap.set(axisDim, axisModel);
  28735. result.firstCategoryDimIndex = index;
  28736. }
  28737. });
  28738. }
  28739. };
  28740. function isCategory(axisModel) {
  28741. return axisModel.get('type') === 'category';
  28742. }
  28743. /*
  28744. * Licensed to the Apache Software Foundation (ASF) under one
  28745. * or more contributor license agreements. See the NOTICE file
  28746. * distributed with this work for additional information
  28747. * regarding copyright ownership. The ASF licenses this file
  28748. * to you under the Apache License, Version 2.0 (the
  28749. * "License"); you may not use this file except in compliance
  28750. * with the License. You may obtain a copy of the License at
  28751. *
  28752. * http://www.apache.org/licenses/LICENSE-2.0
  28753. *
  28754. * Unless required by applicable law or agreed to in writing,
  28755. * software distributed under the License is distributed on an
  28756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28757. * KIND, either express or implied. See the License for the
  28758. * specific language governing permissions and limitations
  28759. * under the License.
  28760. */
  28761. /**
  28762. * Note that it is too complicated to support 3d stack by value
  28763. * (have to create two-dimension inverted index), so in 3d case
  28764. * we just support that stacked by index.
  28765. *
  28766. * @param {module:echarts/model/Series} seriesModel
  28767. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28768. * The input dimensionInfoList will be modified.
  28769. * @param {Object} [opt]
  28770. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28771. * @param {boolean} [opt.byIndex=false]
  28772. * @return {Object} calculationInfo
  28773. * {
  28774. * stackedDimension: string
  28775. * stackedByDimension: string
  28776. * isStackedByIndex: boolean
  28777. * stackedOverDimension: string
  28778. * stackResultDimension: string
  28779. * }
  28780. */
  28781. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28782. opt = opt || {};
  28783. var byIndex = opt.byIndex;
  28784. var stackedCoordDimension = opt.stackedCoordDimension;
  28785. // Compatibal: when `stack` is set as '', do not stack.
  28786. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28787. var stackedByDimInfo;
  28788. var stackedDimInfo;
  28789. var stackResultDimension;
  28790. var stackedOverDimension;
  28791. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28792. if (isString(dimensionInfo)) {
  28793. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28794. }
  28795. if (mayStack && !dimensionInfo.isExtraCoord) {
  28796. // Find the first ordinal dimension as the stackedByDimInfo.
  28797. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28798. stackedByDimInfo = dimensionInfo;
  28799. }
  28800. // Find the first stackable dimension as the stackedDimInfo.
  28801. if (!stackedDimInfo
  28802. && dimensionInfo.type !== 'ordinal'
  28803. && dimensionInfo.type !== 'time'
  28804. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28805. ) {
  28806. stackedDimInfo = dimensionInfo;
  28807. }
  28808. }
  28809. });
  28810. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28811. // Compatible with previous design, value axis (time axis) only stack by index.
  28812. // It may make sense if the user provides elaborately constructed data.
  28813. byIndex = true;
  28814. }
  28815. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28816. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28817. // might not be a good way.
  28818. if (stackedDimInfo) {
  28819. // Use a weird name that not duplicated with other names.
  28820. stackResultDimension = '__\0ecstackresult';
  28821. stackedOverDimension = '__\0ecstackedover';
  28822. // Create inverted index to fast query index by value.
  28823. if (stackedByDimInfo) {
  28824. stackedByDimInfo.createInvertedIndices = true;
  28825. }
  28826. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28827. var stackedDimType = stackedDimInfo.type;
  28828. var stackedDimCoordIndex = 0;
  28829. each$1(dimensionInfoList, function (dimensionInfo) {
  28830. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28831. stackedDimCoordIndex++;
  28832. }
  28833. });
  28834. dimensionInfoList.push({
  28835. name: stackResultDimension,
  28836. coordDim: stackedDimCoordDim,
  28837. coordDimIndex: stackedDimCoordIndex,
  28838. type: stackedDimType,
  28839. isExtraCoord: true,
  28840. isCalculationCoord: true
  28841. });
  28842. stackedDimCoordIndex++;
  28843. dimensionInfoList.push({
  28844. name: stackedOverDimension,
  28845. // This dimension contains stack base (generally, 0), so do not set it as
  28846. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28847. coordDim: stackedOverDimension,
  28848. coordDimIndex: stackedDimCoordIndex,
  28849. type: stackedDimType,
  28850. isExtraCoord: true,
  28851. isCalculationCoord: true
  28852. });
  28853. }
  28854. return {
  28855. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28856. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28857. isStackedByIndex: byIndex,
  28858. stackedOverDimension: stackedOverDimension,
  28859. stackResultDimension: stackResultDimension
  28860. };
  28861. }
  28862. /**
  28863. * @param {module:echarts/data/List} data
  28864. * @param {string} stackedDim
  28865. */
  28866. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28867. // Each single series only maps to one pair of axis. So we do not need to
  28868. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28869. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28870. // && (
  28871. // stackedByDim != null
  28872. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28873. // : data.getCalculationInfo('isStackedByIndex')
  28874. // );
  28875. }
  28876. /**
  28877. * @param {module:echarts/data/List} data
  28878. * @param {string} targetDim
  28879. * @param {string} [stackedByDim] If not input this parameter, check whether
  28880. * stacked by index.
  28881. * @return {string} dimension
  28882. */
  28883. function getStackedDimension(data, targetDim) {
  28884. return isDimensionStacked(data, targetDim)
  28885. ? data.getCalculationInfo('stackResultDimension')
  28886. : targetDim;
  28887. }
  28888. /*
  28889. * Licensed to the Apache Software Foundation (ASF) under one
  28890. * or more contributor license agreements. See the NOTICE file
  28891. * distributed with this work for additional information
  28892. * regarding copyright ownership. The ASF licenses this file
  28893. * to you under the Apache License, Version 2.0 (the
  28894. * "License"); you may not use this file except in compliance
  28895. * with the License. You may obtain a copy of the License at
  28896. *
  28897. * http://www.apache.org/licenses/LICENSE-2.0
  28898. *
  28899. * Unless required by applicable law or agreed to in writing,
  28900. * software distributed under the License is distributed on an
  28901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28902. * KIND, either express or implied. See the License for the
  28903. * specific language governing permissions and limitations
  28904. * under the License.
  28905. */
  28906. /**
  28907. * @param {module:echarts/data/Source|Array} source Or raw data.
  28908. * @param {module:echarts/model/Series} seriesModel
  28909. * @param {Object} [opt]
  28910. * @param {string} [opt.generateCoord]
  28911. * @param {boolean} [opt.useEncodeDefaulter]
  28912. */
  28913. function createListFromArray(source, seriesModel, opt) {
  28914. opt = opt || {};
  28915. if (!Source.isInstance(source)) {
  28916. source = Source.seriesDataToSource(source);
  28917. }
  28918. var coordSysName = seriesModel.get('coordinateSystem');
  28919. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28920. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28921. var coordSysDimDefs;
  28922. if (coordSysInfo) {
  28923. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28924. var dimInfo = {name: dim};
  28925. var axisModel = coordSysInfo.axisMap.get(dim);
  28926. if (axisModel) {
  28927. var axisType = axisModel.get('type');
  28928. dimInfo.type = getDimensionTypeByAxis(axisType);
  28929. // dimInfo.stackable = isStackable(axisType);
  28930. }
  28931. return dimInfo;
  28932. });
  28933. }
  28934. if (!coordSysDimDefs) {
  28935. // Get dimensions from registered coordinate system
  28936. coordSysDimDefs = (registeredCoordSys && (
  28937. registeredCoordSys.getDimensionsInfo
  28938. ? registeredCoordSys.getDimensionsInfo()
  28939. : registeredCoordSys.dimensions.slice()
  28940. )) || ['x', 'y'];
  28941. }
  28942. var dimInfoList = createDimensions(source, {
  28943. coordDimensions: coordSysDimDefs,
  28944. generateCoord: opt.generateCoord,
  28945. encodeDefaulter: opt.useEncodeDefaulter
  28946. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28947. : null
  28948. });
  28949. var firstCategoryDimIndex;
  28950. var hasNameEncode;
  28951. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  28952. var coordDim = dimInfo.coordDim;
  28953. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28954. if (categoryAxisModel) {
  28955. if (firstCategoryDimIndex == null) {
  28956. firstCategoryDimIndex = dimIndex;
  28957. }
  28958. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28959. }
  28960. if (dimInfo.otherDims.itemName != null) {
  28961. hasNameEncode = true;
  28962. }
  28963. });
  28964. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28965. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28966. }
  28967. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28968. var list = new List(dimInfoList, seriesModel);
  28969. list.setCalculationInfo(stackCalculationInfo);
  28970. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  28971. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28972. // Use dataIndex as ordinal value in categoryAxis
  28973. return dimIndex === firstCategoryDimIndex
  28974. ? dataIndex
  28975. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28976. }
  28977. : null;
  28978. list.hasItemOption = false;
  28979. list.initData(source, null, dimValueGetter);
  28980. return list;
  28981. }
  28982. function isNeedCompleteOrdinalData(source) {
  28983. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28984. var sampleItem = firstDataNotNull(source.data || []);
  28985. return sampleItem != null
  28986. && !isArray(getDataItemValue(sampleItem));
  28987. }
  28988. }
  28989. function firstDataNotNull(data) {
  28990. var i = 0;
  28991. while (i < data.length && data[i] == null) {
  28992. i++;
  28993. }
  28994. return data[i];
  28995. }
  28996. /*
  28997. * Licensed to the Apache Software Foundation (ASF) under one
  28998. * or more contributor license agreements. See the NOTICE file
  28999. * distributed with this work for additional information
  29000. * regarding copyright ownership. The ASF licenses this file
  29001. * to you under the Apache License, Version 2.0 (the
  29002. * "License"); you may not use this file except in compliance
  29003. * with the License. You may obtain a copy of the License at
  29004. *
  29005. * http://www.apache.org/licenses/LICENSE-2.0
  29006. *
  29007. * Unless required by applicable law or agreed to in writing,
  29008. * software distributed under the License is distributed on an
  29009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29010. * KIND, either express or implied. See the License for the
  29011. * specific language governing permissions and limitations
  29012. * under the License.
  29013. */
  29014. /**
  29015. * // Scale class management
  29016. * @module echarts/scale/Scale
  29017. */
  29018. /**
  29019. * @param {Object} [setting]
  29020. */
  29021. function Scale(setting) {
  29022. this._setting = setting || {};
  29023. /**
  29024. * Extent
  29025. * @type {Array.<number>}
  29026. * @protected
  29027. */
  29028. this._extent = [Infinity, -Infinity];
  29029. /**
  29030. * Step is calculated in adjustExtent
  29031. * @type {Array.<number>}
  29032. * @protected
  29033. */
  29034. this._interval = 0;
  29035. this.init && this.init.apply(this, arguments);
  29036. }
  29037. /**
  29038. * Parse input val to valid inner number.
  29039. * @param {*} val
  29040. * @return {number}
  29041. */
  29042. Scale.prototype.parse = function (val) {
  29043. // Notice: This would be a trap here, If the implementation
  29044. // of this method depends on extent, and this method is used
  29045. // before extent set (like in dataZoom), it would be wrong.
  29046. // Nevertheless, parse does not depend on extent generally.
  29047. return val;
  29048. };
  29049. Scale.prototype.getSetting = function (name) {
  29050. return this._setting[name];
  29051. };
  29052. Scale.prototype.contain = function (val) {
  29053. var extent = this._extent;
  29054. return val >= extent[0] && val <= extent[1];
  29055. };
  29056. /**
  29057. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29058. * @param {number} val
  29059. * @return {number}
  29060. */
  29061. Scale.prototype.normalize = function (val) {
  29062. var extent = this._extent;
  29063. if (extent[1] === extent[0]) {
  29064. return 0.5;
  29065. }
  29066. return (val - extent[0]) / (extent[1] - extent[0]);
  29067. };
  29068. /**
  29069. * Scale normalized value
  29070. * @param {number} val
  29071. * @return {number}
  29072. */
  29073. Scale.prototype.scale = function (val) {
  29074. var extent = this._extent;
  29075. return val * (extent[1] - extent[0]) + extent[0];
  29076. };
  29077. /**
  29078. * Set extent from data
  29079. * @param {Array.<number>} other
  29080. */
  29081. Scale.prototype.unionExtent = function (other) {
  29082. var extent = this._extent;
  29083. other[0] < extent[0] && (extent[0] = other[0]);
  29084. other[1] > extent[1] && (extent[1] = other[1]);
  29085. // not setExtent because in log axis it may transformed to power
  29086. // this.setExtent(extent[0], extent[1]);
  29087. };
  29088. /**
  29089. * Set extent from data
  29090. * @param {module:echarts/data/List} data
  29091. * @param {string} dim
  29092. */
  29093. Scale.prototype.unionExtentFromData = function (data, dim) {
  29094. this.unionExtent(data.getApproximateExtent(dim));
  29095. };
  29096. /**
  29097. * Get extent
  29098. * @return {Array.<number>}
  29099. */
  29100. Scale.prototype.getExtent = function () {
  29101. return this._extent.slice();
  29102. };
  29103. /**
  29104. * Set extent
  29105. * @param {number} start
  29106. * @param {number} end
  29107. */
  29108. Scale.prototype.setExtent = function (start, end) {
  29109. var thisExtent = this._extent;
  29110. if (!isNaN(start)) {
  29111. thisExtent[0] = start;
  29112. }
  29113. if (!isNaN(end)) {
  29114. thisExtent[1] = end;
  29115. }
  29116. };
  29117. /**
  29118. * When axis extent depends on data and no data exists,
  29119. * axis ticks should not be drawn, which is named 'blank'.
  29120. */
  29121. Scale.prototype.isBlank = function () {
  29122. return this._isBlank;
  29123. },
  29124. /**
  29125. * When axis extent depends on data and no data exists,
  29126. * axis ticks should not be drawn, which is named 'blank'.
  29127. */
  29128. Scale.prototype.setBlank = function (isBlank) {
  29129. this._isBlank = isBlank;
  29130. };
  29131. /**
  29132. * @abstract
  29133. * @param {*} tick
  29134. * @return {string} label of the tick.
  29135. */
  29136. Scale.prototype.getLabel = null;
  29137. enableClassExtend(Scale);
  29138. enableClassManagement(Scale, {
  29139. registerWhenExtend: true
  29140. });
  29141. /*
  29142. * Licensed to the Apache Software Foundation (ASF) under one
  29143. * or more contributor license agreements. See the NOTICE file
  29144. * distributed with this work for additional information
  29145. * regarding copyright ownership. The ASF licenses this file
  29146. * to you under the Apache License, Version 2.0 (the
  29147. * "License"); you may not use this file except in compliance
  29148. * with the License. You may obtain a copy of the License at
  29149. *
  29150. * http://www.apache.org/licenses/LICENSE-2.0
  29151. *
  29152. * Unless required by applicable law or agreed to in writing,
  29153. * software distributed under the License is distributed on an
  29154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29155. * KIND, either express or implied. See the License for the
  29156. * specific language governing permissions and limitations
  29157. * under the License.
  29158. */
  29159. /**
  29160. * @constructor
  29161. * @param {Object} [opt]
  29162. * @param {Object} [opt.categories=[]]
  29163. * @param {Object} [opt.needCollect=false]
  29164. * @param {Object} [opt.deduplication=false]
  29165. */
  29166. function OrdinalMeta(opt) {
  29167. /**
  29168. * @readOnly
  29169. * @type {Array.<string>}
  29170. */
  29171. this.categories = opt.categories || [];
  29172. /**
  29173. * @private
  29174. * @type {boolean}
  29175. */
  29176. this._needCollect = opt.needCollect;
  29177. /**
  29178. * @private
  29179. * @type {boolean}
  29180. */
  29181. this._deduplication = opt.deduplication;
  29182. /**
  29183. * @private
  29184. * @type {boolean}
  29185. */
  29186. this._map;
  29187. }
  29188. /**
  29189. * @param {module:echarts/model/Model} axisModel
  29190. * @return {module:echarts/data/OrdinalMeta}
  29191. */
  29192. OrdinalMeta.createByAxisModel = function (axisModel) {
  29193. var option = axisModel.option;
  29194. var data = option.data;
  29195. var categories = data && map(data, getName);
  29196. return new OrdinalMeta({
  29197. categories: categories,
  29198. needCollect: !categories,
  29199. // deduplication is default in axis.
  29200. deduplication: option.dedplication !== false
  29201. });
  29202. };
  29203. var proto$1 = OrdinalMeta.prototype;
  29204. /**
  29205. * @param {string} category
  29206. * @return {number} ordinal
  29207. */
  29208. proto$1.getOrdinal = function (category) {
  29209. return getOrCreateMap(this).get(category);
  29210. };
  29211. /**
  29212. * @param {*} category
  29213. * @return {number} The ordinal. If not found, return NaN.
  29214. */
  29215. proto$1.parseAndCollect = function (category) {
  29216. var index;
  29217. var needCollect = this._needCollect;
  29218. // The value of category dim can be the index of the given category set.
  29219. // This feature is only supported when !needCollect, because we should
  29220. // consider a common case: a value is 2017, which is a number but is
  29221. // expected to be tread as a category. This case usually happen in dataset,
  29222. // where it happent to be no need of the index feature.
  29223. if (typeof category !== 'string' && !needCollect) {
  29224. return category;
  29225. }
  29226. // Optimize for the scenario:
  29227. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29228. // data has been ensured not duplicate and is large data.
  29229. // Notice, if a dataset dimension provide categroies, usually echarts
  29230. // should remove duplication except user tell echarts dont do that
  29231. // (set axis.deduplication = false), because echarts do not know whether
  29232. // the values in the category dimension has duplication (consider the
  29233. // parallel-aqi example)
  29234. if (needCollect && !this._deduplication) {
  29235. index = this.categories.length;
  29236. this.categories[index] = category;
  29237. return index;
  29238. }
  29239. var map$$1 = getOrCreateMap(this);
  29240. index = map$$1.get(category);
  29241. if (index == null) {
  29242. if (needCollect) {
  29243. index = this.categories.length;
  29244. this.categories[index] = category;
  29245. map$$1.set(category, index);
  29246. }
  29247. else {
  29248. index = NaN;
  29249. }
  29250. }
  29251. return index;
  29252. };
  29253. // Consider big data, do not create map until needed.
  29254. function getOrCreateMap(ordinalMeta) {
  29255. return ordinalMeta._map || (
  29256. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29257. );
  29258. }
  29259. function getName(obj) {
  29260. if (isObject$1(obj) && obj.value != null) {
  29261. return obj.value;
  29262. }
  29263. else {
  29264. return obj + '';
  29265. }
  29266. }
  29267. /*
  29268. * Licensed to the Apache Software Foundation (ASF) under one
  29269. * or more contributor license agreements. See the NOTICE file
  29270. * distributed with this work for additional information
  29271. * regarding copyright ownership. The ASF licenses this file
  29272. * to you under the Apache License, Version 2.0 (the
  29273. * "License"); you may not use this file except in compliance
  29274. * with the License. You may obtain a copy of the License at
  29275. *
  29276. * http://www.apache.org/licenses/LICENSE-2.0
  29277. *
  29278. * Unless required by applicable law or agreed to in writing,
  29279. * software distributed under the License is distributed on an
  29280. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29281. * KIND, either express or implied. See the License for the
  29282. * specific language governing permissions and limitations
  29283. * under the License.
  29284. */
  29285. /**
  29286. * Linear continuous scale
  29287. * @module echarts/coord/scale/Ordinal
  29288. *
  29289. * http://en.wikipedia.org/wiki/Level_of_measurement
  29290. */
  29291. // FIXME only one data
  29292. var scaleProto = Scale.prototype;
  29293. var OrdinalScale = Scale.extend({
  29294. type: 'ordinal',
  29295. /**
  29296. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29297. */
  29298. init: function (ordinalMeta, extent) {
  29299. // Caution: Should not use instanceof, consider ec-extensions using
  29300. // import approach to get OrdinalMeta class.
  29301. if (!ordinalMeta || isArray(ordinalMeta)) {
  29302. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29303. }
  29304. this._ordinalMeta = ordinalMeta;
  29305. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29306. },
  29307. parse: function (val) {
  29308. return typeof val === 'string'
  29309. ? this._ordinalMeta.getOrdinal(val)
  29310. // val might be float.
  29311. : Math.round(val);
  29312. },
  29313. contain: function (rank) {
  29314. rank = this.parse(rank);
  29315. return scaleProto.contain.call(this, rank)
  29316. && this._ordinalMeta.categories[rank] != null;
  29317. },
  29318. /**
  29319. * Normalize given rank or name to linear [0, 1]
  29320. * @param {number|string} [val]
  29321. * @return {number}
  29322. */
  29323. normalize: function (val) {
  29324. return scaleProto.normalize.call(this, this.parse(val));
  29325. },
  29326. scale: function (val) {
  29327. return Math.round(scaleProto.scale.call(this, val));
  29328. },
  29329. /**
  29330. * @return {Array}
  29331. */
  29332. getTicks: function () {
  29333. var ticks = [];
  29334. var extent = this._extent;
  29335. var rank = extent[0];
  29336. while (rank <= extent[1]) {
  29337. ticks.push(rank);
  29338. rank++;
  29339. }
  29340. return ticks;
  29341. },
  29342. /**
  29343. * Get item on rank n
  29344. * @param {number} n
  29345. * @return {string}
  29346. */
  29347. getLabel: function (n) {
  29348. if (!this.isBlank()) {
  29349. // Note that if no data, ordinalMeta.categories is an empty array.
  29350. return this._ordinalMeta.categories[n];
  29351. }
  29352. },
  29353. /**
  29354. * @return {number}
  29355. */
  29356. count: function () {
  29357. return this._extent[1] - this._extent[0] + 1;
  29358. },
  29359. /**
  29360. * @override
  29361. */
  29362. unionExtentFromData: function (data, dim) {
  29363. this.unionExtent(data.getApproximateExtent(dim));
  29364. },
  29365. getOrdinalMeta: function () {
  29366. return this._ordinalMeta;
  29367. },
  29368. niceTicks: noop,
  29369. niceExtent: noop
  29370. });
  29371. /**
  29372. * @return {module:echarts/scale/Time}
  29373. */
  29374. OrdinalScale.create = function () {
  29375. return new OrdinalScale();
  29376. };
  29377. /*
  29378. * Licensed to the Apache Software Foundation (ASF) under one
  29379. * or more contributor license agreements. See the NOTICE file
  29380. * distributed with this work for additional information
  29381. * regarding copyright ownership. The ASF licenses this file
  29382. * to you under the Apache License, Version 2.0 (the
  29383. * "License"); you may not use this file except in compliance
  29384. * with the License. You may obtain a copy of the License at
  29385. *
  29386. * http://www.apache.org/licenses/LICENSE-2.0
  29387. *
  29388. * Unless required by applicable law or agreed to in writing,
  29389. * software distributed under the License is distributed on an
  29390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29391. * KIND, either express or implied. See the License for the
  29392. * specific language governing permissions and limitations
  29393. * under the License.
  29394. */
  29395. /**
  29396. * For testable.
  29397. */
  29398. var roundNumber$1 = round$1;
  29399. /**
  29400. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29401. * Should be extent[0] < extent[1].
  29402. * @param {number} splitNumber splitNumber should be >= 1.
  29403. * @param {number} [minInterval]
  29404. * @param {number} [maxInterval]
  29405. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29406. */
  29407. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29408. var result = {};
  29409. var span = extent[1] - extent[0];
  29410. var interval = result.interval = nice(span / splitNumber, true);
  29411. if (minInterval != null && interval < minInterval) {
  29412. interval = result.interval = minInterval;
  29413. }
  29414. if (maxInterval != null && interval > maxInterval) {
  29415. interval = result.interval = maxInterval;
  29416. }
  29417. // Tow more digital for tick.
  29418. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29419. // Niced extent inside original extent
  29420. var niceTickExtent = result.niceTickExtent = [
  29421. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29422. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29423. ];
  29424. fixExtent(niceTickExtent, extent);
  29425. return result;
  29426. }
  29427. /**
  29428. * @param {number} interval
  29429. * @return {number} interval precision
  29430. */
  29431. function getIntervalPrecision(interval) {
  29432. // Tow more digital for tick.
  29433. return getPrecisionSafe(interval) + 2;
  29434. }
  29435. function clamp(niceTickExtent, idx, extent) {
  29436. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29437. }
  29438. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29439. function fixExtent(niceTickExtent, extent) {
  29440. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29441. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29442. clamp(niceTickExtent, 0, extent);
  29443. clamp(niceTickExtent, 1, extent);
  29444. if (niceTickExtent[0] > niceTickExtent[1]) {
  29445. niceTickExtent[0] = niceTickExtent[1];
  29446. }
  29447. }
  29448. /*
  29449. * Licensed to the Apache Software Foundation (ASF) under one
  29450. * or more contributor license agreements. See the NOTICE file
  29451. * distributed with this work for additional information
  29452. * regarding copyright ownership. The ASF licenses this file
  29453. * to you under the Apache License, Version 2.0 (the
  29454. * "License"); you may not use this file except in compliance
  29455. * with the License. You may obtain a copy of the License at
  29456. *
  29457. * http://www.apache.org/licenses/LICENSE-2.0
  29458. *
  29459. * Unless required by applicable law or agreed to in writing,
  29460. * software distributed under the License is distributed on an
  29461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29462. * KIND, either express or implied. See the License for the
  29463. * specific language governing permissions and limitations
  29464. * under the License.
  29465. */
  29466. /**
  29467. * Interval scale
  29468. * @module echarts/scale/Interval
  29469. */
  29470. var roundNumber = round$1;
  29471. /**
  29472. * @alias module:echarts/coord/scale/Interval
  29473. * @constructor
  29474. */
  29475. var IntervalScale = Scale.extend({
  29476. type: 'interval',
  29477. _interval: 0,
  29478. _intervalPrecision: 2,
  29479. setExtent: function (start, end) {
  29480. var thisExtent = this._extent;
  29481. //start,end may be a Number like '25',so...
  29482. if (!isNaN(start)) {
  29483. thisExtent[0] = parseFloat(start);
  29484. }
  29485. if (!isNaN(end)) {
  29486. thisExtent[1] = parseFloat(end);
  29487. }
  29488. },
  29489. unionExtent: function (other) {
  29490. var extent = this._extent;
  29491. other[0] < extent[0] && (extent[0] = other[0]);
  29492. other[1] > extent[1] && (extent[1] = other[1]);
  29493. // unionExtent may called by it's sub classes
  29494. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29495. },
  29496. /**
  29497. * Get interval
  29498. */
  29499. getInterval: function () {
  29500. return this._interval;
  29501. },
  29502. /**
  29503. * Set interval
  29504. */
  29505. setInterval: function (interval) {
  29506. this._interval = interval;
  29507. // Dropped auto calculated niceExtent and use user setted extent
  29508. // We assume user wan't to set both interval, min, max to get a better result
  29509. this._niceExtent = this._extent.slice();
  29510. this._intervalPrecision = getIntervalPrecision(interval);
  29511. },
  29512. /**
  29513. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29514. * @return {Array.<number>}
  29515. */
  29516. getTicks: function (expandToNicedExtent) {
  29517. var interval = this._interval;
  29518. var extent = this._extent;
  29519. var niceTickExtent = this._niceExtent;
  29520. var intervalPrecision = this._intervalPrecision;
  29521. var ticks = [];
  29522. // If interval is 0, return [];
  29523. if (!interval) {
  29524. return ticks;
  29525. }
  29526. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29527. var safeLimit = 10000;
  29528. if (extent[0] < niceTickExtent[0]) {
  29529. if (expandToNicedExtent) {
  29530. ticks.push(roundNumber(niceTickExtent[0] - interval));
  29531. }
  29532. else {
  29533. ticks.push(extent[0]);
  29534. }
  29535. }
  29536. var tick = niceTickExtent[0];
  29537. while (tick <= niceTickExtent[1]) {
  29538. ticks.push(tick);
  29539. // Avoid rounding error
  29540. tick = roundNumber(tick + interval, intervalPrecision);
  29541. if (tick === ticks[ticks.length - 1]) {
  29542. // Consider out of safe float point, e.g.,
  29543. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29544. break;
  29545. }
  29546. if (ticks.length > safeLimit) {
  29547. return [];
  29548. }
  29549. }
  29550. // Consider this case: the last item of ticks is smaller
  29551. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29552. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29553. if (extent[1] > lastNiceTick) {
  29554. if (expandToNicedExtent) {
  29555. ticks.push(lastNiceTick + interval);
  29556. }
  29557. else {
  29558. ticks.push(extent[1]);
  29559. }
  29560. }
  29561. return ticks;
  29562. },
  29563. /**
  29564. * @param {number} [splitNumber=5]
  29565. * @return {Array.<Array.<number>>}
  29566. */
  29567. getMinorTicks: function (splitNumber) {
  29568. var ticks = this.getTicks(true);
  29569. var minorTicks = [];
  29570. var extent = this.getExtent();
  29571. for (var i = 1; i < ticks.length; i++) {
  29572. var nextTick = ticks[i];
  29573. var prevTick = ticks[i - 1];
  29574. var count = 0;
  29575. var minorTicksGroup = [];
  29576. var interval = nextTick - prevTick;
  29577. var minorInterval = interval / splitNumber;
  29578. while (count < splitNumber - 1) {
  29579. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29580. // For the first and last interval. The count may be less than splitNumber.
  29581. if (minorTick > extent[0] && minorTick < extent[1]) {
  29582. minorTicksGroup.push(minorTick);
  29583. }
  29584. count++;
  29585. }
  29586. minorTicks.push(minorTicksGroup);
  29587. }
  29588. return minorTicks;
  29589. },
  29590. /**
  29591. * @param {number} data
  29592. * @param {Object} [opt]
  29593. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29594. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29595. * @return {string}
  29596. */
  29597. getLabel: function (data, opt) {
  29598. if (data == null) {
  29599. return '';
  29600. }
  29601. var precision = opt && opt.precision;
  29602. if (precision == null) {
  29603. precision = getPrecisionSafe(data) || 0;
  29604. }
  29605. else if (precision === 'auto') {
  29606. // Should be more precise then tick.
  29607. precision = this._intervalPrecision;
  29608. }
  29609. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29610. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29611. data = roundNumber(data, precision, true);
  29612. return addCommas(data);
  29613. },
  29614. /**
  29615. * Update interval and extent of intervals for nice ticks
  29616. *
  29617. * @param {number} [splitNumber = 5] Desired number of ticks
  29618. * @param {number} [minInterval]
  29619. * @param {number} [maxInterval]
  29620. */
  29621. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29622. splitNumber = splitNumber || 5;
  29623. var extent = this._extent;
  29624. var span = extent[1] - extent[0];
  29625. if (!isFinite(span)) {
  29626. return;
  29627. }
  29628. // User may set axis min 0 and data are all negative
  29629. // FIXME If it needs to reverse ?
  29630. if (span < 0) {
  29631. span = -span;
  29632. extent.reverse();
  29633. }
  29634. var result = intervalScaleNiceTicks(
  29635. extent, splitNumber, minInterval, maxInterval
  29636. );
  29637. this._intervalPrecision = result.intervalPrecision;
  29638. this._interval = result.interval;
  29639. this._niceExtent = result.niceTickExtent;
  29640. },
  29641. /**
  29642. * Nice extent.
  29643. * @param {Object} opt
  29644. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29645. * @param {boolean} [opt.fixMin=false]
  29646. * @param {boolean} [opt.fixMax=false]
  29647. * @param {boolean} [opt.minInterval]
  29648. * @param {boolean} [opt.maxInterval]
  29649. */
  29650. niceExtent: function (opt) {
  29651. var extent = this._extent;
  29652. // If extent start and end are same, expand them
  29653. if (extent[0] === extent[1]) {
  29654. if (extent[0] !== 0) {
  29655. // Expand extent
  29656. var expandSize = extent[0];
  29657. // In the fowllowing case
  29658. // Axis has been fixed max 100
  29659. // Plus data are all 100 and axis extent are [100, 100].
  29660. // Extend to the both side will cause expanded max is larger than fixed max.
  29661. // So only expand to the smaller side.
  29662. if (!opt.fixMax) {
  29663. extent[1] += expandSize / 2;
  29664. extent[0] -= expandSize / 2;
  29665. }
  29666. else {
  29667. extent[0] -= expandSize / 2;
  29668. }
  29669. }
  29670. else {
  29671. extent[1] = 1;
  29672. }
  29673. }
  29674. var span = extent[1] - extent[0];
  29675. // If there are no data and extent are [Infinity, -Infinity]
  29676. if (!isFinite(span)) {
  29677. extent[0] = 0;
  29678. extent[1] = 1;
  29679. }
  29680. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29681. // var extent = this._extent;
  29682. var interval = this._interval;
  29683. if (!opt.fixMin) {
  29684. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29685. }
  29686. if (!opt.fixMax) {
  29687. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29688. }
  29689. }
  29690. });
  29691. /**
  29692. * @return {module:echarts/scale/Time}
  29693. */
  29694. IntervalScale.create = function () {
  29695. return new IntervalScale();
  29696. };
  29697. /*
  29698. * Licensed to the Apache Software Foundation (ASF) under one
  29699. * or more contributor license agreements. See the NOTICE file
  29700. * distributed with this work for additional information
  29701. * regarding copyright ownership. The ASF licenses this file
  29702. * to you under the Apache License, Version 2.0 (the
  29703. * "License"); you may not use this file except in compliance
  29704. * with the License. You may obtain a copy of the License at
  29705. *
  29706. * http://www.apache.org/licenses/LICENSE-2.0
  29707. *
  29708. * Unless required by applicable law or agreed to in writing,
  29709. * software distributed under the License is distributed on an
  29710. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29711. * KIND, either express or implied. See the License for the
  29712. * specific language governing permissions and limitations
  29713. * under the License.
  29714. */
  29715. /* global Float32Array */
  29716. var STACK_PREFIX = '__ec_stack_';
  29717. var LARGE_BAR_MIN_WIDTH = 0.5;
  29718. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29719. function getSeriesStackId(seriesModel) {
  29720. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29721. }
  29722. function getAxisKey(axis) {
  29723. return axis.dim + axis.index;
  29724. }
  29725. /**
  29726. * @param {Object} opt
  29727. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29728. * @param {number} opt.count Positive interger.
  29729. * @param {number} [opt.barWidth]
  29730. * @param {number} [opt.barMaxWidth]
  29731. * @param {number} [opt.barMinWidth]
  29732. * @param {number} [opt.barGap]
  29733. * @param {number} [opt.barCategoryGap]
  29734. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29735. */
  29736. function prepareLayoutBarSeries(seriesType, ecModel) {
  29737. var seriesModels = [];
  29738. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29739. // Check series coordinate, do layout for cartesian2d only
  29740. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29741. seriesModels.push(seriesModel);
  29742. }
  29743. });
  29744. return seriesModels;
  29745. }
  29746. /**
  29747. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29748. * values.
  29749. * This works for time axes, value axes, and log axes.
  29750. * For a single time axis, return value is in the form like
  29751. * {'x_0': [1000000]}.
  29752. * The value of 1000000 is in milliseconds.
  29753. */
  29754. function getValueAxesMinGaps(barSeries) {
  29755. /**
  29756. * Map from axis.index to values.
  29757. * For a single time axis, axisValues is in the form like
  29758. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29759. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29760. * series.
  29761. */
  29762. var axisValues = {};
  29763. each$1(barSeries, function (seriesModel) {
  29764. var cartesian = seriesModel.coordinateSystem;
  29765. var baseAxis = cartesian.getBaseAxis();
  29766. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29767. return;
  29768. }
  29769. var data = seriesModel.getData();
  29770. var key = baseAxis.dim + '_' + baseAxis.index;
  29771. var dim = data.mapDimension(baseAxis.dim);
  29772. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29773. var value = data.get(dim, i);
  29774. if (!axisValues[key]) {
  29775. // No previous data for the axis
  29776. axisValues[key] = [value];
  29777. }
  29778. else {
  29779. // No value in previous series
  29780. axisValues[key].push(value);
  29781. }
  29782. // Ignore duplicated time values in the same axis
  29783. }
  29784. });
  29785. var axisMinGaps = [];
  29786. for (var key in axisValues) {
  29787. if (axisValues.hasOwnProperty(key)) {
  29788. var valuesInAxis = axisValues[key];
  29789. if (valuesInAxis) {
  29790. // Sort axis values into ascending order to calculate gaps
  29791. valuesInAxis.sort(function (a, b) {
  29792. return a - b;
  29793. });
  29794. var min = null;
  29795. for (var j = 1; j < valuesInAxis.length; ++j) {
  29796. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29797. if (delta > 0) {
  29798. // Ignore 0 delta because they are of the same axis value
  29799. min = min === null ? delta : Math.min(min, delta);
  29800. }
  29801. }
  29802. // Set to null if only have one data
  29803. axisMinGaps[key] = min;
  29804. }
  29805. }
  29806. }
  29807. return axisMinGaps;
  29808. }
  29809. function makeColumnLayout(barSeries) {
  29810. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29811. var seriesInfoList = [];
  29812. each$1(barSeries, function (seriesModel) {
  29813. var cartesian = seriesModel.coordinateSystem;
  29814. var baseAxis = cartesian.getBaseAxis();
  29815. var axisExtent = baseAxis.getExtent();
  29816. var bandWidth;
  29817. if (baseAxis.type === 'category') {
  29818. bandWidth = baseAxis.getBandWidth();
  29819. }
  29820. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29821. var key = baseAxis.dim + '_' + baseAxis.index;
  29822. var minGap = axisMinGaps[key];
  29823. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29824. var scale = baseAxis.scale.getExtent();
  29825. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29826. bandWidth = minGap
  29827. ? extentSpan / scaleSpan * minGap
  29828. : extentSpan; // When there is only one data value
  29829. }
  29830. else {
  29831. var data = seriesModel.getData();
  29832. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29833. }
  29834. var barWidth = parsePercent$1(
  29835. seriesModel.get('barWidth'), bandWidth
  29836. );
  29837. var barMaxWidth = parsePercent$1(
  29838. seriesModel.get('barMaxWidth'), bandWidth
  29839. );
  29840. var barMinWidth = parsePercent$1(
  29841. // barMinWidth by default is 1 in cartesian. Because in value axis,
  29842. // the auto-calculated bar width might be less than 1.
  29843. seriesModel.get('barMinWidth') || 1, bandWidth
  29844. );
  29845. var barGap = seriesModel.get('barGap');
  29846. var barCategoryGap = seriesModel.get('barCategoryGap');
  29847. seriesInfoList.push({
  29848. bandWidth: bandWidth,
  29849. barWidth: barWidth,
  29850. barMaxWidth: barMaxWidth,
  29851. barMinWidth: barMinWidth,
  29852. barGap: barGap,
  29853. barCategoryGap: barCategoryGap,
  29854. axisKey: getAxisKey(baseAxis),
  29855. stackId: getSeriesStackId(seriesModel)
  29856. });
  29857. });
  29858. return doCalBarWidthAndOffset(seriesInfoList);
  29859. }
  29860. function doCalBarWidthAndOffset(seriesInfoList) {
  29861. // Columns info on each category axis. Key is cartesian name
  29862. var columnsMap = {};
  29863. each$1(seriesInfoList, function (seriesInfo, idx) {
  29864. var axisKey = seriesInfo.axisKey;
  29865. var bandWidth = seriesInfo.bandWidth;
  29866. var columnsOnAxis = columnsMap[axisKey] || {
  29867. bandWidth: bandWidth,
  29868. remainedWidth: bandWidth,
  29869. autoWidthCount: 0,
  29870. categoryGap: '20%',
  29871. gap: '30%',
  29872. stacks: {}
  29873. };
  29874. var stacks = columnsOnAxis.stacks;
  29875. columnsMap[axisKey] = columnsOnAxis;
  29876. var stackId = seriesInfo.stackId;
  29877. if (!stacks[stackId]) {
  29878. columnsOnAxis.autoWidthCount++;
  29879. }
  29880. stacks[stackId] = stacks[stackId] || {
  29881. width: 0,
  29882. maxWidth: 0
  29883. };
  29884. // Caution: In a single coordinate system, these barGrid attributes
  29885. // will be shared by series. Consider that they have default values,
  29886. // only the attributes set on the last series will work.
  29887. // Do not change this fact unless there will be a break change.
  29888. var barWidth = seriesInfo.barWidth;
  29889. if (barWidth && !stacks[stackId].width) {
  29890. // See #6312, do not restrict width.
  29891. stacks[stackId].width = barWidth;
  29892. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29893. columnsOnAxis.remainedWidth -= barWidth;
  29894. }
  29895. var barMaxWidth = seriesInfo.barMaxWidth;
  29896. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29897. var barMinWidth = seriesInfo.barMinWidth;
  29898. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29899. var barGap = seriesInfo.barGap;
  29900. (barGap != null) && (columnsOnAxis.gap = barGap);
  29901. var barCategoryGap = seriesInfo.barCategoryGap;
  29902. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  29903. });
  29904. var result = {};
  29905. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  29906. result[coordSysName] = {};
  29907. var stacks = columnsOnAxis.stacks;
  29908. var bandWidth = columnsOnAxis.bandWidth;
  29909. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  29910. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  29911. var remainedWidth = columnsOnAxis.remainedWidth;
  29912. var autoWidthCount = columnsOnAxis.autoWidthCount;
  29913. var autoWidth = (remainedWidth - categoryGap)
  29914. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29915. autoWidth = Math.max(autoWidth, 0);
  29916. // Find if any auto calculated bar exceeded maxBarWidth
  29917. each$1(stacks, function (column) {
  29918. var maxWidth = column.maxWidth;
  29919. var minWidth = column.minWidth;
  29920. if (!column.width) {
  29921. var finalWidth = autoWidth;
  29922. if (maxWidth && maxWidth < finalWidth) {
  29923. finalWidth = Math.min(maxWidth, remainedWidth);
  29924. }
  29925. // `minWidth` has higher priority. `minWidth` decide that wheter the
  29926. // bar is able to be visible. So `minWidth` should not be restricted
  29927. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  29928. // the extreme cases for `value` axis, bars are allowed to overlap
  29929. // with each other if `minWidth` specified.
  29930. if (minWidth && minWidth > finalWidth) {
  29931. finalWidth = minWidth;
  29932. }
  29933. if (finalWidth !== autoWidth) {
  29934. column.width = finalWidth;
  29935. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29936. autoWidthCount--;
  29937. }
  29938. }
  29939. else {
  29940. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  29941. // CSS does. Becuase barWidth can be a percent value, where
  29942. // `barMaxWidth` can be used to restrict the final width.
  29943. var finalWidth = column.width;
  29944. if (maxWidth) {
  29945. finalWidth = Math.min(finalWidth, maxWidth);
  29946. }
  29947. // `minWidth` has higher priority, as described above
  29948. if (minWidth) {
  29949. finalWidth = Math.max(finalWidth, minWidth);
  29950. }
  29951. column.width = finalWidth;
  29952. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  29953. autoWidthCount--;
  29954. }
  29955. });
  29956. // Recalculate width again
  29957. autoWidth = (remainedWidth - categoryGap)
  29958. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  29959. autoWidth = Math.max(autoWidth, 0);
  29960. var widthSum = 0;
  29961. var lastColumn;
  29962. each$1(stacks, function (column, idx) {
  29963. if (!column.width) {
  29964. column.width = autoWidth;
  29965. }
  29966. lastColumn = column;
  29967. widthSum += column.width * (1 + barGapPercent);
  29968. });
  29969. if (lastColumn) {
  29970. widthSum -= lastColumn.width * barGapPercent;
  29971. }
  29972. var offset = -widthSum / 2;
  29973. each$1(stacks, function (column, stackId) {
  29974. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  29975. bandWidth: bandWidth,
  29976. offset: offset,
  29977. width: column.width
  29978. };
  29979. offset += column.width * (1 + barGapPercent);
  29980. });
  29981. });
  29982. return result;
  29983. }
  29984. /**
  29985. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  29986. * @param {module:echarts/coord/Axis} axis
  29987. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  29988. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  29989. */
  29990. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  29991. if (barWidthAndOffset && axis) {
  29992. var result = barWidthAndOffset[getAxisKey(axis)];
  29993. if (result != null && seriesModel != null) {
  29994. result = result[getSeriesStackId(seriesModel)];
  29995. }
  29996. return result;
  29997. }
  29998. }
  29999. /**
  30000. * @param {string} seriesType
  30001. * @param {module:echarts/model/Global} ecModel
  30002. */
  30003. function layout(seriesType, ecModel) {
  30004. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30005. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30006. var lastStackCoords = {};
  30007. each$1(seriesModels, function (seriesModel) {
  30008. var data = seriesModel.getData();
  30009. var cartesian = seriesModel.coordinateSystem;
  30010. var baseAxis = cartesian.getBaseAxis();
  30011. var stackId = getSeriesStackId(seriesModel);
  30012. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30013. var columnOffset = columnLayoutInfo.offset;
  30014. var columnWidth = columnLayoutInfo.width;
  30015. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30016. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30017. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30018. data.setLayout({
  30019. bandWidth: columnLayoutInfo.bandWidth,
  30020. offset: columnOffset,
  30021. size: columnWidth
  30022. });
  30023. var valueDim = data.mapDimension(valueAxis.dim);
  30024. var baseDim = data.mapDimension(baseAxis.dim);
  30025. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30026. var isValueAxisH = valueAxis.isHorizontal();
  30027. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30028. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30029. var value = data.get(valueDim, idx);
  30030. var baseValue = data.get(baseDim, idx);
  30031. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  30032. if (isNaN(value) || isNaN(baseValue)) {
  30033. continue;
  30034. }
  30035. var sign = value >= 0 ? 'p' : 'n';
  30036. var baseCoord = valueAxisStart;
  30037. // Because of the barMinHeight, we can not use the value in
  30038. // stackResultDimension directly.
  30039. if (stacked) {
  30040. // Only ordinal axis can be stacked.
  30041. if (!lastStackCoords[stackId][baseValue]) {
  30042. lastStackCoords[stackId][baseValue] = {
  30043. p: valueAxisStart, // Positive stack
  30044. n: valueAxisStart // Negative stack
  30045. };
  30046. }
  30047. // Should also consider #4243
  30048. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30049. }
  30050. var x;
  30051. var y;
  30052. var width;
  30053. var height;
  30054. if (isValueAxisH) {
  30055. var coord = cartesian.dataToPoint([value, baseValue]);
  30056. x = baseCoord;
  30057. y = coord[1] + columnOffset;
  30058. width = coord[0] - valueAxisStart;
  30059. height = columnWidth;
  30060. if (Math.abs(width) < barMinHeight) {
  30061. width = (width < 0 ? -1 : 1) * barMinHeight;
  30062. }
  30063. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30064. }
  30065. else {
  30066. var coord = cartesian.dataToPoint([baseValue, value]);
  30067. x = coord[0] + columnOffset;
  30068. y = baseCoord;
  30069. width = columnWidth;
  30070. height = coord[1] - valueAxisStart;
  30071. if (Math.abs(height) < barMinHeight) {
  30072. // Include zero to has a positive bar
  30073. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30074. }
  30075. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30076. }
  30077. data.setItemLayout(idx, {
  30078. x: x,
  30079. y: y,
  30080. width: width,
  30081. height: height
  30082. });
  30083. }
  30084. }, this);
  30085. }
  30086. // TODO: Do not support stack in large mode yet.
  30087. var largeLayout = {
  30088. seriesType: 'bar',
  30089. plan: createRenderPlanner(),
  30090. reset: function (seriesModel) {
  30091. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30092. return;
  30093. }
  30094. var data = seriesModel.getData();
  30095. var cartesian = seriesModel.coordinateSystem;
  30096. var baseAxis = cartesian.getBaseAxis();
  30097. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30098. var valueDim = data.mapDimension(valueAxis.dim);
  30099. var baseDim = data.mapDimension(baseAxis.dim);
  30100. var valueAxisHorizontal = valueAxis.isHorizontal();
  30101. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30102. var barWidth = retrieveColumnLayout(
  30103. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30104. ).width;
  30105. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30106. barWidth = LARGE_BAR_MIN_WIDTH;
  30107. }
  30108. return {progress: progress};
  30109. function progress(params, data) {
  30110. var count = params.count;
  30111. var largePoints = new LargeArr(count * 2);
  30112. var largeDataIndices = new LargeArr(count);
  30113. var dataIndex;
  30114. var coord = [];
  30115. var valuePair = [];
  30116. var pointsOffset = 0;
  30117. var idxOffset = 0;
  30118. while ((dataIndex = params.next()) != null) {
  30119. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30120. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30121. coord = cartesian.dataToPoint(valuePair, null, coord);
  30122. // Data index might not be in order, depends on `progressiveChunkMode`.
  30123. largePoints[pointsOffset++] = coord[0];
  30124. largePoints[pointsOffset++] = coord[1];
  30125. largeDataIndices[idxOffset++] = dataIndex;
  30126. }
  30127. data.setLayout({
  30128. largePoints: largePoints,
  30129. largeDataIndices: largeDataIndices,
  30130. barWidth: barWidth,
  30131. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30132. valueAxisHorizontal: valueAxisHorizontal
  30133. });
  30134. }
  30135. }
  30136. };
  30137. function isOnCartesian(seriesModel) {
  30138. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30139. }
  30140. function isInLargeMode(seriesModel) {
  30141. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30142. }
  30143. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30144. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30145. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30146. }
  30147. /*
  30148. * Licensed to the Apache Software Foundation (ASF) under one
  30149. * or more contributor license agreements. See the NOTICE file
  30150. * distributed with this work for additional information
  30151. * regarding copyright ownership. The ASF licenses this file
  30152. * to you under the Apache License, Version 2.0 (the
  30153. * "License"); you may not use this file except in compliance
  30154. * with the License. You may obtain a copy of the License at
  30155. *
  30156. * http://www.apache.org/licenses/LICENSE-2.0
  30157. *
  30158. * Unless required by applicable law or agreed to in writing,
  30159. * software distributed under the License is distributed on an
  30160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30161. * KIND, either express or implied. See the License for the
  30162. * specific language governing permissions and limitations
  30163. * under the License.
  30164. */
  30165. /*
  30166. * A third-party license is embeded for some of the code in this file:
  30167. * The "scaleLevels" was originally copied from "d3.js" with some
  30168. * modifications made for this project.
  30169. * (See more details in the comment on the definition of "scaleLevels" below.)
  30170. * The use of the source code of this file is also subject to the terms
  30171. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30172. * </licenses/LICENSE-d3>).
  30173. */
  30174. // [About UTC and local time zone]:
  30175. // In most cases, `number.parseDate` will treat input data string as local time
  30176. // (except time zone is specified in time string). And `format.formateTime` returns
  30177. // local time by default. option.useUTC is false by default. This design have
  30178. // concidered these common case:
  30179. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30180. // in local time by default.
  30181. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30182. // as its original time, without any time difference.
  30183. var intervalScaleProto = IntervalScale.prototype;
  30184. var mathCeil = Math.ceil;
  30185. var mathFloor = Math.floor;
  30186. var ONE_SECOND = 1000;
  30187. var ONE_MINUTE = ONE_SECOND * 60;
  30188. var ONE_HOUR = ONE_MINUTE * 60;
  30189. var ONE_DAY = ONE_HOUR * 24;
  30190. // FIXME 公用?
  30191. var bisect = function (a, x, lo, hi) {
  30192. while (lo < hi) {
  30193. var mid = lo + hi >>> 1;
  30194. if (a[mid][1] < x) {
  30195. lo = mid + 1;
  30196. }
  30197. else {
  30198. hi = mid;
  30199. }
  30200. }
  30201. return lo;
  30202. };
  30203. /**
  30204. * @alias module:echarts/coord/scale/Time
  30205. * @constructor
  30206. */
  30207. var TimeScale = IntervalScale.extend({
  30208. type: 'time',
  30209. /**
  30210. * @override
  30211. */
  30212. getLabel: function (val) {
  30213. var stepLvl = this._stepLvl;
  30214. var date = new Date(val);
  30215. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30216. },
  30217. /**
  30218. * @override
  30219. */
  30220. niceExtent: function (opt) {
  30221. var extent = this._extent;
  30222. // If extent start and end are same, expand them
  30223. if (extent[0] === extent[1]) {
  30224. // Expand extent
  30225. extent[0] -= ONE_DAY;
  30226. extent[1] += ONE_DAY;
  30227. }
  30228. // If there are no data and extent are [Infinity, -Infinity]
  30229. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30230. var d = new Date();
  30231. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30232. extent[0] = extent[1] - ONE_DAY;
  30233. }
  30234. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30235. // var extent = this._extent;
  30236. var interval = this._interval;
  30237. if (!opt.fixMin) {
  30238. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30239. }
  30240. if (!opt.fixMax) {
  30241. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30242. }
  30243. },
  30244. /**
  30245. * @override
  30246. */
  30247. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30248. approxTickNum = approxTickNum || 10;
  30249. var extent = this._extent;
  30250. var span = extent[1] - extent[0];
  30251. var approxInterval = span / approxTickNum;
  30252. if (minInterval != null && approxInterval < minInterval) {
  30253. approxInterval = minInterval;
  30254. }
  30255. if (maxInterval != null && approxInterval > maxInterval) {
  30256. approxInterval = maxInterval;
  30257. }
  30258. var scaleLevelsLen = scaleLevels.length;
  30259. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30260. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30261. var interval = level[1];
  30262. // Same with interval scale if span is much larger than 1 year
  30263. if (level[0] === 'year') {
  30264. var yearSpan = span / interval;
  30265. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30266. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30267. var yearStep = nice(yearSpan / approxTickNum, true);
  30268. interval *= yearStep;
  30269. }
  30270. var timezoneOffset = this.getSetting('useUTC')
  30271. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30272. var niceExtent = [
  30273. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30274. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30275. ];
  30276. fixExtent(niceExtent, extent);
  30277. this._stepLvl = level;
  30278. // Interval will be used in getTicks
  30279. this._interval = interval;
  30280. this._niceExtent = niceExtent;
  30281. },
  30282. parse: function (val) {
  30283. // val might be float.
  30284. return +parseDate(val);
  30285. }
  30286. });
  30287. each$1(['contain', 'normalize'], function (methodName) {
  30288. TimeScale.prototype[methodName] = function (val) {
  30289. return intervalScaleProto[methodName].call(this, this.parse(val));
  30290. };
  30291. });
  30292. /**
  30293. * This implementation was originally copied from "d3.js"
  30294. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30295. * with some modifications made for this program.
  30296. * See the license statement at the head of this file.
  30297. */
  30298. var scaleLevels = [
  30299. // Format interval
  30300. ['hh:mm:ss', ONE_SECOND], // 1s
  30301. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30302. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30303. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30304. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30305. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30306. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30307. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30308. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30309. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30310. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30311. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30312. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30313. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30314. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30315. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30316. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30317. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30318. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30319. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30320. ['week', ONE_DAY * 7], // 7d
  30321. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30322. ['week', ONE_DAY * 14], // 2w
  30323. ['week', ONE_DAY * 21], // 3w
  30324. ['month', ONE_DAY * 31], // 1M
  30325. ['week', ONE_DAY * 42], // 6w
  30326. ['month', ONE_DAY * 62], // 2M
  30327. ['week', ONE_DAY * 70], // 10w
  30328. ['quarter', ONE_DAY * 95], // 3M
  30329. ['month', ONE_DAY * 31 * 4], // 4M
  30330. ['month', ONE_DAY * 31 * 5], // 5M
  30331. ['half-year', ONE_DAY * 380 / 2], // 6M
  30332. ['month', ONE_DAY * 31 * 8], // 8M
  30333. ['month', ONE_DAY * 31 * 10], // 10M
  30334. ['year', ONE_DAY * 380] // 1Y
  30335. ];
  30336. /**
  30337. * @param {module:echarts/model/Model}
  30338. * @return {module:echarts/scale/Time}
  30339. */
  30340. TimeScale.create = function (model) {
  30341. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30342. };
  30343. /*
  30344. * Licensed to the Apache Software Foundation (ASF) under one
  30345. * or more contributor license agreements. See the NOTICE file
  30346. * distributed with this work for additional information
  30347. * regarding copyright ownership. The ASF licenses this file
  30348. * to you under the Apache License, Version 2.0 (the
  30349. * "License"); you may not use this file except in compliance
  30350. * with the License. You may obtain a copy of the License at
  30351. *
  30352. * http://www.apache.org/licenses/LICENSE-2.0
  30353. *
  30354. * Unless required by applicable law or agreed to in writing,
  30355. * software distributed under the License is distributed on an
  30356. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30357. * KIND, either express or implied. See the License for the
  30358. * specific language governing permissions and limitations
  30359. * under the License.
  30360. */
  30361. /**
  30362. * Log scale
  30363. * @module echarts/scale/Log
  30364. */
  30365. // Use some method of IntervalScale
  30366. var scaleProto$1 = Scale.prototype;
  30367. var intervalScaleProto$1 = IntervalScale.prototype;
  30368. var getPrecisionSafe$1 = getPrecisionSafe;
  30369. var roundingErrorFix = round$1;
  30370. var mathFloor$1 = Math.floor;
  30371. var mathCeil$1 = Math.ceil;
  30372. var mathPow$1 = Math.pow;
  30373. var mathLog = Math.log;
  30374. var LogScale = Scale.extend({
  30375. type: 'log',
  30376. base: 10,
  30377. $constructor: function () {
  30378. Scale.apply(this, arguments);
  30379. this._originalScale = new IntervalScale();
  30380. },
  30381. /**
  30382. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30383. * @return {Array.<number>}
  30384. */
  30385. getTicks: function (expandToNicedExtent) {
  30386. var originalScale = this._originalScale;
  30387. var extent = this._extent;
  30388. var originalExtent = originalScale.getExtent();
  30389. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30390. var powVal = round$1(mathPow$1(this.base, val));
  30391. // Fix #4158
  30392. powVal = (val === extent[0] && originalScale.__fixMin)
  30393. ? fixRoundingError(powVal, originalExtent[0])
  30394. : powVal;
  30395. powVal = (val === extent[1] && originalScale.__fixMax)
  30396. ? fixRoundingError(powVal, originalExtent[1])
  30397. : powVal;
  30398. return powVal;
  30399. }, this);
  30400. },
  30401. /**
  30402. * @param {number} splitNumber
  30403. * @return {Array.<Array.<number>>}
  30404. */
  30405. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30406. /**
  30407. * @param {number} val
  30408. * @return {string}
  30409. */
  30410. getLabel: intervalScaleProto$1.getLabel,
  30411. /**
  30412. * @param {number} val
  30413. * @return {number}
  30414. */
  30415. scale: function (val) {
  30416. val = scaleProto$1.scale.call(this, val);
  30417. return mathPow$1(this.base, val);
  30418. },
  30419. /**
  30420. * @param {number} start
  30421. * @param {number} end
  30422. */
  30423. setExtent: function (start, end) {
  30424. var base = this.base;
  30425. start = mathLog(start) / mathLog(base);
  30426. end = mathLog(end) / mathLog(base);
  30427. intervalScaleProto$1.setExtent.call(this, start, end);
  30428. },
  30429. /**
  30430. * @return {number} end
  30431. */
  30432. getExtent: function () {
  30433. var base = this.base;
  30434. var extent = scaleProto$1.getExtent.call(this);
  30435. extent[0] = mathPow$1(base, extent[0]);
  30436. extent[1] = mathPow$1(base, extent[1]);
  30437. // Fix #4158
  30438. var originalScale = this._originalScale;
  30439. var originalExtent = originalScale.getExtent();
  30440. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30441. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30442. return extent;
  30443. },
  30444. /**
  30445. * @param {Array.<number>} extent
  30446. */
  30447. unionExtent: function (extent) {
  30448. this._originalScale.unionExtent(extent);
  30449. var base = this.base;
  30450. extent[0] = mathLog(extent[0]) / mathLog(base);
  30451. extent[1] = mathLog(extent[1]) / mathLog(base);
  30452. scaleProto$1.unionExtent.call(this, extent);
  30453. },
  30454. /**
  30455. * @override
  30456. */
  30457. unionExtentFromData: function (data, dim) {
  30458. // TODO
  30459. // filter value that <= 0
  30460. this.unionExtent(data.getApproximateExtent(dim));
  30461. },
  30462. /**
  30463. * Update interval and extent of intervals for nice ticks
  30464. * @param {number} [approxTickNum = 10] Given approx tick number
  30465. */
  30466. niceTicks: function (approxTickNum) {
  30467. approxTickNum = approxTickNum || 10;
  30468. var extent = this._extent;
  30469. var span = extent[1] - extent[0];
  30470. if (span === Infinity || span <= 0) {
  30471. return;
  30472. }
  30473. var interval = quantity(span);
  30474. var err = approxTickNum / span * interval;
  30475. // Filter ticks to get closer to the desired count.
  30476. if (err <= 0.5) {
  30477. interval *= 10;
  30478. }
  30479. // Interval should be integer
  30480. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30481. interval *= 10;
  30482. }
  30483. var niceExtent = [
  30484. round$1(mathCeil$1(extent[0] / interval) * interval),
  30485. round$1(mathFloor$1(extent[1] / interval) * interval)
  30486. ];
  30487. this._interval = interval;
  30488. this._niceExtent = niceExtent;
  30489. },
  30490. /**
  30491. * Nice extent.
  30492. * @override
  30493. */
  30494. niceExtent: function (opt) {
  30495. intervalScaleProto$1.niceExtent.call(this, opt);
  30496. var originalScale = this._originalScale;
  30497. originalScale.__fixMin = opt.fixMin;
  30498. originalScale.__fixMax = opt.fixMax;
  30499. }
  30500. });
  30501. each$1(['contain', 'normalize'], function (methodName) {
  30502. LogScale.prototype[methodName] = function (val) {
  30503. val = mathLog(val) / mathLog(this.base);
  30504. return scaleProto$1[methodName].call(this, val);
  30505. };
  30506. });
  30507. LogScale.create = function () {
  30508. return new LogScale();
  30509. };
  30510. function fixRoundingError(val, originalVal) {
  30511. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30512. }
  30513. /*
  30514. * Licensed to the Apache Software Foundation (ASF) under one
  30515. * or more contributor license agreements. See the NOTICE file
  30516. * distributed with this work for additional information
  30517. * regarding copyright ownership. The ASF licenses this file
  30518. * to you under the Apache License, Version 2.0 (the
  30519. * "License"); you may not use this file except in compliance
  30520. * with the License. You may obtain a copy of the License at
  30521. *
  30522. * http://www.apache.org/licenses/LICENSE-2.0
  30523. *
  30524. * Unless required by applicable law or agreed to in writing,
  30525. * software distributed under the License is distributed on an
  30526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30527. * KIND, either express or implied. See the License for the
  30528. * specific language governing permissions and limitations
  30529. * under the License.
  30530. */
  30531. /**
  30532. * Get axis scale extent before niced.
  30533. * Item of returned array can only be number (including Infinity and NaN).
  30534. */
  30535. function getScaleExtent(scale, model) {
  30536. var scaleType = scale.type;
  30537. var min = model.getMin();
  30538. var max = model.getMax();
  30539. var fixMin = min != null;
  30540. var fixMax = max != null;
  30541. var originalExtent = scale.getExtent();
  30542. var axisDataLen;
  30543. var boundaryGap;
  30544. var span;
  30545. if (scaleType === 'ordinal') {
  30546. axisDataLen = model.getCategories().length;
  30547. }
  30548. else {
  30549. boundaryGap = model.get('boundaryGap');
  30550. if (!isArray(boundaryGap)) {
  30551. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30552. }
  30553. if (typeof boundaryGap[0] === 'boolean') {
  30554. if (__DEV__) {
  30555. console.warn('Boolean type for boundaryGap is only '
  30556. + 'allowed for ordinal axis. Please use string in '
  30557. + 'percentage instead, e.g., "20%". Currently, '
  30558. + 'boundaryGap is set to be 0.');
  30559. }
  30560. boundaryGap = [0, 0];
  30561. }
  30562. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30563. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30564. span = (originalExtent[1] - originalExtent[0])
  30565. || Math.abs(originalExtent[0]);
  30566. }
  30567. // Notice: When min/max is not set (that is, when there are null/undefined,
  30568. // which is the most common case), these cases should be ensured:
  30569. // (1) For 'ordinal', show all axis.data.
  30570. // (2) For others:
  30571. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30572. // disabled).
  30573. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30574. // be the result that originalExtent enlarged by boundaryGap.
  30575. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30576. // FIXME
  30577. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30578. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30579. // that the results processed by boundaryGap are positive/negative?
  30580. if (min == null) {
  30581. min = scaleType === 'ordinal'
  30582. ? (axisDataLen ? 0 : NaN)
  30583. : originalExtent[0] - boundaryGap[0] * span;
  30584. }
  30585. if (max == null) {
  30586. max = scaleType === 'ordinal'
  30587. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30588. : originalExtent[1] + boundaryGap[1] * span;
  30589. }
  30590. if (min === 'dataMin') {
  30591. min = originalExtent[0];
  30592. }
  30593. else if (typeof min === 'function') {
  30594. min = min({
  30595. min: originalExtent[0],
  30596. max: originalExtent[1]
  30597. });
  30598. }
  30599. if (max === 'dataMax') {
  30600. max = originalExtent[1];
  30601. }
  30602. else if (typeof max === 'function') {
  30603. max = max({
  30604. min: originalExtent[0],
  30605. max: originalExtent[1]
  30606. });
  30607. }
  30608. (min == null || !isFinite(min)) && (min = NaN);
  30609. (max == null || !isFinite(max)) && (max = NaN);
  30610. scale.setBlank(
  30611. eqNaN(min)
  30612. || eqNaN(max)
  30613. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30614. );
  30615. // Evaluate if axis needs cross zero
  30616. if (model.getNeedCrossZero()) {
  30617. // Axis is over zero and min is not set
  30618. if (min > 0 && max > 0 && !fixMin) {
  30619. min = 0;
  30620. }
  30621. // Axis is under zero and max is not set
  30622. if (min < 0 && max < 0 && !fixMax) {
  30623. max = 0;
  30624. }
  30625. }
  30626. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30627. // is base axis
  30628. // FIXME
  30629. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30630. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30631. // Should not depend on series type `bar`?
  30632. // (3) Fix that might overlap when using dataZoom.
  30633. // (4) Consider other chart types using `barGrid`?
  30634. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30635. var ecModel = model.ecModel;
  30636. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30637. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30638. var isBaseAxisAndHasBarSeries;
  30639. each$1(barSeriesModels, function (seriesModel) {
  30640. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30641. });
  30642. if (isBaseAxisAndHasBarSeries) {
  30643. // Calculate placement of bars on axis
  30644. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30645. // Adjust axis min and max to account for overflow
  30646. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30647. min = adjustedScale.min;
  30648. max = adjustedScale.max;
  30649. }
  30650. }
  30651. return [min, max];
  30652. }
  30653. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30654. // Get Axis Length
  30655. var axisExtent = model.axis.getExtent();
  30656. var axisLength = axisExtent[1] - axisExtent[0];
  30657. // Get bars on current base axis and calculate min and max overflow
  30658. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30659. if (barsOnCurrentAxis === undefined) {
  30660. return {min: min, max: max};
  30661. }
  30662. var minOverflow = Infinity;
  30663. each$1(barsOnCurrentAxis, function (item) {
  30664. minOverflow = Math.min(item.offset, minOverflow);
  30665. });
  30666. var maxOverflow = -Infinity;
  30667. each$1(barsOnCurrentAxis, function (item) {
  30668. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30669. });
  30670. minOverflow = Math.abs(minOverflow);
  30671. maxOverflow = Math.abs(maxOverflow);
  30672. var totalOverFlow = minOverflow + maxOverflow;
  30673. // Calulate required buffer based on old range and overflow
  30674. var oldRange = max - min;
  30675. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30676. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30677. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30678. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30679. return {min: min, max: max};
  30680. }
  30681. function niceScaleExtent(scale, model) {
  30682. var extent = getScaleExtent(scale, model);
  30683. var fixMin = model.getMin() != null;
  30684. var fixMax = model.getMax() != null;
  30685. var splitNumber = model.get('splitNumber');
  30686. if (scale.type === 'log') {
  30687. scale.base = model.get('logBase');
  30688. }
  30689. var scaleType = scale.type;
  30690. scale.setExtent(extent[0], extent[1]);
  30691. scale.niceExtent({
  30692. splitNumber: splitNumber,
  30693. fixMin: fixMin,
  30694. fixMax: fixMax,
  30695. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30696. ? model.get('minInterval') : null,
  30697. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30698. ? model.get('maxInterval') : null
  30699. });
  30700. // If some one specified the min, max. And the default calculated interval
  30701. // is not good enough. He can specify the interval. It is often appeared
  30702. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30703. // to be 60.
  30704. // FIXME
  30705. var interval = model.get('interval');
  30706. if (interval != null) {
  30707. scale.setInterval && scale.setInterval(interval);
  30708. }
  30709. }
  30710. /**
  30711. * @param {module:echarts/model/Model} model
  30712. * @param {string} [axisType] Default retrieve from model.type
  30713. * @return {module:echarts/scale/*}
  30714. */
  30715. function createScaleByModel(model, axisType) {
  30716. axisType = axisType || model.get('type');
  30717. if (axisType) {
  30718. switch (axisType) {
  30719. // Buildin scale
  30720. case 'category':
  30721. return new OrdinalScale(
  30722. model.getOrdinalMeta
  30723. ? model.getOrdinalMeta()
  30724. : model.getCategories(),
  30725. [Infinity, -Infinity]
  30726. );
  30727. case 'value':
  30728. return new IntervalScale();
  30729. // Extended scale, like time and log
  30730. default:
  30731. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30732. }
  30733. }
  30734. }
  30735. /**
  30736. * Check if the axis corss 0
  30737. */
  30738. function ifAxisCrossZero(axis) {
  30739. var dataExtent = axis.scale.getExtent();
  30740. var min = dataExtent[0];
  30741. var max = dataExtent[1];
  30742. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30743. }
  30744. /**
  30745. * @param {module:echarts/coord/Axis} axis
  30746. * @return {Function} Label formatter function.
  30747. * param: {number} tickValue,
  30748. * param: {number} idx, the index in all ticks.
  30749. * If category axis, this param is not requied.
  30750. * return: {string} label string.
  30751. */
  30752. function makeLabelFormatter(axis) {
  30753. var labelFormatter = axis.getLabelModel().get('formatter');
  30754. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30755. if (typeof labelFormatter === 'string') {
  30756. labelFormatter = (function (tpl) {
  30757. return function (val) {
  30758. // For category axis, get raw value; for numeric axis,
  30759. // get foramtted label like '1,333,444'.
  30760. val = axis.scale.getLabel(val);
  30761. return tpl.replace('{value}', val != null ? val : '');
  30762. };
  30763. })(labelFormatter);
  30764. // Consider empty array
  30765. return labelFormatter;
  30766. }
  30767. else if (typeof labelFormatter === 'function') {
  30768. return function (tickValue, idx) {
  30769. // The original intention of `idx` is "the index of the tick in all ticks".
  30770. // But the previous implementation of category axis do not consider the
  30771. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30772. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30773. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30774. // the definition here for back compatibility.
  30775. if (categoryTickStart != null) {
  30776. idx = tickValue - categoryTickStart;
  30777. }
  30778. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30779. };
  30780. }
  30781. else {
  30782. return function (tick) {
  30783. return axis.scale.getLabel(tick);
  30784. };
  30785. }
  30786. }
  30787. function getAxisRawValue(axis, value) {
  30788. // In category axis with data zoom, tick is not the original
  30789. // index of axis.data. So tick should not be exposed to user
  30790. // in category axis.
  30791. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30792. }
  30793. /**
  30794. * @param {module:echarts/coord/Axis} axis
  30795. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30796. */
  30797. function estimateLabelUnionRect(axis) {
  30798. var axisModel = axis.model;
  30799. var scale = axis.scale;
  30800. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30801. return;
  30802. }
  30803. var isCategory = axis.type === 'category';
  30804. var realNumberScaleTicks;
  30805. var tickCount;
  30806. var categoryScaleExtent = scale.getExtent();
  30807. // Optimize for large category data, avoid call `getTicks()`.
  30808. if (isCategory) {
  30809. tickCount = scale.count();
  30810. }
  30811. else {
  30812. realNumberScaleTicks = scale.getTicks();
  30813. tickCount = realNumberScaleTicks.length;
  30814. }
  30815. var axisLabelModel = axis.getLabelModel();
  30816. var labelFormatter = makeLabelFormatter(axis);
  30817. var rect;
  30818. var step = 1;
  30819. // Simple optimization for large amount of labels
  30820. if (tickCount > 40) {
  30821. step = Math.ceil(tickCount / 40);
  30822. }
  30823. for (var i = 0; i < tickCount; i += step) {
  30824. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  30825. var label = labelFormatter(tickValue);
  30826. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30827. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30828. rect ? rect.union(singleRect) : (rect = singleRect);
  30829. }
  30830. return rect;
  30831. }
  30832. function rotateTextRect(textRect, rotate) {
  30833. var rotateRadians = rotate * Math.PI / 180;
  30834. var boundingBox = textRect.plain();
  30835. var beforeWidth = boundingBox.width;
  30836. var beforeHeight = boundingBox.height;
  30837. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  30838. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  30839. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  30840. return rotatedRect;
  30841. }
  30842. /**
  30843. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  30844. * @return {number|String} Can be null|'auto'|number|function
  30845. */
  30846. function getOptionCategoryInterval(model) {
  30847. var interval = model.get('interval');
  30848. return interval == null ? 'auto' : interval;
  30849. }
  30850. /**
  30851. * Set `categoryInterval` as 0 implicitly indicates that
  30852. * show all labels reguardless of overlap.
  30853. * @param {Object} axis axisModel.axis
  30854. * @return {boolean}
  30855. */
  30856. function shouldShowAllLabels(axis) {
  30857. return axis.type === 'category'
  30858. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30859. }
  30860. /*
  30861. * Licensed to the Apache Software Foundation (ASF) under one
  30862. * or more contributor license agreements. See the NOTICE file
  30863. * distributed with this work for additional information
  30864. * regarding copyright ownership. The ASF licenses this file
  30865. * to you under the Apache License, Version 2.0 (the
  30866. * "License"); you may not use this file except in compliance
  30867. * with the License. You may obtain a copy of the License at
  30868. *
  30869. * http://www.apache.org/licenses/LICENSE-2.0
  30870. *
  30871. * Unless required by applicable law or agreed to in writing,
  30872. * software distributed under the License is distributed on an
  30873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30874. * KIND, either express or implied. See the License for the
  30875. * specific language governing permissions and limitations
  30876. * under the License.
  30877. */
  30878. // import * as axisHelper from './axisHelper';
  30879. var axisModelCommonMixin = {
  30880. /**
  30881. * @param {boolean} origin
  30882. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  30883. */
  30884. getMin: function (origin) {
  30885. var option = this.option;
  30886. var min = (!origin && option.rangeStart != null)
  30887. ? option.rangeStart : option.min;
  30888. if (this.axis
  30889. && min != null
  30890. && min !== 'dataMin'
  30891. && typeof min !== 'function'
  30892. && !eqNaN(min)
  30893. ) {
  30894. min = this.axis.scale.parse(min);
  30895. }
  30896. return min;
  30897. },
  30898. /**
  30899. * @param {boolean} origin
  30900. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  30901. */
  30902. getMax: function (origin) {
  30903. var option = this.option;
  30904. var max = (!origin && option.rangeEnd != null)
  30905. ? option.rangeEnd : option.max;
  30906. if (this.axis
  30907. && max != null
  30908. && max !== 'dataMax'
  30909. && typeof max !== 'function'
  30910. && !eqNaN(max)
  30911. ) {
  30912. max = this.axis.scale.parse(max);
  30913. }
  30914. return max;
  30915. },
  30916. /**
  30917. * @return {boolean}
  30918. */
  30919. getNeedCrossZero: function () {
  30920. var option = this.option;
  30921. return (option.rangeStart != null || option.rangeEnd != null)
  30922. ? false : !option.scale;
  30923. },
  30924. /**
  30925. * Should be implemented by each axis model if necessary.
  30926. * @return {module:echarts/model/Component} coordinate system model
  30927. */
  30928. getCoordSysModel: noop,
  30929. /**
  30930. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  30931. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  30932. */
  30933. setRange: function (rangeStart, rangeEnd) {
  30934. this.option.rangeStart = rangeStart;
  30935. this.option.rangeEnd = rangeEnd;
  30936. },
  30937. /**
  30938. * Reset range
  30939. */
  30940. resetRange: function () {
  30941. // rangeStart and rangeEnd is readonly.
  30942. this.option.rangeStart = this.option.rangeEnd = null;
  30943. }
  30944. };
  30945. /*
  30946. * Licensed to the Apache Software Foundation (ASF) under one
  30947. * or more contributor license agreements. See the NOTICE file
  30948. * distributed with this work for additional information
  30949. * regarding copyright ownership. The ASF licenses this file
  30950. * to you under the Apache License, Version 2.0 (the
  30951. * "License"); you may not use this file except in compliance
  30952. * with the License. You may obtain a copy of the License at
  30953. *
  30954. * http://www.apache.org/licenses/LICENSE-2.0
  30955. *
  30956. * Unless required by applicable law or agreed to in writing,
  30957. * software distributed under the License is distributed on an
  30958. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30959. * KIND, either express or implied. See the License for the
  30960. * specific language governing permissions and limitations
  30961. * under the License.
  30962. */
  30963. // Symbol factory
  30964. /**
  30965. * Triangle shape
  30966. * @inner
  30967. */
  30968. var Triangle = extendShape({
  30969. type: 'triangle',
  30970. shape: {
  30971. cx: 0,
  30972. cy: 0,
  30973. width: 0,
  30974. height: 0
  30975. },
  30976. buildPath: function (path, shape) {
  30977. var cx = shape.cx;
  30978. var cy = shape.cy;
  30979. var width = shape.width / 2;
  30980. var height = shape.height / 2;
  30981. path.moveTo(cx, cy - height);
  30982. path.lineTo(cx + width, cy + height);
  30983. path.lineTo(cx - width, cy + height);
  30984. path.closePath();
  30985. }
  30986. });
  30987. /**
  30988. * Diamond shape
  30989. * @inner
  30990. */
  30991. var Diamond = extendShape({
  30992. type: 'diamond',
  30993. shape: {
  30994. cx: 0,
  30995. cy: 0,
  30996. width: 0,
  30997. height: 0
  30998. },
  30999. buildPath: function (path, shape) {
  31000. var cx = shape.cx;
  31001. var cy = shape.cy;
  31002. var width = shape.width / 2;
  31003. var height = shape.height / 2;
  31004. path.moveTo(cx, cy - height);
  31005. path.lineTo(cx + width, cy);
  31006. path.lineTo(cx, cy + height);
  31007. path.lineTo(cx - width, cy);
  31008. path.closePath();
  31009. }
  31010. });
  31011. /**
  31012. * Pin shape
  31013. * @inner
  31014. */
  31015. var Pin = extendShape({
  31016. type: 'pin',
  31017. shape: {
  31018. // x, y on the cusp
  31019. x: 0,
  31020. y: 0,
  31021. width: 0,
  31022. height: 0
  31023. },
  31024. buildPath: function (path, shape) {
  31025. var x = shape.x;
  31026. var y = shape.y;
  31027. var w = shape.width / 5 * 3;
  31028. // Height must be larger than width
  31029. var h = Math.max(w, shape.height);
  31030. var r = w / 2;
  31031. // Dist on y with tangent point and circle center
  31032. var dy = r * r / (h - r);
  31033. var cy = y - h + r + dy;
  31034. var angle = Math.asin(dy / r);
  31035. // Dist on x with tangent point and circle center
  31036. var dx = Math.cos(angle) * r;
  31037. var tanX = Math.sin(angle);
  31038. var tanY = Math.cos(angle);
  31039. var cpLen = r * 0.6;
  31040. var cpLen2 = r * 0.7;
  31041. path.moveTo(x - dx, cy + dy);
  31042. path.arc(
  31043. x, cy, r,
  31044. Math.PI - angle,
  31045. Math.PI * 2 + angle
  31046. );
  31047. path.bezierCurveTo(
  31048. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31049. x, y - cpLen2,
  31050. x, y
  31051. );
  31052. path.bezierCurveTo(
  31053. x, y - cpLen2,
  31054. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31055. x - dx, cy + dy
  31056. );
  31057. path.closePath();
  31058. }
  31059. });
  31060. /**
  31061. * Arrow shape
  31062. * @inner
  31063. */
  31064. var Arrow = extendShape({
  31065. type: 'arrow',
  31066. shape: {
  31067. x: 0,
  31068. y: 0,
  31069. width: 0,
  31070. height: 0
  31071. },
  31072. buildPath: function (ctx, shape) {
  31073. var height = shape.height;
  31074. var width = shape.width;
  31075. var x = shape.x;
  31076. var y = shape.y;
  31077. var dx = width / 3 * 2;
  31078. ctx.moveTo(x, y);
  31079. ctx.lineTo(x + dx, y + height);
  31080. ctx.lineTo(x, y + height / 4 * 3);
  31081. ctx.lineTo(x - dx, y + height);
  31082. ctx.lineTo(x, y);
  31083. ctx.closePath();
  31084. }
  31085. });
  31086. /**
  31087. * Map of path contructors
  31088. * @type {Object.<string, module:zrender/graphic/Path>}
  31089. */
  31090. var symbolCtors = {
  31091. line: Line,
  31092. rect: Rect,
  31093. roundRect: Rect,
  31094. square: Rect,
  31095. circle: Circle,
  31096. diamond: Diamond,
  31097. pin: Pin,
  31098. arrow: Arrow,
  31099. triangle: Triangle
  31100. };
  31101. var symbolShapeMakers = {
  31102. line: function (x, y, w, h, shape) {
  31103. // FIXME
  31104. shape.x1 = x;
  31105. shape.y1 = y + h / 2;
  31106. shape.x2 = x + w;
  31107. shape.y2 = y + h / 2;
  31108. },
  31109. rect: function (x, y, w, h, shape) {
  31110. shape.x = x;
  31111. shape.y = y;
  31112. shape.width = w;
  31113. shape.height = h;
  31114. },
  31115. roundRect: function (x, y, w, h, shape) {
  31116. shape.x = x;
  31117. shape.y = y;
  31118. shape.width = w;
  31119. shape.height = h;
  31120. shape.r = Math.min(w, h) / 4;
  31121. },
  31122. square: function (x, y, w, h, shape) {
  31123. var size = Math.min(w, h);
  31124. shape.x = x;
  31125. shape.y = y;
  31126. shape.width = size;
  31127. shape.height = size;
  31128. },
  31129. circle: function (x, y, w, h, shape) {
  31130. // Put circle in the center of square
  31131. shape.cx = x + w / 2;
  31132. shape.cy = y + h / 2;
  31133. shape.r = Math.min(w, h) / 2;
  31134. },
  31135. diamond: function (x, y, w, h, shape) {
  31136. shape.cx = x + w / 2;
  31137. shape.cy = y + h / 2;
  31138. shape.width = w;
  31139. shape.height = h;
  31140. },
  31141. pin: function (x, y, w, h, shape) {
  31142. shape.x = x + w / 2;
  31143. shape.y = y + h / 2;
  31144. shape.width = w;
  31145. shape.height = h;
  31146. },
  31147. arrow: function (x, y, w, h, shape) {
  31148. shape.x = x + w / 2;
  31149. shape.y = y + h / 2;
  31150. shape.width = w;
  31151. shape.height = h;
  31152. },
  31153. triangle: function (x, y, w, h, shape) {
  31154. shape.cx = x + w / 2;
  31155. shape.cy = y + h / 2;
  31156. shape.width = w;
  31157. shape.height = h;
  31158. }
  31159. };
  31160. var symbolBuildProxies = {};
  31161. each$1(symbolCtors, function (Ctor, name) {
  31162. symbolBuildProxies[name] = new Ctor();
  31163. });
  31164. var SymbolClz = extendShape({
  31165. type: 'symbol',
  31166. shape: {
  31167. symbolType: '',
  31168. x: 0,
  31169. y: 0,
  31170. width: 0,
  31171. height: 0
  31172. },
  31173. calculateTextPosition: function (out, style, rect) {
  31174. var res = calculateTextPosition(out, style, rect);
  31175. var shape = this.shape;
  31176. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31177. res.y = rect.y + rect.height * 0.4;
  31178. }
  31179. return res;
  31180. },
  31181. buildPath: function (ctx, shape, inBundle) {
  31182. var symbolType = shape.symbolType;
  31183. if (symbolType !== 'none') {
  31184. var proxySymbol = symbolBuildProxies[symbolType];
  31185. if (!proxySymbol) {
  31186. // Default rect
  31187. symbolType = 'rect';
  31188. proxySymbol = symbolBuildProxies[symbolType];
  31189. }
  31190. symbolShapeMakers[symbolType](
  31191. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31192. );
  31193. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31194. }
  31195. }
  31196. });
  31197. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31198. function symbolPathSetColor(color, innerColor) {
  31199. if (this.type !== 'image') {
  31200. var symbolStyle = this.style;
  31201. var symbolShape = this.shape;
  31202. if (symbolShape && symbolShape.symbolType === 'line') {
  31203. symbolStyle.stroke = color;
  31204. }
  31205. else if (this.__isEmptyBrush) {
  31206. symbolStyle.stroke = color;
  31207. symbolStyle.fill = innerColor || '#fff';
  31208. }
  31209. else {
  31210. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31211. symbolStyle.fill && (symbolStyle.fill = color);
  31212. symbolStyle.stroke && (symbolStyle.stroke = color);
  31213. }
  31214. this.dirty(false);
  31215. }
  31216. }
  31217. /**
  31218. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31219. * @param {string} symbolType
  31220. * @param {number} x
  31221. * @param {number} y
  31222. * @param {number} w
  31223. * @param {number} h
  31224. * @param {string} color
  31225. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31226. * for path and image only.
  31227. */
  31228. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31229. // TODO Support image object, DynamicImage.
  31230. var isEmpty = symbolType.indexOf('empty') === 0;
  31231. if (isEmpty) {
  31232. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31233. }
  31234. var symbolPath;
  31235. if (symbolType.indexOf('image://') === 0) {
  31236. symbolPath = makeImage(
  31237. symbolType.slice(8),
  31238. new BoundingRect(x, y, w, h),
  31239. keepAspect ? 'center' : 'cover'
  31240. );
  31241. }
  31242. else if (symbolType.indexOf('path://') === 0) {
  31243. symbolPath = makePath(
  31244. symbolType.slice(7),
  31245. {},
  31246. new BoundingRect(x, y, w, h),
  31247. keepAspect ? 'center' : 'cover'
  31248. );
  31249. }
  31250. else {
  31251. symbolPath = new SymbolClz({
  31252. shape: {
  31253. symbolType: symbolType,
  31254. x: x,
  31255. y: y,
  31256. width: w,
  31257. height: h
  31258. }
  31259. });
  31260. }
  31261. symbolPath.__isEmptyBrush = isEmpty;
  31262. symbolPath.setColor = symbolPathSetColor;
  31263. symbolPath.setColor(color);
  31264. return symbolPath;
  31265. }
  31266. /*
  31267. * Licensed to the Apache Software Foundation (ASF) under one
  31268. * or more contributor license agreements. See the NOTICE file
  31269. * distributed with this work for additional information
  31270. * regarding copyright ownership. The ASF licenses this file
  31271. * to you under the Apache License, Version 2.0 (the
  31272. * "License"); you may not use this file except in compliance
  31273. * with the License. You may obtain a copy of the License at
  31274. *
  31275. * http://www.apache.org/licenses/LICENSE-2.0
  31276. *
  31277. * Unless required by applicable law or agreed to in writing,
  31278. * software distributed under the License is distributed on an
  31279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31280. * KIND, either express or implied. See the License for the
  31281. * specific language governing permissions and limitations
  31282. * under the License.
  31283. */
  31284. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31285. /**
  31286. * Create a muti dimension List structure from seriesModel.
  31287. * @param {module:echarts/model/Model} seriesModel
  31288. * @return {module:echarts/data/List} list
  31289. */
  31290. function createList(seriesModel) {
  31291. return createListFromArray(seriesModel.getSource(), seriesModel);
  31292. }
  31293. var dataStack$1 = {
  31294. isDimensionStacked: isDimensionStacked,
  31295. enableDataStack: enableDataStack,
  31296. getStackedDimension: getStackedDimension
  31297. };
  31298. /**
  31299. * Create scale
  31300. * @param {Array.<number>} dataExtent
  31301. * @param {Object|module:echarts/Model} option
  31302. */
  31303. function createScale(dataExtent, option) {
  31304. var axisModel = option;
  31305. if (!Model.isInstance(option)) {
  31306. axisModel = new Model(option);
  31307. mixin(axisModel, axisModelCommonMixin);
  31308. }
  31309. var scale = createScaleByModel(axisModel);
  31310. scale.setExtent(dataExtent[0], dataExtent[1]);
  31311. niceScaleExtent(scale, axisModel);
  31312. return scale;
  31313. }
  31314. /**
  31315. * Mixin common methods to axis model,
  31316. *
  31317. * Inlcude methods
  31318. * `getFormattedLabels() => Array.<string>`
  31319. * `getCategories() => Array.<string>`
  31320. * `getMin(origin: boolean) => number`
  31321. * `getMax(origin: boolean) => number`
  31322. * `getNeedCrossZero() => boolean`
  31323. * `setRange(start: number, end: number)`
  31324. * `resetRange()`
  31325. */
  31326. function mixinAxisModelCommonMethods(Model$$1) {
  31327. mixin(Model$$1, axisModelCommonMixin);
  31328. }
  31329. var helper = (Object.freeze || Object)({
  31330. createList: createList,
  31331. getLayoutRect: getLayoutRect,
  31332. dataStack: dataStack$1,
  31333. createScale: createScale,
  31334. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31335. completeDimensions: completeDimensions,
  31336. createDimensions: createDimensions,
  31337. createSymbol: createSymbol
  31338. });
  31339. var EPSILON$3 = 1e-8;
  31340. function isAroundEqual$1(a, b) {
  31341. return Math.abs(a - b) < EPSILON$3;
  31342. }
  31343. function contain$1(points, x, y) {
  31344. var w = 0;
  31345. var p = points[0];
  31346. if (!p) {
  31347. return false;
  31348. }
  31349. for (var i = 1; i < points.length; i++) {
  31350. var p2 = points[i];
  31351. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31352. p = p2;
  31353. }
  31354. // Close polygon
  31355. var p0 = points[0];
  31356. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31357. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31358. }
  31359. return w !== 0;
  31360. }
  31361. /*
  31362. * Licensed to the Apache Software Foundation (ASF) under one
  31363. * or more contributor license agreements. See the NOTICE file
  31364. * distributed with this work for additional information
  31365. * regarding copyright ownership. The ASF licenses this file
  31366. * to you under the Apache License, Version 2.0 (the
  31367. * "License"); you may not use this file except in compliance
  31368. * with the License. You may obtain a copy of the License at
  31369. *
  31370. * http://www.apache.org/licenses/LICENSE-2.0
  31371. *
  31372. * Unless required by applicable law or agreed to in writing,
  31373. * software distributed under the License is distributed on an
  31374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31375. * KIND, either express or implied. See the License for the
  31376. * specific language governing permissions and limitations
  31377. * under the License.
  31378. */
  31379. /**
  31380. * @module echarts/coord/geo/Region
  31381. */
  31382. /**
  31383. * @param {string|Region} name
  31384. * @param {Array} geometries
  31385. * @param {Array.<number>} cp
  31386. */
  31387. function Region(name, geometries, cp) {
  31388. /**
  31389. * @type {string}
  31390. * @readOnly
  31391. */
  31392. this.name = name;
  31393. /**
  31394. * @type {Array.<Array>}
  31395. * @readOnly
  31396. */
  31397. this.geometries = geometries;
  31398. if (!cp) {
  31399. var rect = this.getBoundingRect();
  31400. cp = [
  31401. rect.x + rect.width / 2,
  31402. rect.y + rect.height / 2
  31403. ];
  31404. }
  31405. else {
  31406. cp = [cp[0], cp[1]];
  31407. }
  31408. /**
  31409. * @type {Array.<number>}
  31410. */
  31411. this.center = cp;
  31412. }
  31413. Region.prototype = {
  31414. constructor: Region,
  31415. properties: null,
  31416. /**
  31417. * @return {module:zrender/core/BoundingRect}
  31418. */
  31419. getBoundingRect: function () {
  31420. var rect = this._rect;
  31421. if (rect) {
  31422. return rect;
  31423. }
  31424. var MAX_NUMBER = Number.MAX_VALUE;
  31425. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31426. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31427. var min2 = [];
  31428. var max2 = [];
  31429. var geometries = this.geometries;
  31430. for (var i = 0; i < geometries.length; i++) {
  31431. // Only support polygon
  31432. if (geometries[i].type !== 'polygon') {
  31433. continue;
  31434. }
  31435. // Doesn't consider hole
  31436. var exterior = geometries[i].exterior;
  31437. fromPoints(exterior, min2, max2);
  31438. min(min$$1, min$$1, min2);
  31439. max(max$$1, max$$1, max2);
  31440. }
  31441. // No data
  31442. if (i === 0) {
  31443. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31444. }
  31445. return (this._rect = new BoundingRect(
  31446. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31447. ));
  31448. },
  31449. /**
  31450. * @param {<Array.<number>} coord
  31451. * @return {boolean}
  31452. */
  31453. contain: function (coord) {
  31454. var rect = this.getBoundingRect();
  31455. var geometries = this.geometries;
  31456. if (!rect.contain(coord[0], coord[1])) {
  31457. return false;
  31458. }
  31459. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31460. // Only support polygon.
  31461. if (geometries[i].type !== 'polygon') {
  31462. continue;
  31463. }
  31464. var exterior = geometries[i].exterior;
  31465. var interiors = geometries[i].interiors;
  31466. if (contain$1(exterior, coord[0], coord[1])) {
  31467. // Not in the region if point is in the hole.
  31468. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31469. if (contain$1(interiors[k])) {
  31470. continue loopGeo;
  31471. }
  31472. }
  31473. return true;
  31474. }
  31475. }
  31476. return false;
  31477. },
  31478. transformTo: function (x, y, width, height) {
  31479. var rect = this.getBoundingRect();
  31480. var aspect = rect.width / rect.height;
  31481. if (!width) {
  31482. width = aspect * height;
  31483. }
  31484. else if (!height) {
  31485. height = width / aspect;
  31486. }
  31487. var target = new BoundingRect(x, y, width, height);
  31488. var transform = rect.calculateTransform(target);
  31489. var geometries = this.geometries;
  31490. for (var i = 0; i < geometries.length; i++) {
  31491. // Only support polygon.
  31492. if (geometries[i].type !== 'polygon') {
  31493. continue;
  31494. }
  31495. var exterior = geometries[i].exterior;
  31496. var interiors = geometries[i].interiors;
  31497. for (var p = 0; p < exterior.length; p++) {
  31498. applyTransform(exterior[p], exterior[p], transform);
  31499. }
  31500. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31501. for (var p = 0; p < interiors[h].length; p++) {
  31502. applyTransform(interiors[h][p], interiors[h][p], transform);
  31503. }
  31504. }
  31505. }
  31506. rect = this._rect;
  31507. rect.copy(target);
  31508. // Update center
  31509. this.center = [
  31510. rect.x + rect.width / 2,
  31511. rect.y + rect.height / 2
  31512. ];
  31513. },
  31514. cloneShallow: function (name) {
  31515. name == null && (name = this.name);
  31516. var newRegion = new Region(name, this.geometries, this.center);
  31517. newRegion._rect = this._rect;
  31518. newRegion.transformTo = null; // Simply avoid to be called.
  31519. return newRegion;
  31520. }
  31521. };
  31522. /*
  31523. * Licensed to the Apache Software Foundation (ASF) under one
  31524. * or more contributor license agreements. See the NOTICE file
  31525. * distributed with this work for additional information
  31526. * regarding copyright ownership. The ASF licenses this file
  31527. * to you under the Apache License, Version 2.0 (the
  31528. * "License"); you may not use this file except in compliance
  31529. * with the License. You may obtain a copy of the License at
  31530. *
  31531. * http://www.apache.org/licenses/LICENSE-2.0
  31532. *
  31533. * Unless required by applicable law or agreed to in writing,
  31534. * software distributed under the License is distributed on an
  31535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31536. * KIND, either express or implied. See the License for the
  31537. * specific language governing permissions and limitations
  31538. * under the License.
  31539. */
  31540. /**
  31541. * Parse and decode geo json
  31542. * @module echarts/coord/geo/parseGeoJson
  31543. */
  31544. function decode(json) {
  31545. if (!json.UTF8Encoding) {
  31546. return json;
  31547. }
  31548. var encodeScale = json.UTF8Scale;
  31549. if (encodeScale == null) {
  31550. encodeScale = 1024;
  31551. }
  31552. var features = json.features;
  31553. for (var f = 0; f < features.length; f++) {
  31554. var feature = features[f];
  31555. var geometry = feature.geometry;
  31556. var coordinates = geometry.coordinates;
  31557. var encodeOffsets = geometry.encodeOffsets;
  31558. for (var c = 0; c < coordinates.length; c++) {
  31559. var coordinate = coordinates[c];
  31560. if (geometry.type === 'Polygon') {
  31561. coordinates[c] = decodePolygon(
  31562. coordinate,
  31563. encodeOffsets[c],
  31564. encodeScale
  31565. );
  31566. }
  31567. else if (geometry.type === 'MultiPolygon') {
  31568. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31569. var polygon = coordinate[c2];
  31570. coordinate[c2] = decodePolygon(
  31571. polygon,
  31572. encodeOffsets[c][c2],
  31573. encodeScale
  31574. );
  31575. }
  31576. }
  31577. }
  31578. }
  31579. // Has been decoded
  31580. json.UTF8Encoding = false;
  31581. return json;
  31582. }
  31583. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31584. var result = [];
  31585. var prevX = encodeOffsets[0];
  31586. var prevY = encodeOffsets[1];
  31587. for (var i = 0; i < coordinate.length; i += 2) {
  31588. var x = coordinate.charCodeAt(i) - 64;
  31589. var y = coordinate.charCodeAt(i + 1) - 64;
  31590. // ZigZag decoding
  31591. x = (x >> 1) ^ (-(x & 1));
  31592. y = (y >> 1) ^ (-(y & 1));
  31593. // Delta deocding
  31594. x += prevX;
  31595. y += prevY;
  31596. prevX = x;
  31597. prevY = y;
  31598. // Dequantize
  31599. result.push([x / encodeScale, y / encodeScale]);
  31600. }
  31601. return result;
  31602. }
  31603. /**
  31604. * @alias module:echarts/coord/geo/parseGeoJson
  31605. * @param {Object} geoJson
  31606. * @return {module:zrender/container/Group}
  31607. */
  31608. var parseGeoJSON = function (geoJson) {
  31609. decode(geoJson);
  31610. return map(filter(geoJson.features, function (featureObj) {
  31611. // Output of mapshaper may have geometry null
  31612. return featureObj.geometry
  31613. && featureObj.properties
  31614. && featureObj.geometry.coordinates.length > 0;
  31615. }), function (featureObj) {
  31616. var properties = featureObj.properties;
  31617. var geo = featureObj.geometry;
  31618. var coordinates = geo.coordinates;
  31619. var geometries = [];
  31620. if (geo.type === 'Polygon') {
  31621. geometries.push({
  31622. type: 'polygon',
  31623. // According to the GeoJSON specification.
  31624. // First must be exterior, and the rest are all interior(holes).
  31625. exterior: coordinates[0],
  31626. interiors: coordinates.slice(1)
  31627. });
  31628. }
  31629. if (geo.type === 'MultiPolygon') {
  31630. each$1(coordinates, function (item) {
  31631. if (item[0]) {
  31632. geometries.push({
  31633. type: 'polygon',
  31634. exterior: item[0],
  31635. interiors: item.slice(1)
  31636. });
  31637. }
  31638. });
  31639. }
  31640. var region = new Region(
  31641. properties.name,
  31642. geometries,
  31643. properties.cp
  31644. );
  31645. region.properties = properties;
  31646. return region;
  31647. });
  31648. };
  31649. /*
  31650. * Licensed to the Apache Software Foundation (ASF) under one
  31651. * or more contributor license agreements. See the NOTICE file
  31652. * distributed with this work for additional information
  31653. * regarding copyright ownership. The ASF licenses this file
  31654. * to you under the Apache License, Version 2.0 (the
  31655. * "License"); you may not use this file except in compliance
  31656. * with the License. You may obtain a copy of the License at
  31657. *
  31658. * http://www.apache.org/licenses/LICENSE-2.0
  31659. *
  31660. * Unless required by applicable law or agreed to in writing,
  31661. * software distributed under the License is distributed on an
  31662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31663. * KIND, either express or implied. See the License for the
  31664. * specific language governing permissions and limitations
  31665. * under the License.
  31666. */
  31667. var inner$6 = makeInner();
  31668. /**
  31669. * @param {module:echats/coord/Axis} axis
  31670. * @return {Object} {
  31671. * labels: [{
  31672. * formattedLabel: string,
  31673. * rawLabel: string,
  31674. * tickValue: number
  31675. * }, ...],
  31676. * labelCategoryInterval: number
  31677. * }
  31678. */
  31679. function createAxisLabels(axis) {
  31680. // Only ordinal scale support tick interval
  31681. return axis.type === 'category'
  31682. ? makeCategoryLabels(axis)
  31683. : makeRealNumberLabels(axis);
  31684. }
  31685. /**
  31686. * @param {module:echats/coord/Axis} axis
  31687. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31688. * @return {Object} {
  31689. * ticks: Array.<number>
  31690. * tickCategoryInterval: number
  31691. * }
  31692. */
  31693. function createAxisTicks(axis, tickModel) {
  31694. // Only ordinal scale support tick interval
  31695. return axis.type === 'category'
  31696. ? makeCategoryTicks(axis, tickModel)
  31697. : {ticks: axis.scale.getTicks()};
  31698. }
  31699. function makeCategoryLabels(axis) {
  31700. var labelModel = axis.getLabelModel();
  31701. var result = makeCategoryLabelsActually(axis, labelModel);
  31702. return (!labelModel.get('show') || axis.scale.isBlank())
  31703. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31704. : result;
  31705. }
  31706. function makeCategoryLabelsActually(axis, labelModel) {
  31707. var labelsCache = getListCache(axis, 'labels');
  31708. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31709. var result = listCacheGet(labelsCache, optionLabelInterval);
  31710. if (result) {
  31711. return result;
  31712. }
  31713. var labels;
  31714. var numericLabelInterval;
  31715. if (isFunction$1(optionLabelInterval)) {
  31716. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31717. }
  31718. else {
  31719. numericLabelInterval = optionLabelInterval === 'auto'
  31720. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31721. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31722. }
  31723. // Cache to avoid calling interval function repeatly.
  31724. return listCacheSet(labelsCache, optionLabelInterval, {
  31725. labels: labels, labelCategoryInterval: numericLabelInterval
  31726. });
  31727. }
  31728. function makeCategoryTicks(axis, tickModel) {
  31729. var ticksCache = getListCache(axis, 'ticks');
  31730. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31731. var result = listCacheGet(ticksCache, optionTickInterval);
  31732. if (result) {
  31733. return result;
  31734. }
  31735. var ticks;
  31736. var tickCategoryInterval;
  31737. // Optimize for the case that large category data and no label displayed,
  31738. // we should not return all ticks.
  31739. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31740. ticks = [];
  31741. }
  31742. if (isFunction$1(optionTickInterval)) {
  31743. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31744. }
  31745. // Always use label interval by default despite label show. Consider this
  31746. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31747. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31748. else if (optionTickInterval === 'auto') {
  31749. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31750. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31751. ticks = map(labelsResult.labels, function (labelItem) {
  31752. return labelItem.tickValue;
  31753. });
  31754. }
  31755. else {
  31756. tickCategoryInterval = optionTickInterval;
  31757. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31758. }
  31759. // Cache to avoid calling interval function repeatly.
  31760. return listCacheSet(ticksCache, optionTickInterval, {
  31761. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31762. });
  31763. }
  31764. function makeRealNumberLabels(axis) {
  31765. var ticks = axis.scale.getTicks();
  31766. var labelFormatter = makeLabelFormatter(axis);
  31767. return {
  31768. labels: map(ticks, function (tickValue, idx) {
  31769. return {
  31770. formattedLabel: labelFormatter(tickValue, idx),
  31771. rawLabel: axis.scale.getLabel(tickValue),
  31772. tickValue: tickValue
  31773. };
  31774. })
  31775. };
  31776. }
  31777. // Large category data calculation is performence sensitive, and ticks and label
  31778. // probably be fetched by multiple times. So we cache the result.
  31779. // axis is created each time during a ec process, so we do not need to clear cache.
  31780. function getListCache(axis, prop) {
  31781. // Because key can be funciton, and cache size always be small, we use array cache.
  31782. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31783. }
  31784. function listCacheGet(cache, key) {
  31785. for (var i = 0; i < cache.length; i++) {
  31786. if (cache[i].key === key) {
  31787. return cache[i].value;
  31788. }
  31789. }
  31790. }
  31791. function listCacheSet(cache, key, value) {
  31792. cache.push({key: key, value: value});
  31793. return value;
  31794. }
  31795. function makeAutoCategoryInterval(axis) {
  31796. var result = inner$6(axis).autoInterval;
  31797. return result != null
  31798. ? result
  31799. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31800. }
  31801. /**
  31802. * Calculate interval for category axis ticks and labels.
  31803. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31804. * should be implemented in axis.
  31805. */
  31806. function calculateCategoryInterval(axis) {
  31807. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31808. var labelFormatter = makeLabelFormatter(axis);
  31809. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31810. var ordinalScale = axis.scale;
  31811. var ordinalExtent = ordinalScale.getExtent();
  31812. // Providing this method is for optimization:
  31813. // avoid generating a long array by `getTicks`
  31814. // in large category data case.
  31815. var tickCount = ordinalScale.count();
  31816. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31817. return 0;
  31818. }
  31819. var step = 1;
  31820. // Simple optimization. Empirical value: tick count should less than 40.
  31821. if (tickCount > 40) {
  31822. step = Math.max(1, Math.floor(tickCount / 40));
  31823. }
  31824. var tickValue = ordinalExtent[0];
  31825. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31826. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31827. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31828. var maxW = 0;
  31829. var maxH = 0;
  31830. // Caution: Performance sensitive for large category data.
  31831. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31832. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31833. var width = 0;
  31834. var height = 0;
  31835. // Not precise, do not consider align and vertical align
  31836. // and each distance from axis line yet.
  31837. var rect = getBoundingRect(
  31838. labelFormatter(tickValue), params.font, 'center', 'top'
  31839. );
  31840. // Magic number
  31841. width = rect.width * 1.3;
  31842. height = rect.height * 1.3;
  31843. // Min size, void long loop.
  31844. maxW = Math.max(maxW, width, 7);
  31845. maxH = Math.max(maxH, height, 7);
  31846. }
  31847. var dw = maxW / unitW;
  31848. var dh = maxH / unitH;
  31849. // 0/0 is NaN, 1/0 is Infinity.
  31850. isNaN(dw) && (dw = Infinity);
  31851. isNaN(dh) && (dh = Infinity);
  31852. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31853. var cache = inner$6(axis.model);
  31854. var axisExtent = axis.getExtent();
  31855. var lastAutoInterval = cache.lastAutoInterval;
  31856. var lastTickCount = cache.lastTickCount;
  31857. // Use cache to keep interval stable while moving zoom window,
  31858. // otherwise the calculated interval might jitter when the zoom
  31859. // window size is close to the interval-changing size.
  31860. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31861. // The jitter will cause that sometimes the displayed labels are
  31862. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31863. if (lastAutoInterval != null
  31864. && lastTickCount != null
  31865. && Math.abs(lastAutoInterval - interval) <= 1
  31866. && Math.abs(lastTickCount - tickCount) <= 1
  31867. // Always choose the bigger one, otherwise the critical
  31868. // point is not the same when zooming in or zooming out.
  31869. && lastAutoInterval > interval
  31870. // If the axis change is caused by chart resize, the cache should not
  31871. // be used. Otherwise some hiden labels might not be shown again.
  31872. && cache.axisExtend0 === axisExtent[0]
  31873. && cache.axisExtend1 === axisExtent[1]
  31874. ) {
  31875. interval = lastAutoInterval;
  31876. }
  31877. // Only update cache if cache not used, otherwise the
  31878. // changing of interval is too insensitive.
  31879. else {
  31880. cache.lastTickCount = tickCount;
  31881. cache.lastAutoInterval = interval;
  31882. cache.axisExtend0 = axisExtent[0];
  31883. cache.axisExtend1 = axisExtent[1];
  31884. }
  31885. return interval;
  31886. }
  31887. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31888. var labelModel = axis.getLabelModel();
  31889. return {
  31890. axisRotate: axis.getRotate
  31891. ? axis.getRotate()
  31892. : (axis.isHorizontal && !axis.isHorizontal())
  31893. ? 90
  31894. : 0,
  31895. labelRotate: labelModel.get('rotate') || 0,
  31896. font: labelModel.getFont()
  31897. };
  31898. }
  31899. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31900. var labelFormatter = makeLabelFormatter(axis);
  31901. var ordinalScale = axis.scale;
  31902. var ordinalExtent = ordinalScale.getExtent();
  31903. var labelModel = axis.getLabelModel();
  31904. var result = [];
  31905. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31906. var step = Math.max((categoryInterval || 0) + 1, 1);
  31907. var startTick = ordinalExtent[0];
  31908. var tickCount = ordinalScale.count();
  31909. // Calculate start tick based on zero if possible to keep label consistent
  31910. // while zooming and moving while interval > 0. Otherwise the selection
  31911. // of displayable ticks and symbols probably keep changing.
  31912. // 3 is empirical value.
  31913. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31914. startTick = Math.round(Math.ceil(startTick / step) * step);
  31915. }
  31916. // (1) Only add min max label here but leave overlap checking
  31917. // to render stage, which also ensure the returned list
  31918. // suitable for splitLine and splitArea rendering.
  31919. // (2) Scales except category always contain min max label so
  31920. // do not need to perform this process.
  31921. var showAllLabel = shouldShowAllLabels(axis);
  31922. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31923. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31924. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31925. addItem(ordinalExtent[0]);
  31926. }
  31927. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31928. var tickValue = startTick;
  31929. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31930. addItem(tickValue);
  31931. }
  31932. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  31933. addItem(ordinalExtent[1]);
  31934. }
  31935. function addItem(tVal) {
  31936. result.push(onlyTick
  31937. ? tVal
  31938. : {
  31939. formattedLabel: labelFormatter(tVal),
  31940. rawLabel: ordinalScale.getLabel(tVal),
  31941. tickValue: tVal
  31942. }
  31943. );
  31944. }
  31945. return result;
  31946. }
  31947. // When interval is function, the result `false` means ignore the tick.
  31948. // It is time consuming for large category data.
  31949. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31950. var ordinalScale = axis.scale;
  31951. var labelFormatter = makeLabelFormatter(axis);
  31952. var result = [];
  31953. each$1(ordinalScale.getTicks(), function (tickValue) {
  31954. var rawLabel = ordinalScale.getLabel(tickValue);
  31955. if (categoryInterval(tickValue, rawLabel)) {
  31956. result.push(onlyTick
  31957. ? tickValue
  31958. : {
  31959. formattedLabel: labelFormatter(tickValue),
  31960. rawLabel: rawLabel,
  31961. tickValue: tickValue
  31962. }
  31963. );
  31964. }
  31965. });
  31966. return result;
  31967. }
  31968. /*
  31969. * Licensed to the Apache Software Foundation (ASF) under one
  31970. * or more contributor license agreements. See the NOTICE file
  31971. * distributed with this work for additional information
  31972. * regarding copyright ownership. The ASF licenses this file
  31973. * to you under the Apache License, Version 2.0 (the
  31974. * "License"); you may not use this file except in compliance
  31975. * with the License. You may obtain a copy of the License at
  31976. *
  31977. * http://www.apache.org/licenses/LICENSE-2.0
  31978. *
  31979. * Unless required by applicable law or agreed to in writing,
  31980. * software distributed under the License is distributed on an
  31981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31982. * KIND, either express or implied. See the License for the
  31983. * specific language governing permissions and limitations
  31984. * under the License.
  31985. */
  31986. var NORMALIZED_EXTENT = [0, 1];
  31987. /**
  31988. * Base class of Axis.
  31989. * @constructor
  31990. */
  31991. var Axis = function (dim, scale, extent) {
  31992. /**
  31993. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  31994. * @type {string}
  31995. */
  31996. this.dim = dim;
  31997. /**
  31998. * Axis scale
  31999. * @type {module:echarts/coord/scale/*}
  32000. */
  32001. this.scale = scale;
  32002. /**
  32003. * @type {Array.<number>}
  32004. * @private
  32005. */
  32006. this._extent = extent || [0, 0];
  32007. /**
  32008. * @type {boolean}
  32009. */
  32010. this.inverse = false;
  32011. /**
  32012. * Usually true when axis has a ordinal scale
  32013. * @type {boolean}
  32014. */
  32015. this.onBand = false;
  32016. };
  32017. Axis.prototype = {
  32018. constructor: Axis,
  32019. /**
  32020. * If axis extent contain given coord
  32021. * @param {number} coord
  32022. * @return {boolean}
  32023. */
  32024. contain: function (coord) {
  32025. var extent = this._extent;
  32026. var min = Math.min(extent[0], extent[1]);
  32027. var max = Math.max(extent[0], extent[1]);
  32028. return coord >= min && coord <= max;
  32029. },
  32030. /**
  32031. * If axis extent contain given data
  32032. * @param {number} data
  32033. * @return {boolean}
  32034. */
  32035. containData: function (data) {
  32036. return this.scale.contain(data);
  32037. },
  32038. /**
  32039. * Get coord extent.
  32040. * @return {Array.<number>}
  32041. */
  32042. getExtent: function () {
  32043. return this._extent.slice();
  32044. },
  32045. /**
  32046. * Get precision used for formatting
  32047. * @param {Array.<number>} [dataExtent]
  32048. * @return {number}
  32049. */
  32050. getPixelPrecision: function (dataExtent) {
  32051. return getPixelPrecision(
  32052. dataExtent || this.scale.getExtent(),
  32053. this._extent
  32054. );
  32055. },
  32056. /**
  32057. * Set coord extent
  32058. * @param {number} start
  32059. * @param {number} end
  32060. */
  32061. setExtent: function (start, end) {
  32062. var extent = this._extent;
  32063. extent[0] = start;
  32064. extent[1] = end;
  32065. },
  32066. /**
  32067. * Convert data to coord. Data is the rank if it has an ordinal scale
  32068. * @param {number} data
  32069. * @param {boolean} clamp
  32070. * @return {number}
  32071. */
  32072. dataToCoord: function (data, clamp) {
  32073. var extent = this._extent;
  32074. var scale = this.scale;
  32075. data = scale.normalize(data);
  32076. if (this.onBand && scale.type === 'ordinal') {
  32077. extent = extent.slice();
  32078. fixExtentWithBands(extent, scale.count());
  32079. }
  32080. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32081. },
  32082. /**
  32083. * Convert coord to data. Data is the rank if it has an ordinal scale
  32084. * @param {number} coord
  32085. * @param {boolean} clamp
  32086. * @return {number}
  32087. */
  32088. coordToData: function (coord, clamp) {
  32089. var extent = this._extent;
  32090. var scale = this.scale;
  32091. if (this.onBand && scale.type === 'ordinal') {
  32092. extent = extent.slice();
  32093. fixExtentWithBands(extent, scale.count());
  32094. }
  32095. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32096. return this.scale.scale(t);
  32097. },
  32098. /**
  32099. * Convert pixel point to data in axis
  32100. * @param {Array.<number>} point
  32101. * @param {boolean} clamp
  32102. * @return {number} data
  32103. */
  32104. pointToData: function (point, clamp) {
  32105. // Should be implemented in derived class if necessary.
  32106. },
  32107. /**
  32108. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32109. * `axis.getTicksCoords` considers `onBand`, which is used by
  32110. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32111. * @param {Object} [opt]
  32112. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32113. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32114. * tick must be at the axis end points. Otherwise, clip ticks
  32115. * that outside the axis extent.
  32116. * @return {Array.<Object>} [{
  32117. * coord: ...,
  32118. * tickValue: ...
  32119. * }, ...]
  32120. */
  32121. getTicksCoords: function (opt) {
  32122. opt = opt || {};
  32123. var tickModel = opt.tickModel || this.getTickModel();
  32124. var result = createAxisTicks(this, tickModel);
  32125. var ticks = result.ticks;
  32126. var ticksCoords = map(ticks, function (tickValue) {
  32127. return {
  32128. coord: this.dataToCoord(tickValue),
  32129. tickValue: tickValue
  32130. };
  32131. }, this);
  32132. var alignWithLabel = tickModel.get('alignWithLabel');
  32133. fixOnBandTicksCoords(
  32134. this, ticksCoords, alignWithLabel, opt.clamp
  32135. );
  32136. return ticksCoords;
  32137. },
  32138. /**
  32139. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32140. */
  32141. getMinorTicksCoords: function () {
  32142. if (this.scale.type === 'ordinal') {
  32143. // Category axis doesn't support minor ticks
  32144. return [];
  32145. }
  32146. var minorTickModel = this.model.getModel('minorTick');
  32147. var splitNumber = minorTickModel.get('splitNumber');
  32148. // Protection.
  32149. if (!(splitNumber > 0 && splitNumber < 100)) {
  32150. splitNumber = 5;
  32151. }
  32152. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32153. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32154. return map(minorTicksGroup, function (minorTick) {
  32155. return {
  32156. coord: this.dataToCoord(minorTick),
  32157. tickValue: minorTick
  32158. };
  32159. }, this);
  32160. }, this);
  32161. return minorTicksCoords;
  32162. },
  32163. /**
  32164. * @return {Array.<Object>} [{
  32165. * formattedLabel: string,
  32166. * rawLabel: axis.scale.getLabel(tickValue)
  32167. * tickValue: number
  32168. * }, ...]
  32169. */
  32170. getViewLabels: function () {
  32171. return createAxisLabels(this).labels;
  32172. },
  32173. /**
  32174. * @return {module:echarts/coord/model/Model}
  32175. */
  32176. getLabelModel: function () {
  32177. return this.model.getModel('axisLabel');
  32178. },
  32179. /**
  32180. * Notice here we only get the default tick model. For splitLine
  32181. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32182. * manually when calling `getTicksCoords`.
  32183. * In GL, this method may be overrided to:
  32184. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32185. * @return {module:echarts/coord/model/Model}
  32186. */
  32187. getTickModel: function () {
  32188. return this.model.getModel('axisTick');
  32189. },
  32190. /**
  32191. * Get width of band
  32192. * @return {number}
  32193. */
  32194. getBandWidth: function () {
  32195. var axisExtent = this._extent;
  32196. var dataExtent = this.scale.getExtent();
  32197. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32198. // Fix #2728, avoid NaN when only one data.
  32199. len === 0 && (len = 1);
  32200. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32201. return Math.abs(size) / len;
  32202. },
  32203. /**
  32204. * @abstract
  32205. * @return {boolean} Is horizontal
  32206. */
  32207. isHorizontal: null,
  32208. /**
  32209. * @abstract
  32210. * @return {number} Get axis rotate, by degree.
  32211. */
  32212. getRotate: null,
  32213. /**
  32214. * Only be called in category axis.
  32215. * Can be overrided, consider other axes like in 3D.
  32216. * @return {number} Auto interval for cateogry axis tick and label
  32217. */
  32218. calculateCategoryInterval: function () {
  32219. return calculateCategoryInterval(this);
  32220. }
  32221. };
  32222. function fixExtentWithBands(extent, nTick) {
  32223. var size = extent[1] - extent[0];
  32224. var len = nTick;
  32225. var margin = size / len / 2;
  32226. extent[0] += margin;
  32227. extent[1] -= margin;
  32228. }
  32229. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32230. // |---1---|---2---|---3---|---4---|.
  32231. // So the displayed ticks and splitLine/splitArea should between
  32232. // each data item, otherwise cause misleading (e.g., split tow bars
  32233. // of a single data item when there are two bar series).
  32234. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32235. // splitLine/spliteArea should layout appropriately corresponding
  32236. // to displayed labels. (So we should not use `getBandWidth` in this
  32237. // case).
  32238. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32239. var ticksLen = ticksCoords.length;
  32240. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32241. return;
  32242. }
  32243. var axisExtent = axis.getExtent();
  32244. var last;
  32245. var diffSize;
  32246. if (ticksLen === 1) {
  32247. ticksCoords[0].coord = axisExtent[0];
  32248. last = ticksCoords[1] = {coord: axisExtent[0]};
  32249. }
  32250. else {
  32251. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32252. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32253. each$1(ticksCoords, function (ticksItem) {
  32254. ticksItem.coord -= shift / 2;
  32255. });
  32256. var dataExtent = axis.scale.getExtent();
  32257. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32258. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32259. ticksCoords.push(last);
  32260. }
  32261. var inverse = axisExtent[0] > axisExtent[1];
  32262. // Handling clamp.
  32263. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32264. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32265. }
  32266. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32267. ticksCoords.unshift({coord: axisExtent[0]});
  32268. }
  32269. if (littleThan(axisExtent[1], last.coord)) {
  32270. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32271. }
  32272. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32273. ticksCoords.push({coord: axisExtent[1]});
  32274. }
  32275. function littleThan(a, b) {
  32276. // Avoid rounding error cause calculated tick coord different with extent.
  32277. // It may cause an extra unecessary tick added.
  32278. a = round$1(a);
  32279. b = round$1(b);
  32280. return inverse ? a > b : a < b;
  32281. }
  32282. }
  32283. /*
  32284. * Licensed to the Apache Software Foundation (ASF) under one
  32285. * or more contributor license agreements. See the NOTICE file
  32286. * distributed with this work for additional information
  32287. * regarding copyright ownership. The ASF licenses this file
  32288. * to you under the Apache License, Version 2.0 (the
  32289. * "License"); you may not use this file except in compliance
  32290. * with the License. You may obtain a copy of the License at
  32291. *
  32292. * http://www.apache.org/licenses/LICENSE-2.0
  32293. *
  32294. * Unless required by applicable law or agreed to in writing,
  32295. * software distributed under the License is distributed on an
  32296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32297. * KIND, either express or implied. See the License for the
  32298. * specific language governing permissions and limitations
  32299. * under the License.
  32300. */
  32301. /**
  32302. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32303. */
  32304. var parseGeoJson = parseGeoJSON;
  32305. var ecUtil = {};
  32306. each$1(
  32307. [
  32308. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32309. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32310. 'extend', 'defaults', 'clone', 'merge'
  32311. ],
  32312. function (name) {
  32313. ecUtil[name] = zrUtil[name];
  32314. }
  32315. );
  32316. var graphic$1 = {};
  32317. each$1(
  32318. [
  32319. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32320. 'mergePath', 'resizePath', 'createIcon',
  32321. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32322. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32323. 'clipPointsByRect', 'clipRectByRect',
  32324. 'registerShape', 'getShapeClass',
  32325. 'Group',
  32326. 'Image',
  32327. 'Text',
  32328. 'Circle',
  32329. 'Sector',
  32330. 'Ring',
  32331. 'Polygon',
  32332. 'Polyline',
  32333. 'Rect',
  32334. 'Line',
  32335. 'BezierCurve',
  32336. 'Arc',
  32337. 'IncrementalDisplayable',
  32338. 'CompoundPath',
  32339. 'LinearGradient',
  32340. 'RadialGradient',
  32341. 'BoundingRect'
  32342. ],
  32343. function (name) {
  32344. graphic$1[name] = graphic[name];
  32345. }
  32346. );
  32347. /*
  32348. * Licensed to the Apache Software Foundation (ASF) under one
  32349. * or more contributor license agreements. See the NOTICE file
  32350. * distributed with this work for additional information
  32351. * regarding copyright ownership. The ASF licenses this file
  32352. * to you under the Apache License, Version 2.0 (the
  32353. * "License"); you may not use this file except in compliance
  32354. * with the License. You may obtain a copy of the License at
  32355. *
  32356. * http://www.apache.org/licenses/LICENSE-2.0
  32357. *
  32358. * Unless required by applicable law or agreed to in writing,
  32359. * software distributed under the License is distributed on an
  32360. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32361. * KIND, either express or implied. See the License for the
  32362. * specific language governing permissions and limitations
  32363. * under the License.
  32364. */
  32365. SeriesModel.extend({
  32366. type: 'series.line',
  32367. dependencies: ['grid', 'polar'],
  32368. getInitialData: function (option, ecModel) {
  32369. if (__DEV__) {
  32370. var coordSys = option.coordinateSystem;
  32371. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32372. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32373. }
  32374. }
  32375. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32376. },
  32377. defaultOption: {
  32378. zlevel: 0,
  32379. z: 2,
  32380. coordinateSystem: 'cartesian2d',
  32381. legendHoverLink: true,
  32382. hoverAnimation: true,
  32383. // stack: null
  32384. // xAxisIndex: 0,
  32385. // yAxisIndex: 0,
  32386. // polarIndex: 0,
  32387. // If clip the overflow value
  32388. clip: true,
  32389. // cursor: null,
  32390. label: {
  32391. position: 'top'
  32392. },
  32393. // itemStyle: {
  32394. // },
  32395. lineStyle: {
  32396. width: 2,
  32397. type: 'solid'
  32398. },
  32399. // areaStyle: {
  32400. // origin of areaStyle. Valid values:
  32401. // `'auto'/null/undefined`: from axisLine to data
  32402. // `'start'`: from min to data
  32403. // `'end'`: from data to max
  32404. // origin: 'auto'
  32405. // },
  32406. // false, 'start', 'end', 'middle'
  32407. step: false,
  32408. // Disabled if step is true
  32409. smooth: false,
  32410. smoothMonotone: null,
  32411. symbol: 'emptyCircle',
  32412. symbolSize: 4,
  32413. symbolRotate: null,
  32414. showSymbol: true,
  32415. // `false`: follow the label interval strategy.
  32416. // `true`: show all symbols.
  32417. // `'auto'`: If possible, show all symbols, otherwise
  32418. // follow the label interval strategy.
  32419. showAllSymbol: 'auto',
  32420. // Whether to connect break point.
  32421. connectNulls: false,
  32422. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32423. sampling: 'none',
  32424. animationEasing: 'linear',
  32425. // Disable progressive
  32426. progressive: 0,
  32427. hoverLayerThreshold: Infinity
  32428. }
  32429. });
  32430. /*
  32431. * Licensed to the Apache Software Foundation (ASF) under one
  32432. * or more contributor license agreements. See the NOTICE file
  32433. * distributed with this work for additional information
  32434. * regarding copyright ownership. The ASF licenses this file
  32435. * to you under the Apache License, Version 2.0 (the
  32436. * "License"); you may not use this file except in compliance
  32437. * with the License. You may obtain a copy of the License at
  32438. *
  32439. * http://www.apache.org/licenses/LICENSE-2.0
  32440. *
  32441. * Unless required by applicable law or agreed to in writing,
  32442. * software distributed under the License is distributed on an
  32443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32444. * KIND, either express or implied. See the License for the
  32445. * specific language governing permissions and limitations
  32446. * under the License.
  32447. */
  32448. /**
  32449. * @param {module:echarts/data/List} data
  32450. * @param {number} dataIndex
  32451. * @return {string} label string. Not null/undefined
  32452. */
  32453. function getDefaultLabel(data, dataIndex) {
  32454. var labelDims = data.mapDimension('defaultedLabel', true);
  32455. var len = labelDims.length;
  32456. // Simple optimization (in lots of cases, label dims length is 1)
  32457. if (len === 1) {
  32458. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32459. }
  32460. else if (len) {
  32461. var vals = [];
  32462. for (var i = 0; i < labelDims.length; i++) {
  32463. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32464. vals.push(val);
  32465. }
  32466. return vals.join(' ');
  32467. }
  32468. }
  32469. /*
  32470. * Licensed to the Apache Software Foundation (ASF) under one
  32471. * or more contributor license agreements. See the NOTICE file
  32472. * distributed with this work for additional information
  32473. * regarding copyright ownership. The ASF licenses this file
  32474. * to you under the Apache License, Version 2.0 (the
  32475. * "License"); you may not use this file except in compliance
  32476. * with the License. You may obtain a copy of the License at
  32477. *
  32478. * http://www.apache.org/licenses/LICENSE-2.0
  32479. *
  32480. * Unless required by applicable law or agreed to in writing,
  32481. * software distributed under the License is distributed on an
  32482. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32483. * KIND, either express or implied. See the License for the
  32484. * specific language governing permissions and limitations
  32485. * under the License.
  32486. */
  32487. /**
  32488. * @module echarts/chart/helper/Symbol
  32489. */
  32490. /**
  32491. * @constructor
  32492. * @alias {module:echarts/chart/helper/Symbol}
  32493. * @param {module:echarts/data/List} data
  32494. * @param {number} idx
  32495. * @extends {module:zrender/graphic/Group}
  32496. */
  32497. function SymbolClz$1(data, idx, seriesScope) {
  32498. Group.call(this);
  32499. this.updateData(data, idx, seriesScope);
  32500. }
  32501. var symbolProto = SymbolClz$1.prototype;
  32502. /**
  32503. * @public
  32504. * @static
  32505. * @param {module:echarts/data/List} data
  32506. * @param {number} dataIndex
  32507. * @return {Array.<number>} [width, height]
  32508. */
  32509. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32510. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32511. return symbolSize instanceof Array
  32512. ? symbolSize.slice()
  32513. : [+symbolSize, +symbolSize];
  32514. };
  32515. function getScale(symbolSize) {
  32516. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32517. }
  32518. function driftSymbol(dx, dy) {
  32519. this.parent.drift(dx, dy);
  32520. }
  32521. symbolProto._createSymbol = function (
  32522. symbolType,
  32523. data,
  32524. idx,
  32525. symbolSize,
  32526. keepAspect
  32527. ) {
  32528. // Remove paths created before
  32529. this.removeAll();
  32530. var color = data.getItemVisual(idx, 'color');
  32531. // var symbolPath = createSymbol(
  32532. // symbolType, -0.5, -0.5, 1, 1, color
  32533. // );
  32534. // If width/height are set too small (e.g., set to 1) on ios10
  32535. // and macOS Sierra, a circle stroke become a rect, no matter what
  32536. // the scale is set. So we set width/height as 2. See #4150.
  32537. var symbolPath = createSymbol(
  32538. symbolType, -1, -1, 2, 2, color, keepAspect
  32539. );
  32540. symbolPath.attr({
  32541. z2: 100,
  32542. culling: true,
  32543. scale: getScale(symbolSize)
  32544. });
  32545. // Rewrite drift method
  32546. symbolPath.drift = driftSymbol;
  32547. this._symbolType = symbolType;
  32548. this.add(symbolPath);
  32549. };
  32550. /**
  32551. * Stop animation
  32552. * @param {boolean} toLastFrame
  32553. */
  32554. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32555. this.childAt(0).stopAnimation(toLastFrame);
  32556. };
  32557. /**
  32558. * FIXME:
  32559. * Caution: This method breaks the encapsulation of this module,
  32560. * but it indeed brings convenience. So do not use the method
  32561. * unless you detailedly know all the implements of `Symbol`,
  32562. * especially animation.
  32563. *
  32564. * Get symbol path element.
  32565. */
  32566. symbolProto.getSymbolPath = function () {
  32567. return this.childAt(0);
  32568. };
  32569. /**
  32570. * Get scale(aka, current symbol size).
  32571. * Including the change caused by animation
  32572. */
  32573. symbolProto.getScale = function () {
  32574. return this.childAt(0).scale;
  32575. };
  32576. /**
  32577. * Highlight symbol
  32578. */
  32579. symbolProto.highlight = function () {
  32580. this.childAt(0).trigger('emphasis');
  32581. };
  32582. /**
  32583. * Downplay symbol
  32584. */
  32585. symbolProto.downplay = function () {
  32586. this.childAt(0).trigger('normal');
  32587. };
  32588. /**
  32589. * @param {number} zlevel
  32590. * @param {number} z
  32591. */
  32592. symbolProto.setZ = function (zlevel, z) {
  32593. var symbolPath = this.childAt(0);
  32594. symbolPath.zlevel = zlevel;
  32595. symbolPath.z = z;
  32596. };
  32597. symbolProto.setDraggable = function (draggable) {
  32598. var symbolPath = this.childAt(0);
  32599. symbolPath.draggable = draggable;
  32600. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32601. };
  32602. /**
  32603. * Update symbol properties
  32604. * @param {module:echarts/data/List} data
  32605. * @param {number} idx
  32606. * @param {Object} [seriesScope]
  32607. * @param {Object} [seriesScope.itemStyle]
  32608. * @param {Object} [seriesScope.hoverItemStyle]
  32609. * @param {Object} [seriesScope.symbolRotate]
  32610. * @param {Object} [seriesScope.symbolOffset]
  32611. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32612. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32613. * @param {boolean} [seriesScope.hoverAnimation]
  32614. * @param {Object} [seriesScope.cursorStyle]
  32615. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32616. * @param {string} [seriesScope.symbolInnerColor]
  32617. * @param {Object} [seriesScope.fadeIn=false]
  32618. */
  32619. symbolProto.updateData = function (data, idx, seriesScope) {
  32620. this.silent = false;
  32621. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32622. var seriesModel = data.hostModel;
  32623. var symbolSize = getSymbolSize(data, idx);
  32624. var isInit = symbolType !== this._symbolType;
  32625. if (isInit) {
  32626. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32627. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32628. }
  32629. else {
  32630. var symbolPath = this.childAt(0);
  32631. symbolPath.silent = false;
  32632. updateProps(symbolPath, {
  32633. scale: getScale(symbolSize)
  32634. }, seriesModel, idx);
  32635. }
  32636. this._updateCommon(data, idx, symbolSize, seriesScope);
  32637. if (isInit) {
  32638. var symbolPath = this.childAt(0);
  32639. var fadeIn = seriesScope && seriesScope.fadeIn;
  32640. var target = {scale: symbolPath.scale.slice()};
  32641. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32642. symbolPath.scale = [0, 0];
  32643. fadeIn && (symbolPath.style.opacity = 0);
  32644. initProps(symbolPath, target, seriesModel, idx);
  32645. }
  32646. this._seriesModel = seriesModel;
  32647. };
  32648. // Update common properties
  32649. var normalStyleAccessPath = ['itemStyle'];
  32650. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32651. var normalLabelAccessPath = ['label'];
  32652. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32653. /**
  32654. * @param {module:echarts/data/List} data
  32655. * @param {number} idx
  32656. * @param {Array.<number>} symbolSize
  32657. * @param {Object} [seriesScope]
  32658. */
  32659. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32660. var symbolPath = this.childAt(0);
  32661. var seriesModel = data.hostModel;
  32662. var color = data.getItemVisual(idx, 'color');
  32663. // Reset style
  32664. if (symbolPath.type !== 'image') {
  32665. symbolPath.useStyle({
  32666. strokeNoScale: true
  32667. });
  32668. }
  32669. else {
  32670. symbolPath.setStyle({
  32671. opacity: null,
  32672. shadowBlur: null,
  32673. shadowOffsetX: null,
  32674. shadowOffsetY: null,
  32675. shadowColor: null
  32676. });
  32677. }
  32678. var itemStyle = seriesScope && seriesScope.itemStyle;
  32679. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32680. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  32681. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32682. var labelModel = seriesScope && seriesScope.labelModel;
  32683. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32684. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32685. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32686. if (!seriesScope || data.hasItemOption) {
  32687. var itemModel = (seriesScope && seriesScope.itemModel)
  32688. ? seriesScope.itemModel : data.getItemModel(idx);
  32689. // Color must be excluded.
  32690. // Because symbol provide setColor individually to set fill and stroke
  32691. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32692. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32693. symbolRotate = itemModel.getShallow('symbolRotate');
  32694. symbolOffset = itemModel.getShallow('symbolOffset');
  32695. labelModel = itemModel.getModel(normalLabelAccessPath);
  32696. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32697. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32698. cursorStyle = itemModel.getShallow('cursor');
  32699. }
  32700. else {
  32701. hoverItemStyle = extend({}, hoverItemStyle);
  32702. }
  32703. var elStyle = symbolPath.style;
  32704. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32705. if (symbolOffset) {
  32706. symbolPath.attr('position', [
  32707. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32708. parsePercent$1(symbolOffset[1], symbolSize[1])
  32709. ]);
  32710. }
  32711. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32712. // PENDING setColor before setStyle!!!
  32713. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32714. symbolPath.setStyle(itemStyle);
  32715. var opacity = data.getItemVisual(idx, 'opacity');
  32716. if (opacity != null) {
  32717. elStyle.opacity = opacity;
  32718. }
  32719. var liftZ = data.getItemVisual(idx, 'liftZ');
  32720. var z2Origin = symbolPath.__z2Origin;
  32721. if (liftZ != null) {
  32722. if (z2Origin == null) {
  32723. symbolPath.__z2Origin = symbolPath.z2;
  32724. symbolPath.z2 += liftZ;
  32725. }
  32726. }
  32727. else if (z2Origin != null) {
  32728. symbolPath.z2 = z2Origin;
  32729. symbolPath.__z2Origin = null;
  32730. }
  32731. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32732. setLabelStyle(
  32733. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32734. {
  32735. labelFetcher: seriesModel,
  32736. labelDataIndex: idx,
  32737. defaultText: getLabelDefaultText,
  32738. isRectText: true,
  32739. autoColor: color
  32740. }
  32741. );
  32742. // Do not execute util needed.
  32743. function getLabelDefaultText(idx, opt) {
  32744. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32745. }
  32746. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32747. symbolPath.hoverStyle = hoverItemStyle;
  32748. symbolPath.highDownOnUpdate = (
  32749. hoverAnimation && seriesModel.isAnimationEnabled()
  32750. ) ? highDownOnUpdate : null;
  32751. setHoverStyle(symbolPath);
  32752. };
  32753. function highDownOnUpdate(fromState, toState) {
  32754. // Do not support this hover animation util some scenario required.
  32755. // Animation can only be supported in hover layer when using `el.incremetal`.
  32756. if (this.incremental || this.useHoverLayer) {
  32757. return;
  32758. }
  32759. if (toState === 'emphasis') {
  32760. var scale = this.__symbolOriginalScale;
  32761. var ratio = scale[1] / scale[0];
  32762. var emphasisOpt = {
  32763. scale: [
  32764. Math.max(scale[0] * 1.1, scale[0] + 3),
  32765. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32766. ]
  32767. };
  32768. // FIXME
  32769. // modify it after support stop specified animation.
  32770. // toState === fromState
  32771. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32772. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32773. }
  32774. else if (toState === 'normal') {
  32775. this.animateTo({
  32776. scale: this.__symbolOriginalScale
  32777. }, 400, 'elasticOut');
  32778. }
  32779. }
  32780. /**
  32781. * @param {Function} cb
  32782. * @param {Object} [opt]
  32783. * @param {Object} [opt.keepLabel=true]
  32784. */
  32785. symbolProto.fadeOut = function (cb, opt) {
  32786. var symbolPath = this.childAt(0);
  32787. // Avoid mistaken hover when fading out
  32788. this.silent = symbolPath.silent = true;
  32789. // Not show text when animating
  32790. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32791. updateProps(
  32792. symbolPath,
  32793. {
  32794. style: {opacity: 0},
  32795. scale: [0, 0]
  32796. },
  32797. this._seriesModel,
  32798. this.dataIndex,
  32799. cb
  32800. );
  32801. };
  32802. inherits(SymbolClz$1, Group);
  32803. /*
  32804. * Licensed to the Apache Software Foundation (ASF) under one
  32805. * or more contributor license agreements. See the NOTICE file
  32806. * distributed with this work for additional information
  32807. * regarding copyright ownership. The ASF licenses this file
  32808. * to you under the Apache License, Version 2.0 (the
  32809. * "License"); you may not use this file except in compliance
  32810. * with the License. You may obtain a copy of the License at
  32811. *
  32812. * http://www.apache.org/licenses/LICENSE-2.0
  32813. *
  32814. * Unless required by applicable law or agreed to in writing,
  32815. * software distributed under the License is distributed on an
  32816. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32817. * KIND, either express or implied. See the License for the
  32818. * specific language governing permissions and limitations
  32819. * under the License.
  32820. */
  32821. /**
  32822. * @module echarts/chart/helper/SymbolDraw
  32823. */
  32824. /**
  32825. * @constructor
  32826. * @alias module:echarts/chart/helper/SymbolDraw
  32827. * @param {module:zrender/graphic/Group} [symbolCtor]
  32828. */
  32829. function SymbolDraw(symbolCtor) {
  32830. this.group = new Group();
  32831. this._symbolCtor = symbolCtor || SymbolClz$1;
  32832. }
  32833. var symbolDrawProto = SymbolDraw.prototype;
  32834. function symbolNeedsDraw(data, point, idx, opt) {
  32835. return point && !isNaN(point[0]) && !isNaN(point[1])
  32836. && !(opt.isIgnore && opt.isIgnore(idx))
  32837. // We do not set clipShape on group, because it will cut part of
  32838. // the symbol element shape. We use the same clip shape here as
  32839. // the line clip.
  32840. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  32841. && data.getItemVisual(idx, 'symbol') !== 'none';
  32842. }
  32843. /**
  32844. * Update symbols draw by new data
  32845. * @param {module:echarts/data/List} data
  32846. * @param {Object} [opt] Or isIgnore
  32847. * @param {Function} [opt.isIgnore]
  32848. * @param {Object} [opt.clipShape]
  32849. */
  32850. symbolDrawProto.updateData = function (data, opt) {
  32851. opt = normalizeUpdateOpt(opt);
  32852. var group = this.group;
  32853. var seriesModel = data.hostModel;
  32854. var oldData = this._data;
  32855. var SymbolCtor = this._symbolCtor;
  32856. var seriesScope = makeSeriesScope(data);
  32857. // There is no oldLineData only when first rendering or switching from
  32858. // stream mode to normal mode, where previous elements should be removed.
  32859. if (!oldData) {
  32860. group.removeAll();
  32861. }
  32862. data.diff(oldData)
  32863. .add(function (newIdx) {
  32864. var point = data.getItemLayout(newIdx);
  32865. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  32866. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  32867. symbolEl.attr('position', point);
  32868. data.setItemGraphicEl(newIdx, symbolEl);
  32869. group.add(symbolEl);
  32870. }
  32871. })
  32872. .update(function (newIdx, oldIdx) {
  32873. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32874. var point = data.getItemLayout(newIdx);
  32875. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  32876. group.remove(symbolEl);
  32877. return;
  32878. }
  32879. if (!symbolEl) {
  32880. symbolEl = new SymbolCtor(data, newIdx);
  32881. symbolEl.attr('position', point);
  32882. }
  32883. else {
  32884. symbolEl.updateData(data, newIdx, seriesScope);
  32885. updateProps(symbolEl, {
  32886. position: point
  32887. }, seriesModel);
  32888. }
  32889. // Add back
  32890. group.add(symbolEl);
  32891. data.setItemGraphicEl(newIdx, symbolEl);
  32892. })
  32893. .remove(function (oldIdx) {
  32894. var el = oldData.getItemGraphicEl(oldIdx);
  32895. el && el.fadeOut(function () {
  32896. group.remove(el);
  32897. });
  32898. })
  32899. .execute();
  32900. this._data = data;
  32901. };
  32902. symbolDrawProto.isPersistent = function () {
  32903. return true;
  32904. };
  32905. symbolDrawProto.updateLayout = function () {
  32906. var data = this._data;
  32907. if (data) {
  32908. // Not use animation
  32909. data.eachItemGraphicEl(function (el, idx) {
  32910. var point = data.getItemLayout(idx);
  32911. el.attr('position', point);
  32912. });
  32913. }
  32914. };
  32915. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  32916. this._seriesScope = makeSeriesScope(data);
  32917. this._data = null;
  32918. this.group.removeAll();
  32919. };
  32920. /**
  32921. * Update symbols draw by new data
  32922. * @param {module:echarts/data/List} data
  32923. * @param {Object} [opt] Or isIgnore
  32924. * @param {Function} [opt.isIgnore]
  32925. * @param {Object} [opt.clipShape]
  32926. */
  32927. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  32928. opt = normalizeUpdateOpt(opt);
  32929. function updateIncrementalAndHover(el) {
  32930. if (!el.isGroup) {
  32931. el.incremental = el.useHoverLayer = true;
  32932. }
  32933. }
  32934. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  32935. var point = data.getItemLayout(idx);
  32936. if (symbolNeedsDraw(data, point, idx, opt)) {
  32937. var el = new this._symbolCtor(data, idx, this._seriesScope);
  32938. el.traverse(updateIncrementalAndHover);
  32939. el.attr('position', point);
  32940. this.group.add(el);
  32941. data.setItemGraphicEl(idx, el);
  32942. }
  32943. }
  32944. };
  32945. function normalizeUpdateOpt(opt) {
  32946. if (opt != null && !isObject$1(opt)) {
  32947. opt = {isIgnore: opt};
  32948. }
  32949. return opt || {};
  32950. }
  32951. symbolDrawProto.remove = function (enableAnimation) {
  32952. var group = this.group;
  32953. var data = this._data;
  32954. // Incremental model do not have this._data.
  32955. if (data && enableAnimation) {
  32956. data.eachItemGraphicEl(function (el) {
  32957. el.fadeOut(function () {
  32958. group.remove(el);
  32959. });
  32960. });
  32961. }
  32962. else {
  32963. group.removeAll();
  32964. }
  32965. };
  32966. function makeSeriesScope(data) {
  32967. var seriesModel = data.hostModel;
  32968. return {
  32969. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  32970. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  32971. symbolRotate: seriesModel.get('symbolRotate'),
  32972. symbolOffset: seriesModel.get('symbolOffset'),
  32973. hoverAnimation: seriesModel.get('hoverAnimation'),
  32974. labelModel: seriesModel.getModel('label'),
  32975. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  32976. cursorStyle: seriesModel.get('cursor')
  32977. };
  32978. }
  32979. /*
  32980. * Licensed to the Apache Software Foundation (ASF) under one
  32981. * or more contributor license agreements. See the NOTICE file
  32982. * distributed with this work for additional information
  32983. * regarding copyright ownership. The ASF licenses this file
  32984. * to you under the Apache License, Version 2.0 (the
  32985. * "License"); you may not use this file except in compliance
  32986. * with the License. You may obtain a copy of the License at
  32987. *
  32988. * http://www.apache.org/licenses/LICENSE-2.0
  32989. *
  32990. * Unless required by applicable law or agreed to in writing,
  32991. * software distributed under the License is distributed on an
  32992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32993. * KIND, either express or implied. See the License for the
  32994. * specific language governing permissions and limitations
  32995. * under the License.
  32996. */
  32997. /**
  32998. * @param {Object} coordSys
  32999. * @param {module:echarts/data/List} data
  33000. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33001. */
  33002. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33003. var baseAxis = coordSys.getBaseAxis();
  33004. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33005. var valueStart = getValueStart(valueAxis, valueOrigin);
  33006. var baseAxisDim = baseAxis.dim;
  33007. var valueAxisDim = valueAxis.dim;
  33008. var valueDim = data.mapDimension(valueAxisDim);
  33009. var baseDim = data.mapDimension(baseAxisDim);
  33010. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33011. var dims = map(coordSys.dimensions, function (coordDim) {
  33012. return data.mapDimension(coordDim);
  33013. });
  33014. var stacked;
  33015. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33016. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33017. dims[0] = stackResultDim;
  33018. }
  33019. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33020. dims[1] = stackResultDim;
  33021. }
  33022. return {
  33023. dataDimsForPoint: dims,
  33024. valueStart: valueStart,
  33025. valueAxisDim: valueAxisDim,
  33026. baseAxisDim: baseAxisDim,
  33027. stacked: !!stacked,
  33028. valueDim: valueDim,
  33029. baseDim: baseDim,
  33030. baseDataOffset: baseDataOffset,
  33031. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33032. };
  33033. }
  33034. function getValueStart(valueAxis, valueOrigin) {
  33035. var valueStart = 0;
  33036. var extent = valueAxis.scale.getExtent();
  33037. if (valueOrigin === 'start') {
  33038. valueStart = extent[0];
  33039. }
  33040. else if (valueOrigin === 'end') {
  33041. valueStart = extent[1];
  33042. }
  33043. // auto
  33044. else {
  33045. // Both positive
  33046. if (extent[0] > 0) {
  33047. valueStart = extent[0];
  33048. }
  33049. // Both negative
  33050. else if (extent[1] < 0) {
  33051. valueStart = extent[1];
  33052. }
  33053. // If is one positive, and one negative, onZero shall be true
  33054. }
  33055. return valueStart;
  33056. }
  33057. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33058. var value = NaN;
  33059. if (dataCoordInfo.stacked) {
  33060. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33061. }
  33062. if (isNaN(value)) {
  33063. value = dataCoordInfo.valueStart;
  33064. }
  33065. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33066. var stackedData = [];
  33067. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33068. stackedData[1 - baseDataOffset] = value;
  33069. return coordSys.dataToPoint(stackedData);
  33070. }
  33071. /*
  33072. * Licensed to the Apache Software Foundation (ASF) under one
  33073. * or more contributor license agreements. See the NOTICE file
  33074. * distributed with this work for additional information
  33075. * regarding copyright ownership. The ASF licenses this file
  33076. * to you under the Apache License, Version 2.0 (the
  33077. * "License"); you may not use this file except in compliance
  33078. * with the License. You may obtain a copy of the License at
  33079. *
  33080. * http://www.apache.org/licenses/LICENSE-2.0
  33081. *
  33082. * Unless required by applicable law or agreed to in writing,
  33083. * software distributed under the License is distributed on an
  33084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33085. * KIND, either express or implied. See the License for the
  33086. * specific language governing permissions and limitations
  33087. * under the License.
  33088. */
  33089. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33090. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33091. // not do well in performance when roam with fixed dataZoom window.
  33092. // function convertToIntId(newIdList, oldIdList) {
  33093. // // Generate int id instead of string id.
  33094. // // Compare string maybe slow in score function of arrDiff
  33095. // // Assume id in idList are all unique
  33096. // var idIndicesMap = {};
  33097. // var idx = 0;
  33098. // for (var i = 0; i < newIdList.length; i++) {
  33099. // idIndicesMap[newIdList[i]] = idx;
  33100. // newIdList[i] = idx++;
  33101. // }
  33102. // for (var i = 0; i < oldIdList.length; i++) {
  33103. // var oldId = oldIdList[i];
  33104. // // Same with newIdList
  33105. // if (idIndicesMap[oldId]) {
  33106. // oldIdList[i] = idIndicesMap[oldId];
  33107. // }
  33108. // else {
  33109. // oldIdList[i] = idx++;
  33110. // }
  33111. // }
  33112. // }
  33113. function diffData(oldData, newData) {
  33114. var diffResult = [];
  33115. newData.diff(oldData)
  33116. .add(function (idx) {
  33117. diffResult.push({cmd: '+', idx: idx});
  33118. })
  33119. .update(function (newIdx, oldIdx) {
  33120. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33121. })
  33122. .remove(function (idx) {
  33123. diffResult.push({cmd: '-', idx: idx});
  33124. })
  33125. .execute();
  33126. return diffResult;
  33127. }
  33128. var lineAnimationDiff = function (
  33129. oldData, newData,
  33130. oldStackedOnPoints, newStackedOnPoints,
  33131. oldCoordSys, newCoordSys,
  33132. oldValueOrigin, newValueOrigin
  33133. ) {
  33134. var diff = diffData(oldData, newData);
  33135. // var newIdList = newData.mapArray(newData.getId);
  33136. // var oldIdList = oldData.mapArray(oldData.getId);
  33137. // convertToIntId(newIdList, oldIdList);
  33138. // // FIXME One data ?
  33139. // diff = arrayDiff(oldIdList, newIdList);
  33140. var currPoints = [];
  33141. var nextPoints = [];
  33142. // Points for stacking base line
  33143. var currStackedPoints = [];
  33144. var nextStackedPoints = [];
  33145. var status = [];
  33146. var sortedIndices = [];
  33147. var rawIndices = [];
  33148. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33149. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33150. for (var i = 0; i < diff.length; i++) {
  33151. var diffItem = diff[i];
  33152. var pointAdded = true;
  33153. // FIXME, animation is not so perfect when dataZoom window moves fast
  33154. // Which is in case remvoing or add more than one data in the tail or head
  33155. switch (diffItem.cmd) {
  33156. case '=':
  33157. var currentPt = oldData.getItemLayout(diffItem.idx);
  33158. var nextPt = newData.getItemLayout(diffItem.idx1);
  33159. // If previous data is NaN, use next point directly
  33160. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33161. currentPt = nextPt.slice();
  33162. }
  33163. currPoints.push(currentPt);
  33164. nextPoints.push(nextPt);
  33165. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33166. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33167. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33168. break;
  33169. case '+':
  33170. var idx = diffItem.idx;
  33171. currPoints.push(
  33172. oldCoordSys.dataToPoint([
  33173. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33174. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33175. ])
  33176. );
  33177. nextPoints.push(newData.getItemLayout(idx).slice());
  33178. currStackedPoints.push(
  33179. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33180. );
  33181. nextStackedPoints.push(newStackedOnPoints[idx]);
  33182. rawIndices.push(newData.getRawIndex(idx));
  33183. break;
  33184. case '-':
  33185. var idx = diffItem.idx;
  33186. var rawIndex = oldData.getRawIndex(idx);
  33187. // Data is replaced. In the case of dynamic data queue
  33188. // FIXME FIXME FIXME
  33189. if (rawIndex !== idx) {
  33190. currPoints.push(oldData.getItemLayout(idx));
  33191. nextPoints.push(newCoordSys.dataToPoint([
  33192. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33193. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33194. ]));
  33195. currStackedPoints.push(oldStackedOnPoints[idx]);
  33196. nextStackedPoints.push(
  33197. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33198. );
  33199. rawIndices.push(rawIndex);
  33200. }
  33201. else {
  33202. pointAdded = false;
  33203. }
  33204. }
  33205. // Original indices
  33206. if (pointAdded) {
  33207. status.push(diffItem);
  33208. sortedIndices.push(sortedIndices.length);
  33209. }
  33210. }
  33211. // Diff result may be crossed if all items are changed
  33212. // Sort by data index
  33213. sortedIndices.sort(function (a, b) {
  33214. return rawIndices[a] - rawIndices[b];
  33215. });
  33216. var sortedCurrPoints = [];
  33217. var sortedNextPoints = [];
  33218. var sortedCurrStackedPoints = [];
  33219. var sortedNextStackedPoints = [];
  33220. var sortedStatus = [];
  33221. for (var i = 0; i < sortedIndices.length; i++) {
  33222. var idx = sortedIndices[i];
  33223. sortedCurrPoints[i] = currPoints[idx];
  33224. sortedNextPoints[i] = nextPoints[idx];
  33225. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33226. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33227. sortedStatus[i] = status[idx];
  33228. }
  33229. return {
  33230. current: sortedCurrPoints,
  33231. next: sortedNextPoints,
  33232. stackedOnCurrent: sortedCurrStackedPoints,
  33233. stackedOnNext: sortedNextStackedPoints,
  33234. status: sortedStatus
  33235. };
  33236. };
  33237. /*
  33238. * Licensed to the Apache Software Foundation (ASF) under one
  33239. * or more contributor license agreements. See the NOTICE file
  33240. * distributed with this work for additional information
  33241. * regarding copyright ownership. The ASF licenses this file
  33242. * to you under the Apache License, Version 2.0 (the
  33243. * "License"); you may not use this file except in compliance
  33244. * with the License. You may obtain a copy of the License at
  33245. *
  33246. * http://www.apache.org/licenses/LICENSE-2.0
  33247. *
  33248. * Unless required by applicable law or agreed to in writing,
  33249. * software distributed under the License is distributed on an
  33250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33251. * KIND, either express or implied. See the License for the
  33252. * specific language governing permissions and limitations
  33253. * under the License.
  33254. */
  33255. // Poly path support NaN point
  33256. var vec2Min = min;
  33257. var vec2Max = max;
  33258. var scaleAndAdd$1 = scaleAndAdd;
  33259. var v2Copy = copy;
  33260. // Temporary variable
  33261. var v = [];
  33262. var cp0 = [];
  33263. var cp1 = [];
  33264. function isPointNull(p) {
  33265. return isNaN(p[0]) || isNaN(p[1]);
  33266. }
  33267. function drawSegment(
  33268. ctx, points, start, segLen, allLen,
  33269. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33270. ) {
  33271. // if (smoothMonotone == null) {
  33272. // if (isMono(points, 'x')) {
  33273. // return drawMono(ctx, points, start, segLen, allLen,
  33274. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33275. // }
  33276. // else if (isMono(points, 'y')) {
  33277. // return drawMono(ctx, points, start, segLen, allLen,
  33278. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33279. // }
  33280. // else {
  33281. // return drawNonMono.apply(this, arguments);
  33282. // }
  33283. // }
  33284. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33285. // return drawMono.apply(this, arguments);
  33286. // }
  33287. // else {
  33288. // return drawNonMono.apply(this, arguments);
  33289. // }
  33290. if (smoothMonotone === 'none' || !smoothMonotone) {
  33291. return drawNonMono.apply(this, arguments);
  33292. }
  33293. else {
  33294. return drawMono.apply(this, arguments);
  33295. }
  33296. }
  33297. /**
  33298. * Check if points is in monotone.
  33299. *
  33300. * @param {number[][]} points Array of points which is in [x, y] form
  33301. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33302. * dimension that is checking.
  33303. * If is 'none', `drawNonMono` should be
  33304. * called.
  33305. * If is undefined, either being monotone
  33306. * in 'x' or 'y' will call `drawMono`.
  33307. */
  33308. // function isMono(points, smoothMonotone) {
  33309. // if (points.length <= 1) {
  33310. // return true;
  33311. // }
  33312. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33313. // var last = points[0][dim];
  33314. // var lastDiff = 0;
  33315. // for (var i = 1; i < points.length; ++i) {
  33316. // var diff = points[i][dim] - last;
  33317. // if (!isNaN(diff) && !isNaN(lastDiff)
  33318. // && diff !== 0 && lastDiff !== 0
  33319. // && ((diff >= 0) !== (lastDiff >= 0))
  33320. // ) {
  33321. // return false;
  33322. // }
  33323. // if (!isNaN(diff) && diff !== 0) {
  33324. // lastDiff = diff;
  33325. // last = points[i][dim];
  33326. // }
  33327. // }
  33328. // return true;
  33329. // }
  33330. /**
  33331. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33332. * control points will be used. This should be used when points are monotone
  33333. * either in x or y dimension.
  33334. */
  33335. function drawMono(
  33336. ctx, points, start, segLen, allLen,
  33337. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33338. ) {
  33339. var prevIdx = 0;
  33340. var idx = start;
  33341. for (var k = 0; k < segLen; k++) {
  33342. var p = points[idx];
  33343. if (idx >= allLen || idx < 0) {
  33344. break;
  33345. }
  33346. if (isPointNull(p)) {
  33347. if (connectNulls) {
  33348. idx += dir;
  33349. continue;
  33350. }
  33351. break;
  33352. }
  33353. if (idx === start) {
  33354. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33355. }
  33356. else {
  33357. if (smooth > 0) {
  33358. var prevP = points[prevIdx];
  33359. var dim = smoothMonotone === 'y' ? 1 : 0;
  33360. // Length of control point to p, either in x or y, but not both
  33361. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33362. v2Copy(cp0, prevP);
  33363. cp0[dim] = prevP[dim] + ctrlLen;
  33364. v2Copy(cp1, p);
  33365. cp1[dim] = p[dim] - ctrlLen;
  33366. ctx.bezierCurveTo(
  33367. cp0[0], cp0[1],
  33368. cp1[0], cp1[1],
  33369. p[0], p[1]
  33370. );
  33371. }
  33372. else {
  33373. ctx.lineTo(p[0], p[1]);
  33374. }
  33375. }
  33376. prevIdx = idx;
  33377. idx += dir;
  33378. }
  33379. return k;
  33380. }
  33381. /**
  33382. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33383. * situations. This should be used when points are non-monotone neither in x or
  33384. * y dimension.
  33385. */
  33386. function drawNonMono(
  33387. ctx, points, start, segLen, allLen,
  33388. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33389. ) {
  33390. var prevIdx = 0;
  33391. var idx = start;
  33392. for (var k = 0; k < segLen; k++) {
  33393. var p = points[idx];
  33394. if (idx >= allLen || idx < 0) {
  33395. break;
  33396. }
  33397. if (isPointNull(p)) {
  33398. if (connectNulls) {
  33399. idx += dir;
  33400. continue;
  33401. }
  33402. break;
  33403. }
  33404. if (idx === start) {
  33405. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33406. v2Copy(cp0, p);
  33407. }
  33408. else {
  33409. if (smooth > 0) {
  33410. var nextIdx = idx + dir;
  33411. var nextP = points[nextIdx];
  33412. if (connectNulls) {
  33413. // Find next point not null
  33414. while (nextP && isPointNull(points[nextIdx])) {
  33415. nextIdx += dir;
  33416. nextP = points[nextIdx];
  33417. }
  33418. }
  33419. var ratioNextSeg = 0.5;
  33420. var prevP = points[prevIdx];
  33421. var nextP = points[nextIdx];
  33422. // Last point
  33423. if (!nextP || isPointNull(nextP)) {
  33424. v2Copy(cp1, p);
  33425. }
  33426. else {
  33427. // If next data is null in not connect case
  33428. if (isPointNull(nextP) && !connectNulls) {
  33429. nextP = p;
  33430. }
  33431. sub(v, nextP, prevP);
  33432. var lenPrevSeg;
  33433. var lenNextSeg;
  33434. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33435. var dim = smoothMonotone === 'x' ? 0 : 1;
  33436. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33437. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33438. }
  33439. else {
  33440. lenPrevSeg = dist(p, prevP);
  33441. lenNextSeg = dist(p, nextP);
  33442. }
  33443. // Use ratio of seg length
  33444. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33445. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33446. }
  33447. // Smooth constraint
  33448. vec2Min(cp0, cp0, smoothMax);
  33449. vec2Max(cp0, cp0, smoothMin);
  33450. vec2Min(cp1, cp1, smoothMax);
  33451. vec2Max(cp1, cp1, smoothMin);
  33452. ctx.bezierCurveTo(
  33453. cp0[0], cp0[1],
  33454. cp1[0], cp1[1],
  33455. p[0], p[1]
  33456. );
  33457. // cp0 of next segment
  33458. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33459. }
  33460. else {
  33461. ctx.lineTo(p[0], p[1]);
  33462. }
  33463. }
  33464. prevIdx = idx;
  33465. idx += dir;
  33466. }
  33467. return k;
  33468. }
  33469. function getBoundingBox(points, smoothConstraint) {
  33470. var ptMin = [Infinity, Infinity];
  33471. var ptMax = [-Infinity, -Infinity];
  33472. if (smoothConstraint) {
  33473. for (var i = 0; i < points.length; i++) {
  33474. var pt = points[i];
  33475. if (pt[0] < ptMin[0]) {
  33476. ptMin[0] = pt[0];
  33477. }
  33478. if (pt[1] < ptMin[1]) {
  33479. ptMin[1] = pt[1];
  33480. }
  33481. if (pt[0] > ptMax[0]) {
  33482. ptMax[0] = pt[0];
  33483. }
  33484. if (pt[1] > ptMax[1]) {
  33485. ptMax[1] = pt[1];
  33486. }
  33487. }
  33488. }
  33489. return {
  33490. min: smoothConstraint ? ptMin : ptMax,
  33491. max: smoothConstraint ? ptMax : ptMin
  33492. };
  33493. }
  33494. var Polyline$1 = Path.extend({
  33495. type: 'ec-polyline',
  33496. shape: {
  33497. points: [],
  33498. smooth: 0,
  33499. smoothConstraint: true,
  33500. smoothMonotone: null,
  33501. connectNulls: false
  33502. },
  33503. style: {
  33504. fill: null,
  33505. stroke: '#000'
  33506. },
  33507. brush: fixClipWithShadow(Path.prototype.brush),
  33508. buildPath: function (ctx, shape) {
  33509. var points = shape.points;
  33510. var i = 0;
  33511. var len$$1 = points.length;
  33512. var result = getBoundingBox(points, shape.smoothConstraint);
  33513. if (shape.connectNulls) {
  33514. // Must remove first and last null values avoid draw error in polygon
  33515. for (; len$$1 > 0; len$$1--) {
  33516. if (!isPointNull(points[len$$1 - 1])) {
  33517. break;
  33518. }
  33519. }
  33520. for (; i < len$$1; i++) {
  33521. if (!isPointNull(points[i])) {
  33522. break;
  33523. }
  33524. }
  33525. }
  33526. while (i < len$$1) {
  33527. i += drawSegment(
  33528. ctx, points, i, len$$1, len$$1,
  33529. 1, result.min, result.max, shape.smooth,
  33530. shape.smoothMonotone, shape.connectNulls
  33531. ) + 1;
  33532. }
  33533. }
  33534. });
  33535. var Polygon$1 = Path.extend({
  33536. type: 'ec-polygon',
  33537. shape: {
  33538. points: [],
  33539. // Offset between stacked base points and points
  33540. stackedOnPoints: [],
  33541. smooth: 0,
  33542. stackedOnSmooth: 0,
  33543. smoothConstraint: true,
  33544. smoothMonotone: null,
  33545. connectNulls: false
  33546. },
  33547. brush: fixClipWithShadow(Path.prototype.brush),
  33548. buildPath: function (ctx, shape) {
  33549. var points = shape.points;
  33550. var stackedOnPoints = shape.stackedOnPoints;
  33551. var i = 0;
  33552. var len$$1 = points.length;
  33553. var smoothMonotone = shape.smoothMonotone;
  33554. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33555. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33556. if (shape.connectNulls) {
  33557. // Must remove first and last null values avoid draw error in polygon
  33558. for (; len$$1 > 0; len$$1--) {
  33559. if (!isPointNull(points[len$$1 - 1])) {
  33560. break;
  33561. }
  33562. }
  33563. for (; i < len$$1; i++) {
  33564. if (!isPointNull(points[i])) {
  33565. break;
  33566. }
  33567. }
  33568. }
  33569. while (i < len$$1) {
  33570. var k = drawSegment(
  33571. ctx, points, i, len$$1, len$$1,
  33572. 1, bbox.min, bbox.max, shape.smooth,
  33573. smoothMonotone, shape.connectNulls
  33574. );
  33575. drawSegment(
  33576. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33577. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33578. smoothMonotone, shape.connectNulls
  33579. );
  33580. i += k + 1;
  33581. ctx.closePath();
  33582. }
  33583. }
  33584. });
  33585. /*
  33586. * Licensed to the Apache Software Foundation (ASF) under one
  33587. * or more contributor license agreements. See the NOTICE file
  33588. * distributed with this work for additional information
  33589. * regarding copyright ownership. The ASF licenses this file
  33590. * to you under the Apache License, Version 2.0 (the
  33591. * "License"); you may not use this file except in compliance
  33592. * with the License. You may obtain a copy of the License at
  33593. *
  33594. * http://www.apache.org/licenses/LICENSE-2.0
  33595. *
  33596. * Unless required by applicable law or agreed to in writing,
  33597. * software distributed under the License is distributed on an
  33598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33599. * KIND, either express or implied. See the License for the
  33600. * specific language governing permissions and limitations
  33601. * under the License.
  33602. */
  33603. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33604. var rect = cartesian.getArea();
  33605. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33606. var x = rect.x;
  33607. var y = rect.y;
  33608. var width = rect.width;
  33609. var height = rect.height;
  33610. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33611. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33612. x -= lineWidth / 2;
  33613. y -= lineWidth / 2;
  33614. width += lineWidth;
  33615. height += lineWidth;
  33616. var clipPath = new Rect({
  33617. shape: {
  33618. x: x,
  33619. y: y,
  33620. width: width,
  33621. height: height
  33622. }
  33623. });
  33624. if (hasAnimation) {
  33625. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33626. initProps(clipPath, {
  33627. shape: {
  33628. width: width,
  33629. height: height
  33630. }
  33631. }, seriesModel);
  33632. }
  33633. return clipPath;
  33634. }
  33635. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33636. var sectorArea = polar.getArea();
  33637. // Avoid float number rounding error for symbol on the edge of axis extent.
  33638. var clipPath = new Sector({
  33639. shape: {
  33640. cx: round$1(polar.cx, 1),
  33641. cy: round$1(polar.cy, 1),
  33642. r0: round$1(sectorArea.r0, 1),
  33643. r: round$1(sectorArea.r, 1),
  33644. startAngle: sectorArea.startAngle,
  33645. endAngle: sectorArea.endAngle,
  33646. clockwise: sectorArea.clockwise
  33647. }
  33648. });
  33649. if (hasAnimation) {
  33650. clipPath.shape.endAngle = sectorArea.startAngle;
  33651. initProps(clipPath, {
  33652. shape: {
  33653. endAngle: sectorArea.endAngle
  33654. }
  33655. }, seriesModel);
  33656. }
  33657. return clipPath;
  33658. }
  33659. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33660. if (!coordSys) {
  33661. return null;
  33662. }
  33663. else if (coordSys.type === 'polar') {
  33664. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33665. }
  33666. else if (coordSys.type === 'cartesian2d') {
  33667. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33668. }
  33669. return null;
  33670. }
  33671. /*
  33672. * Licensed to the Apache Software Foundation (ASF) under one
  33673. * or more contributor license agreements. See the NOTICE file
  33674. * distributed with this work for additional information
  33675. * regarding copyright ownership. The ASF licenses this file
  33676. * to you under the Apache License, Version 2.0 (the
  33677. * "License"); you may not use this file except in compliance
  33678. * with the License. You may obtain a copy of the License at
  33679. *
  33680. * http://www.apache.org/licenses/LICENSE-2.0
  33681. *
  33682. * Unless required by applicable law or agreed to in writing,
  33683. * software distributed under the License is distributed on an
  33684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33685. * KIND, either express or implied. See the License for the
  33686. * specific language governing permissions and limitations
  33687. * under the License.
  33688. */
  33689. // FIXME step not support polar
  33690. function isPointsSame(points1, points2) {
  33691. if (points1.length !== points2.length) {
  33692. return;
  33693. }
  33694. for (var i = 0; i < points1.length; i++) {
  33695. var p1 = points1[i];
  33696. var p2 = points2[i];
  33697. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33698. return;
  33699. }
  33700. }
  33701. return true;
  33702. }
  33703. function getSmooth(smooth) {
  33704. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33705. }
  33706. /**
  33707. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33708. * @param {module:echarts/data/List} data
  33709. * @param {Object} dataCoordInfo
  33710. * @param {Array.<Array.<number>>} points
  33711. */
  33712. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33713. if (!dataCoordInfo.valueDim) {
  33714. return [];
  33715. }
  33716. var points = [];
  33717. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33718. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33719. }
  33720. return points;
  33721. }
  33722. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33723. var baseAxis = coordSys.getBaseAxis();
  33724. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33725. var stepPoints = [];
  33726. for (var i = 0; i < points.length - 1; i++) {
  33727. var nextPt = points[i + 1];
  33728. var pt = points[i];
  33729. stepPoints.push(pt);
  33730. var stepPt = [];
  33731. switch (stepTurnAt) {
  33732. case 'end':
  33733. stepPt[baseIndex] = nextPt[baseIndex];
  33734. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33735. // default is start
  33736. stepPoints.push(stepPt);
  33737. break;
  33738. case 'middle':
  33739. // default is start
  33740. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33741. var stepPt2 = [];
  33742. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33743. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33744. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33745. stepPoints.push(stepPt);
  33746. stepPoints.push(stepPt2);
  33747. break;
  33748. default:
  33749. stepPt[baseIndex] = pt[baseIndex];
  33750. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33751. // default is start
  33752. stepPoints.push(stepPt);
  33753. }
  33754. }
  33755. // Last points
  33756. points[i] && stepPoints.push(points[i]);
  33757. return stepPoints;
  33758. }
  33759. function getVisualGradient(data, coordSys) {
  33760. var visualMetaList = data.getVisual('visualMeta');
  33761. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33762. // When data.count() is 0, gradient range can not be calculated.
  33763. return;
  33764. }
  33765. if (coordSys.type !== 'cartesian2d') {
  33766. if (__DEV__) {
  33767. console.warn('Visual map on line style is only supported on cartesian2d.');
  33768. }
  33769. return;
  33770. }
  33771. var coordDim;
  33772. var visualMeta;
  33773. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33774. var dimIndex = visualMetaList[i].dimension;
  33775. var dimName = data.dimensions[dimIndex];
  33776. var dimInfo = data.getDimensionInfo(dimName);
  33777. coordDim = dimInfo && dimInfo.coordDim;
  33778. // Can only be x or y
  33779. if (coordDim === 'x' || coordDim === 'y') {
  33780. visualMeta = visualMetaList[i];
  33781. break;
  33782. }
  33783. }
  33784. if (!visualMeta) {
  33785. if (__DEV__) {
  33786. console.warn('Visual map on line style only support x or y dimension.');
  33787. }
  33788. return;
  33789. }
  33790. // If the area to be rendered is bigger than area defined by LinearGradient,
  33791. // the canvas spec prescribes that the color of the first stop and the last
  33792. // stop should be used. But if two stops are added at offset 0, in effect
  33793. // browsers use the color of the second stop to render area outside
  33794. // LinearGradient. So we can only infinitesimally extend area defined in
  33795. // LinearGradient to render `outerColors`.
  33796. var axis = coordSys.getAxis(coordDim);
  33797. // dataToCoor mapping may not be linear, but must be monotonic.
  33798. var colorStops = map(visualMeta.stops, function (stop) {
  33799. return {
  33800. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  33801. color: stop.color
  33802. };
  33803. });
  33804. var stopLen = colorStops.length;
  33805. var outerColors = visualMeta.outerColors.slice();
  33806. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  33807. colorStops.reverse();
  33808. outerColors.reverse();
  33809. }
  33810. var tinyExtent = 10; // Arbitrary value: 10px
  33811. var minCoord = colorStops[0].coord - tinyExtent;
  33812. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  33813. var coordSpan = maxCoord - minCoord;
  33814. if (coordSpan < 1e-3) {
  33815. return 'transparent';
  33816. }
  33817. each$1(colorStops, function (stop) {
  33818. stop.offset = (stop.coord - minCoord) / coordSpan;
  33819. });
  33820. colorStops.push({
  33821. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  33822. color: outerColors[1] || 'transparent'
  33823. });
  33824. colorStops.unshift({ // notice colorStops.length have been changed.
  33825. offset: stopLen ? colorStops[0].offset : 0.5,
  33826. color: outerColors[0] || 'transparent'
  33827. });
  33828. // zrUtil.each(colorStops, function (colorStop) {
  33829. // // Make sure each offset has rounded px to avoid not sharp edge
  33830. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  33831. // });
  33832. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  33833. gradient[coordDim] = minCoord;
  33834. gradient[coordDim + '2'] = maxCoord;
  33835. return gradient;
  33836. }
  33837. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  33838. var showAllSymbol = seriesModel.get('showAllSymbol');
  33839. var isAuto = showAllSymbol === 'auto';
  33840. if (showAllSymbol && !isAuto) {
  33841. return;
  33842. }
  33843. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  33844. if (!categoryAxis) {
  33845. return;
  33846. }
  33847. // Note that category label interval strategy might bring some weird effect
  33848. // in some scenario: users may wonder why some of the symbols are not
  33849. // displayed. So we show all symbols as possible as we can.
  33850. if (isAuto
  33851. // Simplify the logic, do not determine label overlap here.
  33852. && canShowAllSymbolForCategory(categoryAxis, data)
  33853. ) {
  33854. return;
  33855. }
  33856. // Otherwise follow the label interval strategy on category axis.
  33857. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  33858. var labelMap = {};
  33859. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  33860. labelMap[labelItem.tickValue] = 1;
  33861. });
  33862. return function (dataIndex) {
  33863. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  33864. };
  33865. }
  33866. function canShowAllSymbolForCategory(categoryAxis, data) {
  33867. // In mose cases, line is monotonous on category axis, and the label size
  33868. // is close with each other. So we check the symbol size and some of the
  33869. // label size alone with the category axis to estimate whether all symbol
  33870. // can be shown without overlap.
  33871. var axisExtent = categoryAxis.getExtent();
  33872. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  33873. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  33874. // Sampling some points, max 5.
  33875. var dataLen = data.count();
  33876. var step = Math.max(1, Math.round(dataLen / 5));
  33877. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  33878. if (SymbolClz$1.getSymbolSize(
  33879. data, dataIndex
  33880. // Only for cartesian, where `isHorizontal` exists.
  33881. )[categoryAxis.isHorizontal() ? 1 : 0]
  33882. // Empirical number
  33883. * 1.5 > availSize
  33884. ) {
  33885. return false;
  33886. }
  33887. }
  33888. return true;
  33889. }
  33890. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  33891. if (coordSys.type === 'cartesian2d') {
  33892. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  33893. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  33894. // Expand clip shape to avoid clipping when line value exceeds axis
  33895. if (!seriesModel.get('clip', true)) {
  33896. var rectShape = clipPath.shape;
  33897. var expandSize = Math.max(rectShape.width, rectShape.height);
  33898. if (isHorizontal) {
  33899. rectShape.y -= expandSize;
  33900. rectShape.height += expandSize * 2;
  33901. }
  33902. else {
  33903. rectShape.x -= expandSize;
  33904. rectShape.width += expandSize * 2;
  33905. }
  33906. }
  33907. return clipPath;
  33908. }
  33909. else {
  33910. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33911. }
  33912. }
  33913. Chart.extend({
  33914. type: 'line',
  33915. init: function () {
  33916. var lineGroup = new Group();
  33917. var symbolDraw = new SymbolDraw();
  33918. this.group.add(symbolDraw.group);
  33919. this._symbolDraw = symbolDraw;
  33920. this._lineGroup = lineGroup;
  33921. },
  33922. render: function (seriesModel, ecModel, api) {
  33923. var coordSys = seriesModel.coordinateSystem;
  33924. var group = this.group;
  33925. var data = seriesModel.getData();
  33926. var lineStyleModel = seriesModel.getModel('lineStyle');
  33927. var areaStyleModel = seriesModel.getModel('areaStyle');
  33928. var points = data.mapArray(data.getItemLayout);
  33929. var isCoordSysPolar = coordSys.type === 'polar';
  33930. var prevCoordSys = this._coordSys;
  33931. var symbolDraw = this._symbolDraw;
  33932. var polyline = this._polyline;
  33933. var polygon = this._polygon;
  33934. var lineGroup = this._lineGroup;
  33935. var hasAnimation = seriesModel.get('animation');
  33936. var isAreaChart = !areaStyleModel.isEmpty();
  33937. var valueOrigin = areaStyleModel.get('origin');
  33938. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  33939. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  33940. var showSymbol = seriesModel.get('showSymbol');
  33941. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  33942. && getIsIgnoreFunc(seriesModel, data, coordSys);
  33943. // Remove temporary symbols
  33944. var oldData = this._data;
  33945. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  33946. if (el.__temp) {
  33947. group.remove(el);
  33948. oldData.setItemGraphicEl(idx, null);
  33949. }
  33950. });
  33951. // Remove previous created symbols if showSymbol changed to false
  33952. if (!showSymbol) {
  33953. symbolDraw.remove();
  33954. }
  33955. group.add(lineGroup);
  33956. // FIXME step not support polar
  33957. var step = !isCoordSysPolar && seriesModel.get('step');
  33958. var clipShapeForSymbol;
  33959. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  33960. clipShapeForSymbol = coordSys.getArea();
  33961. // Avoid float number rounding error for symbol on the edge of axis extent.
  33962. // See #7913 and `test/dataZoom-clip.html`.
  33963. if (clipShapeForSymbol.width != null) {
  33964. clipShapeForSymbol.x -= 0.1;
  33965. clipShapeForSymbol.y -= 0.1;
  33966. clipShapeForSymbol.width += 0.2;
  33967. clipShapeForSymbol.height += 0.2;
  33968. }
  33969. else if (clipShapeForSymbol.r0) {
  33970. clipShapeForSymbol.r0 -= 0.5;
  33971. clipShapeForSymbol.r1 += 0.5;
  33972. }
  33973. }
  33974. this._clipShapeForSymbol = clipShapeForSymbol;
  33975. // Initialization animation or coordinate system changed
  33976. if (
  33977. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  33978. ) {
  33979. showSymbol && symbolDraw.updateData(data, {
  33980. isIgnore: isIgnoreFunc,
  33981. clipShape: clipShapeForSymbol
  33982. });
  33983. if (step) {
  33984. // TODO If stacked series is not step
  33985. points = turnPointsIntoStep(points, coordSys, step);
  33986. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  33987. }
  33988. polyline = this._newPolyline(points, coordSys, hasAnimation);
  33989. if (isAreaChart) {
  33990. polygon = this._newPolygon(
  33991. points, stackedOnPoints,
  33992. coordSys, hasAnimation
  33993. );
  33994. }
  33995. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  33996. }
  33997. else {
  33998. if (isAreaChart && !polygon) {
  33999. // If areaStyle is added
  34000. polygon = this._newPolygon(
  34001. points, stackedOnPoints,
  34002. coordSys, hasAnimation
  34003. );
  34004. }
  34005. else if (polygon && !isAreaChart) {
  34006. // If areaStyle is removed
  34007. lineGroup.remove(polygon);
  34008. polygon = this._polygon = null;
  34009. }
  34010. // Update clipPath
  34011. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34012. // Always update, or it is wrong in the case turning on legend
  34013. // because points are not changed
  34014. showSymbol && symbolDraw.updateData(data, {
  34015. isIgnore: isIgnoreFunc,
  34016. clipShape: clipShapeForSymbol
  34017. });
  34018. // Stop symbol animation and sync with line points
  34019. // FIXME performance?
  34020. data.eachItemGraphicEl(function (el) {
  34021. el.stopAnimation(true);
  34022. });
  34023. // In the case data zoom triggerred refreshing frequently
  34024. // Data may not change if line has a category axis. So it should animate nothing
  34025. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34026. || !isPointsSame(this._points, points)
  34027. ) {
  34028. if (hasAnimation) {
  34029. this._updateAnimation(
  34030. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34031. );
  34032. }
  34033. else {
  34034. // Not do it in update with animation
  34035. if (step) {
  34036. // TODO If stacked series is not step
  34037. points = turnPointsIntoStep(points, coordSys, step);
  34038. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34039. }
  34040. polyline.setShape({
  34041. points: points
  34042. });
  34043. polygon && polygon.setShape({
  34044. points: points,
  34045. stackedOnPoints: stackedOnPoints
  34046. });
  34047. }
  34048. }
  34049. }
  34050. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34051. polyline.useStyle(defaults(
  34052. // Use color in lineStyle first
  34053. lineStyleModel.getLineStyle(),
  34054. {
  34055. fill: 'none',
  34056. stroke: visualColor,
  34057. lineJoin: 'bevel'
  34058. }
  34059. ));
  34060. var smooth = seriesModel.get('smooth');
  34061. smooth = getSmooth(seriesModel.get('smooth'));
  34062. polyline.setShape({
  34063. smooth: smooth,
  34064. smoothMonotone: seriesModel.get('smoothMonotone'),
  34065. connectNulls: seriesModel.get('connectNulls')
  34066. });
  34067. if (polygon) {
  34068. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34069. var stackedOnSmooth = 0;
  34070. polygon.useStyle(defaults(
  34071. areaStyleModel.getAreaStyle(),
  34072. {
  34073. fill: visualColor,
  34074. opacity: 0.7,
  34075. lineJoin: 'bevel'
  34076. }
  34077. ));
  34078. if (stackedOnSeries) {
  34079. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34080. }
  34081. polygon.setShape({
  34082. smooth: smooth,
  34083. stackedOnSmooth: stackedOnSmooth,
  34084. smoothMonotone: seriesModel.get('smoothMonotone'),
  34085. connectNulls: seriesModel.get('connectNulls')
  34086. });
  34087. }
  34088. this._data = data;
  34089. // Save the coordinate system for transition animation when data changed
  34090. this._coordSys = coordSys;
  34091. this._stackedOnPoints = stackedOnPoints;
  34092. this._points = points;
  34093. this._step = step;
  34094. this._valueOrigin = valueOrigin;
  34095. },
  34096. dispose: function () {},
  34097. highlight: function (seriesModel, ecModel, api, payload) {
  34098. var data = seriesModel.getData();
  34099. var dataIndex = queryDataIndex(data, payload);
  34100. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34101. var symbol = data.getItemGraphicEl(dataIndex);
  34102. if (!symbol) {
  34103. // Create a temporary symbol if it is not exists
  34104. var pt = data.getItemLayout(dataIndex);
  34105. if (!pt) {
  34106. // Null data
  34107. return;
  34108. }
  34109. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34110. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34111. return;
  34112. }
  34113. symbol = new SymbolClz$1(data, dataIndex);
  34114. symbol.position = pt;
  34115. symbol.setZ(
  34116. seriesModel.get('zlevel'),
  34117. seriesModel.get('z')
  34118. );
  34119. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34120. symbol.__temp = true;
  34121. data.setItemGraphicEl(dataIndex, symbol);
  34122. // Stop scale animation
  34123. symbol.stopSymbolAnimation(true);
  34124. this.group.add(symbol);
  34125. }
  34126. symbol.highlight();
  34127. }
  34128. else {
  34129. // Highlight whole series
  34130. Chart.prototype.highlight.call(
  34131. this, seriesModel, ecModel, api, payload
  34132. );
  34133. }
  34134. },
  34135. downplay: function (seriesModel, ecModel, api, payload) {
  34136. var data = seriesModel.getData();
  34137. var dataIndex = queryDataIndex(data, payload);
  34138. if (dataIndex != null && dataIndex >= 0) {
  34139. var symbol = data.getItemGraphicEl(dataIndex);
  34140. if (symbol) {
  34141. if (symbol.__temp) {
  34142. data.setItemGraphicEl(dataIndex, null);
  34143. this.group.remove(symbol);
  34144. }
  34145. else {
  34146. symbol.downplay();
  34147. }
  34148. }
  34149. }
  34150. else {
  34151. // FIXME
  34152. // can not downplay completely.
  34153. // Downplay whole series
  34154. Chart.prototype.downplay.call(
  34155. this, seriesModel, ecModel, api, payload
  34156. );
  34157. }
  34158. },
  34159. /**
  34160. * @param {module:zrender/container/Group} group
  34161. * @param {Array.<Array.<number>>} points
  34162. * @private
  34163. */
  34164. _newPolyline: function (points) {
  34165. var polyline = this._polyline;
  34166. // Remove previous created polyline
  34167. if (polyline) {
  34168. this._lineGroup.remove(polyline);
  34169. }
  34170. polyline = new Polyline$1({
  34171. shape: {
  34172. points: points
  34173. },
  34174. silent: true,
  34175. z2: 10
  34176. });
  34177. this._lineGroup.add(polyline);
  34178. this._polyline = polyline;
  34179. return polyline;
  34180. },
  34181. /**
  34182. * @param {module:zrender/container/Group} group
  34183. * @param {Array.<Array.<number>>} stackedOnPoints
  34184. * @param {Array.<Array.<number>>} points
  34185. * @private
  34186. */
  34187. _newPolygon: function (points, stackedOnPoints) {
  34188. var polygon = this._polygon;
  34189. // Remove previous created polygon
  34190. if (polygon) {
  34191. this._lineGroup.remove(polygon);
  34192. }
  34193. polygon = new Polygon$1({
  34194. shape: {
  34195. points: points,
  34196. stackedOnPoints: stackedOnPoints
  34197. },
  34198. silent: true
  34199. });
  34200. this._lineGroup.add(polygon);
  34201. this._polygon = polygon;
  34202. return polygon;
  34203. },
  34204. /**
  34205. * @private
  34206. */
  34207. // FIXME Two value axis
  34208. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34209. var polyline = this._polyline;
  34210. var polygon = this._polygon;
  34211. var seriesModel = data.hostModel;
  34212. var diff = lineAnimationDiff(
  34213. this._data, data,
  34214. this._stackedOnPoints, stackedOnPoints,
  34215. this._coordSys, coordSys,
  34216. this._valueOrigin, valueOrigin
  34217. );
  34218. var current = diff.current;
  34219. var stackedOnCurrent = diff.stackedOnCurrent;
  34220. var next = diff.next;
  34221. var stackedOnNext = diff.stackedOnNext;
  34222. if (step) {
  34223. // TODO If stacked series is not step
  34224. current = turnPointsIntoStep(diff.current, coordSys, step);
  34225. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34226. next = turnPointsIntoStep(diff.next, coordSys, step);
  34227. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34228. }
  34229. // `diff.current` is subset of `current` (which should be ensured by
  34230. // turnPointsIntoStep), so points in `__points` can be updated when
  34231. // points in `current` are update during animation.
  34232. polyline.shape.__points = diff.current;
  34233. polyline.shape.points = current;
  34234. updateProps(polyline, {
  34235. shape: {
  34236. points: next
  34237. }
  34238. }, seriesModel);
  34239. if (polygon) {
  34240. polygon.setShape({
  34241. points: current,
  34242. stackedOnPoints: stackedOnCurrent
  34243. });
  34244. updateProps(polygon, {
  34245. shape: {
  34246. points: next,
  34247. stackedOnPoints: stackedOnNext
  34248. }
  34249. }, seriesModel);
  34250. }
  34251. var updatedDataInfo = [];
  34252. var diffStatus = diff.status;
  34253. for (var i = 0; i < diffStatus.length; i++) {
  34254. var cmd = diffStatus[i].cmd;
  34255. if (cmd === '=') {
  34256. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34257. if (el) {
  34258. updatedDataInfo.push({
  34259. el: el,
  34260. ptIdx: i // Index of points
  34261. });
  34262. }
  34263. }
  34264. }
  34265. if (polyline.animators && polyline.animators.length) {
  34266. polyline.animators[0].during(function () {
  34267. for (var i = 0; i < updatedDataInfo.length; i++) {
  34268. var el = updatedDataInfo[i].el;
  34269. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34270. }
  34271. });
  34272. }
  34273. },
  34274. remove: function (ecModel) {
  34275. var group = this.group;
  34276. var oldData = this._data;
  34277. this._lineGroup.removeAll();
  34278. this._symbolDraw.remove(true);
  34279. // Remove temporary created elements when highlighting
  34280. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34281. if (el.__temp) {
  34282. group.remove(el);
  34283. oldData.setItemGraphicEl(idx, null);
  34284. }
  34285. });
  34286. this._polyline =
  34287. this._polygon =
  34288. this._coordSys =
  34289. this._points =
  34290. this._stackedOnPoints =
  34291. this._data = null;
  34292. }
  34293. });
  34294. /*
  34295. * Licensed to the Apache Software Foundation (ASF) under one
  34296. * or more contributor license agreements. See the NOTICE file
  34297. * distributed with this work for additional information
  34298. * regarding copyright ownership. The ASF licenses this file
  34299. * to you under the Apache License, Version 2.0 (the
  34300. * "License"); you may not use this file except in compliance
  34301. * with the License. You may obtain a copy of the License at
  34302. *
  34303. * http://www.apache.org/licenses/LICENSE-2.0
  34304. *
  34305. * Unless required by applicable law or agreed to in writing,
  34306. * software distributed under the License is distributed on an
  34307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34308. * KIND, either express or implied. See the License for the
  34309. * specific language governing permissions and limitations
  34310. * under the License.
  34311. */
  34312. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34313. // Encoding visual for all series include which is filtered for legend drawing
  34314. return {
  34315. seriesType: seriesType,
  34316. // For legend.
  34317. performRawSeries: true,
  34318. reset: function (seriesModel, ecModel, api) {
  34319. var data = seriesModel.getData();
  34320. var symbolType = seriesModel.get('symbol');
  34321. var symbolSize = seriesModel.get('symbolSize');
  34322. var keepAspect = seriesModel.get('symbolKeepAspect');
  34323. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34324. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34325. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  34326. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34327. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34328. data.setVisual({
  34329. legendSymbol: legendSymbol || seriesSymbol,
  34330. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34331. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34332. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34333. // some cases but generally it is not recommanded.
  34334. symbol: seriesSymbol,
  34335. symbolSize: seriesSymbolSize,
  34336. symbolKeepAspect: keepAspect
  34337. });
  34338. // Only visible series has each data be visual encoded
  34339. if (ecModel.isSeriesFiltered(seriesModel)) {
  34340. return;
  34341. }
  34342. function dataEach(data, idx) {
  34343. if (hasCallback) {
  34344. var rawValue = seriesModel.getRawValue(idx);
  34345. var params = seriesModel.getDataParams(idx);
  34346. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34347. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34348. }
  34349. if (data.hasItemOption) {
  34350. var itemModel = data.getItemModel(idx);
  34351. var itemSymbolType = itemModel.getShallow('symbol', true);
  34352. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34353. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34354. // If has item symbol
  34355. if (itemSymbolType != null) {
  34356. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34357. }
  34358. if (itemSymbolSize != null) {
  34359. // PENDING Transform symbolSize ?
  34360. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34361. }
  34362. if (itemSymbolKeepAspect != null) {
  34363. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34364. }
  34365. }
  34366. }
  34367. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34368. }
  34369. };
  34370. };
  34371. /*
  34372. * Licensed to the Apache Software Foundation (ASF) under one
  34373. * or more contributor license agreements. See the NOTICE file
  34374. * distributed with this work for additional information
  34375. * regarding copyright ownership. The ASF licenses this file
  34376. * to you under the Apache License, Version 2.0 (the
  34377. * "License"); you may not use this file except in compliance
  34378. * with the License. You may obtain a copy of the License at
  34379. *
  34380. * http://www.apache.org/licenses/LICENSE-2.0
  34381. *
  34382. * Unless required by applicable law or agreed to in writing,
  34383. * software distributed under the License is distributed on an
  34384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34385. * KIND, either express or implied. See the License for the
  34386. * specific language governing permissions and limitations
  34387. * under the License.
  34388. */
  34389. /* global Float32Array */
  34390. var pointsLayout = function (seriesType) {
  34391. return {
  34392. seriesType: seriesType,
  34393. plan: createRenderPlanner(),
  34394. reset: function (seriesModel) {
  34395. var data = seriesModel.getData();
  34396. var coordSys = seriesModel.coordinateSystem;
  34397. var pipelineContext = seriesModel.pipelineContext;
  34398. var isLargeRender = pipelineContext.large;
  34399. if (!coordSys) {
  34400. return;
  34401. }
  34402. var dims = map(coordSys.dimensions, function (dim) {
  34403. return data.mapDimension(dim);
  34404. }).slice(0, 2);
  34405. var dimLen = dims.length;
  34406. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34407. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34408. dims[0] = stackResultDim;
  34409. }
  34410. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34411. dims[1] = stackResultDim;
  34412. }
  34413. function progress(params, data) {
  34414. var segCount = params.end - params.start;
  34415. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34416. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34417. var point;
  34418. if (dimLen === 1) {
  34419. var x = data.get(dims[0], i);
  34420. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34421. }
  34422. else {
  34423. var x = tmpIn[0] = data.get(dims[0], i);
  34424. var y = tmpIn[1] = data.get(dims[1], i);
  34425. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34426. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34427. }
  34428. if (isLargeRender) {
  34429. points[offset++] = point ? point[0] : NaN;
  34430. points[offset++] = point ? point[1] : NaN;
  34431. }
  34432. else {
  34433. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34434. }
  34435. }
  34436. isLargeRender && data.setLayout('symbolPoints', points);
  34437. }
  34438. return dimLen && {progress: progress};
  34439. }
  34440. };
  34441. };
  34442. /*
  34443. * Licensed to the Apache Software Foundation (ASF) under one
  34444. * or more contributor license agreements. See the NOTICE file
  34445. * distributed with this work for additional information
  34446. * regarding copyright ownership. The ASF licenses this file
  34447. * to you under the Apache License, Version 2.0 (the
  34448. * "License"); you may not use this file except in compliance
  34449. * with the License. You may obtain a copy of the License at
  34450. *
  34451. * http://www.apache.org/licenses/LICENSE-2.0
  34452. *
  34453. * Unless required by applicable law or agreed to in writing,
  34454. * software distributed under the License is distributed on an
  34455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34456. * KIND, either express or implied. See the License for the
  34457. * specific language governing permissions and limitations
  34458. * under the License.
  34459. */
  34460. var samplers = {
  34461. average: function (frame) {
  34462. var sum = 0;
  34463. var count = 0;
  34464. for (var i = 0; i < frame.length; i++) {
  34465. if (!isNaN(frame[i])) {
  34466. sum += frame[i];
  34467. count++;
  34468. }
  34469. }
  34470. // Return NaN if count is 0
  34471. return count === 0 ? NaN : sum / count;
  34472. },
  34473. sum: function (frame) {
  34474. var sum = 0;
  34475. for (var i = 0; i < frame.length; i++) {
  34476. // Ignore NaN
  34477. sum += frame[i] || 0;
  34478. }
  34479. return sum;
  34480. },
  34481. max: function (frame) {
  34482. var max = -Infinity;
  34483. for (var i = 0; i < frame.length; i++) {
  34484. frame[i] > max && (max = frame[i]);
  34485. }
  34486. // NaN will cause illegal axis extent.
  34487. return isFinite(max) ? max : NaN;
  34488. },
  34489. min: function (frame) {
  34490. var min = Infinity;
  34491. for (var i = 0; i < frame.length; i++) {
  34492. frame[i] < min && (min = frame[i]);
  34493. }
  34494. // NaN will cause illegal axis extent.
  34495. return isFinite(min) ? min : NaN;
  34496. },
  34497. // TODO
  34498. // Median
  34499. nearest: function (frame) {
  34500. return frame[0];
  34501. }
  34502. };
  34503. var indexSampler = function (frame, value) {
  34504. return Math.round(frame.length / 2);
  34505. };
  34506. var dataSample = function (seriesType) {
  34507. return {
  34508. seriesType: seriesType,
  34509. modifyOutputEnd: true,
  34510. reset: function (seriesModel, ecModel, api) {
  34511. var data = seriesModel.getData();
  34512. var sampling = seriesModel.get('sampling');
  34513. var coordSys = seriesModel.coordinateSystem;
  34514. // Only cartesian2d support down sampling
  34515. if (coordSys.type === 'cartesian2d' && sampling) {
  34516. var baseAxis = coordSys.getBaseAxis();
  34517. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34518. var extent = baseAxis.getExtent();
  34519. // Coordinste system has been resized
  34520. var size = extent[1] - extent[0];
  34521. var rate = Math.round(data.count() / size);
  34522. if (rate > 1) {
  34523. var sampler;
  34524. if (typeof sampling === 'string') {
  34525. sampler = samplers[sampling];
  34526. }
  34527. else if (typeof sampling === 'function') {
  34528. sampler = sampling;
  34529. }
  34530. if (sampler) {
  34531. // Only support sample the first dim mapped from value axis.
  34532. seriesModel.setData(data.downSample(
  34533. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34534. ));
  34535. }
  34536. }
  34537. }
  34538. }
  34539. };
  34540. };
  34541. /*
  34542. * Licensed to the Apache Software Foundation (ASF) under one
  34543. * or more contributor license agreements. See the NOTICE file
  34544. * distributed with this work for additional information
  34545. * regarding copyright ownership. The ASF licenses this file
  34546. * to you under the Apache License, Version 2.0 (the
  34547. * "License"); you may not use this file except in compliance
  34548. * with the License. You may obtain a copy of the License at
  34549. *
  34550. * http://www.apache.org/licenses/LICENSE-2.0
  34551. *
  34552. * Unless required by applicable law or agreed to in writing,
  34553. * software distributed under the License is distributed on an
  34554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34555. * KIND, either express or implied. See the License for the
  34556. * specific language governing permissions and limitations
  34557. * under the License.
  34558. */
  34559. /**
  34560. * Cartesian coordinate system
  34561. * @module echarts/coord/Cartesian
  34562. *
  34563. */
  34564. function dimAxisMapper(dim) {
  34565. return this._axes[dim];
  34566. }
  34567. /**
  34568. * @alias module:echarts/coord/Cartesian
  34569. * @constructor
  34570. */
  34571. var Cartesian = function (name) {
  34572. this._axes = {};
  34573. this._dimList = [];
  34574. /**
  34575. * @type {string}
  34576. */
  34577. this.name = name || '';
  34578. };
  34579. Cartesian.prototype = {
  34580. constructor: Cartesian,
  34581. type: 'cartesian',
  34582. /**
  34583. * Get axis
  34584. * @param {number|string} dim
  34585. * @return {module:echarts/coord/Cartesian~Axis}
  34586. */
  34587. getAxis: function (dim) {
  34588. return this._axes[dim];
  34589. },
  34590. /**
  34591. * Get axes list
  34592. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34593. */
  34594. getAxes: function () {
  34595. return map(this._dimList, dimAxisMapper, this);
  34596. },
  34597. /**
  34598. * Get axes list by given scale type
  34599. */
  34600. getAxesByScale: function (scaleType) {
  34601. scaleType = scaleType.toLowerCase();
  34602. return filter(
  34603. this.getAxes(),
  34604. function (axis) {
  34605. return axis.scale.type === scaleType;
  34606. }
  34607. );
  34608. },
  34609. /**
  34610. * Add axis
  34611. * @param {module:echarts/coord/Cartesian.Axis}
  34612. */
  34613. addAxis: function (axis) {
  34614. var dim = axis.dim;
  34615. this._axes[dim] = axis;
  34616. this._dimList.push(dim);
  34617. },
  34618. /**
  34619. * Convert data to coord in nd space
  34620. * @param {Array.<number>|Object.<string, number>} val
  34621. * @return {Array.<number>|Object.<string, number>}
  34622. */
  34623. dataToCoord: function (val) {
  34624. return this._dataCoordConvert(val, 'dataToCoord');
  34625. },
  34626. /**
  34627. * Convert coord in nd space to data
  34628. * @param {Array.<number>|Object.<string, number>} val
  34629. * @return {Array.<number>|Object.<string, number>}
  34630. */
  34631. coordToData: function (val) {
  34632. return this._dataCoordConvert(val, 'coordToData');
  34633. },
  34634. _dataCoordConvert: function (input, method) {
  34635. var dimList = this._dimList;
  34636. var output = input instanceof Array ? [] : {};
  34637. for (var i = 0; i < dimList.length; i++) {
  34638. var dim = dimList[i];
  34639. var axis = this._axes[dim];
  34640. output[dim] = axis[method](input[dim]);
  34641. }
  34642. return output;
  34643. }
  34644. };
  34645. /*
  34646. * Licensed to the Apache Software Foundation (ASF) under one
  34647. * or more contributor license agreements. See the NOTICE file
  34648. * distributed with this work for additional information
  34649. * regarding copyright ownership. The ASF licenses this file
  34650. * to you under the Apache License, Version 2.0 (the
  34651. * "License"); you may not use this file except in compliance
  34652. * with the License. You may obtain a copy of the License at
  34653. *
  34654. * http://www.apache.org/licenses/LICENSE-2.0
  34655. *
  34656. * Unless required by applicable law or agreed to in writing,
  34657. * software distributed under the License is distributed on an
  34658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34659. * KIND, either express or implied. See the License for the
  34660. * specific language governing permissions and limitations
  34661. * under the License.
  34662. */
  34663. function Cartesian2D(name) {
  34664. Cartesian.call(this, name);
  34665. }
  34666. Cartesian2D.prototype = {
  34667. constructor: Cartesian2D,
  34668. type: 'cartesian2d',
  34669. /**
  34670. * @type {Array.<string>}
  34671. * @readOnly
  34672. */
  34673. dimensions: ['x', 'y'],
  34674. /**
  34675. * Base axis will be used on stacking.
  34676. *
  34677. * @return {module:echarts/coord/cartesian/Axis2D}
  34678. */
  34679. getBaseAxis: function () {
  34680. return this.getAxesByScale('ordinal')[0]
  34681. || this.getAxesByScale('time')[0]
  34682. || this.getAxis('x');
  34683. },
  34684. /**
  34685. * If contain point
  34686. * @param {Array.<number>} point
  34687. * @return {boolean}
  34688. */
  34689. containPoint: function (point) {
  34690. var axisX = this.getAxis('x');
  34691. var axisY = this.getAxis('y');
  34692. return axisX.contain(axisX.toLocalCoord(point[0]))
  34693. && axisY.contain(axisY.toLocalCoord(point[1]));
  34694. },
  34695. /**
  34696. * If contain data
  34697. * @param {Array.<number>} data
  34698. * @return {boolean}
  34699. */
  34700. containData: function (data) {
  34701. return this.getAxis('x').containData(data[0])
  34702. && this.getAxis('y').containData(data[1]);
  34703. },
  34704. /**
  34705. * @param {Array.<number>} data
  34706. * @param {Array.<number>} out
  34707. * @return {Array.<number>}
  34708. */
  34709. dataToPoint: function (data, reserved, out) {
  34710. var xAxis = this.getAxis('x');
  34711. var yAxis = this.getAxis('y');
  34712. out = out || [];
  34713. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34714. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34715. return out;
  34716. },
  34717. /**
  34718. * @param {Array.<number>} data
  34719. * @param {Array.<number>} out
  34720. * @return {Array.<number>}
  34721. */
  34722. clampData: function (data, out) {
  34723. var xScale = this.getAxis('x').scale;
  34724. var yScale = this.getAxis('y').scale;
  34725. var xAxisExtent = xScale.getExtent();
  34726. var yAxisExtent = yScale.getExtent();
  34727. var x = xScale.parse(data[0]);
  34728. var y = yScale.parse(data[1]);
  34729. out = out || [];
  34730. out[0] = Math.min(
  34731. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34732. Math.max(xAxisExtent[0], xAxisExtent[1])
  34733. );
  34734. out[1] = Math.min(
  34735. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34736. Math.max(yAxisExtent[0], yAxisExtent[1])
  34737. );
  34738. return out;
  34739. },
  34740. /**
  34741. * @param {Array.<number>} point
  34742. * @param {Array.<number>} out
  34743. * @return {Array.<number>}
  34744. */
  34745. pointToData: function (point, out) {
  34746. var xAxis = this.getAxis('x');
  34747. var yAxis = this.getAxis('y');
  34748. out = out || [];
  34749. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34750. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34751. return out;
  34752. },
  34753. /**
  34754. * Get other axis
  34755. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34756. */
  34757. getOtherAxis: function (axis) {
  34758. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34759. },
  34760. /**
  34761. * Get rect area of cartesian.
  34762. * Area will have a contain function to determine if a point is in the coordinate system.
  34763. * @return {BoundingRect}
  34764. */
  34765. getArea: function () {
  34766. var xExtent = this.getAxis('x').getGlobalExtent();
  34767. var yExtent = this.getAxis('y').getGlobalExtent();
  34768. var x = Math.min(xExtent[0], xExtent[1]);
  34769. var y = Math.min(yExtent[0], yExtent[1]);
  34770. var width = Math.max(xExtent[0], xExtent[1]) - x;
  34771. var height = Math.max(yExtent[0], yExtent[1]) - y;
  34772. var rect = new BoundingRect(x, y, width, height);
  34773. return rect;
  34774. }
  34775. };
  34776. inherits(Cartesian2D, Cartesian);
  34777. /*
  34778. * Licensed to the Apache Software Foundation (ASF) under one
  34779. * or more contributor license agreements. See the NOTICE file
  34780. * distributed with this work for additional information
  34781. * regarding copyright ownership. The ASF licenses this file
  34782. * to you under the Apache License, Version 2.0 (the
  34783. * "License"); you may not use this file except in compliance
  34784. * with the License. You may obtain a copy of the License at
  34785. *
  34786. * http://www.apache.org/licenses/LICENSE-2.0
  34787. *
  34788. * Unless required by applicable law or agreed to in writing,
  34789. * software distributed under the License is distributed on an
  34790. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34791. * KIND, either express or implied. See the License for the
  34792. * specific language governing permissions and limitations
  34793. * under the License.
  34794. */
  34795. /**
  34796. * Extend axis 2d
  34797. * @constructor module:echarts/coord/cartesian/Axis2D
  34798. * @extends {module:echarts/coord/cartesian/Axis}
  34799. * @param {string} dim
  34800. * @param {*} scale
  34801. * @param {Array.<number>} coordExtent
  34802. * @param {string} axisType
  34803. * @param {string} position
  34804. */
  34805. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  34806. Axis.call(this, dim, scale, coordExtent);
  34807. /**
  34808. * Axis type
  34809. * - 'category'
  34810. * - 'value'
  34811. * - 'time'
  34812. * - 'log'
  34813. * @type {string}
  34814. */
  34815. this.type = axisType || 'value';
  34816. /**
  34817. * Axis position
  34818. * - 'top'
  34819. * - 'bottom'
  34820. * - 'left'
  34821. * - 'right'
  34822. */
  34823. this.position = position || 'bottom';
  34824. };
  34825. Axis2D.prototype = {
  34826. constructor: Axis2D,
  34827. /**
  34828. * Index of axis, can be used as key
  34829. */
  34830. index: 0,
  34831. /**
  34832. * Implemented in <module:echarts/coord/cartesian/Grid>.
  34833. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  34834. * If not on zero of other axis, return null/undefined.
  34835. * If no axes, return an empty array.
  34836. */
  34837. getAxesOnZeroOf: null,
  34838. /**
  34839. * Axis model
  34840. * @param {module:echarts/coord/cartesian/AxisModel}
  34841. */
  34842. model: null,
  34843. isHorizontal: function () {
  34844. var position = this.position;
  34845. return position === 'top' || position === 'bottom';
  34846. },
  34847. /**
  34848. * Each item cooresponds to this.getExtent(), which
  34849. * means globalExtent[0] may greater than globalExtent[1],
  34850. * unless `asc` is input.
  34851. *
  34852. * @param {boolean} [asc]
  34853. * @return {Array.<number>}
  34854. */
  34855. getGlobalExtent: function (asc) {
  34856. var ret = this.getExtent();
  34857. ret[0] = this.toGlobalCoord(ret[0]);
  34858. ret[1] = this.toGlobalCoord(ret[1]);
  34859. asc && ret[0] > ret[1] && ret.reverse();
  34860. return ret;
  34861. },
  34862. getOtherAxis: function () {
  34863. this.grid.getOtherAxis();
  34864. },
  34865. /**
  34866. * @override
  34867. */
  34868. pointToData: function (point, clamp) {
  34869. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  34870. },
  34871. /**
  34872. * Transform global coord to local coord,
  34873. * i.e. var localCoord = axis.toLocalCoord(80);
  34874. * designate by module:echarts/coord/cartesian/Grid.
  34875. * @type {Function}
  34876. */
  34877. toLocalCoord: null,
  34878. /**
  34879. * Transform global coord to local coord,
  34880. * i.e. var globalCoord = axis.toLocalCoord(40);
  34881. * designate by module:echarts/coord/cartesian/Grid.
  34882. * @type {Function}
  34883. */
  34884. toGlobalCoord: null
  34885. };
  34886. inherits(Axis2D, Axis);
  34887. /*
  34888. * Licensed to the Apache Software Foundation (ASF) under one
  34889. * or more contributor license agreements. See the NOTICE file
  34890. * distributed with this work for additional information
  34891. * regarding copyright ownership. The ASF licenses this file
  34892. * to you under the Apache License, Version 2.0 (the
  34893. * "License"); you may not use this file except in compliance
  34894. * with the License. You may obtain a copy of the License at
  34895. *
  34896. * http://www.apache.org/licenses/LICENSE-2.0
  34897. *
  34898. * Unless required by applicable law or agreed to in writing,
  34899. * software distributed under the License is distributed on an
  34900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34901. * KIND, either express or implied. See the License for the
  34902. * specific language governing permissions and limitations
  34903. * under the License.
  34904. */
  34905. var defaultOption = {
  34906. show: true,
  34907. zlevel: 0,
  34908. z: 0,
  34909. // Inverse the axis.
  34910. inverse: false,
  34911. // Axis name displayed.
  34912. name: '',
  34913. // 'start' | 'middle' | 'end'
  34914. nameLocation: 'end',
  34915. // By degree. By defualt auto rotate by nameLocation.
  34916. nameRotate: null,
  34917. nameTruncate: {
  34918. maxWidth: null,
  34919. ellipsis: '...',
  34920. placeholder: '.'
  34921. },
  34922. // Use global text style by default.
  34923. nameTextStyle: {},
  34924. // The gap between axisName and axisLine.
  34925. nameGap: 15,
  34926. // Default `false` to support tooltip.
  34927. silent: false,
  34928. // Default `false` to avoid legacy user event listener fail.
  34929. triggerEvent: false,
  34930. tooltip: {
  34931. show: false
  34932. },
  34933. axisPointer: {},
  34934. axisLine: {
  34935. show: true,
  34936. onZero: true,
  34937. onZeroAxisIndex: null,
  34938. lineStyle: {
  34939. color: '#333',
  34940. width: 1,
  34941. type: 'solid'
  34942. },
  34943. // The arrow at both ends the the axis.
  34944. symbol: ['none', 'none'],
  34945. symbolSize: [10, 15]
  34946. },
  34947. axisTick: {
  34948. show: true,
  34949. // Whether axisTick is inside the grid or outside the grid.
  34950. inside: false,
  34951. // The length of axisTick.
  34952. length: 5,
  34953. lineStyle: {
  34954. width: 1
  34955. }
  34956. },
  34957. axisLabel: {
  34958. show: true,
  34959. // Whether axisLabel is inside the grid or outside the grid.
  34960. inside: false,
  34961. rotate: 0,
  34962. // true | false | null/undefined (auto)
  34963. showMinLabel: null,
  34964. // true | false | null/undefined (auto)
  34965. showMaxLabel: null,
  34966. margin: 8,
  34967. // formatter: null,
  34968. fontSize: 12
  34969. },
  34970. splitLine: {
  34971. show: true,
  34972. lineStyle: {
  34973. color: ['#ccc'],
  34974. width: 1,
  34975. type: 'solid'
  34976. }
  34977. },
  34978. splitArea: {
  34979. show: false,
  34980. areaStyle: {
  34981. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  34982. }
  34983. }
  34984. };
  34985. var axisDefault = {};
  34986. axisDefault.categoryAxis = merge({
  34987. // The gap at both ends of the axis. For categoryAxis, boolean.
  34988. boundaryGap: true,
  34989. // Set false to faster category collection.
  34990. // Only usefull in the case like: category is
  34991. // ['2012-01-01', '2012-01-02', ...], where the input
  34992. // data has been ensured not duplicate and is large data.
  34993. // null means "auto":
  34994. // if axis.data provided, do not deduplication,
  34995. // else do deduplication.
  34996. deduplication: null,
  34997. // splitArea: {
  34998. // show: false
  34999. // },
  35000. splitLine: {
  35001. show: false
  35002. },
  35003. axisTick: {
  35004. // If tick is align with label when boundaryGap is true
  35005. alignWithLabel: false,
  35006. interval: 'auto'
  35007. },
  35008. axisLabel: {
  35009. interval: 'auto'
  35010. }
  35011. }, defaultOption);
  35012. axisDefault.valueAxis = merge({
  35013. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35014. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35015. boundaryGap: [0, 0],
  35016. // TODO
  35017. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35018. // Min value of the axis. can be:
  35019. // + a number
  35020. // + 'dataMin': use the min value in data.
  35021. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35022. // min: null,
  35023. // Max value of the axis. can be:
  35024. // + a number
  35025. // + 'dataMax': use the max value in data.
  35026. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35027. // max: null,
  35028. // Readonly prop, specifies start value of the range when using data zoom.
  35029. // rangeStart: null
  35030. // Readonly prop, specifies end value of the range when using data zoom.
  35031. // rangeEnd: null
  35032. // Optional value can be:
  35033. // + `false`: always include value 0.
  35034. // + `true`: the extent do not consider value 0.
  35035. // scale: false,
  35036. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35037. splitNumber: 5,
  35038. // Interval specifies the span of the ticks is mandatorily.
  35039. // interval: null
  35040. // Specify min interval when auto calculate tick interval.
  35041. // minInterval: null
  35042. // Specify max interval when auto calculate tick interval.
  35043. // maxInterval: null
  35044. minorTick: {
  35045. // Minor tick, not available for cateogry axis.
  35046. show: false,
  35047. // Split number of minor ticks. The value should be in range of (0, 100)
  35048. splitNumber: 5,
  35049. // Lenght of minor tick
  35050. length: 3,
  35051. // Same inside with axisTick
  35052. // Line style
  35053. lineStyle: {
  35054. // Default to be same with axisTick
  35055. }
  35056. },
  35057. minorSplitLine: {
  35058. show: false,
  35059. lineStyle: {
  35060. color: '#eee',
  35061. width: 1
  35062. }
  35063. }
  35064. }, defaultOption);
  35065. axisDefault.timeAxis = defaults({
  35066. scale: true,
  35067. min: 'dataMin',
  35068. max: 'dataMax'
  35069. }, axisDefault.valueAxis);
  35070. axisDefault.logAxis = defaults({
  35071. scale: true,
  35072. logBase: 10
  35073. }, axisDefault.valueAxis);
  35074. /*
  35075. * Licensed to the Apache Software Foundation (ASF) under one
  35076. * or more contributor license agreements. See the NOTICE file
  35077. * distributed with this work for additional information
  35078. * regarding copyright ownership. The ASF licenses this file
  35079. * to you under the Apache License, Version 2.0 (the
  35080. * "License"); you may not use this file except in compliance
  35081. * with the License. You may obtain a copy of the License at
  35082. *
  35083. * http://www.apache.org/licenses/LICENSE-2.0
  35084. *
  35085. * Unless required by applicable law or agreed to in writing,
  35086. * software distributed under the License is distributed on an
  35087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35088. * KIND, either express or implied. See the License for the
  35089. * specific language governing permissions and limitations
  35090. * under the License.
  35091. */
  35092. // FIXME axisType is fixed ?
  35093. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35094. /**
  35095. * Generate sub axis model class
  35096. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35097. * @param {module:echarts/model/Component} BaseAxisModelClass
  35098. * @param {Function} axisTypeDefaulter
  35099. * @param {Object} [extraDefaultOption]
  35100. */
  35101. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35102. each$1(AXIS_TYPES, function (axisType) {
  35103. BaseAxisModelClass.extend({
  35104. /**
  35105. * @readOnly
  35106. */
  35107. type: axisName + 'Axis.' + axisType,
  35108. mergeDefaultAndTheme: function (option, ecModel) {
  35109. var layoutMode = this.layoutMode;
  35110. var inputPositionParams = layoutMode
  35111. ? getLayoutParams(option) : {};
  35112. var themeModel = ecModel.getTheme();
  35113. merge(option, themeModel.get(axisType + 'Axis'));
  35114. merge(option, this.getDefaultOption());
  35115. option.type = axisTypeDefaulter(axisName, option);
  35116. if (layoutMode) {
  35117. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35118. }
  35119. },
  35120. /**
  35121. * @override
  35122. */
  35123. optionUpdated: function () {
  35124. var thisOption = this.option;
  35125. if (thisOption.type === 'category') {
  35126. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35127. }
  35128. },
  35129. /**
  35130. * Should not be called before all of 'getInitailData' finished.
  35131. * Because categories are collected during initializing data.
  35132. */
  35133. getCategories: function (rawData) {
  35134. var option = this.option;
  35135. // FIXME
  35136. // warning if called before all of 'getInitailData' finished.
  35137. if (option.type === 'category') {
  35138. if (rawData) {
  35139. return option.data;
  35140. }
  35141. return this.__ordinalMeta.categories;
  35142. }
  35143. },
  35144. getOrdinalMeta: function () {
  35145. return this.__ordinalMeta;
  35146. },
  35147. defaultOption: mergeAll(
  35148. [
  35149. {},
  35150. axisDefault[axisType + 'Axis'],
  35151. extraDefaultOption
  35152. ],
  35153. true
  35154. )
  35155. });
  35156. });
  35157. ComponentModel.registerSubTypeDefaulter(
  35158. axisName + 'Axis',
  35159. curry(axisTypeDefaulter, axisName)
  35160. );
  35161. };
  35162. /*
  35163. * Licensed to the Apache Software Foundation (ASF) under one
  35164. * or more contributor license agreements. See the NOTICE file
  35165. * distributed with this work for additional information
  35166. * regarding copyright ownership. The ASF licenses this file
  35167. * to you under the Apache License, Version 2.0 (the
  35168. * "License"); you may not use this file except in compliance
  35169. * with the License. You may obtain a copy of the License at
  35170. *
  35171. * http://www.apache.org/licenses/LICENSE-2.0
  35172. *
  35173. * Unless required by applicable law or agreed to in writing,
  35174. * software distributed under the License is distributed on an
  35175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35176. * KIND, either express or implied. See the License for the
  35177. * specific language governing permissions and limitations
  35178. * under the License.
  35179. */
  35180. var AxisModel = ComponentModel.extend({
  35181. type: 'cartesian2dAxis',
  35182. /**
  35183. * @type {module:echarts/coord/cartesian/Axis2D}
  35184. */
  35185. axis: null,
  35186. /**
  35187. * @override
  35188. */
  35189. init: function () {
  35190. AxisModel.superApply(this, 'init', arguments);
  35191. this.resetRange();
  35192. },
  35193. /**
  35194. * @override
  35195. */
  35196. mergeOption: function () {
  35197. AxisModel.superApply(this, 'mergeOption', arguments);
  35198. this.resetRange();
  35199. },
  35200. /**
  35201. * @override
  35202. */
  35203. restoreData: function () {
  35204. AxisModel.superApply(this, 'restoreData', arguments);
  35205. this.resetRange();
  35206. },
  35207. /**
  35208. * @override
  35209. * @return {module:echarts/model/Component}
  35210. */
  35211. getCoordSysModel: function () {
  35212. return this.ecModel.queryComponents({
  35213. mainType: 'grid',
  35214. index: this.option.gridIndex,
  35215. id: this.option.gridId
  35216. })[0];
  35217. }
  35218. });
  35219. function getAxisType(axisDim, option) {
  35220. // Default axis with data is category axis
  35221. return option.type || (option.data ? 'category' : 'value');
  35222. }
  35223. merge(AxisModel.prototype, axisModelCommonMixin);
  35224. var extraOption = {
  35225. // gridIndex: 0,
  35226. // gridId: '',
  35227. // Offset is for multiple axis on the same position
  35228. offset: 0
  35229. };
  35230. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35231. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35232. /*
  35233. * Licensed to the Apache Software Foundation (ASF) under one
  35234. * or more contributor license agreements. See the NOTICE file
  35235. * distributed with this work for additional information
  35236. * regarding copyright ownership. The ASF licenses this file
  35237. * to you under the Apache License, Version 2.0 (the
  35238. * "License"); you may not use this file except in compliance
  35239. * with the License. You may obtain a copy of the License at
  35240. *
  35241. * http://www.apache.org/licenses/LICENSE-2.0
  35242. *
  35243. * Unless required by applicable law or agreed to in writing,
  35244. * software distributed under the License is distributed on an
  35245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35246. * KIND, either express or implied. See the License for the
  35247. * specific language governing permissions and limitations
  35248. * under the License.
  35249. */
  35250. // Grid 是在有直角坐标系的时候必须要存在的
  35251. // 所以这里也要被 Cartesian2D 依赖
  35252. ComponentModel.extend({
  35253. type: 'grid',
  35254. dependencies: ['xAxis', 'yAxis'],
  35255. layoutMode: 'box',
  35256. /**
  35257. * @type {module:echarts/coord/cartesian/Grid}
  35258. */
  35259. coordinateSystem: null,
  35260. defaultOption: {
  35261. show: false,
  35262. zlevel: 0,
  35263. z: 0,
  35264. left: '10%',
  35265. top: 60,
  35266. right: '10%',
  35267. bottom: 60,
  35268. // If grid size contain label
  35269. containLabel: false,
  35270. // width: {totalWidth} - left - right,
  35271. // height: {totalHeight} - top - bottom,
  35272. backgroundColor: 'rgba(0,0,0,0)',
  35273. borderWidth: 1,
  35274. borderColor: '#ccc'
  35275. }
  35276. });
  35277. /*
  35278. * Licensed to the Apache Software Foundation (ASF) under one
  35279. * or more contributor license agreements. See the NOTICE file
  35280. * distributed with this work for additional information
  35281. * regarding copyright ownership. The ASF licenses this file
  35282. * to you under the Apache License, Version 2.0 (the
  35283. * "License"); you may not use this file except in compliance
  35284. * with the License. You may obtain a copy of the License at
  35285. *
  35286. * http://www.apache.org/licenses/LICENSE-2.0
  35287. *
  35288. * Unless required by applicable law or agreed to in writing,
  35289. * software distributed under the License is distributed on an
  35290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35291. * KIND, either express or implied. See the License for the
  35292. * specific language governing permissions and limitations
  35293. * under the License.
  35294. */
  35295. /**
  35296. * Grid is a region which contains at most 4 cartesian systems
  35297. *
  35298. * TODO Default cartesian
  35299. */
  35300. // Depends on GridModel, AxisModel, which performs preprocess.
  35301. /**
  35302. * Check if the axis is used in the specified grid
  35303. * @inner
  35304. */
  35305. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35306. return axisModel.getCoordSysModel() === gridModel;
  35307. }
  35308. function Grid(gridModel, ecModel, api) {
  35309. /**
  35310. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35311. * @private
  35312. */
  35313. this._coordsMap = {};
  35314. /**
  35315. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35316. * @private
  35317. */
  35318. this._coordsList = [];
  35319. /**
  35320. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35321. * @private
  35322. */
  35323. this._axesMap = {};
  35324. /**
  35325. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35326. * @private
  35327. */
  35328. this._axesList = [];
  35329. this._initCartesian(gridModel, ecModel, api);
  35330. this.model = gridModel;
  35331. }
  35332. var gridProto = Grid.prototype;
  35333. gridProto.type = 'grid';
  35334. gridProto.axisPointerEnabled = true;
  35335. gridProto.getRect = function () {
  35336. return this._rect;
  35337. };
  35338. gridProto.update = function (ecModel, api) {
  35339. var axesMap = this._axesMap;
  35340. this._updateScale(ecModel, this.model);
  35341. each$1(axesMap.x, function (xAxis) {
  35342. niceScaleExtent(xAxis.scale, xAxis.model);
  35343. });
  35344. each$1(axesMap.y, function (yAxis) {
  35345. niceScaleExtent(yAxis.scale, yAxis.model);
  35346. });
  35347. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35348. var onZeroRecords = {};
  35349. each$1(axesMap.x, function (xAxis) {
  35350. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35351. });
  35352. each$1(axesMap.y, function (yAxis) {
  35353. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35354. });
  35355. // Resize again if containLabel is enabled
  35356. // FIXME It may cause getting wrong grid size in data processing stage
  35357. this.resize(this.model, api);
  35358. };
  35359. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35360. axis.getAxesOnZeroOf = function () {
  35361. // TODO: onZero of multiple axes.
  35362. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35363. };
  35364. // onZero can not be enabled in these two situations:
  35365. // 1. When any other axis is a category axis.
  35366. // 2. When no axis is cross 0 point.
  35367. var otherAxes = axesMap[otherAxisDim];
  35368. var otherAxisOnZeroOf;
  35369. var axisModel = axis.model;
  35370. var onZero = axisModel.get('axisLine.onZero');
  35371. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35372. if (!onZero) {
  35373. return;
  35374. }
  35375. // If target axis is specified.
  35376. if (onZeroAxisIndex != null) {
  35377. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35378. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35379. }
  35380. }
  35381. else {
  35382. // Find the first available other axis.
  35383. for (var idx in otherAxes) {
  35384. if (otherAxes.hasOwnProperty(idx)
  35385. && canOnZeroToAxis(otherAxes[idx])
  35386. // Consider that two Y axes on one value axis,
  35387. // if both onZero, the two Y axes overlap.
  35388. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35389. ) {
  35390. otherAxisOnZeroOf = otherAxes[idx];
  35391. break;
  35392. }
  35393. }
  35394. }
  35395. if (otherAxisOnZeroOf) {
  35396. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35397. }
  35398. function getOnZeroRecordKey(axis) {
  35399. return axis.dim + '_' + axis.index;
  35400. }
  35401. }
  35402. function canOnZeroToAxis(axis) {
  35403. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35404. }
  35405. /**
  35406. * Resize the grid
  35407. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35408. * @param {module:echarts/ExtensionAPI} api
  35409. */
  35410. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35411. var gridRect = getLayoutRect(
  35412. gridModel.getBoxLayoutParams(), {
  35413. width: api.getWidth(),
  35414. height: api.getHeight()
  35415. });
  35416. this._rect = gridRect;
  35417. var axesList = this._axesList;
  35418. adjustAxes();
  35419. // Minus label size
  35420. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35421. each$1(axesList, function (axis) {
  35422. if (!axis.model.get('axisLabel.inside')) {
  35423. var labelUnionRect = estimateLabelUnionRect(axis);
  35424. if (labelUnionRect) {
  35425. var dim = axis.isHorizontal() ? 'height' : 'width';
  35426. var margin = axis.model.get('axisLabel.margin');
  35427. gridRect[dim] -= labelUnionRect[dim] + margin;
  35428. if (axis.position === 'top') {
  35429. gridRect.y += labelUnionRect.height + margin;
  35430. }
  35431. else if (axis.position === 'left') {
  35432. gridRect.x += labelUnionRect.width + margin;
  35433. }
  35434. }
  35435. }
  35436. });
  35437. adjustAxes();
  35438. }
  35439. function adjustAxes() {
  35440. each$1(axesList, function (axis) {
  35441. var isHorizontal = axis.isHorizontal();
  35442. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35443. var idx = axis.inverse ? 1 : 0;
  35444. axis.setExtent(extent[idx], extent[1 - idx]);
  35445. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35446. });
  35447. }
  35448. };
  35449. /**
  35450. * @param {string} axisType
  35451. * @param {number} [axisIndex]
  35452. */
  35453. gridProto.getAxis = function (axisType, axisIndex) {
  35454. var axesMapOnDim = this._axesMap[axisType];
  35455. if (axesMapOnDim != null) {
  35456. if (axisIndex == null) {
  35457. // Find first axis
  35458. for (var name in axesMapOnDim) {
  35459. if (axesMapOnDim.hasOwnProperty(name)) {
  35460. return axesMapOnDim[name];
  35461. }
  35462. }
  35463. }
  35464. return axesMapOnDim[axisIndex];
  35465. }
  35466. };
  35467. /**
  35468. * @return {Array.<module:echarts/coord/Axis>}
  35469. */
  35470. gridProto.getAxes = function () {
  35471. return this._axesList.slice();
  35472. };
  35473. /**
  35474. * Usage:
  35475. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35476. * grid.getCartesian(xAxisIndex);
  35477. * grid.getCartesian(null, yAxisIndex);
  35478. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35479. *
  35480. * @param {number|Object} [xAxisIndex]
  35481. * @param {number} [yAxisIndex]
  35482. */
  35483. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35484. if (xAxisIndex != null && yAxisIndex != null) {
  35485. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35486. return this._coordsMap[key];
  35487. }
  35488. if (isObject$1(xAxisIndex)) {
  35489. yAxisIndex = xAxisIndex.yAxisIndex;
  35490. xAxisIndex = xAxisIndex.xAxisIndex;
  35491. }
  35492. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35493. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35494. if (coordList[i].getAxis('x').index === xAxisIndex
  35495. || coordList[i].getAxis('y').index === yAxisIndex
  35496. ) {
  35497. return coordList[i];
  35498. }
  35499. }
  35500. };
  35501. gridProto.getCartesians = function () {
  35502. return this._coordsList.slice();
  35503. };
  35504. /**
  35505. * @implements
  35506. * see {module:echarts/CoodinateSystem}
  35507. */
  35508. gridProto.convertToPixel = function (ecModel, finder, value) {
  35509. var target = this._findConvertTarget(ecModel, finder);
  35510. return target.cartesian
  35511. ? target.cartesian.dataToPoint(value)
  35512. : target.axis
  35513. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35514. : null;
  35515. };
  35516. /**
  35517. * @implements
  35518. * see {module:echarts/CoodinateSystem}
  35519. */
  35520. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35521. var target = this._findConvertTarget(ecModel, finder);
  35522. return target.cartesian
  35523. ? target.cartesian.pointToData(value)
  35524. : target.axis
  35525. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35526. : null;
  35527. };
  35528. /**
  35529. * @inner
  35530. */
  35531. gridProto._findConvertTarget = function (ecModel, finder) {
  35532. var seriesModel = finder.seriesModel;
  35533. var xAxisModel = finder.xAxisModel
  35534. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35535. var yAxisModel = finder.yAxisModel
  35536. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35537. var gridModel = finder.gridModel;
  35538. var coordsList = this._coordsList;
  35539. var cartesian;
  35540. var axis;
  35541. if (seriesModel) {
  35542. cartesian = seriesModel.coordinateSystem;
  35543. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35544. }
  35545. else if (xAxisModel && yAxisModel) {
  35546. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35547. }
  35548. else if (xAxisModel) {
  35549. axis = this.getAxis('x', xAxisModel.componentIndex);
  35550. }
  35551. else if (yAxisModel) {
  35552. axis = this.getAxis('y', yAxisModel.componentIndex);
  35553. }
  35554. // Lowest priority.
  35555. else if (gridModel) {
  35556. var grid = gridModel.coordinateSystem;
  35557. if (grid === this) {
  35558. cartesian = this._coordsList[0];
  35559. }
  35560. }
  35561. return {cartesian: cartesian, axis: axis};
  35562. };
  35563. /**
  35564. * @implements
  35565. * see {module:echarts/CoodinateSystem}
  35566. */
  35567. gridProto.containPoint = function (point) {
  35568. var coord = this._coordsList[0];
  35569. if (coord) {
  35570. return coord.containPoint(point);
  35571. }
  35572. };
  35573. /**
  35574. * Initialize cartesian coordinate systems
  35575. * @private
  35576. */
  35577. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35578. var axisPositionUsed = {
  35579. left: false,
  35580. right: false,
  35581. top: false,
  35582. bottom: false
  35583. };
  35584. var axesMap = {
  35585. x: {},
  35586. y: {}
  35587. };
  35588. var axesCount = {
  35589. x: 0,
  35590. y: 0
  35591. };
  35592. /// Create axis
  35593. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35594. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35595. if (!axesCount.x || !axesCount.y) {
  35596. // Roll back when there no either x or y axis
  35597. this._axesMap = {};
  35598. this._axesList = [];
  35599. return;
  35600. }
  35601. this._axesMap = axesMap;
  35602. /// Create cartesian2d
  35603. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35604. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35605. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35606. var cartesian = new Cartesian2D(key);
  35607. cartesian.grid = this;
  35608. cartesian.model = gridModel;
  35609. this._coordsMap[key] = cartesian;
  35610. this._coordsList.push(cartesian);
  35611. cartesian.addAxis(xAxis);
  35612. cartesian.addAxis(yAxis);
  35613. }, this);
  35614. }, this);
  35615. function createAxisCreator(axisType) {
  35616. return function (axisModel, idx) {
  35617. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35618. return;
  35619. }
  35620. var axisPosition = axisModel.get('position');
  35621. if (axisType === 'x') {
  35622. // Fix position
  35623. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35624. // Default bottom of X
  35625. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35626. }
  35627. }
  35628. else {
  35629. // Fix position
  35630. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35631. // Default left of Y
  35632. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35633. }
  35634. }
  35635. axisPositionUsed[axisPosition] = true;
  35636. var axis = new Axis2D(
  35637. axisType, createScaleByModel(axisModel),
  35638. [0, 0],
  35639. axisModel.get('type'),
  35640. axisPosition
  35641. );
  35642. var isCategory = axis.type === 'category';
  35643. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35644. axis.inverse = axisModel.get('inverse');
  35645. // Inject axis into axisModel
  35646. axisModel.axis = axis;
  35647. // Inject axisModel into axis
  35648. axis.model = axisModel;
  35649. // Inject grid info axis
  35650. axis.grid = this;
  35651. // Index of axis, can be used as key
  35652. axis.index = idx;
  35653. this._axesList.push(axis);
  35654. axesMap[axisType][idx] = axis;
  35655. axesCount[axisType]++;
  35656. };
  35657. }
  35658. };
  35659. /**
  35660. * Update cartesian properties from series
  35661. * @param {module:echarts/model/Option} option
  35662. * @private
  35663. */
  35664. gridProto._updateScale = function (ecModel, gridModel) {
  35665. // Reset scale
  35666. each$1(this._axesList, function (axis) {
  35667. axis.scale.setExtent(Infinity, -Infinity);
  35668. });
  35669. ecModel.eachSeries(function (seriesModel) {
  35670. if (isCartesian2D(seriesModel)) {
  35671. var axesModels = findAxesModels(seriesModel, ecModel);
  35672. var xAxisModel = axesModels[0];
  35673. var yAxisModel = axesModels[1];
  35674. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35675. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35676. ) {
  35677. return;
  35678. }
  35679. var cartesian = this.getCartesian(
  35680. xAxisModel.componentIndex, yAxisModel.componentIndex
  35681. );
  35682. var data = seriesModel.getData();
  35683. var xAxis = cartesian.getAxis('x');
  35684. var yAxis = cartesian.getAxis('y');
  35685. if (data.type === 'list') {
  35686. unionExtent(data, xAxis, seriesModel);
  35687. unionExtent(data, yAxis, seriesModel);
  35688. }
  35689. }
  35690. }, this);
  35691. function unionExtent(data, axis, seriesModel) {
  35692. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35693. axis.scale.unionExtentFromData(
  35694. // For example, the extent of the orginal dimension
  35695. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35696. // is [7, 9], the final extent should not include [0.1, 0.5].
  35697. data, getStackedDimension(data, dim)
  35698. );
  35699. });
  35700. }
  35701. };
  35702. /**
  35703. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35704. * @return {Object} {baseAxes: [], otherAxes: []}
  35705. */
  35706. gridProto.getTooltipAxes = function (dim) {
  35707. var baseAxes = [];
  35708. var otherAxes = [];
  35709. each$1(this.getCartesians(), function (cartesian) {
  35710. var baseAxis = (dim != null && dim !== 'auto')
  35711. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35712. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35713. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35714. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35715. });
  35716. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35717. };
  35718. /**
  35719. * @inner
  35720. */
  35721. function updateAxisTransform(axis, coordBase) {
  35722. var axisExtent = axis.getExtent();
  35723. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35724. // Fast transform
  35725. axis.toGlobalCoord = axis.dim === 'x'
  35726. ? function (coord) {
  35727. return coord + coordBase;
  35728. }
  35729. : function (coord) {
  35730. return axisExtentSum - coord + coordBase;
  35731. };
  35732. axis.toLocalCoord = axis.dim === 'x'
  35733. ? function (coord) {
  35734. return coord - coordBase;
  35735. }
  35736. : function (coord) {
  35737. return axisExtentSum - coord + coordBase;
  35738. };
  35739. }
  35740. var axesTypes = ['xAxis', 'yAxis'];
  35741. /**
  35742. * @inner
  35743. */
  35744. function findAxesModels(seriesModel, ecModel) {
  35745. return map(axesTypes, function (axisType) {
  35746. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35747. if (__DEV__) {
  35748. if (!axisModel) {
  35749. throw new Error(axisType + ' "' + retrieve(
  35750. seriesModel.get(axisType + 'Index'),
  35751. seriesModel.get(axisType + 'Id'),
  35752. 0
  35753. ) + '" not found');
  35754. }
  35755. }
  35756. return axisModel;
  35757. });
  35758. }
  35759. /**
  35760. * @inner
  35761. */
  35762. function isCartesian2D(seriesModel) {
  35763. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35764. }
  35765. Grid.create = function (ecModel, api) {
  35766. var grids = [];
  35767. ecModel.eachComponent('grid', function (gridModel, idx) {
  35768. var grid = new Grid(gridModel, ecModel, api);
  35769. grid.name = 'grid_' + idx;
  35770. // dataSampling requires axis extent, so resize
  35771. // should be performed in create stage.
  35772. grid.resize(gridModel, api, true);
  35773. gridModel.coordinateSystem = grid;
  35774. grids.push(grid);
  35775. });
  35776. // Inject the coordinateSystems into seriesModel
  35777. ecModel.eachSeries(function (seriesModel) {
  35778. if (!isCartesian2D(seriesModel)) {
  35779. return;
  35780. }
  35781. var axesModels = findAxesModels(seriesModel, ecModel);
  35782. var xAxisModel = axesModels[0];
  35783. var yAxisModel = axesModels[1];
  35784. var gridModel = xAxisModel.getCoordSysModel();
  35785. if (__DEV__) {
  35786. if (!gridModel) {
  35787. throw new Error(
  35788. 'Grid "' + retrieve(
  35789. xAxisModel.get('gridIndex'),
  35790. xAxisModel.get('gridId'),
  35791. 0
  35792. ) + '" not found'
  35793. );
  35794. }
  35795. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  35796. throw new Error('xAxis and yAxis must use the same grid');
  35797. }
  35798. }
  35799. var grid = gridModel.coordinateSystem;
  35800. seriesModel.coordinateSystem = grid.getCartesian(
  35801. xAxisModel.componentIndex, yAxisModel.componentIndex
  35802. );
  35803. });
  35804. return grids;
  35805. };
  35806. // For deciding which dimensions to use when creating list data
  35807. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  35808. CoordinateSystemManager.register('cartesian2d', Grid);
  35809. /*
  35810. * Licensed to the Apache Software Foundation (ASF) under one
  35811. * or more contributor license agreements. See the NOTICE file
  35812. * distributed with this work for additional information
  35813. * regarding copyright ownership. The ASF licenses this file
  35814. * to you under the Apache License, Version 2.0 (the
  35815. * "License"); you may not use this file except in compliance
  35816. * with the License. You may obtain a copy of the License at
  35817. *
  35818. * http://www.apache.org/licenses/LICENSE-2.0
  35819. *
  35820. * Unless required by applicable law or agreed to in writing,
  35821. * software distributed under the License is distributed on an
  35822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35823. * KIND, either express or implied. See the License for the
  35824. * specific language governing permissions and limitations
  35825. * under the License.
  35826. */
  35827. var PI$2 = Math.PI;
  35828. /**
  35829. * A final axis is translated and rotated from a "standard axis".
  35830. * So opt.position and opt.rotation is required.
  35831. *
  35832. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  35833. * for example: (0, 0) ------------> (0, 50)
  35834. *
  35835. * nameDirection or tickDirection or labelDirection is 1 means tick
  35836. * or label is below the standard axis, whereas is -1 means above
  35837. * the standard axis. labelOffset means offset between label and axis,
  35838. * which is useful when 'onZero', where axisLabel is in the grid and
  35839. * label in outside grid.
  35840. *
  35841. * Tips: like always,
  35842. * positive rotation represents anticlockwise, and negative rotation
  35843. * represents clockwise.
  35844. * The direction of position coordinate is the same as the direction
  35845. * of screen coordinate.
  35846. *
  35847. * Do not need to consider axis 'inverse', which is auto processed by
  35848. * axis extent.
  35849. *
  35850. * @param {module:zrender/container/Group} group
  35851. * @param {Object} axisModel
  35852. * @param {Object} opt Standard axis parameters.
  35853. * @param {Array.<number>} opt.position [x, y]
  35854. * @param {number} opt.rotation by radian
  35855. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  35856. * @param {number} [opt.tickDirection=1] 1 or -1
  35857. * @param {number} [opt.labelDirection=1] 1 or -1
  35858. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  35859. * @param {string} [opt.axisLabelShow] default get from axisModel.
  35860. * @param {string} [opt.axisName] default get from axisModel.
  35861. * @param {number} [opt.axisNameAvailableWidth]
  35862. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  35863. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  35864. * @param {number} [opt.nameTruncateMaxWidth]
  35865. */
  35866. var AxisBuilder = function (axisModel, opt) {
  35867. /**
  35868. * @readOnly
  35869. */
  35870. this.opt = opt;
  35871. /**
  35872. * @readOnly
  35873. */
  35874. this.axisModel = axisModel;
  35875. // Default value
  35876. defaults(
  35877. opt,
  35878. {
  35879. labelOffset: 0,
  35880. nameDirection: 1,
  35881. tickDirection: 1,
  35882. labelDirection: 1,
  35883. silent: true
  35884. }
  35885. );
  35886. /**
  35887. * @readOnly
  35888. */
  35889. this.group = new Group();
  35890. // FIXME Not use a seperate text group?
  35891. var dumbGroup = new Group({
  35892. position: opt.position.slice(),
  35893. rotation: opt.rotation
  35894. });
  35895. // this.group.add(dumbGroup);
  35896. // this._dumbGroup = dumbGroup;
  35897. dumbGroup.updateTransform();
  35898. this._transform = dumbGroup.transform;
  35899. this._dumbGroup = dumbGroup;
  35900. };
  35901. AxisBuilder.prototype = {
  35902. constructor: AxisBuilder,
  35903. hasBuilder: function (name) {
  35904. return !!builders[name];
  35905. },
  35906. add: function (name) {
  35907. builders[name].call(this);
  35908. },
  35909. getGroup: function () {
  35910. return this.group;
  35911. }
  35912. };
  35913. var builders = {
  35914. /**
  35915. * @private
  35916. */
  35917. axisLine: function () {
  35918. var opt = this.opt;
  35919. var axisModel = this.axisModel;
  35920. if (!axisModel.get('axisLine.show')) {
  35921. return;
  35922. }
  35923. var extent = this.axisModel.axis.getExtent();
  35924. var matrix = this._transform;
  35925. var pt1 = [extent[0], 0];
  35926. var pt2 = [extent[1], 0];
  35927. if (matrix) {
  35928. applyTransform(pt1, pt1, matrix);
  35929. applyTransform(pt2, pt2, matrix);
  35930. }
  35931. var lineStyle = extend(
  35932. {
  35933. lineCap: 'round'
  35934. },
  35935. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  35936. );
  35937. this.group.add(new Line({
  35938. // Id for animation
  35939. anid: 'line',
  35940. subPixelOptimize: true,
  35941. shape: {
  35942. x1: pt1[0],
  35943. y1: pt1[1],
  35944. x2: pt2[0],
  35945. y2: pt2[1]
  35946. },
  35947. style: lineStyle,
  35948. strokeContainThreshold: opt.strokeContainThreshold || 5,
  35949. silent: true,
  35950. z2: 1
  35951. }));
  35952. var arrows = axisModel.get('axisLine.symbol');
  35953. var arrowSize = axisModel.get('axisLine.symbolSize');
  35954. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  35955. if (typeof arrowOffset === 'number') {
  35956. arrowOffset = [arrowOffset, arrowOffset];
  35957. }
  35958. if (arrows != null) {
  35959. if (typeof arrows === 'string') {
  35960. // Use the same arrow for start and end point
  35961. arrows = [arrows, arrows];
  35962. }
  35963. if (typeof arrowSize === 'string'
  35964. || typeof arrowSize === 'number'
  35965. ) {
  35966. // Use the same size for width and height
  35967. arrowSize = [arrowSize, arrowSize];
  35968. }
  35969. var symbolWidth = arrowSize[0];
  35970. var symbolHeight = arrowSize[1];
  35971. each$1([{
  35972. rotate: opt.rotation + Math.PI / 2,
  35973. offset: arrowOffset[0],
  35974. r: 0
  35975. }, {
  35976. rotate: opt.rotation - Math.PI / 2,
  35977. offset: arrowOffset[1],
  35978. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  35979. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  35980. }], function (point, index) {
  35981. if (arrows[index] !== 'none' && arrows[index] != null) {
  35982. var symbol = createSymbol(
  35983. arrows[index],
  35984. -symbolWidth / 2,
  35985. -symbolHeight / 2,
  35986. symbolWidth,
  35987. symbolHeight,
  35988. lineStyle.stroke,
  35989. true
  35990. );
  35991. // Calculate arrow position with offset
  35992. var r = point.r + point.offset;
  35993. var pos = [
  35994. pt1[0] + r * Math.cos(opt.rotation),
  35995. pt1[1] - r * Math.sin(opt.rotation)
  35996. ];
  35997. symbol.attr({
  35998. rotation: point.rotate,
  35999. position: pos,
  36000. silent: true,
  36001. z2: 11
  36002. });
  36003. this.group.add(symbol);
  36004. }
  36005. }, this);
  36006. }
  36007. },
  36008. /**
  36009. * @private
  36010. */
  36011. axisTickLabel: function () {
  36012. var axisModel = this.axisModel;
  36013. var opt = this.opt;
  36014. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36015. var labelEls = buildAxisLabel(this, axisModel, opt);
  36016. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36017. buildAxisMinorTicks(this, axisModel, opt);
  36018. },
  36019. /**
  36020. * @private
  36021. */
  36022. axisName: function () {
  36023. var opt = this.opt;
  36024. var axisModel = this.axisModel;
  36025. var name = retrieve(opt.axisName, axisModel.get('name'));
  36026. if (!name) {
  36027. return;
  36028. }
  36029. var nameLocation = axisModel.get('nameLocation');
  36030. var nameDirection = opt.nameDirection;
  36031. var textStyleModel = axisModel.getModel('nameTextStyle');
  36032. var gap = axisModel.get('nameGap') || 0;
  36033. var extent = this.axisModel.axis.getExtent();
  36034. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36035. var pos = [
  36036. nameLocation === 'start'
  36037. ? extent[0] - gapSignal * gap
  36038. : nameLocation === 'end'
  36039. ? extent[1] + gapSignal * gap
  36040. : (extent[0] + extent[1]) / 2, // 'middle'
  36041. // Reuse labelOffset.
  36042. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36043. ];
  36044. var labelLayout;
  36045. var nameRotation = axisModel.get('nameRotate');
  36046. if (nameRotation != null) {
  36047. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36048. }
  36049. var axisNameAvailableWidth;
  36050. if (isNameLocationCenter(nameLocation)) {
  36051. labelLayout = innerTextLayout(
  36052. opt.rotation,
  36053. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36054. nameDirection
  36055. );
  36056. }
  36057. else {
  36058. labelLayout = endTextLayout(
  36059. opt, nameLocation, nameRotation || 0, extent
  36060. );
  36061. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36062. if (axisNameAvailableWidth != null) {
  36063. axisNameAvailableWidth = Math.abs(
  36064. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36065. );
  36066. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36067. }
  36068. }
  36069. var textFont = textStyleModel.getFont();
  36070. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36071. var ellipsis = truncateOpt.ellipsis;
  36072. var maxWidth = retrieve(
  36073. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36074. );
  36075. // FIXME
  36076. // truncate rich text? (consider performance)
  36077. var truncatedText = (ellipsis != null && maxWidth != null)
  36078. ? truncateText$1(
  36079. name, maxWidth, textFont, ellipsis,
  36080. {minChar: 2, placeholder: truncateOpt.placeholder}
  36081. )
  36082. : name;
  36083. var tooltipOpt = axisModel.get('tooltip', true);
  36084. var mainType = axisModel.mainType;
  36085. var formatterParams = {
  36086. componentType: mainType,
  36087. name: name,
  36088. $vars: ['name']
  36089. };
  36090. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36091. var textEl = new Text({
  36092. // Id for animation
  36093. anid: 'name',
  36094. __fullText: name,
  36095. __truncatedText: truncatedText,
  36096. position: pos,
  36097. rotation: labelLayout.rotation,
  36098. silent: isLabelSilent(axisModel),
  36099. z2: 1,
  36100. tooltip: (tooltipOpt && tooltipOpt.show)
  36101. ? extend({
  36102. content: name,
  36103. formatter: function () {
  36104. return name;
  36105. },
  36106. formatterParams: formatterParams
  36107. }, tooltipOpt)
  36108. : null
  36109. });
  36110. setTextStyle(textEl.style, textStyleModel, {
  36111. text: truncatedText,
  36112. textFont: textFont,
  36113. textFill: textStyleModel.getTextColor()
  36114. || axisModel.get('axisLine.lineStyle.color'),
  36115. textAlign: textStyleModel.get('align')
  36116. || labelLayout.textAlign,
  36117. textVerticalAlign: textStyleModel.get('verticalAlign')
  36118. || labelLayout.textVerticalAlign
  36119. });
  36120. if (axisModel.get('triggerEvent')) {
  36121. textEl.eventData = makeAxisEventDataBase(axisModel);
  36122. textEl.eventData.targetType = 'axisName';
  36123. textEl.eventData.name = name;
  36124. }
  36125. // FIXME
  36126. this._dumbGroup.add(textEl);
  36127. textEl.updateTransform();
  36128. this.group.add(textEl);
  36129. textEl.decomposeTransform();
  36130. }
  36131. };
  36132. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36133. var eventData = {
  36134. componentType: axisModel.mainType,
  36135. componentIndex: axisModel.componentIndex
  36136. };
  36137. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36138. return eventData;
  36139. };
  36140. /**
  36141. * @public
  36142. * @static
  36143. * @param {Object} opt
  36144. * @param {number} axisRotation in radian
  36145. * @param {number} textRotation in radian
  36146. * @param {number} direction
  36147. * @return {Object} {
  36148. * rotation, // according to axis
  36149. * textAlign,
  36150. * textVerticalAlign
  36151. * }
  36152. */
  36153. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36154. var rotationDiff = remRadian(textRotation - axisRotation);
  36155. var textAlign;
  36156. var textVerticalAlign;
  36157. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36158. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36159. textAlign = 'center';
  36160. }
  36161. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36162. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36163. textAlign = 'center';
  36164. }
  36165. else {
  36166. textVerticalAlign = 'middle';
  36167. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36168. textAlign = direction > 0 ? 'right' : 'left';
  36169. }
  36170. else {
  36171. textAlign = direction > 0 ? 'left' : 'right';
  36172. }
  36173. }
  36174. return {
  36175. rotation: rotationDiff,
  36176. textAlign: textAlign,
  36177. textVerticalAlign: textVerticalAlign
  36178. };
  36179. };
  36180. function endTextLayout(opt, textPosition, textRotate, extent) {
  36181. var rotationDiff = remRadian(textRotate - opt.rotation);
  36182. var textAlign;
  36183. var textVerticalAlign;
  36184. var inverse = extent[0] > extent[1];
  36185. var onLeft = (textPosition === 'start' && !inverse)
  36186. || (textPosition !== 'start' && inverse);
  36187. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36188. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36189. textAlign = 'center';
  36190. }
  36191. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36192. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36193. textAlign = 'center';
  36194. }
  36195. else {
  36196. textVerticalAlign = 'middle';
  36197. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36198. textAlign = onLeft ? 'left' : 'right';
  36199. }
  36200. else {
  36201. textAlign = onLeft ? 'right' : 'left';
  36202. }
  36203. }
  36204. return {
  36205. rotation: rotationDiff,
  36206. textAlign: textAlign,
  36207. textVerticalAlign: textVerticalAlign
  36208. };
  36209. }
  36210. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36211. var tooltipOpt = axisModel.get('tooltip');
  36212. return axisModel.get('silent')
  36213. // Consider mouse cursor, add these restrictions.
  36214. || !(
  36215. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36216. );
  36217. };
  36218. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36219. if (shouldShowAllLabels(axisModel.axis)) {
  36220. return;
  36221. }
  36222. // If min or max are user set, we need to check
  36223. // If the tick on min(max) are overlap on their neighbour tick
  36224. // If they are overlapped, we need to hide the min(max) tick label
  36225. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36226. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36227. // FIXME
  36228. // Have not consider onBand yet, where tick els is more than label els.
  36229. labelEls = labelEls || [];
  36230. tickEls = tickEls || [];
  36231. var firstLabel = labelEls[0];
  36232. var nextLabel = labelEls[1];
  36233. var lastLabel = labelEls[labelEls.length - 1];
  36234. var prevLabel = labelEls[labelEls.length - 2];
  36235. var firstTick = tickEls[0];
  36236. var nextTick = tickEls[1];
  36237. var lastTick = tickEls[tickEls.length - 1];
  36238. var prevTick = tickEls[tickEls.length - 2];
  36239. if (showMinLabel === false) {
  36240. ignoreEl(firstLabel);
  36241. ignoreEl(firstTick);
  36242. }
  36243. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36244. if (showMinLabel) {
  36245. ignoreEl(nextLabel);
  36246. ignoreEl(nextTick);
  36247. }
  36248. else {
  36249. ignoreEl(firstLabel);
  36250. ignoreEl(firstTick);
  36251. }
  36252. }
  36253. if (showMaxLabel === false) {
  36254. ignoreEl(lastLabel);
  36255. ignoreEl(lastTick);
  36256. }
  36257. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36258. if (showMaxLabel) {
  36259. ignoreEl(prevLabel);
  36260. ignoreEl(prevTick);
  36261. }
  36262. else {
  36263. ignoreEl(lastLabel);
  36264. ignoreEl(lastTick);
  36265. }
  36266. }
  36267. }
  36268. function ignoreEl(el) {
  36269. el && (el.ignore = true);
  36270. }
  36271. function isTwoLabelOverlapped(current, next, labelLayout) {
  36272. // current and next has the same rotation.
  36273. var firstRect = current && current.getBoundingRect().clone();
  36274. var nextRect = next && next.getBoundingRect().clone();
  36275. if (!firstRect || !nextRect) {
  36276. return;
  36277. }
  36278. // When checking intersect of two rotated labels, we use mRotationBack
  36279. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36280. var mRotationBack = identity([]);
  36281. rotate(mRotationBack, mRotationBack, -current.rotation);
  36282. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36283. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36284. return firstRect.intersect(nextRect);
  36285. }
  36286. function isNameLocationCenter(nameLocation) {
  36287. return nameLocation === 'middle' || nameLocation === 'center';
  36288. }
  36289. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36290. var tickEls = [];
  36291. var pt1 = [];
  36292. var pt2 = [];
  36293. for (var i = 0; i < ticksCoords.length; i++) {
  36294. var tickCoord = ticksCoords[i].coord;
  36295. pt1[0] = tickCoord;
  36296. pt1[1] = 0;
  36297. pt2[0] = tickCoord;
  36298. pt2[1] = tickEndCoord;
  36299. if (tickTransform) {
  36300. applyTransform(pt1, pt1, tickTransform);
  36301. applyTransform(pt2, pt2, tickTransform);
  36302. }
  36303. // Tick line, Not use group transform to have better line draw
  36304. var tickEl = new Line({
  36305. // Id for animation
  36306. anid: aniid + '_' + ticksCoords[i].tickValue,
  36307. subPixelOptimize: true,
  36308. shape: {
  36309. x1: pt1[0],
  36310. y1: pt1[1],
  36311. x2: pt2[0],
  36312. y2: pt2[1]
  36313. },
  36314. style: tickLineStyle,
  36315. z2: 2,
  36316. silent: true
  36317. });
  36318. tickEls.push(tickEl);
  36319. }
  36320. return tickEls;
  36321. }
  36322. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36323. var axis = axisModel.axis;
  36324. var tickModel = axisModel.getModel('axisTick');
  36325. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36326. return;
  36327. }
  36328. var lineStyleModel = tickModel.getModel('lineStyle');
  36329. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36330. var ticksCoords = axis.getTicksCoords();
  36331. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36332. lineStyleModel.getLineStyle(),
  36333. {
  36334. stroke: axisModel.get('axisLine.lineStyle.color')
  36335. }
  36336. ), 'ticks');
  36337. for (var i = 0; i < ticksEls.length; i++) {
  36338. axisBuilder.group.add(ticksEls[i]);
  36339. }
  36340. return ticksEls;
  36341. }
  36342. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36343. var axis = axisModel.axis;
  36344. var minorTickModel = axisModel.getModel('minorTick');
  36345. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36346. return;
  36347. }
  36348. var minorTicksCoords = axis.getMinorTicksCoords();
  36349. if (!minorTicksCoords.length) {
  36350. return;
  36351. }
  36352. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36353. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36354. var minorTickLineStyle = defaults(
  36355. lineStyleModel.getLineStyle(),
  36356. defaults(
  36357. axisModel.getModel('axisTick').getLineStyle(),
  36358. {
  36359. stroke: axisModel.get('axisLine.lineStyle.color')
  36360. }
  36361. )
  36362. );
  36363. for (var i = 0; i < minorTicksCoords.length; i++) {
  36364. var minorTicksEls = createTicks(
  36365. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36366. );
  36367. for (var k = 0; k < minorTicksEls.length; k++) {
  36368. axisBuilder.group.add(minorTicksEls[k]);
  36369. }
  36370. }
  36371. }
  36372. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36373. var axis = axisModel.axis;
  36374. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36375. if (!show || axis.scale.isBlank()) {
  36376. return;
  36377. }
  36378. var labelModel = axisModel.getModel('axisLabel');
  36379. var labelMargin = labelModel.get('margin');
  36380. var labels = axis.getViewLabels();
  36381. // Special label rotate.
  36382. var labelRotation = (
  36383. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36384. ) * PI$2 / 180;
  36385. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36386. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36387. var labelEls = [];
  36388. var silent = isLabelSilent(axisModel);
  36389. var triggerEvent = axisModel.get('triggerEvent');
  36390. each$1(labels, function (labelItem, index) {
  36391. var tickValue = labelItem.tickValue;
  36392. var formattedLabel = labelItem.formattedLabel;
  36393. var rawLabel = labelItem.rawLabel;
  36394. var itemLabelModel = labelModel;
  36395. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36396. itemLabelModel = new Model(
  36397. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36398. );
  36399. }
  36400. var textColor = itemLabelModel.getTextColor()
  36401. || axisModel.get('axisLine.lineStyle.color');
  36402. var tickCoord = axis.dataToCoord(tickValue);
  36403. var pos = [
  36404. tickCoord,
  36405. opt.labelOffset + opt.labelDirection * labelMargin
  36406. ];
  36407. var textEl = new Text({
  36408. // Id for animation
  36409. anid: 'label_' + tickValue,
  36410. position: pos,
  36411. rotation: labelLayout.rotation,
  36412. silent: silent,
  36413. z2: 10
  36414. });
  36415. setTextStyle(textEl.style, itemLabelModel, {
  36416. text: formattedLabel,
  36417. textAlign: itemLabelModel.getShallow('align', true)
  36418. || labelLayout.textAlign,
  36419. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36420. || itemLabelModel.getShallow('baseline', true)
  36421. || labelLayout.textVerticalAlign,
  36422. textFill: typeof textColor === 'function'
  36423. ? textColor(
  36424. // (1) In category axis with data zoom, tick is not the original
  36425. // index of axis.data. So tick should not be exposed to user
  36426. // in category axis.
  36427. // (2) Compatible with previous version, which always use formatted label as
  36428. // input. But in interval scale the formatted label is like '223,445', which
  36429. // maked user repalce ','. So we modify it to return original val but remain
  36430. // it as 'string' to avoid error in replacing.
  36431. axis.type === 'category'
  36432. ? rawLabel
  36433. : axis.type === 'value'
  36434. ? tickValue + ''
  36435. : tickValue,
  36436. index
  36437. )
  36438. : textColor
  36439. });
  36440. // Pack data for mouse event
  36441. if (triggerEvent) {
  36442. textEl.eventData = makeAxisEventDataBase(axisModel);
  36443. textEl.eventData.targetType = 'axisLabel';
  36444. textEl.eventData.value = rawLabel;
  36445. }
  36446. // FIXME
  36447. axisBuilder._dumbGroup.add(textEl);
  36448. textEl.updateTransform();
  36449. labelEls.push(textEl);
  36450. axisBuilder.group.add(textEl);
  36451. textEl.decomposeTransform();
  36452. });
  36453. return labelEls;
  36454. }
  36455. /*
  36456. * Licensed to the Apache Software Foundation (ASF) under one
  36457. * or more contributor license agreements. See the NOTICE file
  36458. * distributed with this work for additional information
  36459. * regarding copyright ownership. The ASF licenses this file
  36460. * to you under the Apache License, Version 2.0 (the
  36461. * "License"); you may not use this file except in compliance
  36462. * with the License. You may obtain a copy of the License at
  36463. *
  36464. * http://www.apache.org/licenses/LICENSE-2.0
  36465. *
  36466. * Unless required by applicable law or agreed to in writing,
  36467. * software distributed under the License is distributed on an
  36468. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36469. * KIND, either express or implied. See the License for the
  36470. * specific language governing permissions and limitations
  36471. * under the License.
  36472. */
  36473. var each$6 = each$1;
  36474. var curry$1 = curry;
  36475. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36476. // allAxesInfo should be updated when setOption performed.
  36477. function collect(ecModel, api) {
  36478. var result = {
  36479. /**
  36480. * key: makeKey(axis.model)
  36481. * value: {
  36482. * axis,
  36483. * coordSys,
  36484. * axisPointerModel,
  36485. * triggerTooltip,
  36486. * involveSeries,
  36487. * snap,
  36488. * seriesModels,
  36489. * seriesDataCount
  36490. * }
  36491. */
  36492. axesInfo: {},
  36493. seriesInvolved: false,
  36494. /**
  36495. * key: makeKey(coordSys.model)
  36496. * value: Object: key makeKey(axis.model), value: axisInfo
  36497. */
  36498. coordSysAxesInfo: {},
  36499. coordSysMap: {}
  36500. };
  36501. collectAxesInfo(result, ecModel, api);
  36502. // Check seriesInvolved for performance, in case too many series in some chart.
  36503. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36504. return result;
  36505. }
  36506. function collectAxesInfo(result, ecModel, api) {
  36507. var globalTooltipModel = ecModel.getComponent('tooltip');
  36508. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36509. // links can only be set on global.
  36510. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36511. var linkGroups = [];
  36512. // Collect axes info.
  36513. each$6(api.getCoordinateSystems(), function (coordSys) {
  36514. // Some coordinate system do not support axes, like geo.
  36515. if (!coordSys.axisPointerEnabled) {
  36516. return;
  36517. }
  36518. var coordSysKey = makeKey(coordSys.model);
  36519. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36520. result.coordSysMap[coordSysKey] = coordSys;
  36521. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36522. // for user. So we enable seting tooltip on coordSys model.
  36523. var coordSysModel = coordSys.model;
  36524. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36525. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36526. // If axis tooltip used, choose tooltip axis for each coordSys.
  36527. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36528. if (coordSys.getTooltipAxes
  36529. && globalTooltipModel
  36530. // If tooltip.showContent is set as false, tooltip will not
  36531. // show but axisPointer will show as normal.
  36532. && baseTooltipModel.get('show')
  36533. ) {
  36534. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36535. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36536. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36537. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36538. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36539. if (triggerAxis || cross) {
  36540. each$6(tooltipAxes.baseAxes, curry$1(
  36541. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36542. ));
  36543. }
  36544. if (cross) {
  36545. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36546. }
  36547. }
  36548. // fromTooltip: true | false | 'cross'
  36549. // triggerTooltip: true | false | null
  36550. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36551. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36552. var axisPointerShow = axisPointerModel.get('show');
  36553. if (!axisPointerShow || (
  36554. axisPointerShow === 'auto'
  36555. && !fromTooltip
  36556. && !isHandleTrigger(axisPointerModel)
  36557. )) {
  36558. return;
  36559. }
  36560. if (triggerTooltip == null) {
  36561. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36562. }
  36563. axisPointerModel = fromTooltip
  36564. ? makeAxisPointerModel(
  36565. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36566. fromTooltip, triggerTooltip
  36567. )
  36568. : axisPointerModel;
  36569. var snap = axisPointerModel.get('snap');
  36570. var key = makeKey(axis.model);
  36571. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36572. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36573. var axisInfo = result.axesInfo[key] = {
  36574. key: key,
  36575. axis: axis,
  36576. coordSys: coordSys,
  36577. axisPointerModel: axisPointerModel,
  36578. triggerTooltip: triggerTooltip,
  36579. involveSeries: involveSeries,
  36580. snap: snap,
  36581. useHandle: isHandleTrigger(axisPointerModel),
  36582. seriesModels: []
  36583. };
  36584. axesInfoInCoordSys[key] = axisInfo;
  36585. result.seriesInvolved |= involveSeries;
  36586. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36587. if (groupIndex != null) {
  36588. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36589. linkGroup.axesInfo[key] = axisInfo;
  36590. linkGroup.mapper = linksOption[groupIndex].mapper;
  36591. axisInfo.linkGroup = linkGroup;
  36592. }
  36593. }
  36594. });
  36595. }
  36596. function makeAxisPointerModel(
  36597. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36598. ) {
  36599. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36600. var volatileOption = {};
  36601. each$6(
  36602. [
  36603. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36604. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36605. ],
  36606. function (field) {
  36607. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36608. }
  36609. );
  36610. // category axis do not auto snap, otherwise some tick that do not
  36611. // has value can not be hovered. value/time/log axis default snap if
  36612. // triggered from tooltip and trigger tooltip.
  36613. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36614. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36615. // Only these properties can be overrided from tooltip to axisPointer.
  36616. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36617. volatileOption.type = 'line';
  36618. }
  36619. var labelOption = volatileOption.label || (volatileOption.label = {});
  36620. // Follow the convention, do not show label when triggered by tooltip by default.
  36621. labelOption.show == null && (labelOption.show = false);
  36622. if (fromTooltip === 'cross') {
  36623. // When 'cross', both axes show labels.
  36624. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36625. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36626. // If triggerTooltip, this is a base axis, which should better not use cross style
  36627. // (cross style is dashed by default)
  36628. if (!triggerTooltip) {
  36629. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36630. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36631. }
  36632. }
  36633. return axis.model.getModel(
  36634. 'axisPointer',
  36635. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36636. );
  36637. }
  36638. function collectSeriesInfo(result, ecModel) {
  36639. // Prepare data for axis trigger
  36640. ecModel.eachSeries(function (seriesModel) {
  36641. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36642. var coordSys = seriesModel.coordinateSystem;
  36643. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36644. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36645. if (!coordSys
  36646. || seriesTooltipTrigger === 'none'
  36647. || seriesTooltipTrigger === false
  36648. || seriesTooltipTrigger === 'item'
  36649. || seriesTooltipShow === false
  36650. || seriesModel.get('axisPointer.show', true) === false
  36651. ) {
  36652. return;
  36653. }
  36654. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36655. var axis = axisInfo.axis;
  36656. if (coordSys.getAxis(axis.dim) === axis) {
  36657. axisInfo.seriesModels.push(seriesModel);
  36658. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36659. axisInfo.seriesDataCount += seriesModel.getData().count();
  36660. }
  36661. });
  36662. }, this);
  36663. }
  36664. /**
  36665. * For example:
  36666. * {
  36667. * axisPointer: {
  36668. * links: [{
  36669. * xAxisIndex: [2, 4],
  36670. * yAxisIndex: 'all'
  36671. * }, {
  36672. * xAxisId: ['a5', 'a7'],
  36673. * xAxisName: 'xxx'
  36674. * }]
  36675. * }
  36676. * }
  36677. */
  36678. function getLinkGroupIndex(linksOption, axis) {
  36679. var axisModel = axis.model;
  36680. var dim = axis.dim;
  36681. for (var i = 0; i < linksOption.length; i++) {
  36682. var linkOption = linksOption[i] || {};
  36683. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36684. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36685. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36686. ) {
  36687. return i;
  36688. }
  36689. }
  36690. }
  36691. function checkPropInLink(linkPropValue, axisPropValue) {
  36692. return linkPropValue === 'all'
  36693. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36694. || linkPropValue === axisPropValue;
  36695. }
  36696. function fixValue(axisModel) {
  36697. var axisInfo = getAxisInfo(axisModel);
  36698. if (!axisInfo) {
  36699. return;
  36700. }
  36701. var axisPointerModel = axisInfo.axisPointerModel;
  36702. var scale = axisInfo.axis.scale;
  36703. var option = axisPointerModel.option;
  36704. var status = axisPointerModel.get('status');
  36705. var value = axisPointerModel.get('value');
  36706. // Parse init value for category and time axis.
  36707. if (value != null) {
  36708. value = scale.parse(value);
  36709. }
  36710. var useHandle = isHandleTrigger(axisPointerModel);
  36711. // If `handle` used, `axisPointer` will always be displayed, so value
  36712. // and status should be initialized.
  36713. if (status == null) {
  36714. option.status = useHandle ? 'show' : 'hide';
  36715. }
  36716. var extent = scale.getExtent().slice();
  36717. extent[0] > extent[1] && extent.reverse();
  36718. if (// Pick a value on axis when initializing.
  36719. value == null
  36720. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36721. // where we should re-pick a value to keep `handle` displaying normally.
  36722. || value > extent[1]
  36723. ) {
  36724. // Make handle displayed on the end of the axis when init, which looks better.
  36725. value = extent[1];
  36726. }
  36727. if (value < extent[0]) {
  36728. value = extent[0];
  36729. }
  36730. option.value = value;
  36731. if (useHandle) {
  36732. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36733. }
  36734. }
  36735. function getAxisInfo(axisModel) {
  36736. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36737. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36738. }
  36739. function getAxisPointerModel(axisModel) {
  36740. var axisInfo = getAxisInfo(axisModel);
  36741. return axisInfo && axisInfo.axisPointerModel;
  36742. }
  36743. function isHandleTrigger(axisPointerModel) {
  36744. return !!axisPointerModel.get('handle.show');
  36745. }
  36746. /**
  36747. * @param {module:echarts/model/Model} model
  36748. * @return {string} unique key
  36749. */
  36750. function makeKey(model) {
  36751. return model.type + '||' + model.id;
  36752. }
  36753. /*
  36754. * Licensed to the Apache Software Foundation (ASF) under one
  36755. * or more contributor license agreements. See the NOTICE file
  36756. * distributed with this work for additional information
  36757. * regarding copyright ownership. The ASF licenses this file
  36758. * to you under the Apache License, Version 2.0 (the
  36759. * "License"); you may not use this file except in compliance
  36760. * with the License. You may obtain a copy of the License at
  36761. *
  36762. * http://www.apache.org/licenses/LICENSE-2.0
  36763. *
  36764. * Unless required by applicable law or agreed to in writing,
  36765. * software distributed under the License is distributed on an
  36766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36767. * KIND, either express or implied. See the License for the
  36768. * specific language governing permissions and limitations
  36769. * under the License.
  36770. */
  36771. /**
  36772. * Base class of AxisView.
  36773. */
  36774. var AxisView = extendComponentView({
  36775. type: 'axis',
  36776. /**
  36777. * @private
  36778. */
  36779. _axisPointer: null,
  36780. /**
  36781. * @protected
  36782. * @type {string}
  36783. */
  36784. axisPointerClass: null,
  36785. /**
  36786. * @override
  36787. */
  36788. render: function (axisModel, ecModel, api, payload) {
  36789. // FIXME
  36790. // This process should proformed after coordinate systems updated
  36791. // (axis scale updated), and should be performed each time update.
  36792. // So put it here temporarily, although it is not appropriate to
  36793. // put a model-writing procedure in `view`.
  36794. this.axisPointerClass && fixValue(axisModel);
  36795. AxisView.superApply(this, 'render', arguments);
  36796. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  36797. },
  36798. /**
  36799. * Action handler.
  36800. * @public
  36801. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36802. * @param {module:echarts/model/Global} ecModel
  36803. * @param {module:echarts/ExtensionAPI} api
  36804. * @param {Object} payload
  36805. */
  36806. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  36807. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  36808. },
  36809. /**
  36810. * @override
  36811. */
  36812. remove: function (ecModel, api) {
  36813. var axisPointer = this._axisPointer;
  36814. axisPointer && axisPointer.remove(api);
  36815. AxisView.superApply(this, 'remove', arguments);
  36816. },
  36817. /**
  36818. * @override
  36819. */
  36820. dispose: function (ecModel, api) {
  36821. disposeAxisPointer(this, api);
  36822. AxisView.superApply(this, 'dispose', arguments);
  36823. }
  36824. });
  36825. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  36826. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  36827. if (!Clazz) {
  36828. return;
  36829. }
  36830. var axisPointerModel = getAxisPointerModel(axisModel);
  36831. axisPointerModel
  36832. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  36833. .render(axisModel, axisPointerModel, api, forceRender)
  36834. : disposeAxisPointer(axisView, api);
  36835. }
  36836. function disposeAxisPointer(axisView, ecModel, api) {
  36837. var axisPointer = axisView._axisPointer;
  36838. axisPointer && axisPointer.dispose(ecModel, api);
  36839. axisView._axisPointer = null;
  36840. }
  36841. var axisPointerClazz = [];
  36842. AxisView.registerAxisPointerClass = function (type, clazz) {
  36843. if (__DEV__) {
  36844. if (axisPointerClazz[type]) {
  36845. throw new Error('axisPointer ' + type + ' exists');
  36846. }
  36847. }
  36848. axisPointerClazz[type] = clazz;
  36849. };
  36850. AxisView.getAxisPointerClass = function (type) {
  36851. return type && axisPointerClazz[type];
  36852. };
  36853. /*
  36854. * Licensed to the Apache Software Foundation (ASF) under one
  36855. * or more contributor license agreements. See the NOTICE file
  36856. * distributed with this work for additional information
  36857. * regarding copyright ownership. The ASF licenses this file
  36858. * to you under the Apache License, Version 2.0 (the
  36859. * "License"); you may not use this file except in compliance
  36860. * with the License. You may obtain a copy of the License at
  36861. *
  36862. * http://www.apache.org/licenses/LICENSE-2.0
  36863. *
  36864. * Unless required by applicable law or agreed to in writing,
  36865. * software distributed under the License is distributed on an
  36866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36867. * KIND, either express or implied. See the License for the
  36868. * specific language governing permissions and limitations
  36869. * under the License.
  36870. */
  36871. /**
  36872. * Can only be called after coordinate system creation stage.
  36873. * (Can be called before coordinate system update stage).
  36874. *
  36875. * @param {Object} opt {labelInside}
  36876. * @return {Object} {
  36877. * position, rotation, labelDirection, labelOffset,
  36878. * tickDirection, labelRotate, z2
  36879. * }
  36880. */
  36881. function layout$1(gridModel, axisModel, opt) {
  36882. opt = opt || {};
  36883. var grid = gridModel.coordinateSystem;
  36884. var axis = axisModel.axis;
  36885. var layout = {};
  36886. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  36887. var rawAxisPosition = axis.position;
  36888. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  36889. var axisDim = axis.dim;
  36890. var rect = grid.getRect();
  36891. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  36892. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  36893. var axisOffset = axisModel.get('offset') || 0;
  36894. var posBound = axisDim === 'x'
  36895. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  36896. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  36897. if (otherAxisOnZeroOf) {
  36898. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  36899. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  36900. }
  36901. // Axis position
  36902. layout.position = [
  36903. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  36904. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  36905. ];
  36906. // Axis rotation
  36907. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  36908. // Tick and label direction, x y is axisDim
  36909. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  36910. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  36911. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  36912. if (axisModel.get('axisTick.inside')) {
  36913. layout.tickDirection = -layout.tickDirection;
  36914. }
  36915. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  36916. layout.labelDirection = -layout.labelDirection;
  36917. }
  36918. // Special label rotation
  36919. var labelRotate = axisModel.get('axisLabel.rotate');
  36920. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  36921. // Over splitLine and splitArea
  36922. layout.z2 = 1;
  36923. return layout;
  36924. }
  36925. /*
  36926. * Licensed to the Apache Software Foundation (ASF) under one
  36927. * or more contributor license agreements. See the NOTICE file
  36928. * distributed with this work for additional information
  36929. * regarding copyright ownership. The ASF licenses this file
  36930. * to you under the Apache License, Version 2.0 (the
  36931. * "License"); you may not use this file except in compliance
  36932. * with the License. You may obtain a copy of the License at
  36933. *
  36934. * http://www.apache.org/licenses/LICENSE-2.0
  36935. *
  36936. * Unless required by applicable law or agreed to in writing,
  36937. * software distributed under the License is distributed on an
  36938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36939. * KIND, either express or implied. See the License for the
  36940. * specific language governing permissions and limitations
  36941. * under the License.
  36942. */
  36943. var axisBuilderAttrs = [
  36944. 'axisLine', 'axisTickLabel', 'axisName'
  36945. ];
  36946. var selfBuilderAttrs = [
  36947. 'splitArea', 'splitLine', 'minorSplitLine'
  36948. ];
  36949. var CartesianAxisView = AxisView.extend({
  36950. type: 'cartesianAxis',
  36951. axisPointerClass: 'CartesianAxisPointer',
  36952. /**
  36953. * @override
  36954. */
  36955. render: function (axisModel, ecModel, api, payload) {
  36956. this.group.removeAll();
  36957. var oldAxisGroup = this._axisGroup;
  36958. this._axisGroup = new Group();
  36959. this.group.add(this._axisGroup);
  36960. if (!axisModel.get('show')) {
  36961. return;
  36962. }
  36963. var gridModel = axisModel.getCoordSysModel();
  36964. var layout = layout$1(gridModel, axisModel);
  36965. var axisBuilder = new AxisBuilder(axisModel, layout);
  36966. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  36967. this._axisGroup.add(axisBuilder.getGroup());
  36968. each$1(selfBuilderAttrs, function (name) {
  36969. if (axisModel.get(name + '.show')) {
  36970. this['_' + name](axisModel, gridModel);
  36971. }
  36972. }, this);
  36973. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  36974. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  36975. },
  36976. remove: function () {
  36977. this._splitAreaColors = null;
  36978. },
  36979. /**
  36980. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36981. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  36982. * @private
  36983. */
  36984. _splitLine: function (axisModel, gridModel) {
  36985. var axis = axisModel.axis;
  36986. if (axis.scale.isBlank()) {
  36987. return;
  36988. }
  36989. var splitLineModel = axisModel.getModel('splitLine');
  36990. var lineStyleModel = splitLineModel.getModel('lineStyle');
  36991. var lineColors = lineStyleModel.get('color');
  36992. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  36993. var gridRect = gridModel.coordinateSystem.getRect();
  36994. var isHorizontal = axis.isHorizontal();
  36995. var lineCount = 0;
  36996. var ticksCoords = axis.getTicksCoords({
  36997. tickModel: splitLineModel
  36998. });
  36999. var p1 = [];
  37000. var p2 = [];
  37001. var lineStyle = lineStyleModel.getLineStyle();
  37002. for (var i = 0; i < ticksCoords.length; i++) {
  37003. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37004. if (isHorizontal) {
  37005. p1[0] = tickCoord;
  37006. p1[1] = gridRect.y;
  37007. p2[0] = tickCoord;
  37008. p2[1] = gridRect.y + gridRect.height;
  37009. }
  37010. else {
  37011. p1[0] = gridRect.x;
  37012. p1[1] = tickCoord;
  37013. p2[0] = gridRect.x + gridRect.width;
  37014. p2[1] = tickCoord;
  37015. }
  37016. var colorIndex = (lineCount++) % lineColors.length;
  37017. var tickValue = ticksCoords[i].tickValue;
  37018. this._axisGroup.add(new Line({
  37019. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37020. subPixelOptimize: true,
  37021. shape: {
  37022. x1: p1[0],
  37023. y1: p1[1],
  37024. x2: p2[0],
  37025. y2: p2[1]
  37026. },
  37027. style: defaults({
  37028. stroke: lineColors[colorIndex]
  37029. }, lineStyle),
  37030. silent: true
  37031. }));
  37032. }
  37033. },
  37034. /**
  37035. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37036. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37037. * @private
  37038. */
  37039. _minorSplitLine: function (axisModel, gridModel) {
  37040. var axis = axisModel.axis;
  37041. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37042. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37043. var gridRect = gridModel.coordinateSystem.getRect();
  37044. var isHorizontal = axis.isHorizontal();
  37045. var minorTicksCoords = axis.getMinorTicksCoords();
  37046. if (!minorTicksCoords.length) {
  37047. return;
  37048. }
  37049. var p1 = [];
  37050. var p2 = [];
  37051. var lineStyle = lineStyleModel.getLineStyle();
  37052. for (var i = 0; i < minorTicksCoords.length; i++) {
  37053. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37054. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37055. if (isHorizontal) {
  37056. p1[0] = tickCoord;
  37057. p1[1] = gridRect.y;
  37058. p2[0] = tickCoord;
  37059. p2[1] = gridRect.y + gridRect.height;
  37060. }
  37061. else {
  37062. p1[0] = gridRect.x;
  37063. p1[1] = tickCoord;
  37064. p2[0] = gridRect.x + gridRect.width;
  37065. p2[1] = tickCoord;
  37066. }
  37067. this._axisGroup.add(new Line({
  37068. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37069. subPixelOptimize: true,
  37070. shape: {
  37071. x1: p1[0],
  37072. y1: p1[1],
  37073. x2: p2[0],
  37074. y2: p2[1]
  37075. },
  37076. style: lineStyle,
  37077. silent: true
  37078. }));
  37079. }
  37080. }
  37081. },
  37082. /**
  37083. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37084. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37085. * @private
  37086. */
  37087. _splitArea: function (axisModel, gridModel) {
  37088. var axis = axisModel.axis;
  37089. if (axis.scale.isBlank()) {
  37090. return;
  37091. }
  37092. var splitAreaModel = axisModel.getModel('splitArea');
  37093. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37094. var areaColors = areaStyleModel.get('color');
  37095. var gridRect = gridModel.coordinateSystem.getRect();
  37096. var ticksCoords = axis.getTicksCoords({
  37097. tickModel: splitAreaModel,
  37098. clamp: true
  37099. });
  37100. if (!ticksCoords.length) {
  37101. return;
  37102. }
  37103. // For Making appropriate splitArea animation, the color and anid
  37104. // should be corresponding to previous one if possible.
  37105. var areaColorsLen = areaColors.length;
  37106. var lastSplitAreaColors = this._splitAreaColors;
  37107. var newSplitAreaColors = createHashMap();
  37108. var colorIndex = 0;
  37109. if (lastSplitAreaColors) {
  37110. for (var i = 0; i < ticksCoords.length; i++) {
  37111. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37112. if (cIndex != null) {
  37113. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37114. break;
  37115. }
  37116. }
  37117. }
  37118. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37119. var areaStyle = areaStyleModel.getAreaStyle();
  37120. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37121. for (var i = 1; i < ticksCoords.length; i++) {
  37122. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37123. var x;
  37124. var y;
  37125. var width;
  37126. var height;
  37127. if (axis.isHorizontal()) {
  37128. x = prev;
  37129. y = gridRect.y;
  37130. width = tickCoord - x;
  37131. height = gridRect.height;
  37132. prev = x + width;
  37133. }
  37134. else {
  37135. x = gridRect.x;
  37136. y = prev;
  37137. width = gridRect.width;
  37138. height = tickCoord - y;
  37139. prev = y + height;
  37140. }
  37141. var tickValue = ticksCoords[i - 1].tickValue;
  37142. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37143. this._axisGroup.add(new Rect({
  37144. anid: tickValue != null ? 'area_' + tickValue : null,
  37145. shape: {
  37146. x: x,
  37147. y: y,
  37148. width: width,
  37149. height: height
  37150. },
  37151. style: defaults({
  37152. fill: areaColors[colorIndex]
  37153. }, areaStyle),
  37154. silent: true
  37155. }));
  37156. colorIndex = (colorIndex + 1) % areaColorsLen;
  37157. }
  37158. this._splitAreaColors = newSplitAreaColors;
  37159. }
  37160. });
  37161. CartesianAxisView.extend({
  37162. type: 'xAxis'
  37163. });
  37164. CartesianAxisView.extend({
  37165. type: 'yAxis'
  37166. });
  37167. /*
  37168. * Licensed to the Apache Software Foundation (ASF) under one
  37169. * or more contributor license agreements. See the NOTICE file
  37170. * distributed with this work for additional information
  37171. * regarding copyright ownership. The ASF licenses this file
  37172. * to you under the Apache License, Version 2.0 (the
  37173. * "License"); you may not use this file except in compliance
  37174. * with the License. You may obtain a copy of the License at
  37175. *
  37176. * http://www.apache.org/licenses/LICENSE-2.0
  37177. *
  37178. * Unless required by applicable law or agreed to in writing,
  37179. * software distributed under the License is distributed on an
  37180. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37181. * KIND, either express or implied. See the License for the
  37182. * specific language governing permissions and limitations
  37183. * under the License.
  37184. */
  37185. /*
  37186. * Licensed to the Apache Software Foundation (ASF) under one
  37187. * or more contributor license agreements. See the NOTICE file
  37188. * distributed with this work for additional information
  37189. * regarding copyright ownership. The ASF licenses this file
  37190. * to you under the Apache License, Version 2.0 (the
  37191. * "License"); you may not use this file except in compliance
  37192. * with the License. You may obtain a copy of the License at
  37193. *
  37194. * http://www.apache.org/licenses/LICENSE-2.0
  37195. *
  37196. * Unless required by applicable law or agreed to in writing,
  37197. * software distributed under the License is distributed on an
  37198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37199. * KIND, either express or implied. See the License for the
  37200. * specific language governing permissions and limitations
  37201. * under the License.
  37202. */
  37203. // Grid view
  37204. extendComponentView({
  37205. type: 'grid',
  37206. render: function (gridModel, ecModel) {
  37207. this.group.removeAll();
  37208. if (gridModel.get('show')) {
  37209. this.group.add(new Rect({
  37210. shape: gridModel.coordinateSystem.getRect(),
  37211. style: defaults({
  37212. fill: gridModel.get('backgroundColor')
  37213. }, gridModel.getItemStyle()),
  37214. silent: true,
  37215. z2: -1
  37216. }));
  37217. }
  37218. }
  37219. });
  37220. registerPreprocessor(function (option) {
  37221. // Only create grid when need
  37222. if (option.xAxis && option.yAxis && !option.grid) {
  37223. option.grid = {};
  37224. }
  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. // In case developer forget to include grid component
  37245. registerVisual(visualSymbol('line', 'circle', 'line'));
  37246. registerLayout(pointsLayout('line'));
  37247. // Down sample after filter
  37248. registerProcessor(
  37249. PRIORITY.PROCESSOR.STATISTIC,
  37250. dataSample('line')
  37251. );
  37252. /*
  37253. * Licensed to the Apache Software Foundation (ASF) under one
  37254. * or more contributor license agreements. See the NOTICE file
  37255. * distributed with this work for additional information
  37256. * regarding copyright ownership. The ASF licenses this file
  37257. * to you under the Apache License, Version 2.0 (the
  37258. * "License"); you may not use this file except in compliance
  37259. * with the License. You may obtain a copy of the License at
  37260. *
  37261. * http://www.apache.org/licenses/LICENSE-2.0
  37262. *
  37263. * Unless required by applicable law or agreed to in writing,
  37264. * software distributed under the License is distributed on an
  37265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37266. * KIND, either express or implied. See the License for the
  37267. * specific language governing permissions and limitations
  37268. * under the License.
  37269. */
  37270. var BaseBarSeries = SeriesModel.extend({
  37271. type: 'series.__base_bar__',
  37272. getInitialData: function (option, ecModel) {
  37273. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37274. },
  37275. getMarkerPosition: function (value) {
  37276. var coordSys = this.coordinateSystem;
  37277. if (coordSys) {
  37278. // PENDING if clamp ?
  37279. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37280. var data = this.getData();
  37281. var offset = data.getLayout('offset');
  37282. var size = data.getLayout('size');
  37283. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37284. pt[offsetIndex] += offset + size / 2;
  37285. return pt;
  37286. }
  37287. return [NaN, NaN];
  37288. },
  37289. defaultOption: {
  37290. zlevel: 0, // 一级层叠
  37291. z: 2, // 二级层叠
  37292. coordinateSystem: 'cartesian2d',
  37293. legendHoverLink: true,
  37294. // stack: null
  37295. // Cartesian coordinate system
  37296. // xAxisIndex: 0,
  37297. // yAxisIndex: 0,
  37298. // 最小高度改为0
  37299. barMinHeight: 0,
  37300. // 最小角度为0,仅对极坐标系下的柱状图有效
  37301. barMinAngle: 0,
  37302. // cursor: null,
  37303. large: false,
  37304. largeThreshold: 400,
  37305. progressive: 3e3,
  37306. progressiveChunkMode: 'mod',
  37307. // barMaxWidth: null,
  37308. // In cartesian, the default value is 1. Otherwise null.
  37309. // barMinWidth: null,
  37310. // 默认自适应
  37311. // barWidth: null,
  37312. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37313. // barGap: '30%',
  37314. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37315. // barCategoryGap: '20%',
  37316. // label: {
  37317. // show: false
  37318. // },
  37319. itemStyle: {},
  37320. emphasis: {}
  37321. }
  37322. });
  37323. /*
  37324. * Licensed to the Apache Software Foundation (ASF) under one
  37325. * or more contributor license agreements. See the NOTICE file
  37326. * distributed with this work for additional information
  37327. * regarding copyright ownership. The ASF licenses this file
  37328. * to you under the Apache License, Version 2.0 (the
  37329. * "License"); you may not use this file except in compliance
  37330. * with the License. You may obtain a copy of the License at
  37331. *
  37332. * http://www.apache.org/licenses/LICENSE-2.0
  37333. *
  37334. * Unless required by applicable law or agreed to in writing,
  37335. * software distributed under the License is distributed on an
  37336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37337. * KIND, either express or implied. See the License for the
  37338. * specific language governing permissions and limitations
  37339. * under the License.
  37340. */
  37341. BaseBarSeries.extend({
  37342. type: 'series.bar',
  37343. dependencies: ['grid', 'polar'],
  37344. brushSelector: 'rect',
  37345. /**
  37346. * @override
  37347. */
  37348. getProgressive: function () {
  37349. // Do not support progressive in normal mode.
  37350. return this.get('large')
  37351. ? this.get('progressive')
  37352. : false;
  37353. },
  37354. /**
  37355. * @override
  37356. */
  37357. getProgressiveThreshold: function () {
  37358. // Do not support progressive in normal mode.
  37359. var progressiveThreshold = this.get('progressiveThreshold');
  37360. var largeThreshold = this.get('largeThreshold');
  37361. if (largeThreshold > progressiveThreshold) {
  37362. progressiveThreshold = largeThreshold;
  37363. }
  37364. return progressiveThreshold;
  37365. },
  37366. defaultOption: {
  37367. // If clipped
  37368. // Only available on cartesian2d
  37369. clip: true,
  37370. // If use caps on two sides of bars
  37371. // Only available on tangential polar bar
  37372. roundCap: false
  37373. }
  37374. });
  37375. /*
  37376. * Licensed to the Apache Software Foundation (ASF) under one
  37377. * or more contributor license agreements. See the NOTICE file
  37378. * distributed with this work for additional information
  37379. * regarding copyright ownership. The ASF licenses this file
  37380. * to you under the Apache License, Version 2.0 (the
  37381. * "License"); you may not use this file except in compliance
  37382. * with the License. You may obtain a copy of the License at
  37383. *
  37384. * http://www.apache.org/licenses/LICENSE-2.0
  37385. *
  37386. * Unless required by applicable law or agreed to in writing,
  37387. * software distributed under the License is distributed on an
  37388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37389. * KIND, either express or implied. See the License for the
  37390. * specific language governing permissions and limitations
  37391. * under the License.
  37392. */
  37393. function setLabel(
  37394. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37395. ) {
  37396. var labelModel = itemModel.getModel('label');
  37397. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37398. setLabelStyle(
  37399. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37400. {
  37401. labelFetcher: seriesModel,
  37402. labelDataIndex: dataIndex,
  37403. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37404. isRectText: true,
  37405. autoColor: color
  37406. }
  37407. );
  37408. fixPosition(normalStyle);
  37409. fixPosition(hoverStyle);
  37410. }
  37411. function fixPosition(style, labelPositionOutside) {
  37412. if (style.textPosition === 'outside') {
  37413. style.textPosition = labelPositionOutside;
  37414. }
  37415. }
  37416. /*
  37417. * Licensed to the Apache Software Foundation (ASF) under one
  37418. * or more contributor license agreements. See the NOTICE file
  37419. * distributed with this work for additional information
  37420. * regarding copyright ownership. The ASF licenses this file
  37421. * to you under the Apache License, Version 2.0 (the
  37422. * "License"); you may not use this file except in compliance
  37423. * with the License. You may obtain a copy of the License at
  37424. *
  37425. * http://www.apache.org/licenses/LICENSE-2.0
  37426. *
  37427. * Unless required by applicable law or agreed to in writing,
  37428. * software distributed under the License is distributed on an
  37429. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37430. * KIND, either express or implied. See the License for the
  37431. * specific language governing permissions and limitations
  37432. * under the License.
  37433. */
  37434. var getBarItemStyle = makeStyleMapper(
  37435. [
  37436. ['fill', 'color'],
  37437. ['stroke', 'borderColor'],
  37438. ['lineWidth', 'borderWidth'],
  37439. // Compatitable with 2
  37440. ['stroke', 'barBorderColor'],
  37441. ['lineWidth', 'barBorderWidth'],
  37442. ['opacity'],
  37443. ['shadowBlur'],
  37444. ['shadowOffsetX'],
  37445. ['shadowOffsetY'],
  37446. ['shadowColor']
  37447. ]
  37448. );
  37449. var barItemStyle = {
  37450. getBarItemStyle: function (excludes) {
  37451. var style = getBarItemStyle(this, excludes);
  37452. if (this.getBorderLineDash) {
  37453. var lineDash = this.getBorderLineDash();
  37454. lineDash && (style.lineDash = lineDash);
  37455. }
  37456. return style;
  37457. }
  37458. };
  37459. /*
  37460. * Licensed to the Apache Software Foundation (ASF) under one
  37461. * or more contributor license agreements. See the NOTICE file
  37462. * distributed with this work for additional information
  37463. * regarding copyright ownership. The ASF licenses this file
  37464. * to you under the Apache License, Version 2.0 (the
  37465. * "License"); you may not use this file except in compliance
  37466. * with the License. You may obtain a copy of the License at
  37467. *
  37468. * http://www.apache.org/licenses/LICENSE-2.0
  37469. *
  37470. * Unless required by applicable law or agreed to in writing,
  37471. * software distributed under the License is distributed on an
  37472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37473. * KIND, either express or implied. See the License for the
  37474. * specific language governing permissions and limitations
  37475. * under the License.
  37476. */
  37477. /**
  37478. * Sausage: similar to sector, but have half circle on both sides
  37479. * @public
  37480. */
  37481. var Sausage = extendShape({
  37482. type: 'sausage',
  37483. shape: {
  37484. cx: 0,
  37485. cy: 0,
  37486. r0: 0,
  37487. r: 0,
  37488. startAngle: 0,
  37489. endAngle: Math.PI * 2,
  37490. clockwise: true
  37491. },
  37492. buildPath: function (ctx, shape) {
  37493. var x = shape.cx;
  37494. var y = shape.cy;
  37495. var r0 = Math.max(shape.r0 || 0, 0);
  37496. var r = Math.max(shape.r, 0);
  37497. var dr = (r - r0) * 0.5;
  37498. var rCenter = r0 + dr;
  37499. var startAngle = shape.startAngle;
  37500. var endAngle = shape.endAngle;
  37501. var clockwise = shape.clockwise;
  37502. var unitStartX = Math.cos(startAngle);
  37503. var unitStartY = Math.sin(startAngle);
  37504. var unitEndX = Math.cos(endAngle);
  37505. var unitEndY = Math.sin(endAngle);
  37506. var lessThanCircle = clockwise
  37507. ? endAngle - startAngle < Math.PI * 2
  37508. : startAngle - endAngle < Math.PI * 2;
  37509. if (lessThanCircle) {
  37510. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37511. ctx.arc(
  37512. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37513. -Math.PI + startAngle, startAngle, !clockwise
  37514. );
  37515. }
  37516. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37517. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37518. ctx.arc(
  37519. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37520. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37521. );
  37522. if (r0 !== 0) {
  37523. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37524. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37525. }
  37526. ctx.closePath();
  37527. }
  37528. });
  37529. /*
  37530. * Licensed to the Apache Software Foundation (ASF) under one
  37531. * or more contributor license agreements. See the NOTICE file
  37532. * distributed with this work for additional information
  37533. * regarding copyright ownership. The ASF licenses this file
  37534. * to you under the Apache License, Version 2.0 (the
  37535. * "License"); you may not use this file except in compliance
  37536. * with the License. You may obtain a copy of the License at
  37537. *
  37538. * http://www.apache.org/licenses/LICENSE-2.0
  37539. *
  37540. * Unless required by applicable law or agreed to in writing,
  37541. * software distributed under the License is distributed on an
  37542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37543. * KIND, either express or implied. See the License for the
  37544. * specific language governing permissions and limitations
  37545. * under the License.
  37546. */
  37547. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37548. var _eventPos = [0, 0];
  37549. // FIXME
  37550. // Just for compatible with ec2.
  37551. extend(Model.prototype, barItemStyle);
  37552. function getClipArea(coord, data) {
  37553. var coordSysClipArea = coord.getArea && coord.getArea();
  37554. if (coord.type === 'cartesian2d') {
  37555. var baseAxis = coord.getBaseAxis();
  37556. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37557. // We should not clip this part.
  37558. // See test/bar2.html
  37559. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37560. var expandWidth = data.getLayout('bandWidth');
  37561. if (baseAxis.isHorizontal()) {
  37562. coordSysClipArea.x -= expandWidth;
  37563. coordSysClipArea.width += expandWidth * 2;
  37564. }
  37565. else {
  37566. coordSysClipArea.y -= expandWidth;
  37567. coordSysClipArea.height += expandWidth * 2;
  37568. }
  37569. }
  37570. }
  37571. return coordSysClipArea;
  37572. }
  37573. extendChartView({
  37574. type: 'bar',
  37575. render: function (seriesModel, ecModel, api) {
  37576. this._updateDrawMode(seriesModel);
  37577. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37578. if (coordinateSystemType === 'cartesian2d'
  37579. || coordinateSystemType === 'polar'
  37580. ) {
  37581. this._isLargeDraw
  37582. ? this._renderLarge(seriesModel, ecModel, api)
  37583. : this._renderNormal(seriesModel, ecModel, api);
  37584. }
  37585. else if (__DEV__) {
  37586. console.warn('Only cartesian2d and polar supported for bar.');
  37587. }
  37588. return this.group;
  37589. },
  37590. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37591. this._clear();
  37592. this._updateDrawMode(seriesModel);
  37593. },
  37594. incrementalRender: function (params, seriesModel, ecModel, api) {
  37595. // Do not support progressive in normal mode.
  37596. this._incrementalRenderLarge(params, seriesModel);
  37597. },
  37598. _updateDrawMode: function (seriesModel) {
  37599. var isLargeDraw = seriesModel.pipelineContext.large;
  37600. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37601. this._isLargeDraw = isLargeDraw;
  37602. this._clear();
  37603. }
  37604. },
  37605. _renderNormal: function (seriesModel, ecModel, api) {
  37606. var group = this.group;
  37607. var data = seriesModel.getData();
  37608. var oldData = this._data;
  37609. var coord = seriesModel.coordinateSystem;
  37610. var baseAxis = coord.getBaseAxis();
  37611. var isHorizontalOrRadial;
  37612. if (coord.type === 'cartesian2d') {
  37613. isHorizontalOrRadial = baseAxis.isHorizontal();
  37614. }
  37615. else if (coord.type === 'polar') {
  37616. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37617. }
  37618. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37619. var needsClip = seriesModel.get('clip', true);
  37620. var coordSysClipArea = getClipArea(coord, data);
  37621. // If there is clipPath created in large mode. Remove it.
  37622. group.removeClipPath();
  37623. // We don't use clipPath in normal mode because we needs a perfect animation
  37624. // And don't want the label are clipped.
  37625. var roundCap = seriesModel.get('roundCap', true);
  37626. data.diff(oldData)
  37627. .add(function (dataIndex) {
  37628. if (!data.hasValue(dataIndex)) {
  37629. return;
  37630. }
  37631. var itemModel = data.getItemModel(dataIndex);
  37632. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37633. if (needsClip) {
  37634. // Clip will modify the layout params.
  37635. // And return a boolean to determine if the shape are fully clipped.
  37636. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37637. if (isClipped) {
  37638. group.remove(el);
  37639. return;
  37640. }
  37641. }
  37642. var el = elementCreator[coord.type](
  37643. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37644. );
  37645. data.setItemGraphicEl(dataIndex, el);
  37646. group.add(el);
  37647. updateStyle(
  37648. el, data, dataIndex, itemModel, layout,
  37649. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37650. );
  37651. })
  37652. .update(function (newIndex, oldIndex) {
  37653. var el = oldData.getItemGraphicEl(oldIndex);
  37654. if (!data.hasValue(newIndex)) {
  37655. group.remove(el);
  37656. return;
  37657. }
  37658. var itemModel = data.getItemModel(newIndex);
  37659. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37660. if (needsClip) {
  37661. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37662. if (isClipped) {
  37663. group.remove(el);
  37664. return;
  37665. }
  37666. }
  37667. if (el) {
  37668. updateProps(el, {shape: layout}, animationModel, newIndex);
  37669. }
  37670. else {
  37671. el = elementCreator[coord.type](
  37672. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37673. );
  37674. }
  37675. data.setItemGraphicEl(newIndex, el);
  37676. // Add back
  37677. group.add(el);
  37678. updateStyle(
  37679. el, data, newIndex, itemModel, layout,
  37680. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37681. );
  37682. })
  37683. .remove(function (dataIndex) {
  37684. var el = oldData.getItemGraphicEl(dataIndex);
  37685. if (coord.type === 'cartesian2d') {
  37686. el && removeRect(dataIndex, animationModel, el);
  37687. }
  37688. else {
  37689. el && removeSector(dataIndex, animationModel, el);
  37690. }
  37691. })
  37692. .execute();
  37693. this._data = data;
  37694. },
  37695. _renderLarge: function (seriesModel, ecModel, api) {
  37696. this._clear();
  37697. createLarge(seriesModel, this.group);
  37698. // Use clipPath in large mode.
  37699. var clipPath = seriesModel.get('clip', true)
  37700. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  37701. : null;
  37702. if (clipPath) {
  37703. this.group.setClipPath(clipPath);
  37704. }
  37705. else {
  37706. this.group.removeClipPath();
  37707. }
  37708. },
  37709. _incrementalRenderLarge: function (params, seriesModel) {
  37710. createLarge(seriesModel, this.group, true);
  37711. },
  37712. dispose: noop,
  37713. remove: function (ecModel) {
  37714. this._clear(ecModel);
  37715. },
  37716. _clear: function (ecModel) {
  37717. var group = this.group;
  37718. var data = this._data;
  37719. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  37720. data.eachItemGraphicEl(function (el) {
  37721. if (el.type === 'sector') {
  37722. removeSector(el.dataIndex, ecModel, el);
  37723. }
  37724. else {
  37725. removeRect(el.dataIndex, ecModel, el);
  37726. }
  37727. });
  37728. }
  37729. else {
  37730. group.removeAll();
  37731. }
  37732. this._data = null;
  37733. }
  37734. });
  37735. var mathMax$4 = Math.max;
  37736. var mathMin$4 = Math.min;
  37737. var clip = {
  37738. cartesian2d: function (coordSysBoundingRect, layout) {
  37739. var signWidth = layout.width < 0 ? -1 : 1;
  37740. var signHeight = layout.height < 0 ? -1 : 1;
  37741. // Needs positive width and height
  37742. if (signWidth < 0) {
  37743. layout.x += layout.width;
  37744. layout.width = -layout.width;
  37745. }
  37746. if (signHeight < 0) {
  37747. layout.y += layout.height;
  37748. layout.height = -layout.height;
  37749. }
  37750. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  37751. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  37752. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  37753. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  37754. layout.x = x;
  37755. layout.y = y;
  37756. layout.width = x2 - x;
  37757. layout.height = y2 - y;
  37758. var clipped = layout.width < 0 || layout.height < 0;
  37759. // Reverse back
  37760. if (signWidth < 0) {
  37761. layout.x += layout.width;
  37762. layout.width = -layout.width;
  37763. }
  37764. if (signHeight < 0) {
  37765. layout.y += layout.height;
  37766. layout.height = -layout.height;
  37767. }
  37768. return clipped;
  37769. },
  37770. polar: function (coordSysClipArea) {
  37771. return false;
  37772. }
  37773. };
  37774. var elementCreator = {
  37775. cartesian2d: function (
  37776. dataIndex, layout, isHorizontal,
  37777. animationModel, isUpdate
  37778. ) {
  37779. var rect = new Rect({shape: extend({}, layout)});
  37780. // Animation
  37781. if (animationModel) {
  37782. var rectShape = rect.shape;
  37783. var animateProperty = isHorizontal ? 'height' : 'width';
  37784. var animateTarget = {};
  37785. rectShape[animateProperty] = 0;
  37786. animateTarget[animateProperty] = layout[animateProperty];
  37787. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  37788. shape: animateTarget
  37789. }, animationModel, dataIndex);
  37790. }
  37791. return rect;
  37792. },
  37793. polar: function (
  37794. dataIndex, layout, isRadial,
  37795. animationModel, isUpdate, roundCap
  37796. ) {
  37797. // Keep the same logic with bar in catesion: use end value to control
  37798. // direction. Notice that if clockwise is true (by default), the sector
  37799. // will always draw clockwisely, no matter whether endAngle is greater
  37800. // or less than startAngle.
  37801. var clockwise = layout.startAngle < layout.endAngle;
  37802. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  37803. var sector = new ShapeClass({
  37804. shape: defaults({clockwise: clockwise}, layout)
  37805. });
  37806. // Animation
  37807. if (animationModel) {
  37808. var sectorShape = sector.shape;
  37809. var animateProperty = isRadial ? 'r' : 'endAngle';
  37810. var animateTarget = {};
  37811. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37812. animateTarget[animateProperty] = layout[animateProperty];
  37813. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  37814. shape: animateTarget
  37815. }, animationModel, dataIndex);
  37816. }
  37817. return sector;
  37818. }
  37819. };
  37820. function removeRect(dataIndex, animationModel, el) {
  37821. // Not show text when animating
  37822. el.style.text = null;
  37823. updateProps(el, {
  37824. shape: {
  37825. width: 0
  37826. }
  37827. }, animationModel, dataIndex, function () {
  37828. el.parent && el.parent.remove(el);
  37829. });
  37830. }
  37831. function removeSector(dataIndex, animationModel, el) {
  37832. // Not show text when animating
  37833. el.style.text = null;
  37834. updateProps(el, {
  37835. shape: {
  37836. r: el.shape.r0
  37837. }
  37838. }, animationModel, dataIndex, function () {
  37839. el.parent && el.parent.remove(el);
  37840. });
  37841. }
  37842. var getLayout = {
  37843. cartesian2d: function (data, dataIndex, itemModel) {
  37844. var layout = data.getItemLayout(dataIndex);
  37845. var fixedLineWidth = getLineWidth(itemModel, layout);
  37846. // fix layout with lineWidth
  37847. var signX = layout.width > 0 ? 1 : -1;
  37848. var signY = layout.height > 0 ? 1 : -1;
  37849. return {
  37850. x: layout.x + signX * fixedLineWidth / 2,
  37851. y: layout.y + signY * fixedLineWidth / 2,
  37852. width: layout.width - signX * fixedLineWidth,
  37853. height: layout.height - signY * fixedLineWidth
  37854. };
  37855. },
  37856. polar: function (data, dataIndex, itemModel) {
  37857. var layout = data.getItemLayout(dataIndex);
  37858. return {
  37859. cx: layout.cx,
  37860. cy: layout.cy,
  37861. r0: layout.r0,
  37862. r: layout.r,
  37863. startAngle: layout.startAngle,
  37864. endAngle: layout.endAngle
  37865. };
  37866. }
  37867. };
  37868. function isZeroOnPolar(layout) {
  37869. return layout.startAngle != null
  37870. && layout.endAngle != null
  37871. && layout.startAngle === layout.endAngle;
  37872. }
  37873. function updateStyle(
  37874. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  37875. ) {
  37876. var color = data.getItemVisual(dataIndex, 'color');
  37877. var opacity = data.getItemVisual(dataIndex, 'opacity');
  37878. var stroke = data.getVisual('borderColor');
  37879. var itemStyleModel = itemModel.getModel('itemStyle');
  37880. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  37881. if (!isPolar) {
  37882. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  37883. }
  37884. el.useStyle(defaults(
  37885. {
  37886. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  37887. fill: isZeroOnPolar(layout) ? 'none' : color,
  37888. opacity: opacity
  37889. },
  37890. itemStyleModel.getBarItemStyle()
  37891. ));
  37892. var cursorStyle = itemModel.getShallow('cursor');
  37893. cursorStyle && el.attr('cursor', cursorStyle);
  37894. var labelPositionOutside = isHorizontal
  37895. ? (layout.height > 0 ? 'bottom' : 'top')
  37896. : (layout.width > 0 ? 'left' : 'right');
  37897. if (!isPolar) {
  37898. setLabel(
  37899. el.style, hoverStyle, itemModel, color,
  37900. seriesModel, dataIndex, labelPositionOutside
  37901. );
  37902. }
  37903. if (isZeroOnPolar(layout)) {
  37904. hoverStyle.fill = hoverStyle.stroke = 'none';
  37905. }
  37906. setHoverStyle(el, hoverStyle);
  37907. }
  37908. // In case width or height are too small.
  37909. function getLineWidth(itemModel, rawLayout) {
  37910. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  37911. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  37912. }
  37913. var LargePath = Path.extend({
  37914. type: 'largeBar',
  37915. shape: {points: []},
  37916. buildPath: function (ctx, shape) {
  37917. // Drawing lines is more efficient than drawing
  37918. // a whole line or drawing rects.
  37919. var points = shape.points;
  37920. var startPoint = this.__startPoint;
  37921. var baseDimIdx = this.__baseDimIdx;
  37922. for (var i = 0; i < points.length; i += 2) {
  37923. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37924. ctx.moveTo(startPoint[0], startPoint[1]);
  37925. ctx.lineTo(points[i], points[i + 1]);
  37926. }
  37927. }
  37928. });
  37929. function createLarge(seriesModel, group, incremental) {
  37930. // TODO support polar
  37931. var data = seriesModel.getData();
  37932. var startPoint = [];
  37933. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  37934. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  37935. var el = new LargePath({
  37936. shape: {points: data.getLayout('largePoints')},
  37937. incremental: !!incremental,
  37938. __startPoint: startPoint,
  37939. __baseDimIdx: baseDimIdx,
  37940. __largeDataIndices: data.getLayout('largeDataIndices'),
  37941. __barWidth: data.getLayout('barWidth')
  37942. });
  37943. group.add(el);
  37944. setLargeStyle(el, seriesModel, data);
  37945. // Enable tooltip and user mouse/touch event handlers.
  37946. el.seriesIndex = seriesModel.seriesIndex;
  37947. if (!seriesModel.get('silent')) {
  37948. el.on('mousedown', largePathUpdateDataIndex);
  37949. el.on('mousemove', largePathUpdateDataIndex);
  37950. }
  37951. }
  37952. // Use throttle to avoid frequently traverse to find dataIndex.
  37953. var largePathUpdateDataIndex = throttle(function (event) {
  37954. var largePath = this;
  37955. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  37956. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  37957. }, 30, false);
  37958. function largePathFindDataIndex(largePath, x, y) {
  37959. var baseDimIdx = largePath.__baseDimIdx;
  37960. var valueDimIdx = 1 - baseDimIdx;
  37961. var points = largePath.shape.points;
  37962. var largeDataIndices = largePath.__largeDataIndices;
  37963. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  37964. var startValueVal = largePath.__startPoint[valueDimIdx];
  37965. _eventPos[0] = x;
  37966. _eventPos[1] = y;
  37967. var pointerBaseVal = _eventPos[baseDimIdx];
  37968. var pointerValueVal = _eventPos[1 - baseDimIdx];
  37969. var baseLowerBound = pointerBaseVal - barWidthHalf;
  37970. var baseUpperBound = pointerBaseVal + barWidthHalf;
  37971. for (var i = 0, len = points.length / 2; i < len; i++) {
  37972. var ii = i * 2;
  37973. var barBaseVal = points[ii + baseDimIdx];
  37974. var barValueVal = points[ii + valueDimIdx];
  37975. if (
  37976. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  37977. && (
  37978. startValueVal <= barValueVal
  37979. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  37980. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  37981. )
  37982. ) {
  37983. return largeDataIndices[i];
  37984. }
  37985. }
  37986. return -1;
  37987. }
  37988. function setLargeStyle(el, seriesModel, data) {
  37989. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  37990. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  37991. el.useStyle(itemStyle);
  37992. el.style.fill = null;
  37993. el.style.stroke = borderColor;
  37994. el.style.lineWidth = data.getLayout('barWidth');
  37995. }
  37996. /*
  37997. * Licensed to the Apache Software Foundation (ASF) under one
  37998. * or more contributor license agreements. See the NOTICE file
  37999. * distributed with this work for additional information
  38000. * regarding copyright ownership. The ASF licenses this file
  38001. * to you under the Apache License, Version 2.0 (the
  38002. * "License"); you may not use this file except in compliance
  38003. * with the License. You may obtain a copy of the License at
  38004. *
  38005. * http://www.apache.org/licenses/LICENSE-2.0
  38006. *
  38007. * Unless required by applicable law or agreed to in writing,
  38008. * software distributed under the License is distributed on an
  38009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38010. * KIND, either express or implied. See the License for the
  38011. * specific language governing permissions and limitations
  38012. * under the License.
  38013. */
  38014. // In case developer forget to include grid component
  38015. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38016. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38017. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38018. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38019. registerVisual({
  38020. seriesType: 'bar',
  38021. reset: function (seriesModel) {
  38022. // Visual coding for legend
  38023. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38024. }
  38025. });
  38026. /*
  38027. * Licensed to the Apache Software Foundation (ASF) under one
  38028. * or more contributor license agreements. See the NOTICE file
  38029. * distributed with this work for additional information
  38030. * regarding copyright ownership. The ASF licenses this file
  38031. * to you under the Apache License, Version 2.0 (the
  38032. * "License"); you may not use this file except in compliance
  38033. * with the License. You may obtain a copy of the License at
  38034. *
  38035. * http://www.apache.org/licenses/LICENSE-2.0
  38036. *
  38037. * Unless required by applicable law or agreed to in writing,
  38038. * software distributed under the License is distributed on an
  38039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38040. * KIND, either express or implied. See the License for the
  38041. * specific language governing permissions and limitations
  38042. * under the License.
  38043. */
  38044. /**
  38045. * [Usage]:
  38046. * (1)
  38047. * createListSimply(seriesModel, ['value']);
  38048. * (2)
  38049. * createListSimply(seriesModel, {
  38050. * coordDimensions: ['value'],
  38051. * dimensionsCount: 5
  38052. * });
  38053. *
  38054. * @param {module:echarts/model/Series} seriesModel
  38055. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38056. * The options in opt, see `echarts/data/helper/createDimensions`
  38057. * @param {Array.<string>} [nameList]
  38058. * @return {module:echarts/data/List}
  38059. */
  38060. var createListSimply = function (seriesModel, opt, nameList) {
  38061. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38062. var source = seriesModel.getSource();
  38063. var dimensionsInfo = createDimensions(source, opt);
  38064. var list = new List(dimensionsInfo, seriesModel);
  38065. list.initData(source, nameList);
  38066. return list;
  38067. };
  38068. /*
  38069. * Licensed to the Apache Software Foundation (ASF) under one
  38070. * or more contributor license agreements. See the NOTICE file
  38071. * distributed with this work for additional information
  38072. * regarding copyright ownership. The ASF licenses this file
  38073. * to you under the Apache License, Version 2.0 (the
  38074. * "License"); you may not use this file except in compliance
  38075. * with the License. You may obtain a copy of the License at
  38076. *
  38077. * http://www.apache.org/licenses/LICENSE-2.0
  38078. *
  38079. * Unless required by applicable law or agreed to in writing,
  38080. * software distributed under the License is distributed on an
  38081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38082. * KIND, either express or implied. See the License for the
  38083. * specific language governing permissions and limitations
  38084. * under the License.
  38085. */
  38086. /**
  38087. * Data selectable mixin for chart series.
  38088. * To eanble data select, option of series must have `selectedMode`.
  38089. * And each data item will use `selected` to toggle itself selected status
  38090. */
  38091. var dataSelectableMixin = {
  38092. /**
  38093. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38094. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38095. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38096. */
  38097. updateSelectedMap: function (targetList) {
  38098. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38099. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38100. targetMap.set(target.name, target);
  38101. return targetMap;
  38102. }, createHashMap());
  38103. },
  38104. /**
  38105. * Either name or id should be passed as input here.
  38106. * If both of them are defined, id is used.
  38107. *
  38108. * @param {string|undefined} name name of data
  38109. * @param {number|undefined} id dataIndex of data
  38110. */
  38111. // PENGING If selectedMode is null ?
  38112. select: function (name, id) {
  38113. var target = id != null
  38114. ? this._targetList[id]
  38115. : this._selectTargetMap.get(name);
  38116. var selectedMode = this.get('selectedMode');
  38117. if (selectedMode === 'single') {
  38118. this._selectTargetMap.each(function (target) {
  38119. target.selected = false;
  38120. });
  38121. }
  38122. target && (target.selected = true);
  38123. },
  38124. /**
  38125. * Either name or id should be passed as input here.
  38126. * If both of them are defined, id is used.
  38127. *
  38128. * @param {string|undefined} name name of data
  38129. * @param {number|undefined} id dataIndex of data
  38130. */
  38131. unSelect: function (name, id) {
  38132. var target = id != null
  38133. ? this._targetList[id]
  38134. : this._selectTargetMap.get(name);
  38135. // var selectedMode = this.get('selectedMode');
  38136. // selectedMode !== 'single' && target && (target.selected = false);
  38137. target && (target.selected = false);
  38138. },
  38139. /**
  38140. * Either name or id should be passed as input here.
  38141. * If both of them are defined, id is used.
  38142. *
  38143. * @param {string|undefined} name name of data
  38144. * @param {number|undefined} id dataIndex of data
  38145. */
  38146. toggleSelected: function (name, id) {
  38147. var target = id != null
  38148. ? this._targetList[id]
  38149. : this._selectTargetMap.get(name);
  38150. if (target != null) {
  38151. this[target.selected ? 'unSelect' : 'select'](name, id);
  38152. return target.selected;
  38153. }
  38154. },
  38155. /**
  38156. * Either name or id should be passed as input here.
  38157. * If both of them are defined, id is used.
  38158. *
  38159. * @param {string|undefined} name name of data
  38160. * @param {number|undefined} id dataIndex of data
  38161. */
  38162. isSelected: function (name, id) {
  38163. var target = id != null
  38164. ? this._targetList[id]
  38165. : this._selectTargetMap.get(name);
  38166. return target && target.selected;
  38167. }
  38168. };
  38169. /*
  38170. * Licensed to the Apache Software Foundation (ASF) under one
  38171. * or more contributor license agreements. See the NOTICE file
  38172. * distributed with this work for additional information
  38173. * regarding copyright ownership. The ASF licenses this file
  38174. * to you under the Apache License, Version 2.0 (the
  38175. * "License"); you may not use this file except in compliance
  38176. * with the License. You may obtain a copy of the License at
  38177. *
  38178. * http://www.apache.org/licenses/LICENSE-2.0
  38179. *
  38180. * Unless required by applicable law or agreed to in writing,
  38181. * software distributed under the License is distributed on an
  38182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38183. * KIND, either express or implied. See the License for the
  38184. * specific language governing permissions and limitations
  38185. * under the License.
  38186. */
  38187. /**
  38188. * LegendVisualProvider is an bridge that pick encoded color from data and
  38189. * provide to the legend component.
  38190. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38191. * @param {Function} getRawData Function to get raw data before filtered.
  38192. */
  38193. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38194. this.getAllNames = function () {
  38195. var rawData = getRawData();
  38196. // We find the name from the raw data. In case it's filtered by the legend component.
  38197. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38198. return rawData.mapArray(rawData.getName);
  38199. };
  38200. this.containName = function (name) {
  38201. var rawData = getRawData();
  38202. return rawData.indexOfName(name) >= 0;
  38203. };
  38204. this.indexOfName = function (name) {
  38205. // Only get data when necessary.
  38206. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38207. // Invoking Series#getData immediately will throw an error.
  38208. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38209. return dataWithEncodedVisual.indexOfName(name);
  38210. };
  38211. this.getItemVisual = function (dataIndex, key) {
  38212. // Get encoded visual properties from final filtered data.
  38213. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38214. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38215. };
  38216. }
  38217. /*
  38218. * Licensed to the Apache Software Foundation (ASF) under one
  38219. * or more contributor license agreements. See the NOTICE file
  38220. * distributed with this work for additional information
  38221. * regarding copyright ownership. The ASF licenses this file
  38222. * to you under the Apache License, Version 2.0 (the
  38223. * "License"); you may not use this file except in compliance
  38224. * with the License. You may obtain a copy of the License at
  38225. *
  38226. * http://www.apache.org/licenses/LICENSE-2.0
  38227. *
  38228. * Unless required by applicable law or agreed to in writing,
  38229. * software distributed under the License is distributed on an
  38230. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38231. * KIND, either express or implied. See the License for the
  38232. * specific language governing permissions and limitations
  38233. * under the License.
  38234. */
  38235. var PieSeries = extendSeriesModel({
  38236. type: 'series.pie',
  38237. // Overwrite
  38238. init: function (option) {
  38239. PieSeries.superApply(this, 'init', arguments);
  38240. // Enable legend selection for each data item
  38241. // Use a function instead of direct access because data reference may changed
  38242. this.legendVisualProvider = new LegendVisualProvider(
  38243. bind(this.getData, this), bind(this.getRawData, this)
  38244. );
  38245. this.updateSelectedMap(this._createSelectableList());
  38246. this._defaultLabelLine(option);
  38247. },
  38248. // Overwrite
  38249. mergeOption: function (newOption) {
  38250. PieSeries.superCall(this, 'mergeOption', newOption);
  38251. this.updateSelectedMap(this._createSelectableList());
  38252. },
  38253. getInitialData: function (option, ecModel) {
  38254. return createListSimply(this, {
  38255. coordDimensions: ['value'],
  38256. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38257. });
  38258. },
  38259. _createSelectableList: function () {
  38260. var data = this.getRawData();
  38261. var valueDim = data.mapDimension('value');
  38262. var targetList = [];
  38263. for (var i = 0, len = data.count(); i < len; i++) {
  38264. targetList.push({
  38265. name: data.getName(i),
  38266. value: data.get(valueDim, i),
  38267. selected: retrieveRawAttr(data, i, 'selected')
  38268. });
  38269. }
  38270. return targetList;
  38271. },
  38272. // Overwrite
  38273. getDataParams: function (dataIndex) {
  38274. var data = this.getData();
  38275. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38276. // FIXME toFixed?
  38277. var valueList = [];
  38278. data.each(data.mapDimension('value'), function (value) {
  38279. valueList.push(value);
  38280. });
  38281. params.percent = getPercentWithPrecision(
  38282. valueList,
  38283. dataIndex,
  38284. data.hostModel.get('percentPrecision')
  38285. );
  38286. params.$vars.push('percent');
  38287. return params;
  38288. },
  38289. _defaultLabelLine: function (option) {
  38290. // Extend labelLine emphasis
  38291. defaultEmphasis(option, 'labelLine', ['show']);
  38292. var labelLineNormalOpt = option.labelLine;
  38293. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38294. // Not show label line if `label.normal.show = false`
  38295. labelLineNormalOpt.show = labelLineNormalOpt.show
  38296. && option.label.show;
  38297. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38298. && option.emphasis.label.show;
  38299. },
  38300. defaultOption: {
  38301. zlevel: 0,
  38302. z: 2,
  38303. legendHoverLink: true,
  38304. hoverAnimation: true,
  38305. // 默认全局居中
  38306. center: ['50%', '50%'],
  38307. radius: [0, '75%'],
  38308. // 默认顺时针
  38309. clockwise: true,
  38310. startAngle: 90,
  38311. // 最小角度改为0
  38312. minAngle: 0,
  38313. // If the angle of a sector less than `minShowLabelAngle`,
  38314. // the label will not be displayed.
  38315. minShowLabelAngle: 0,
  38316. // 选中时扇区偏移量
  38317. selectedOffset: 10,
  38318. // 高亮扇区偏移量
  38319. hoverOffset: 10,
  38320. // If use strategy to avoid label overlapping
  38321. avoidLabelOverlap: true,
  38322. // 选择模式,默认关闭,可选single,multiple
  38323. // selectedMode: false,
  38324. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38325. // roseType: null,
  38326. percentPrecision: 2,
  38327. // If still show when all data zero.
  38328. stillShowZeroSum: true,
  38329. // cursor: null,
  38330. left: 0,
  38331. top: 0,
  38332. right: 0,
  38333. bottom: 0,
  38334. width: null,
  38335. height: null,
  38336. label: {
  38337. // If rotate around circle
  38338. rotate: false,
  38339. show: true,
  38340. // 'outer', 'inside', 'center'
  38341. position: 'outer',
  38342. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38343. alignTo: 'none',
  38344. // Closest distance between label and chart edge.
  38345. // Works only position is 'outer' and alignTo is 'edge'.
  38346. margin: '25%',
  38347. // Works only position is 'outer' and alignTo is not 'edge'.
  38348. bleedMargin: 10,
  38349. // Distance between text and label line.
  38350. distanceToLabelLine: 5
  38351. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38352. // 默认使用全局文本样式,详见TEXTSTYLE
  38353. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38354. },
  38355. // Enabled when label.normal.position is 'outer'
  38356. labelLine: {
  38357. show: true,
  38358. // 引导线两段中的第一段长度
  38359. length: 15,
  38360. // 引导线两段中的第二段长度
  38361. length2: 15,
  38362. smooth: false,
  38363. lineStyle: {
  38364. // color: 各异,
  38365. width: 1,
  38366. type: 'solid'
  38367. }
  38368. },
  38369. itemStyle: {
  38370. borderWidth: 1
  38371. },
  38372. // Animation type. Valid values: expansion, scale
  38373. animationType: 'expansion',
  38374. // Animation type when update. Valid values: transition, expansion
  38375. animationTypeUpdate: 'transition',
  38376. animationEasing: 'cubicOut'
  38377. }
  38378. });
  38379. mixin(PieSeries, dataSelectableMixin);
  38380. /*
  38381. * Licensed to the Apache Software Foundation (ASF) under one
  38382. * or more contributor license agreements. See the NOTICE file
  38383. * distributed with this work for additional information
  38384. * regarding copyright ownership. The ASF licenses this file
  38385. * to you under the Apache License, Version 2.0 (the
  38386. * "License"); you may not use this file except in compliance
  38387. * with the License. You may obtain a copy of the License at
  38388. *
  38389. * http://www.apache.org/licenses/LICENSE-2.0
  38390. *
  38391. * Unless required by applicable law or agreed to in writing,
  38392. * software distributed under the License is distributed on an
  38393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38394. * KIND, either express or implied. See the License for the
  38395. * specific language governing permissions and limitations
  38396. * under the License.
  38397. */
  38398. /**
  38399. * @param {module:echarts/model/Series} seriesModel
  38400. * @param {boolean} hasAnimation
  38401. * @inner
  38402. */
  38403. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38404. var data = seriesModel.getData();
  38405. var dataIndex = this.dataIndex;
  38406. var name = data.getName(dataIndex);
  38407. var selectedOffset = seriesModel.get('selectedOffset');
  38408. api.dispatchAction({
  38409. type: 'pieToggleSelect',
  38410. from: uid,
  38411. name: name,
  38412. seriesId: seriesModel.id
  38413. });
  38414. data.each(function (idx) {
  38415. toggleItemSelected(
  38416. data.getItemGraphicEl(idx),
  38417. data.getItemLayout(idx),
  38418. seriesModel.isSelected(data.getName(idx)),
  38419. selectedOffset,
  38420. hasAnimation
  38421. );
  38422. });
  38423. }
  38424. /**
  38425. * @param {module:zrender/graphic/Sector} el
  38426. * @param {Object} layout
  38427. * @param {boolean} isSelected
  38428. * @param {number} selectedOffset
  38429. * @param {boolean} hasAnimation
  38430. * @inner
  38431. */
  38432. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38433. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38434. var dx = Math.cos(midAngle);
  38435. var dy = Math.sin(midAngle);
  38436. var offset = isSelected ? selectedOffset : 0;
  38437. var position = [dx * offset, dy * offset];
  38438. hasAnimation
  38439. // animateTo will stop revious animation like update transition
  38440. ? el.animate()
  38441. .when(200, {
  38442. position: position
  38443. })
  38444. .start('bounceOut')
  38445. : el.attr('position', position);
  38446. }
  38447. /**
  38448. * Piece of pie including Sector, Label, LabelLine
  38449. * @constructor
  38450. * @extends {module:zrender/graphic/Group}
  38451. */
  38452. function PiePiece(data, idx) {
  38453. Group.call(this);
  38454. var sector = new Sector({
  38455. z2: 2
  38456. });
  38457. var polyline = new Polyline();
  38458. var text = new Text();
  38459. this.add(sector);
  38460. this.add(polyline);
  38461. this.add(text);
  38462. this.updateData(data, idx, true);
  38463. }
  38464. var piePieceProto = PiePiece.prototype;
  38465. piePieceProto.updateData = function (data, idx, firstCreate) {
  38466. var sector = this.childAt(0);
  38467. var labelLine = this.childAt(1);
  38468. var labelText = this.childAt(2);
  38469. var seriesModel = data.hostModel;
  38470. var itemModel = data.getItemModel(idx);
  38471. var layout = data.getItemLayout(idx);
  38472. var sectorShape = extend({}, layout);
  38473. sectorShape.label = null;
  38474. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38475. if (firstCreate) {
  38476. sector.setShape(sectorShape);
  38477. var animationType = seriesModel.getShallow('animationType');
  38478. if (animationType === 'scale') {
  38479. sector.shape.r = layout.r0;
  38480. initProps(sector, {
  38481. shape: {
  38482. r: layout.r
  38483. }
  38484. }, seriesModel, idx);
  38485. }
  38486. // Expansion
  38487. else {
  38488. sector.shape.endAngle = layout.startAngle;
  38489. updateProps(sector, {
  38490. shape: {
  38491. endAngle: layout.endAngle
  38492. }
  38493. }, seriesModel, idx);
  38494. }
  38495. }
  38496. else {
  38497. if (animationTypeUpdate === 'expansion') {
  38498. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38499. sector.setShape(sectorShape);
  38500. }
  38501. else {
  38502. // Transition animation from the old shape
  38503. updateProps(sector, {
  38504. shape: sectorShape
  38505. }, seriesModel, idx);
  38506. }
  38507. }
  38508. // Update common style
  38509. var visualColor = data.getItemVisual(idx, 'color');
  38510. sector.useStyle(
  38511. defaults(
  38512. {
  38513. lineJoin: 'bevel',
  38514. fill: visualColor
  38515. },
  38516. itemModel.getModel('itemStyle').getItemStyle()
  38517. )
  38518. );
  38519. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38520. var cursorStyle = itemModel.getShallow('cursor');
  38521. cursorStyle && sector.attr('cursor', cursorStyle);
  38522. // Toggle selected
  38523. toggleItemSelected(
  38524. this,
  38525. data.getItemLayout(idx),
  38526. seriesModel.isSelected(null, idx),
  38527. seriesModel.get('selectedOffset'),
  38528. seriesModel.get('animation')
  38529. );
  38530. // Label and text animation should be applied only for transition type animation when update
  38531. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38532. this._updateLabel(data, idx, withAnimation);
  38533. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  38534. ? function (fromState, toState) {
  38535. if (toState === 'emphasis') {
  38536. labelLine.ignore = labelLine.hoverIgnore;
  38537. labelText.ignore = labelText.hoverIgnore;
  38538. // Sector may has animation of updating data. Force to move to the last frame
  38539. // Or it may stopped on the wrong shape
  38540. sector.stopAnimation(true);
  38541. sector.animateTo({
  38542. shape: {
  38543. r: layout.r + seriesModel.get('hoverOffset')
  38544. }
  38545. }, 300, 'elasticOut');
  38546. }
  38547. else {
  38548. labelLine.ignore = labelLine.normalIgnore;
  38549. labelText.ignore = labelText.normalIgnore;
  38550. sector.stopAnimation(true);
  38551. sector.animateTo({
  38552. shape: {
  38553. r: layout.r
  38554. }
  38555. }, 300, 'elasticOut');
  38556. }
  38557. }
  38558. : null;
  38559. setHoverStyle(this);
  38560. };
  38561. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38562. var labelLine = this.childAt(1);
  38563. var labelText = this.childAt(2);
  38564. var seriesModel = data.hostModel;
  38565. var itemModel = data.getItemModel(idx);
  38566. var layout = data.getItemLayout(idx);
  38567. var labelLayout = layout.label;
  38568. var visualColor = data.getItemVisual(idx, 'color');
  38569. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38570. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38571. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38572. return;
  38573. }
  38574. var targetLineShape = {
  38575. points: labelLayout.linePoints || [
  38576. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38577. ]
  38578. };
  38579. var targetTextStyle = {
  38580. x: labelLayout.x,
  38581. y: labelLayout.y
  38582. };
  38583. if (withAnimation) {
  38584. updateProps(labelLine, {
  38585. shape: targetLineShape
  38586. }, seriesModel, idx);
  38587. updateProps(labelText, {
  38588. style: targetTextStyle
  38589. }, seriesModel, idx);
  38590. }
  38591. else {
  38592. labelLine.attr({
  38593. shape: targetLineShape
  38594. });
  38595. labelText.attr({
  38596. style: targetTextStyle
  38597. });
  38598. }
  38599. labelText.attr({
  38600. rotation: labelLayout.rotation,
  38601. origin: [labelLayout.x, labelLayout.y],
  38602. z2: 10
  38603. });
  38604. var labelModel = itemModel.getModel('label');
  38605. var labelHoverModel = itemModel.getModel('emphasis.label');
  38606. var labelLineModel = itemModel.getModel('labelLine');
  38607. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  38608. var visualColor = data.getItemVisual(idx, 'color');
  38609. setLabelStyle(
  38610. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38611. {
  38612. labelFetcher: data.hostModel,
  38613. labelDataIndex: idx,
  38614. defaultText: labelLayout.text,
  38615. autoColor: visualColor,
  38616. useInsideStyle: !!labelLayout.inside
  38617. },
  38618. {
  38619. textAlign: labelLayout.textAlign,
  38620. textVerticalAlign: labelLayout.verticalAlign,
  38621. opacity: data.getItemVisual(idx, 'opacity')
  38622. }
  38623. );
  38624. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38625. labelText.hoverIgnore = !labelHoverModel.get('show');
  38626. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38627. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38628. // Default use item visual color
  38629. labelLine.setStyle({
  38630. stroke: visualColor,
  38631. opacity: data.getItemVisual(idx, 'opacity')
  38632. });
  38633. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38634. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38635. var smooth = labelLineModel.get('smooth');
  38636. if (smooth && smooth === true) {
  38637. smooth = 0.4;
  38638. }
  38639. labelLine.setShape({
  38640. smooth: smooth
  38641. });
  38642. };
  38643. inherits(PiePiece, Group);
  38644. // Pie view
  38645. var PieView = Chart.extend({
  38646. type: 'pie',
  38647. init: function () {
  38648. var sectorGroup = new Group();
  38649. this._sectorGroup = sectorGroup;
  38650. },
  38651. render: function (seriesModel, ecModel, api, payload) {
  38652. if (payload && (payload.from === this.uid)) {
  38653. return;
  38654. }
  38655. var data = seriesModel.getData();
  38656. var oldData = this._data;
  38657. var group = this.group;
  38658. var hasAnimation = ecModel.get('animation');
  38659. var isFirstRender = !oldData;
  38660. var animationType = seriesModel.get('animationType');
  38661. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  38662. var onSectorClick = curry(
  38663. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  38664. );
  38665. var selectedMode = seriesModel.get('selectedMode');
  38666. data.diff(oldData)
  38667. .add(function (idx) {
  38668. var piePiece = new PiePiece(data, idx);
  38669. // Default expansion animation
  38670. if (isFirstRender && animationType !== 'scale') {
  38671. piePiece.eachChild(function (child) {
  38672. child.stopAnimation(true);
  38673. });
  38674. }
  38675. selectedMode && piePiece.on('click', onSectorClick);
  38676. data.setItemGraphicEl(idx, piePiece);
  38677. group.add(piePiece);
  38678. })
  38679. .update(function (newIdx, oldIdx) {
  38680. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38681. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  38682. piePiece.eachChild(function (child) {
  38683. child.stopAnimation(true);
  38684. });
  38685. }
  38686. piePiece.updateData(data, newIdx);
  38687. piePiece.off('click');
  38688. selectedMode && piePiece.on('click', onSectorClick);
  38689. group.add(piePiece);
  38690. data.setItemGraphicEl(newIdx, piePiece);
  38691. })
  38692. .remove(function (idx) {
  38693. var piePiece = oldData.getItemGraphicEl(idx);
  38694. group.remove(piePiece);
  38695. })
  38696. .execute();
  38697. if (
  38698. hasAnimation && data.count() > 0
  38699. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  38700. ) {
  38701. var shape = data.getItemLayout(0);
  38702. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  38703. shape = data.getItemLayout(s);
  38704. }
  38705. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  38706. var removeClipPath = bind(group.removeClipPath, group);
  38707. group.setClipPath(this._createClipPath(
  38708. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  38709. ));
  38710. }
  38711. else {
  38712. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  38713. group.removeClipPath();
  38714. }
  38715. this._data = data;
  38716. },
  38717. dispose: function () {},
  38718. _createClipPath: function (
  38719. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  38720. ) {
  38721. var clipPath = new Sector({
  38722. shape: {
  38723. cx: cx,
  38724. cy: cy,
  38725. r0: 0,
  38726. r: r,
  38727. startAngle: startAngle,
  38728. endAngle: startAngle,
  38729. clockwise: clockwise
  38730. }
  38731. });
  38732. var initOrUpdate = isFirstRender ? initProps : updateProps;
  38733. initOrUpdate(clipPath, {
  38734. shape: {
  38735. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  38736. }
  38737. }, seriesModel, cb);
  38738. return clipPath;
  38739. },
  38740. /**
  38741. * @implement
  38742. */
  38743. containPoint: function (point, seriesModel) {
  38744. var data = seriesModel.getData();
  38745. var itemLayout = data.getItemLayout(0);
  38746. if (itemLayout) {
  38747. var dx = point[0] - itemLayout.cx;
  38748. var dy = point[1] - itemLayout.cy;
  38749. var radius = Math.sqrt(dx * dx + dy * dy);
  38750. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38751. }
  38752. }
  38753. });
  38754. /*
  38755. * Licensed to the Apache Software Foundation (ASF) under one
  38756. * or more contributor license agreements. See the NOTICE file
  38757. * distributed with this work for additional information
  38758. * regarding copyright ownership. The ASF licenses this file
  38759. * to you under the Apache License, Version 2.0 (the
  38760. * "License"); you may not use this file except in compliance
  38761. * with the License. You may obtain a copy of the License at
  38762. *
  38763. * http://www.apache.org/licenses/LICENSE-2.0
  38764. *
  38765. * Unless required by applicable law or agreed to in writing,
  38766. * software distributed under the License is distributed on an
  38767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38768. * KIND, either express or implied. See the License for the
  38769. * specific language governing permissions and limitations
  38770. * under the License.
  38771. */
  38772. var createDataSelectAction = function (seriesType, actionInfos) {
  38773. each$1(actionInfos, function (actionInfo) {
  38774. actionInfo.update = 'updateView';
  38775. /**
  38776. * @payload
  38777. * @property {string} seriesName
  38778. * @property {string} name
  38779. */
  38780. registerAction(actionInfo, function (payload, ecModel) {
  38781. var selected = {};
  38782. ecModel.eachComponent(
  38783. {mainType: 'series', subType: seriesType, query: payload},
  38784. function (seriesModel) {
  38785. if (seriesModel[actionInfo.method]) {
  38786. seriesModel[actionInfo.method](
  38787. payload.name,
  38788. payload.dataIndex
  38789. );
  38790. }
  38791. var data = seriesModel.getData();
  38792. // Create selected map
  38793. data.each(function (idx) {
  38794. var name = data.getName(idx);
  38795. selected[name] = seriesModel.isSelected(name)
  38796. || false;
  38797. });
  38798. }
  38799. );
  38800. return {
  38801. name: payload.name,
  38802. selected: selected,
  38803. seriesId: payload.seriesId
  38804. };
  38805. });
  38806. });
  38807. };
  38808. /*
  38809. * Licensed to the Apache Software Foundation (ASF) under one
  38810. * or more contributor license agreements. See the NOTICE file
  38811. * distributed with this work for additional information
  38812. * regarding copyright ownership. The ASF licenses this file
  38813. * to you under the Apache License, Version 2.0 (the
  38814. * "License"); you may not use this file except in compliance
  38815. * with the License. You may obtain a copy of the License at
  38816. *
  38817. * http://www.apache.org/licenses/LICENSE-2.0
  38818. *
  38819. * Unless required by applicable law or agreed to in writing,
  38820. * software distributed under the License is distributed on an
  38821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38822. * KIND, either express or implied. See the License for the
  38823. * specific language governing permissions and limitations
  38824. * under the License.
  38825. */
  38826. // Pick color from palette for each data item.
  38827. // Applicable for charts that require applying color palette
  38828. // in data level (like pie, funnel, chord).
  38829. var dataColor = function (seriesType) {
  38830. return {
  38831. getTargetSeries: function (ecModel) {
  38832. // Pie and funnel may use diferrent scope
  38833. var paletteScope = {};
  38834. var seiresModelMap = createHashMap();
  38835. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38836. seriesModel.__paletteScope = paletteScope;
  38837. seiresModelMap.set(seriesModel.uid, seriesModel);
  38838. });
  38839. return seiresModelMap;
  38840. },
  38841. reset: function (seriesModel, ecModel) {
  38842. var dataAll = seriesModel.getRawData();
  38843. var idxMap = {};
  38844. var data = seriesModel.getData();
  38845. data.each(function (idx) {
  38846. var rawIdx = data.getRawIndex(idx);
  38847. idxMap[rawIdx] = idx;
  38848. });
  38849. dataAll.each(function (rawIdx) {
  38850. var filteredIdx = idxMap[rawIdx];
  38851. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  38852. var singleDataColor = filteredIdx != null
  38853. && data.getItemVisual(filteredIdx, 'color', true);
  38854. var singleDataBorderColor = filteredIdx != null
  38855. && data.getItemVisual(filteredIdx, 'borderColor', true);
  38856. var itemModel;
  38857. if (!singleDataColor || !singleDataBorderColor) {
  38858. // FIXME Performance
  38859. itemModel = dataAll.getItemModel(rawIdx);
  38860. }
  38861. if (!singleDataColor) {
  38862. var color = itemModel.get('itemStyle.color')
  38863. || seriesModel.getColorFromPalette(
  38864. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  38865. dataAll.count()
  38866. );
  38867. // Data is not filtered
  38868. if (filteredIdx != null) {
  38869. data.setItemVisual(filteredIdx, 'color', color);
  38870. }
  38871. }
  38872. if (!singleDataBorderColor) {
  38873. var borderColor = itemModel.get('itemStyle.borderColor');
  38874. // Data is not filtered
  38875. if (filteredIdx != null) {
  38876. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  38877. }
  38878. }
  38879. });
  38880. }
  38881. };
  38882. };
  38883. /*
  38884. * Licensed to the Apache Software Foundation (ASF) under one
  38885. * or more contributor license agreements. See the NOTICE file
  38886. * distributed with this work for additional information
  38887. * regarding copyright ownership. The ASF licenses this file
  38888. * to you under the Apache License, Version 2.0 (the
  38889. * "License"); you may not use this file except in compliance
  38890. * with the License. You may obtain a copy of the License at
  38891. *
  38892. * http://www.apache.org/licenses/LICENSE-2.0
  38893. *
  38894. * Unless required by applicable law or agreed to in writing,
  38895. * software distributed under the License is distributed on an
  38896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38897. * KIND, either express or implied. See the License for the
  38898. * specific language governing permissions and limitations
  38899. * under the License.
  38900. */
  38901. // FIXME emphasis label position is not same with normal label position
  38902. var RADIAN$1 = Math.PI / 180;
  38903. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  38904. list.sort(function (a, b) {
  38905. return a.y - b.y;
  38906. });
  38907. function shiftDown(start, end, delta, dir) {
  38908. for (var j = start; j < end; j++) {
  38909. if (list[j].y + delta > viewTop + viewHeight) {
  38910. break;
  38911. }
  38912. list[j].y += delta;
  38913. if (j > start
  38914. && j + 1 < end
  38915. && list[j + 1].y > list[j].y + list[j].height
  38916. ) {
  38917. shiftUp(j, delta / 2);
  38918. return;
  38919. }
  38920. }
  38921. shiftUp(end - 1, delta / 2);
  38922. }
  38923. function shiftUp(end, delta) {
  38924. for (var j = end; j >= 0; j--) {
  38925. if (list[j].y - delta < viewTop) {
  38926. break;
  38927. }
  38928. list[j].y -= delta;
  38929. if (j > 0
  38930. && list[j].y > list[j - 1].y + list[j - 1].height
  38931. ) {
  38932. break;
  38933. }
  38934. }
  38935. }
  38936. function changeX(list, isDownList, cx, cy, r, dir) {
  38937. var lastDeltaX = dir > 0
  38938. ? isDownList // right-side
  38939. ? Number.MAX_VALUE // down
  38940. : 0 // up
  38941. : isDownList // left-side
  38942. ? Number.MAX_VALUE // down
  38943. : 0; // up
  38944. for (var i = 0, l = list.length; i < l; i++) {
  38945. if (list[i].labelAlignTo !== 'none') {
  38946. continue;
  38947. }
  38948. var deltaY = Math.abs(list[i].y - cy);
  38949. var length = list[i].len;
  38950. var length2 = list[i].len2;
  38951. var deltaX = (deltaY < r + length)
  38952. ? Math.sqrt(
  38953. (r + length + length2) * (r + length + length2)
  38954. - deltaY * deltaY
  38955. )
  38956. : Math.abs(list[i].x - cx);
  38957. if (isDownList && deltaX >= lastDeltaX) {
  38958. // right-down, left-down
  38959. deltaX = lastDeltaX - 10;
  38960. }
  38961. if (!isDownList && deltaX <= lastDeltaX) {
  38962. // right-up, left-up
  38963. deltaX = lastDeltaX + 10;
  38964. }
  38965. list[i].x = cx + deltaX * dir;
  38966. lastDeltaX = deltaX;
  38967. }
  38968. }
  38969. var lastY = 0;
  38970. var delta;
  38971. var len = list.length;
  38972. var upList = [];
  38973. var downList = [];
  38974. for (var i = 0; i < len; i++) {
  38975. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  38976. var dx = list[i].x - farthestX;
  38977. list[i].linePoints[1][0] += dx;
  38978. list[i].x = farthestX;
  38979. }
  38980. delta = list[i].y - lastY;
  38981. if (delta < 0) {
  38982. shiftDown(i, len, -delta, dir);
  38983. }
  38984. lastY = list[i].y + list[i].height;
  38985. }
  38986. if (viewHeight - lastY < 0) {
  38987. shiftUp(len - 1, lastY - viewHeight);
  38988. }
  38989. for (var i = 0; i < len; i++) {
  38990. if (list[i].y >= cy) {
  38991. downList.push(list[i]);
  38992. }
  38993. else {
  38994. upList.push(list[i]);
  38995. }
  38996. }
  38997. changeX(upList, false, cx, cy, r, dir);
  38998. changeX(downList, true, cx, cy, r, dir);
  38999. }
  39000. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39001. var leftList = [];
  39002. var rightList = [];
  39003. var leftmostX = Number.MAX_VALUE;
  39004. var rightmostX = -Number.MAX_VALUE;
  39005. for (var i = 0; i < labelLayoutList.length; i++) {
  39006. if (isPositionCenter(labelLayoutList[i])) {
  39007. continue;
  39008. }
  39009. if (labelLayoutList[i].x < cx) {
  39010. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39011. leftList.push(labelLayoutList[i]);
  39012. }
  39013. else {
  39014. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39015. rightList.push(labelLayoutList[i]);
  39016. }
  39017. }
  39018. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39019. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39020. for (var i = 0; i < labelLayoutList.length; i++) {
  39021. var layout = labelLayoutList[i];
  39022. if (isPositionCenter(layout)) {
  39023. continue;
  39024. }
  39025. var linePoints = layout.linePoints;
  39026. if (linePoints) {
  39027. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39028. var realTextWidth = layout.textRect.width;
  39029. var targetTextWidth;
  39030. if (isAlignToEdge) {
  39031. if (layout.x < cx) {
  39032. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39033. - viewLeft - layout.labelMargin;
  39034. }
  39035. else {
  39036. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39037. - linePoints[2][0] - layout.labelDistance;
  39038. }
  39039. }
  39040. else {
  39041. if (layout.x < cx) {
  39042. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39043. }
  39044. else {
  39045. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39046. }
  39047. }
  39048. if (targetTextWidth < layout.textRect.width) {
  39049. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39050. if (layout.labelAlignTo === 'edge') {
  39051. realTextWidth = getWidth(layout.text, layout.font);
  39052. }
  39053. }
  39054. var dist = linePoints[1][0] - linePoints[2][0];
  39055. if (isAlignToEdge) {
  39056. if (layout.x < cx) {
  39057. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39058. }
  39059. else {
  39060. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39061. - realTextWidth - layout.labelDistance;
  39062. }
  39063. }
  39064. else {
  39065. if (layout.x < cx) {
  39066. linePoints[2][0] = layout.x + layout.labelDistance;
  39067. }
  39068. else {
  39069. linePoints[2][0] = layout.x - layout.labelDistance;
  39070. }
  39071. linePoints[1][0] = linePoints[2][0] + dist;
  39072. }
  39073. linePoints[1][1] = linePoints[2][1] = layout.y;
  39074. }
  39075. }
  39076. }
  39077. function isPositionCenter(layout) {
  39078. // Not change x for center label
  39079. return layout.position === 'center';
  39080. }
  39081. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39082. var data = seriesModel.getData();
  39083. var labelLayoutList = [];
  39084. var cx;
  39085. var cy;
  39086. var hasLabelRotate = false;
  39087. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39088. data.each(function (idx) {
  39089. var layout = data.getItemLayout(idx);
  39090. var itemModel = data.getItemModel(idx);
  39091. var labelModel = itemModel.getModel('label');
  39092. // Use position in normal or emphasis
  39093. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39094. var labelDistance = labelModel.get('distanceToLabelLine');
  39095. var labelAlignTo = labelModel.get('alignTo');
  39096. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39097. var bleedMargin = labelModel.get('bleedMargin');
  39098. var font = labelModel.getFont();
  39099. var labelLineModel = itemModel.getModel('labelLine');
  39100. var labelLineLen = labelLineModel.get('length');
  39101. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39102. var labelLineLen2 = labelLineModel.get('length2');
  39103. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39104. if (layout.angle < minShowLabelRadian) {
  39105. return;
  39106. }
  39107. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39108. var dx = Math.cos(midAngle);
  39109. var dy = Math.sin(midAngle);
  39110. var textX;
  39111. var textY;
  39112. var linePoints;
  39113. var textAlign;
  39114. cx = layout.cx;
  39115. cy = layout.cy;
  39116. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39117. || data.getName(idx);
  39118. var textRect = getBoundingRect(
  39119. text, font, textAlign, 'top'
  39120. );
  39121. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39122. if (labelPosition === 'center') {
  39123. textX = layout.cx;
  39124. textY = layout.cy;
  39125. textAlign = 'center';
  39126. }
  39127. else {
  39128. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39129. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39130. textX = x1 + dx * 3;
  39131. textY = y1 + dy * 3;
  39132. if (!isLabelInside) {
  39133. // For roseType
  39134. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39135. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39136. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39137. var y3 = y2;
  39138. if (labelAlignTo === 'edge') {
  39139. // Adjust textX because text align of edge is opposite
  39140. textX = dx < 0
  39141. ? viewLeft + labelMargin
  39142. : viewLeft + viewWidth - labelMargin;
  39143. }
  39144. else {
  39145. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39146. }
  39147. textY = y3;
  39148. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39149. }
  39150. textAlign = isLabelInside
  39151. ? 'center'
  39152. : (labelAlignTo === 'edge'
  39153. ? (dx > 0 ? 'right' : 'left')
  39154. : (dx > 0 ? 'left' : 'right'));
  39155. }
  39156. var labelRotate;
  39157. var rotate = labelModel.get('rotate');
  39158. if (typeof rotate === 'number') {
  39159. labelRotate = rotate * (Math.PI / 180);
  39160. }
  39161. else {
  39162. labelRotate = rotate
  39163. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39164. : 0;
  39165. }
  39166. hasLabelRotate = !!labelRotate;
  39167. layout.label = {
  39168. x: textX,
  39169. y: textY,
  39170. position: labelPosition,
  39171. height: textRect.height,
  39172. len: labelLineLen,
  39173. len2: labelLineLen2,
  39174. linePoints: linePoints,
  39175. textAlign: textAlign,
  39176. verticalAlign: 'middle',
  39177. rotation: labelRotate,
  39178. inside: isLabelInside,
  39179. labelDistance: labelDistance,
  39180. labelAlignTo: labelAlignTo,
  39181. labelMargin:labelMargin,
  39182. bleedMargin: bleedMargin,
  39183. textRect: textRect,
  39184. text: text,
  39185. font: font
  39186. };
  39187. // Not layout the inside label
  39188. if (!isLabelInside) {
  39189. labelLayoutList.push(layout.label);
  39190. }
  39191. });
  39192. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39193. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39194. }
  39195. };
  39196. /*
  39197. * Licensed to the Apache Software Foundation (ASF) under one
  39198. * or more contributor license agreements. See the NOTICE file
  39199. * distributed with this work for additional information
  39200. * regarding copyright ownership. The ASF licenses this file
  39201. * to you under the Apache License, Version 2.0 (the
  39202. * "License"); you may not use this file except in compliance
  39203. * with the License. You may obtain a copy of the License at
  39204. *
  39205. * http://www.apache.org/licenses/LICENSE-2.0
  39206. *
  39207. * Unless required by applicable law or agreed to in writing,
  39208. * software distributed under the License is distributed on an
  39209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39210. * KIND, either express or implied. See the License for the
  39211. * specific language governing permissions and limitations
  39212. * under the License.
  39213. */
  39214. var PI2$4 = Math.PI * 2;
  39215. var RADIAN = Math.PI / 180;
  39216. function getViewRect(seriesModel, api) {
  39217. return getLayoutRect(
  39218. seriesModel.getBoxLayoutParams(), {
  39219. width: api.getWidth(),
  39220. height: api.getHeight()
  39221. }
  39222. );
  39223. }
  39224. var pieLayout = function (seriesType, ecModel, api, payload) {
  39225. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39226. var data = seriesModel.getData();
  39227. var valueDim = data.mapDimension('value');
  39228. var viewRect = getViewRect(seriesModel, api);
  39229. var center = seriesModel.get('center');
  39230. var radius = seriesModel.get('radius');
  39231. if (!isArray(radius)) {
  39232. radius = [0, radius];
  39233. }
  39234. if (!isArray(center)) {
  39235. center = [center, center];
  39236. }
  39237. var width = parsePercent$1(viewRect.width, api.getWidth());
  39238. var height = parsePercent$1(viewRect.height, api.getHeight());
  39239. var size = Math.min(width, height);
  39240. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39241. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39242. var r0 = parsePercent$1(radius[0], size / 2);
  39243. var r = parsePercent$1(radius[1], size / 2);
  39244. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39245. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39246. var validDataCount = 0;
  39247. data.each(valueDim, function (value) {
  39248. !isNaN(value) && validDataCount++;
  39249. });
  39250. var sum = data.getSum(valueDim);
  39251. // Sum may be 0
  39252. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39253. var clockwise = seriesModel.get('clockwise');
  39254. var roseType = seriesModel.get('roseType');
  39255. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39256. // [0...max]
  39257. var extent = data.getDataExtent(valueDim);
  39258. extent[0] = 0;
  39259. // In the case some sector angle is smaller than minAngle
  39260. var restAngle = PI2$4;
  39261. var valueSumLargerThanMinAngle = 0;
  39262. var currentAngle = startAngle;
  39263. var dir = clockwise ? 1 : -1;
  39264. data.each(valueDim, function (value, idx) {
  39265. var angle;
  39266. if (isNaN(value)) {
  39267. data.setItemLayout(idx, {
  39268. angle: NaN,
  39269. startAngle: NaN,
  39270. endAngle: NaN,
  39271. clockwise: clockwise,
  39272. cx: cx,
  39273. cy: cy,
  39274. r0: r0,
  39275. r: roseType
  39276. ? NaN
  39277. : r,
  39278. viewRect: viewRect
  39279. });
  39280. return;
  39281. }
  39282. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39283. if (roseType !== 'area') {
  39284. angle = (sum === 0 && stillShowZeroSum)
  39285. ? unitRadian : (value * unitRadian);
  39286. }
  39287. else {
  39288. angle = PI2$4 / validDataCount;
  39289. }
  39290. if (angle < minAngle) {
  39291. angle = minAngle;
  39292. restAngle -= minAngle;
  39293. }
  39294. else {
  39295. valueSumLargerThanMinAngle += value;
  39296. }
  39297. var endAngle = currentAngle + dir * angle;
  39298. data.setItemLayout(idx, {
  39299. angle: angle,
  39300. startAngle: currentAngle,
  39301. endAngle: endAngle,
  39302. clockwise: clockwise,
  39303. cx: cx,
  39304. cy: cy,
  39305. r0: r0,
  39306. r: roseType
  39307. ? linearMap(value, extent, [r0, r])
  39308. : r,
  39309. viewRect: viewRect
  39310. });
  39311. currentAngle = endAngle;
  39312. });
  39313. // Some sector is constrained by minAngle
  39314. // Rest sectors needs recalculate angle
  39315. if (restAngle < PI2$4 && validDataCount) {
  39316. // Average the angle if rest angle is not enough after all angles is
  39317. // Constrained by minAngle
  39318. if (restAngle <= 1e-3) {
  39319. var angle = PI2$4 / validDataCount;
  39320. data.each(valueDim, function (value, idx) {
  39321. if (!isNaN(value)) {
  39322. var layout = data.getItemLayout(idx);
  39323. layout.angle = angle;
  39324. layout.startAngle = startAngle + dir * idx * angle;
  39325. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39326. }
  39327. });
  39328. }
  39329. else {
  39330. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39331. currentAngle = startAngle;
  39332. data.each(valueDim, function (value, idx) {
  39333. if (!isNaN(value)) {
  39334. var layout = data.getItemLayout(idx);
  39335. var angle = layout.angle === minAngle
  39336. ? minAngle : value * unitRadian;
  39337. layout.startAngle = currentAngle;
  39338. layout.endAngle = currentAngle + dir * angle;
  39339. currentAngle += dir * angle;
  39340. }
  39341. });
  39342. }
  39343. }
  39344. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39345. });
  39346. };
  39347. /*
  39348. * Licensed to the Apache Software Foundation (ASF) under one
  39349. * or more contributor license agreements. See the NOTICE file
  39350. * distributed with this work for additional information
  39351. * regarding copyright ownership. The ASF licenses this file
  39352. * to you under the Apache License, Version 2.0 (the
  39353. * "License"); you may not use this file except in compliance
  39354. * with the License. You may obtain a copy of the License at
  39355. *
  39356. * http://www.apache.org/licenses/LICENSE-2.0
  39357. *
  39358. * Unless required by applicable law or agreed to in writing,
  39359. * software distributed under the License is distributed on an
  39360. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39361. * KIND, either express or implied. See the License for the
  39362. * specific language governing permissions and limitations
  39363. * under the License.
  39364. */
  39365. var dataFilter = function (seriesType) {
  39366. return {
  39367. seriesType: seriesType,
  39368. reset: function (seriesModel, ecModel) {
  39369. var legendModels = ecModel.findComponents({
  39370. mainType: 'legend'
  39371. });
  39372. if (!legendModels || !legendModels.length) {
  39373. return;
  39374. }
  39375. var data = seriesModel.getData();
  39376. data.filterSelf(function (idx) {
  39377. var name = data.getName(idx);
  39378. // If in any legend component the status is not selected.
  39379. for (var i = 0; i < legendModels.length; i++) {
  39380. if (!legendModels[i].isSelected(name)) {
  39381. return false;
  39382. }
  39383. }
  39384. return true;
  39385. });
  39386. }
  39387. };
  39388. };
  39389. /*
  39390. * Licensed to the Apache Software Foundation (ASF) under one
  39391. * or more contributor license agreements. See the NOTICE file
  39392. * distributed with this work for additional information
  39393. * regarding copyright ownership. The ASF licenses this file
  39394. * to you under the Apache License, Version 2.0 (the
  39395. * "License"); you may not use this file except in compliance
  39396. * with the License. You may obtain a copy of the License at
  39397. *
  39398. * http://www.apache.org/licenses/LICENSE-2.0
  39399. *
  39400. * Unless required by applicable law or agreed to in writing,
  39401. * software distributed under the License is distributed on an
  39402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39403. * KIND, either express or implied. See the License for the
  39404. * specific language governing permissions and limitations
  39405. * under the License.
  39406. */
  39407. createDataSelectAction('pie', [{
  39408. type: 'pieToggleSelect',
  39409. event: 'pieselectchanged',
  39410. method: 'toggleSelected'
  39411. }, {
  39412. type: 'pieSelect',
  39413. event: 'pieselected',
  39414. method: 'select'
  39415. }, {
  39416. type: 'pieUnSelect',
  39417. event: 'pieunselected',
  39418. method: 'unSelect'
  39419. }]);
  39420. registerVisual(dataColor('pie'));
  39421. registerLayout(curry(pieLayout, 'pie'));
  39422. registerProcessor(dataFilter('pie'));
  39423. /*
  39424. * Licensed to the Apache Software Foundation (ASF) under one
  39425. * or more contributor license agreements. See the NOTICE file
  39426. * distributed with this work for additional information
  39427. * regarding copyright ownership. The ASF licenses this file
  39428. * to you under the Apache License, Version 2.0 (the
  39429. * "License"); you may not use this file except in compliance
  39430. * with the License. You may obtain a copy of the License at
  39431. *
  39432. * http://www.apache.org/licenses/LICENSE-2.0
  39433. *
  39434. * Unless required by applicable law or agreed to in writing,
  39435. * software distributed under the License is distributed on an
  39436. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39437. * KIND, either express or implied. See the License for the
  39438. * specific language governing permissions and limitations
  39439. * under the License.
  39440. */
  39441. SeriesModel.extend({
  39442. type: 'series.scatter',
  39443. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39444. getInitialData: function (option, ecModel) {
  39445. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39446. },
  39447. brushSelector: 'point',
  39448. getProgressive: function () {
  39449. var progressive = this.option.progressive;
  39450. if (progressive == null) {
  39451. // PENDING
  39452. return this.option.large ? 5e3 : this.get('progressive');
  39453. }
  39454. return progressive;
  39455. },
  39456. getProgressiveThreshold: function () {
  39457. var progressiveThreshold = this.option.progressiveThreshold;
  39458. if (progressiveThreshold == null) {
  39459. // PENDING
  39460. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39461. }
  39462. return progressiveThreshold;
  39463. },
  39464. defaultOption: {
  39465. coordinateSystem: 'cartesian2d',
  39466. zlevel: 0,
  39467. z: 2,
  39468. legendHoverLink: true,
  39469. hoverAnimation: true,
  39470. // Cartesian coordinate system
  39471. // xAxisIndex: 0,
  39472. // yAxisIndex: 0,
  39473. // Polar coordinate system
  39474. // polarIndex: 0,
  39475. // Geo coordinate system
  39476. // geoIndex: 0,
  39477. // symbol: null, // 图形类型
  39478. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39479. // symbolRotate: null, // 图形旋转控制
  39480. large: false,
  39481. // Available when large is true
  39482. largeThreshold: 2000,
  39483. // cursor: null,
  39484. // label: {
  39485. // show: false
  39486. // distance: 5,
  39487. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39488. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39489. // 'inside'|'left'|'right'|'top'|'bottom'
  39490. // 默认使用全局文本样式,详见TEXTSTYLE
  39491. // },
  39492. itemStyle: {
  39493. opacity: 0.8
  39494. // color: 各异
  39495. },
  39496. // If clip the overflow graphics
  39497. // Works on cartesian / polar series
  39498. clip: true
  39499. // progressive: null
  39500. }
  39501. });
  39502. /*
  39503. * Licensed to the Apache Software Foundation (ASF) under one
  39504. * or more contributor license agreements. See the NOTICE file
  39505. * distributed with this work for additional information
  39506. * regarding copyright ownership. The ASF licenses this file
  39507. * to you under the Apache License, Version 2.0 (the
  39508. * "License"); you may not use this file except in compliance
  39509. * with the License. You may obtain a copy of the License at
  39510. *
  39511. * http://www.apache.org/licenses/LICENSE-2.0
  39512. *
  39513. * Unless required by applicable law or agreed to in writing,
  39514. * software distributed under the License is distributed on an
  39515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39516. * KIND, either express or implied. See the License for the
  39517. * specific language governing permissions and limitations
  39518. * under the License.
  39519. */
  39520. /* global Float32Array */
  39521. // TODO Batch by color
  39522. var BOOST_SIZE_THRESHOLD = 4;
  39523. var LargeSymbolPath = extendShape({
  39524. shape: {
  39525. points: null
  39526. },
  39527. symbolProxy: null,
  39528. softClipShape: null,
  39529. buildPath: function (path, shape) {
  39530. var points = shape.points;
  39531. var size = shape.size;
  39532. var symbolProxy = this.symbolProxy;
  39533. var symbolProxyShape = symbolProxy.shape;
  39534. var ctx = path.getContext ? path.getContext() : path;
  39535. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39536. // Do draw in afterBrush.
  39537. if (canBoost) {
  39538. return;
  39539. }
  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. symbolProxyShape.x = x - size[0] / 2;
  39550. symbolProxyShape.y = y - size[1] / 2;
  39551. symbolProxyShape.width = size[0];
  39552. symbolProxyShape.height = size[1];
  39553. symbolProxy.buildPath(path, symbolProxyShape, true);
  39554. }
  39555. },
  39556. afterBrush: function (ctx) {
  39557. var shape = this.shape;
  39558. var points = shape.points;
  39559. var size = shape.size;
  39560. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39561. if (!canBoost) {
  39562. return;
  39563. }
  39564. this.setTransform(ctx);
  39565. // PENDING If style or other canvas status changed?
  39566. for (var i = 0; i < points.length;) {
  39567. var x = points[i++];
  39568. var y = points[i++];
  39569. if (isNaN(x) || isNaN(y)) {
  39570. continue;
  39571. }
  39572. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39573. continue;
  39574. }
  39575. // fillRect is faster than building a rect path and draw.
  39576. // And it support light globalCompositeOperation.
  39577. ctx.fillRect(
  39578. x - size[0] / 2, y - size[1] / 2,
  39579. size[0], size[1]
  39580. );
  39581. }
  39582. this.restoreTransform(ctx);
  39583. },
  39584. findDataIndex: function (x, y) {
  39585. // TODO ???
  39586. // Consider transform
  39587. var shape = this.shape;
  39588. var points = shape.points;
  39589. var size = shape.size;
  39590. var w = Math.max(size[0], 4);
  39591. var h = Math.max(size[1], 4);
  39592. // Not consider transform
  39593. // Treat each element as a rect
  39594. // top down traverse
  39595. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  39596. var i = idx * 2;
  39597. var x0 = points[i] - w / 2;
  39598. var y0 = points[i + 1] - h / 2;
  39599. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  39600. return idx;
  39601. }
  39602. }
  39603. return -1;
  39604. }
  39605. });
  39606. function LargeSymbolDraw() {
  39607. this.group = new Group();
  39608. }
  39609. var largeSymbolProto = LargeSymbolDraw.prototype;
  39610. largeSymbolProto.isPersistent = function () {
  39611. return !this._incremental;
  39612. };
  39613. /**
  39614. * Update symbols draw by new data
  39615. * @param {module:echarts/data/List} data
  39616. * @param {Object} opt
  39617. * @param {Object} [opt.clipShape]
  39618. */
  39619. largeSymbolProto.updateData = function (data, opt) {
  39620. this.group.removeAll();
  39621. var symbolEl = new LargeSymbolPath({
  39622. rectHover: true,
  39623. cursor: 'default'
  39624. });
  39625. symbolEl.setShape({
  39626. points: data.getLayout('symbolPoints')
  39627. });
  39628. this._setCommon(symbolEl, data, false, opt);
  39629. this.group.add(symbolEl);
  39630. this._incremental = null;
  39631. };
  39632. largeSymbolProto.updateLayout = function (data) {
  39633. if (this._incremental) {
  39634. return;
  39635. }
  39636. var points = data.getLayout('symbolPoints');
  39637. this.group.eachChild(function (child) {
  39638. if (child.startIndex != null) {
  39639. var len = (child.endIndex - child.startIndex) * 2;
  39640. var byteOffset = child.startIndex * 4 * 2;
  39641. points = new Float32Array(points.buffer, byteOffset, len);
  39642. }
  39643. child.setShape('points', points);
  39644. });
  39645. };
  39646. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  39647. this.group.removeAll();
  39648. this._clearIncremental();
  39649. // Only use incremental displayables when data amount is larger than 2 million.
  39650. // PENDING Incremental data?
  39651. if (data.count() > 2e6) {
  39652. if (!this._incremental) {
  39653. this._incremental = new IncrementalDisplayble({
  39654. silent: true
  39655. });
  39656. }
  39657. this.group.add(this._incremental);
  39658. }
  39659. else {
  39660. this._incremental = null;
  39661. }
  39662. };
  39663. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  39664. var symbolEl;
  39665. if (this._incremental) {
  39666. symbolEl = new LargeSymbolPath();
  39667. this._incremental.addDisplayable(symbolEl, true);
  39668. }
  39669. else {
  39670. symbolEl = new LargeSymbolPath({
  39671. rectHover: true,
  39672. cursor: 'default',
  39673. startIndex: taskParams.start,
  39674. endIndex: taskParams.end
  39675. });
  39676. symbolEl.incremental = true;
  39677. this.group.add(symbolEl);
  39678. }
  39679. symbolEl.setShape({
  39680. points: data.getLayout('symbolPoints')
  39681. });
  39682. this._setCommon(symbolEl, data, !!this._incremental, opt);
  39683. };
  39684. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  39685. var hostModel = data.hostModel;
  39686. opt = opt || {};
  39687. // TODO
  39688. // if (data.hasItemVisual.symbolSize) {
  39689. // // TODO typed array?
  39690. // symbolEl.setShape('sizes', data.mapArray(
  39691. // function (idx) {
  39692. // var size = data.getItemVisual(idx, 'symbolSize');
  39693. // return (size instanceof Array) ? size : [size, size];
  39694. // }
  39695. // ));
  39696. // }
  39697. // else {
  39698. var size = data.getVisual('symbolSize');
  39699. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  39700. // }
  39701. symbolEl.softClipShape = opt.clipShape || null;
  39702. // Create symbolProxy to build path for each data
  39703. symbolEl.symbolProxy = createSymbol(
  39704. data.getVisual('symbol'), 0, 0, 0, 0
  39705. );
  39706. // Use symbolProxy setColor method
  39707. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  39708. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  39709. symbolEl.useStyle(
  39710. // Draw shadow when doing fillRect is extremely slow.
  39711. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  39712. );
  39713. var visualColor = data.getVisual('color');
  39714. if (visualColor) {
  39715. symbolEl.setColor(visualColor);
  39716. }
  39717. if (!isIncremental) {
  39718. // Enable tooltip
  39719. // PENDING May have performance issue when path is extremely large
  39720. symbolEl.seriesIndex = hostModel.seriesIndex;
  39721. symbolEl.on('mousemove', function (e) {
  39722. symbolEl.dataIndex = null;
  39723. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  39724. if (dataIndex >= 0) {
  39725. // Provide dataIndex for tooltip
  39726. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  39727. }
  39728. });
  39729. }
  39730. };
  39731. largeSymbolProto.remove = function () {
  39732. this._clearIncremental();
  39733. this._incremental = null;
  39734. this.group.removeAll();
  39735. };
  39736. largeSymbolProto._clearIncremental = function () {
  39737. var incremental = this._incremental;
  39738. if (incremental) {
  39739. incremental.clearDisplaybles();
  39740. }
  39741. };
  39742. /*
  39743. * Licensed to the Apache Software Foundation (ASF) under one
  39744. * or more contributor license agreements. See the NOTICE file
  39745. * distributed with this work for additional information
  39746. * regarding copyright ownership. The ASF licenses this file
  39747. * to you under the Apache License, Version 2.0 (the
  39748. * "License"); you may not use this file except in compliance
  39749. * with the License. You may obtain a copy of the License at
  39750. *
  39751. * http://www.apache.org/licenses/LICENSE-2.0
  39752. *
  39753. * Unless required by applicable law or agreed to in writing,
  39754. * software distributed under the License is distributed on an
  39755. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39756. * KIND, either express or implied. See the License for the
  39757. * specific language governing permissions and limitations
  39758. * under the License.
  39759. */
  39760. extendChartView({
  39761. type: 'scatter',
  39762. render: function (seriesModel, ecModel, api) {
  39763. var data = seriesModel.getData();
  39764. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39765. symbolDraw.updateData(data, {
  39766. // TODO
  39767. // If this parameter should be a shape or a bounding volume
  39768. // shape will be more general.
  39769. // But bounding volume like bounding rect will be much faster in the contain calculation
  39770. clipShape: this._getClipShape(seriesModel)
  39771. });
  39772. this._finished = true;
  39773. },
  39774. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  39775. var data = seriesModel.getData();
  39776. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39777. symbolDraw.incrementalPrepareUpdate(data);
  39778. this._finished = false;
  39779. },
  39780. incrementalRender: function (taskParams, seriesModel, ecModel) {
  39781. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  39782. clipShape: this._getClipShape(seriesModel)
  39783. });
  39784. this._finished = taskParams.end === seriesModel.getData().count();
  39785. },
  39786. updateTransform: function (seriesModel, ecModel, api) {
  39787. var data = seriesModel.getData();
  39788. // Must mark group dirty and make sure the incremental layer will be cleared
  39789. // PENDING
  39790. this.group.dirty();
  39791. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  39792. return {
  39793. update: true
  39794. };
  39795. }
  39796. else {
  39797. var res = pointsLayout().reset(seriesModel);
  39798. if (res.progress) {
  39799. res.progress({ start: 0, end: data.count() }, data);
  39800. }
  39801. this._symbolDraw.updateLayout(data);
  39802. }
  39803. },
  39804. _getClipShape: function (seriesModel) {
  39805. var coordSys = seriesModel.coordinateSystem;
  39806. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  39807. return seriesModel.get('clip', true) ? clipArea : null;
  39808. },
  39809. _updateSymbolDraw: function (data, seriesModel) {
  39810. var symbolDraw = this._symbolDraw;
  39811. var pipelineContext = seriesModel.pipelineContext;
  39812. var isLargeDraw = pipelineContext.large;
  39813. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  39814. symbolDraw && symbolDraw.remove();
  39815. symbolDraw = this._symbolDraw = isLargeDraw
  39816. ? new LargeSymbolDraw()
  39817. : new SymbolDraw();
  39818. this._isLargeDraw = isLargeDraw;
  39819. this.group.removeAll();
  39820. }
  39821. this.group.add(symbolDraw.group);
  39822. return symbolDraw;
  39823. },
  39824. remove: function (ecModel, api) {
  39825. this._symbolDraw && this._symbolDraw.remove(true);
  39826. this._symbolDraw = null;
  39827. },
  39828. dispose: function () {}
  39829. });
  39830. /*
  39831. * Licensed to the Apache Software Foundation (ASF) under one
  39832. * or more contributor license agreements. See the NOTICE file
  39833. * distributed with this work for additional information
  39834. * regarding copyright ownership. The ASF licenses this file
  39835. * to you under the Apache License, Version 2.0 (the
  39836. * "License"); you may not use this file except in compliance
  39837. * with the License. You may obtain a copy of the License at
  39838. *
  39839. * http://www.apache.org/licenses/LICENSE-2.0
  39840. *
  39841. * Unless required by applicable law or agreed to in writing,
  39842. * software distributed under the License is distributed on an
  39843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39844. * KIND, either express or implied. See the License for the
  39845. * specific language governing permissions and limitations
  39846. * under the License.
  39847. */
  39848. // import * as zrUtil from 'zrender/src/core/util';
  39849. // In case developer forget to include grid component
  39850. registerVisual(visualSymbol('scatter', 'circle'));
  39851. registerLayout(pointsLayout('scatter'));
  39852. // echarts.registerProcessor(function (ecModel, api) {
  39853. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  39854. // var data = seriesModel.getData();
  39855. // var coordSys = seriesModel.coordinateSystem;
  39856. // if (coordSys.type !== 'geo') {
  39857. // return;
  39858. // }
  39859. // var startPt = coordSys.pointToData([0, 0]);
  39860. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  39861. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  39862. // return data.mapDimension(dim);
  39863. // });
  39864. // var range = {};
  39865. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  39866. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  39867. // data.selectRange(range);
  39868. // });
  39869. // });
  39870. /*
  39871. * Licensed to the Apache Software Foundation (ASF) under one
  39872. * or more contributor license agreements. See the NOTICE file
  39873. * distributed with this work for additional information
  39874. * regarding copyright ownership. The ASF licenses this file
  39875. * to you under the Apache License, Version 2.0 (the
  39876. * "License"); you may not use this file except in compliance
  39877. * with the License. You may obtain a copy of the License at
  39878. *
  39879. * http://www.apache.org/licenses/LICENSE-2.0
  39880. *
  39881. * Unless required by applicable law or agreed to in writing,
  39882. * software distributed under the License is distributed on an
  39883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39884. * KIND, either express or implied. See the License for the
  39885. * specific language governing permissions and limitations
  39886. * under the License.
  39887. */
  39888. var _nonShapeGraphicElements = {
  39889. // Reserved but not supported in graphic component.
  39890. path: null,
  39891. compoundPath: null,
  39892. // Supported in graphic component.
  39893. group: Group,
  39894. image: ZImage,
  39895. text: Text
  39896. };
  39897. // -------------
  39898. // Preprocessor
  39899. // -------------
  39900. registerPreprocessor(function (option) {
  39901. var graphicOption = option.graphic;
  39902. // Convert
  39903. // {graphic: [{left: 10, type: 'circle'}, ...]}
  39904. // or
  39905. // {graphic: {left: 10, type: 'circle'}}
  39906. // to
  39907. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  39908. if (isArray(graphicOption)) {
  39909. if (!graphicOption[0] || !graphicOption[0].elements) {
  39910. option.graphic = [{elements: graphicOption}];
  39911. }
  39912. else {
  39913. // Only one graphic instance can be instantiated. (We dont
  39914. // want that too many views are created in echarts._viewMap)
  39915. option.graphic = [option.graphic[0]];
  39916. }
  39917. }
  39918. else if (graphicOption && !graphicOption.elements) {
  39919. option.graphic = [{elements: [graphicOption]}];
  39920. }
  39921. });
  39922. // ------
  39923. // Model
  39924. // ------
  39925. var GraphicModel = extendComponentModel({
  39926. type: 'graphic',
  39927. defaultOption: {
  39928. // Extra properties for each elements:
  39929. //
  39930. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  39931. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  39932. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  39933. // This mechanism is useful when you want to position a group/element
  39934. // against the right side or the center of this container.
  39935. //
  39936. // width/height: (can only be pixel value, default 0)
  39937. // Only be used to specify contianer(group) size, if needed. And
  39938. // can not be percentage value (like '33%'). See the reason in the
  39939. // layout algorithm below.
  39940. //
  39941. // bounding: (enum: 'all' (default) | 'raw')
  39942. // Specify how to calculate boundingRect when locating.
  39943. // 'all': Get uioned and transformed boundingRect
  39944. // from both itself and its descendants.
  39945. // This mode simplies confining a group of elements in the bounding
  39946. // of their ancester container (e.g., using 'right: 0').
  39947. // 'raw': Only use the boundingRect of itself and before transformed.
  39948. // This mode is similar to css behavior, which is useful when you
  39949. // want an element to be able to overflow its container. (Consider
  39950. // a rotated circle needs to be located in a corner.)
  39951. // info: custom info. enables user to mount some info on elements and use them
  39952. // in event handlers. Update them only when user specified, otherwise, remain.
  39953. // Note: elements is always behind its ancestors in this elements array.
  39954. elements: [],
  39955. parentId: null
  39956. },
  39957. /**
  39958. * Save el options for the sake of the performance (only update modified graphics).
  39959. * The order is the same as those in option. (ancesters -> descendants)
  39960. *
  39961. * @private
  39962. * @type {Array.<Object>}
  39963. */
  39964. _elOptionsToUpdate: null,
  39965. /**
  39966. * @override
  39967. */
  39968. mergeOption: function (option) {
  39969. // Prevent default merge to elements
  39970. var elements = this.option.elements;
  39971. this.option.elements = null;
  39972. GraphicModel.superApply(this, 'mergeOption', arguments);
  39973. this.option.elements = elements;
  39974. },
  39975. /**
  39976. * @override
  39977. */
  39978. optionUpdated: function (newOption, isInit) {
  39979. var thisOption = this.option;
  39980. var newList = (isInit ? thisOption : newOption).elements;
  39981. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  39982. var flattenedList = [];
  39983. this._flatten(newList, flattenedList);
  39984. var mappingResult = mappingToExists(existList, flattenedList);
  39985. makeIdAndName(mappingResult);
  39986. // Clear elOptionsToUpdate
  39987. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  39988. each$1(mappingResult, function (resultItem, index) {
  39989. var newElOption = resultItem.option;
  39990. if (__DEV__) {
  39991. assert$1(
  39992. isObject$1(newElOption) || resultItem.exist,
  39993. 'Empty graphic option definition'
  39994. );
  39995. }
  39996. if (!newElOption) {
  39997. return;
  39998. }
  39999. elOptionsToUpdate.push(newElOption);
  40000. setKeyInfoToNewElOption(resultItem, newElOption);
  40001. mergeNewElOptionToExist(existList, index, newElOption);
  40002. setLayoutInfoToExist(existList[index], newElOption);
  40003. }, this);
  40004. // Clean
  40005. for (var i = existList.length - 1; i >= 0; i--) {
  40006. if (existList[i] == null) {
  40007. existList.splice(i, 1);
  40008. }
  40009. else {
  40010. // $action should be volatile, otherwise option gotten from
  40011. // `getOption` will contain unexpected $action.
  40012. delete existList[i].$action;
  40013. }
  40014. }
  40015. },
  40016. /**
  40017. * Convert
  40018. * [{
  40019. * type: 'group',
  40020. * id: 'xx',
  40021. * children: [{type: 'circle'}, {type: 'polygon'}]
  40022. * }]
  40023. * to
  40024. * [
  40025. * {type: 'group', id: 'xx'},
  40026. * {type: 'circle', parentId: 'xx'},
  40027. * {type: 'polygon', parentId: 'xx'}
  40028. * ]
  40029. *
  40030. * @private
  40031. * @param {Array.<Object>} optionList option list
  40032. * @param {Array.<Object>} result result of flatten
  40033. * @param {Object} parentOption parent option
  40034. */
  40035. _flatten: function (optionList, result, parentOption) {
  40036. each$1(optionList, function (option) {
  40037. if (!option) {
  40038. return;
  40039. }
  40040. if (parentOption) {
  40041. option.parentOption = parentOption;
  40042. }
  40043. result.push(option);
  40044. var children = option.children;
  40045. if (option.type === 'group' && children) {
  40046. this._flatten(children, result, option);
  40047. }
  40048. // Deleting for JSON output, and for not affecting group creation.
  40049. delete option.children;
  40050. }, this);
  40051. },
  40052. // FIXME
  40053. // Pass to view using payload? setOption has a payload?
  40054. useElOptionsToUpdate: function () {
  40055. var els = this._elOptionsToUpdate;
  40056. // Clear to avoid render duplicately when zooming.
  40057. this._elOptionsToUpdate = null;
  40058. return els;
  40059. }
  40060. });
  40061. // -----
  40062. // View
  40063. // -----
  40064. extendComponentView({
  40065. type: 'graphic',
  40066. /**
  40067. * @override
  40068. */
  40069. init: function (ecModel, api) {
  40070. /**
  40071. * @private
  40072. * @type {module:zrender/core/util.HashMap}
  40073. */
  40074. this._elMap = createHashMap();
  40075. /**
  40076. * @private
  40077. * @type {module:echarts/graphic/GraphicModel}
  40078. */
  40079. this._lastGraphicModel;
  40080. },
  40081. /**
  40082. * @override
  40083. */
  40084. render: function (graphicModel, ecModel, api) {
  40085. // Having leveraged between use cases and algorithm complexity, a very
  40086. // simple layout mechanism is used:
  40087. // The size(width/height) can be determined by itself or its parent (not
  40088. // implemented yet), but can not by its children. (Top-down travel)
  40089. // The location(x/y) can be determined by the bounding rect of itself
  40090. // (can including its descendants or not) and the size of its parent.
  40091. // (Bottom-up travel)
  40092. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  40093. // view will be reused.
  40094. if (graphicModel !== this._lastGraphicModel) {
  40095. this._clear();
  40096. }
  40097. this._lastGraphicModel = graphicModel;
  40098. this._updateElements(graphicModel);
  40099. this._relocate(graphicModel, api);
  40100. },
  40101. /**
  40102. * Update graphic elements.
  40103. *
  40104. * @private
  40105. * @param {Object} graphicModel graphic model
  40106. */
  40107. _updateElements: function (graphicModel) {
  40108. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  40109. if (!elOptionsToUpdate) {
  40110. return;
  40111. }
  40112. var elMap = this._elMap;
  40113. var rootGroup = this.group;
  40114. // Top-down tranverse to assign graphic settings to each elements.
  40115. each$1(elOptionsToUpdate, function (elOption) {
  40116. var $action = elOption.$action;
  40117. var id = elOption.id;
  40118. var existEl = elMap.get(id);
  40119. var parentId = elOption.parentId;
  40120. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  40121. var elOptionStyle = elOption.style;
  40122. if (elOption.type === 'text' && elOptionStyle) {
  40123. // In top/bottom mode, textVerticalAlign should not be used, which cause
  40124. // inaccurately locating.
  40125. if (elOption.hv && elOption.hv[1]) {
  40126. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  40127. }
  40128. // Compatible with previous setting: both support fill and textFill,
  40129. // stroke and textStroke.
  40130. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  40131. elOptionStyle.textFill = elOptionStyle.fill
  40132. );
  40133. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  40134. elOptionStyle.textStroke = elOptionStyle.stroke
  40135. );
  40136. }
  40137. // Remove unnecessary props to avoid potential problems.
  40138. var elOptionCleaned = getCleanedElOption(elOption);
  40139. // For simple, do not support parent change, otherwise reorder is needed.
  40140. if (__DEV__) {
  40141. existEl && assert$1(
  40142. targetElParent === existEl.parent,
  40143. 'Changing parent is not supported.'
  40144. );
  40145. }
  40146. if (!$action || $action === 'merge') {
  40147. existEl
  40148. ? existEl.attr(elOptionCleaned)
  40149. : createEl(id, targetElParent, elOptionCleaned, elMap);
  40150. }
  40151. else if ($action === 'replace') {
  40152. removeEl(existEl, elMap);
  40153. createEl(id, targetElParent, elOptionCleaned, elMap);
  40154. }
  40155. else if ($action === 'remove') {
  40156. removeEl(existEl, elMap);
  40157. }
  40158. var el = elMap.get(id);
  40159. if (el) {
  40160. el.__ecGraphicWidthOption = elOption.width;
  40161. el.__ecGraphicHeightOption = elOption.height;
  40162. setEventData(el, graphicModel, elOption);
  40163. }
  40164. });
  40165. },
  40166. /**
  40167. * Locate graphic elements.
  40168. *
  40169. * @private
  40170. * @param {Object} graphicModel graphic model
  40171. * @param {module:echarts/ExtensionAPI} api extension API
  40172. */
  40173. _relocate: function (graphicModel, api) {
  40174. var elOptions = graphicModel.option.elements;
  40175. var rootGroup = this.group;
  40176. var elMap = this._elMap;
  40177. var apiWidth = api.getWidth();
  40178. var apiHeight = api.getHeight();
  40179. // Top-down to calculate percentage width/height of group
  40180. for (var i = 0; i < elOptions.length; i++) {
  40181. var elOption = elOptions[i];
  40182. var el = elMap.get(elOption.id);
  40183. if (!el || !el.isGroup) {
  40184. continue;
  40185. }
  40186. var parentEl = el.parent;
  40187. var isParentRoot = parentEl === rootGroup;
  40188. // Like 'position:absolut' in css, default 0.
  40189. el.__ecGraphicWidth = parsePercent$1(
  40190. el.__ecGraphicWidthOption,
  40191. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  40192. ) || 0;
  40193. el.__ecGraphicHeight = parsePercent$1(
  40194. el.__ecGraphicHeightOption,
  40195. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  40196. ) || 0;
  40197. }
  40198. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  40199. for (var i = elOptions.length - 1; i >= 0; i--) {
  40200. var elOption = elOptions[i];
  40201. var el = elMap.get(elOption.id);
  40202. if (!el) {
  40203. continue;
  40204. }
  40205. var parentEl = el.parent;
  40206. var containerInfo = parentEl === rootGroup
  40207. ? {
  40208. width: apiWidth,
  40209. height: apiHeight
  40210. }
  40211. : {
  40212. width: parentEl.__ecGraphicWidth,
  40213. height: parentEl.__ecGraphicHeight
  40214. };
  40215. // PENDING
  40216. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  40217. // does not include the rect of [0, 0, group.width, group.height], which
  40218. // is probably weird for users. Should we make a break change for it?
  40219. positionElement(
  40220. el, elOption, containerInfo, null,
  40221. {hv: elOption.hv, boundingMode: elOption.bounding}
  40222. );
  40223. }
  40224. },
  40225. /**
  40226. * Clear all elements.
  40227. *
  40228. * @private
  40229. */
  40230. _clear: function () {
  40231. var elMap = this._elMap;
  40232. elMap.each(function (el) {
  40233. removeEl(el, elMap);
  40234. });
  40235. this._elMap = createHashMap();
  40236. },
  40237. /**
  40238. * @override
  40239. */
  40240. dispose: function () {
  40241. this._clear();
  40242. }
  40243. });
  40244. function createEl(id, targetElParent, elOption, elMap) {
  40245. var graphicType = elOption.type;
  40246. if (__DEV__) {
  40247. assert$1(graphicType, 'graphic type MUST be set');
  40248. }
  40249. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  40250. // Those graphic elements are not shapes. They should not be
  40251. // overwritten by users, so do them first.
  40252. ? _nonShapeGraphicElements[graphicType]
  40253. : getShapeClass(graphicType);
  40254. if (__DEV__) {
  40255. assert$1(Clz, 'graphic type can not be found');
  40256. }
  40257. var el = new Clz(elOption);
  40258. targetElParent.add(el);
  40259. elMap.set(id, el);
  40260. el.__ecGraphicId = id;
  40261. }
  40262. function removeEl(existEl, elMap) {
  40263. var existElParent = existEl && existEl.parent;
  40264. if (existElParent) {
  40265. existEl.type === 'group' && existEl.traverse(function (el) {
  40266. removeEl(el, elMap);
  40267. });
  40268. elMap.removeKey(existEl.__ecGraphicId);
  40269. existElParent.remove(existEl);
  40270. }
  40271. }
  40272. // Remove unnecessary props to avoid potential problems.
  40273. function getCleanedElOption(elOption) {
  40274. elOption = extend({}, elOption);
  40275. each$1(
  40276. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  40277. function (name) {
  40278. delete elOption[name];
  40279. }
  40280. );
  40281. return elOption;
  40282. }
  40283. function isSetLoc(obj, props) {
  40284. var isSet;
  40285. each$1(props, function (prop) {
  40286. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  40287. });
  40288. return isSet;
  40289. }
  40290. function setKeyInfoToNewElOption(resultItem, newElOption) {
  40291. var existElOption = resultItem.exist;
  40292. // Set id and type after id assigned.
  40293. newElOption.id = resultItem.keyInfo.id;
  40294. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  40295. // Set parent id if not specified
  40296. if (newElOption.parentId == null) {
  40297. var newElParentOption = newElOption.parentOption;
  40298. if (newElParentOption) {
  40299. newElOption.parentId = newElParentOption.id;
  40300. }
  40301. else if (existElOption) {
  40302. newElOption.parentId = existElOption.parentId;
  40303. }
  40304. }
  40305. // Clear
  40306. newElOption.parentOption = null;
  40307. }
  40308. function mergeNewElOptionToExist(existList, index, newElOption) {
  40309. // Update existing options, for `getOption` feature.
  40310. var newElOptCopy = extend({}, newElOption);
  40311. var existElOption = existList[index];
  40312. var $action = newElOption.$action || 'merge';
  40313. if ($action === 'merge') {
  40314. if (existElOption) {
  40315. if (__DEV__) {
  40316. var newType = newElOption.type;
  40317. assert$1(
  40318. !newType || existElOption.type === newType,
  40319. 'Please set $action: "replace" to change `type`'
  40320. );
  40321. }
  40322. // We can ensure that newElOptCopy and existElOption are not
  40323. // the same object, so `merge` will not change newElOptCopy.
  40324. merge(existElOption, newElOptCopy, true);
  40325. // Rigid body, use ignoreSize.
  40326. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  40327. // Will be used in render.
  40328. copyLayoutParams(newElOption, existElOption);
  40329. }
  40330. else {
  40331. existList[index] = newElOptCopy;
  40332. }
  40333. }
  40334. else if ($action === 'replace') {
  40335. existList[index] = newElOptCopy;
  40336. }
  40337. else if ($action === 'remove') {
  40338. // null will be cleaned later.
  40339. existElOption && (existList[index] = null);
  40340. }
  40341. }
  40342. function setLayoutInfoToExist(existItem, newElOption) {
  40343. if (!existItem) {
  40344. return;
  40345. }
  40346. existItem.hv = newElOption.hv = [
  40347. // Rigid body, dont care `width`.
  40348. isSetLoc(newElOption, ['left', 'right']),
  40349. // Rigid body, dont care `height`.
  40350. isSetLoc(newElOption, ['top', 'bottom'])
  40351. ];
  40352. // Give default group size. Otherwise layout error may occur.
  40353. if (existItem.type === 'group') {
  40354. existItem.width == null && (existItem.width = newElOption.width = 0);
  40355. existItem.height == null && (existItem.height = newElOption.height = 0);
  40356. }
  40357. }
  40358. function setEventData(el, graphicModel, elOption) {
  40359. var eventData = el.eventData;
  40360. // Simple optimize for large amount of elements that no need event.
  40361. if (!el.silent && !el.ignore && !eventData) {
  40362. eventData = el.eventData = {
  40363. componentType: 'graphic',
  40364. componentIndex: graphicModel.componentIndex,
  40365. name: el.name
  40366. };
  40367. }
  40368. // `elOption.info` enables user to mount some info on
  40369. // elements and use them in event handlers.
  40370. if (eventData) {
  40371. eventData.info = el.info;
  40372. }
  40373. }
  40374. /*
  40375. * Licensed to the Apache Software Foundation (ASF) under one
  40376. * or more contributor license agreements. See the NOTICE file
  40377. * distributed with this work for additional information
  40378. * regarding copyright ownership. The ASF licenses this file
  40379. * to you under the Apache License, Version 2.0 (the
  40380. * "License"); you may not use this file except in compliance
  40381. * with the License. You may obtain a copy of the License at
  40382. *
  40383. * http://www.apache.org/licenses/LICENSE-2.0
  40384. *
  40385. * Unless required by applicable law or agreed to in writing,
  40386. * software distributed under the License is distributed on an
  40387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40388. * KIND, either express or implied. See the License for the
  40389. * specific language governing permissions and limitations
  40390. * under the License.
  40391. */
  40392. /**
  40393. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  40394. * @param {module:echarts/model/Global} ecModel
  40395. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  40396. */
  40397. var findPointFromSeries = function (finder, ecModel) {
  40398. var point = [];
  40399. var seriesIndex = finder.seriesIndex;
  40400. var seriesModel;
  40401. if (seriesIndex == null || !(
  40402. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  40403. )) {
  40404. return {point: []};
  40405. }
  40406. var data = seriesModel.getData();
  40407. var dataIndex = queryDataIndex(data, finder);
  40408. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  40409. return {point: []};
  40410. }
  40411. var el = data.getItemGraphicEl(dataIndex);
  40412. var coordSys = seriesModel.coordinateSystem;
  40413. if (seriesModel.getTooltipPosition) {
  40414. point = seriesModel.getTooltipPosition(dataIndex) || [];
  40415. }
  40416. else if (coordSys && coordSys.dataToPoint) {
  40417. point = coordSys.dataToPoint(
  40418. data.getValues(
  40419. map(coordSys.dimensions, function (dim) {
  40420. return data.mapDimension(dim);
  40421. }), dataIndex, true
  40422. )
  40423. ) || [];
  40424. }
  40425. else if (el) {
  40426. // Use graphic bounding rect
  40427. var rect = el.getBoundingRect().clone();
  40428. rect.applyTransform(el.transform);
  40429. point = [
  40430. rect.x + rect.width / 2,
  40431. rect.y + rect.height / 2
  40432. ];
  40433. }
  40434. return {point: point, el: el};
  40435. };
  40436. /*
  40437. * Licensed to the Apache Software Foundation (ASF) under one
  40438. * or more contributor license agreements. See the NOTICE file
  40439. * distributed with this work for additional information
  40440. * regarding copyright ownership. The ASF licenses this file
  40441. * to you under the Apache License, Version 2.0 (the
  40442. * "License"); you may not use this file except in compliance
  40443. * with the License. You may obtain a copy of the License at
  40444. *
  40445. * http://www.apache.org/licenses/LICENSE-2.0
  40446. *
  40447. * Unless required by applicable law or agreed to in writing,
  40448. * software distributed under the License is distributed on an
  40449. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40450. * KIND, either express or implied. See the License for the
  40451. * specific language governing permissions and limitations
  40452. * under the License.
  40453. */
  40454. var each$7 = each$1;
  40455. var curry$2 = curry;
  40456. var inner$7 = makeInner();
  40457. /**
  40458. * Basic logic: check all axis, if they do not demand show/highlight,
  40459. * then hide/downplay them.
  40460. *
  40461. * @param {Object} coordSysAxesInfo
  40462. * @param {Object} payload
  40463. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  40464. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  40465. * trigger axisPointer and tooltip.
  40466. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  40467. * trigger axisPointer and tooltip.
  40468. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  40469. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  40470. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  40471. * [{
  40472. * axisDim: 'x'|'y'|'angle'|...,
  40473. * axisIndex: ...,
  40474. * value: ...
  40475. * }, ...]
  40476. * @param {Function} [payload.dispatchAction]
  40477. * @param {Object} [payload.tooltipOption]
  40478. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  40479. * which can be specified in dispatchAction
  40480. * @param {module:echarts/model/Global} ecModel
  40481. * @param {module:echarts/ExtensionAPI} api
  40482. * @return {Object} content of event obj for echarts.connect.
  40483. */
  40484. var axisTrigger = function (payload, ecModel, api) {
  40485. var currTrigger = payload.currTrigger;
  40486. var point = [payload.x, payload.y];
  40487. var finder = payload;
  40488. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  40489. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40490. // Pending
  40491. // See #6121. But we are not able to reproduce it yet.
  40492. if (!coordSysAxesInfo) {
  40493. return;
  40494. }
  40495. if (illegalPoint(point)) {
  40496. // Used in the default behavior of `connection`: use the sample seriesIndex
  40497. // and dataIndex. And also used in the tooltipView trigger.
  40498. point = findPointFromSeries({
  40499. seriesIndex: finder.seriesIndex,
  40500. // Do not use dataIndexInside from other ec instance.
  40501. // FIXME: auto detect it?
  40502. dataIndex: finder.dataIndex
  40503. }, ecModel).point;
  40504. }
  40505. var isIllegalPoint = illegalPoint(point);
  40506. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  40507. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  40508. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  40509. // and dataIndex.
  40510. var inputAxesInfo = finder.axesInfo;
  40511. var axesInfo = coordSysAxesInfo.axesInfo;
  40512. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  40513. var outputFinder = {};
  40514. var showValueMap = {};
  40515. var dataByCoordSys = {list: [], map: {}};
  40516. var updaters = {
  40517. showPointer: curry$2(showPointer, showValueMap),
  40518. showTooltip: curry$2(showTooltip, dataByCoordSys)
  40519. };
  40520. // Process for triggered axes.
  40521. each$7(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  40522. // If a point given, it must be contained by the coordinate system.
  40523. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  40524. each$7(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  40525. var axis = axisInfo.axis;
  40526. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  40527. // If no inputAxesInfo, no axis is restricted.
  40528. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  40529. var val = inputAxisInfo && inputAxisInfo.value;
  40530. if (val == null && !isIllegalPoint) {
  40531. val = axis.pointToData(point);
  40532. }
  40533. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  40534. }
  40535. });
  40536. });
  40537. // Process for linked axes.
  40538. var linkTriggers = {};
  40539. each$7(axesInfo, function (tarAxisInfo, tarKey) {
  40540. var linkGroup = tarAxisInfo.linkGroup;
  40541. // If axis has been triggered in the previous stage, it should not be triggered by link.
  40542. if (linkGroup && !showValueMap[tarKey]) {
  40543. each$7(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  40544. var srcValItem = showValueMap[srcKey];
  40545. // If srcValItem exist, source axis is triggered, so link to target axis.
  40546. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  40547. var val = srcValItem.value;
  40548. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  40549. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  40550. )));
  40551. linkTriggers[tarAxisInfo.key] = val;
  40552. }
  40553. });
  40554. }
  40555. });
  40556. each$7(linkTriggers, function (val, tarKey) {
  40557. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  40558. });
  40559. updateModelActually(showValueMap, axesInfo, outputFinder);
  40560. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  40561. dispatchHighDownActually(axesInfo, dispatchAction, api);
  40562. return outputFinder;
  40563. };
  40564. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  40565. var axis = axisInfo.axis;
  40566. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  40567. return;
  40568. }
  40569. if (!axisInfo.involveSeries) {
  40570. updaters.showPointer(axisInfo, newValue);
  40571. return;
  40572. }
  40573. // Heavy calculation. So put it after axis.containData checking.
  40574. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  40575. var payloadBatch = payloadInfo.payloadBatch;
  40576. var snapToValue = payloadInfo.snapToValue;
  40577. // Fill content of event obj for echarts.connect.
  40578. // By defualt use the first involved series data as a sample to connect.
  40579. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  40580. extend(outputFinder, payloadBatch[0]);
  40581. }
  40582. // If no linkSource input, this process is for collecting link
  40583. // target, where snap should not be accepted.
  40584. if (!dontSnap && axisInfo.snap) {
  40585. if (axis.containData(snapToValue) && snapToValue != null) {
  40586. newValue = snapToValue;
  40587. }
  40588. }
  40589. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  40590. // Tooltip should always be snapToValue, otherwise there will be
  40591. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  40592. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  40593. }
  40594. function buildPayloadsBySeries(value, axisInfo) {
  40595. var axis = axisInfo.axis;
  40596. var dim = axis.dim;
  40597. var snapToValue = value;
  40598. var payloadBatch = [];
  40599. var minDist = Number.MAX_VALUE;
  40600. var minDiff = -1;
  40601. each$7(axisInfo.seriesModels, function (series, idx) {
  40602. var dataDim = series.getData().mapDimension(dim, true);
  40603. var seriesNestestValue;
  40604. var dataIndices;
  40605. if (series.getAxisTooltipData) {
  40606. var result = series.getAxisTooltipData(dataDim, value, axis);
  40607. dataIndices = result.dataIndices;
  40608. seriesNestestValue = result.nestestValue;
  40609. }
  40610. else {
  40611. dataIndices = series.getData().indicesOfNearest(
  40612. dataDim[0],
  40613. value,
  40614. // Add a threshold to avoid find the wrong dataIndex
  40615. // when data length is not same.
  40616. // false,
  40617. axis.type === 'category' ? 0.5 : null
  40618. );
  40619. if (!dataIndices.length) {
  40620. return;
  40621. }
  40622. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  40623. }
  40624. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  40625. return;
  40626. }
  40627. var diff = value - seriesNestestValue;
  40628. var dist = Math.abs(diff);
  40629. // Consider category case
  40630. if (dist <= minDist) {
  40631. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  40632. minDist = dist;
  40633. minDiff = diff;
  40634. snapToValue = seriesNestestValue;
  40635. payloadBatch.length = 0;
  40636. }
  40637. each$7(dataIndices, function (dataIndex) {
  40638. payloadBatch.push({
  40639. seriesIndex: series.seriesIndex,
  40640. dataIndexInside: dataIndex,
  40641. dataIndex: series.getData().getRawIndex(dataIndex)
  40642. });
  40643. });
  40644. }
  40645. });
  40646. return {
  40647. payloadBatch: payloadBatch,
  40648. snapToValue: snapToValue
  40649. };
  40650. }
  40651. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  40652. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  40653. }
  40654. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  40655. var payloadBatch = payloadInfo.payloadBatch;
  40656. var axis = axisInfo.axis;
  40657. var axisModel = axis.model;
  40658. var axisPointerModel = axisInfo.axisPointerModel;
  40659. // If no data, do not create anything in dataByCoordSys,
  40660. // whose length will be used to judge whether dispatch action.
  40661. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  40662. return;
  40663. }
  40664. var coordSysModel = axisInfo.coordSys.model;
  40665. var coordSysKey = makeKey(coordSysModel);
  40666. var coordSysItem = dataByCoordSys.map[coordSysKey];
  40667. if (!coordSysItem) {
  40668. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  40669. coordSysId: coordSysModel.id,
  40670. coordSysIndex: coordSysModel.componentIndex,
  40671. coordSysType: coordSysModel.type,
  40672. coordSysMainType: coordSysModel.mainType,
  40673. dataByAxis: []
  40674. };
  40675. dataByCoordSys.list.push(coordSysItem);
  40676. }
  40677. coordSysItem.dataByAxis.push({
  40678. axisDim: axis.dim,
  40679. axisIndex: axisModel.componentIndex,
  40680. axisType: axisModel.type,
  40681. axisId: axisModel.id,
  40682. value: value,
  40683. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  40684. // depends that all models have been updated. So it should not be performed
  40685. // here. Considering axisPointerModel used here is volatile, which is hard
  40686. // to be retrieve in TooltipView, we prepare parameters here.
  40687. valueLabelOpt: {
  40688. precision: axisPointerModel.get('label.precision'),
  40689. formatter: axisPointerModel.get('label.formatter')
  40690. },
  40691. seriesDataIndices: payloadBatch.slice()
  40692. });
  40693. }
  40694. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  40695. var outputAxesInfo = outputFinder.axesInfo = [];
  40696. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  40697. each$7(axesInfo, function (axisInfo, key) {
  40698. var option = axisInfo.axisPointerModel.option;
  40699. var valItem = showValueMap[key];
  40700. if (valItem) {
  40701. !axisInfo.useHandle && (option.status = 'show');
  40702. option.value = valItem.value;
  40703. // For label formatter param and highlight.
  40704. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  40705. }
  40706. // When always show (e.g., handle used), remain
  40707. // original value and status.
  40708. else {
  40709. // If hide, value still need to be set, consider
  40710. // click legend to toggle axis blank.
  40711. !axisInfo.useHandle && (option.status = 'hide');
  40712. }
  40713. // If status is 'hide', should be no info in payload.
  40714. option.status === 'show' && outputAxesInfo.push({
  40715. axisDim: axisInfo.axis.dim,
  40716. axisIndex: axisInfo.axis.model.componentIndex,
  40717. value: option.value
  40718. });
  40719. });
  40720. }
  40721. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  40722. // Basic logic: If no showTip required, hideTip will be dispatched.
  40723. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  40724. dispatchAction({type: 'hideTip'});
  40725. return;
  40726. }
  40727. // In most case only one axis (or event one series is used). It is
  40728. // convinient to fetch payload.seriesIndex and payload.dataIndex
  40729. // dirtectly. So put the first seriesIndex and dataIndex of the first
  40730. // axis on the payload.
  40731. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  40732. dispatchAction({
  40733. type: 'showTip',
  40734. escapeConnect: true,
  40735. x: point[0],
  40736. y: point[1],
  40737. tooltipOption: payload.tooltipOption,
  40738. position: payload.position,
  40739. dataIndexInside: sampleItem.dataIndexInside,
  40740. dataIndex: sampleItem.dataIndex,
  40741. seriesIndex: sampleItem.seriesIndex,
  40742. dataByCoordSys: dataByCoordSys.list
  40743. });
  40744. }
  40745. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  40746. // FIXME
  40747. // highlight status modification shoule be a stage of main process?
  40748. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  40749. var zr = api.getZr();
  40750. var highDownKey = 'axisPointerLastHighlights';
  40751. var lastHighlights = inner$7(zr)[highDownKey] || {};
  40752. var newHighlights = inner$7(zr)[highDownKey] = {};
  40753. // Update highlight/downplay status according to axisPointer model.
  40754. // Build hash map and remove duplicate incidentally.
  40755. each$7(axesInfo, function (axisInfo, key) {
  40756. var option = axisInfo.axisPointerModel.option;
  40757. option.status === 'show' && each$7(option.seriesDataIndices, function (batchItem) {
  40758. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  40759. newHighlights[key] = batchItem;
  40760. });
  40761. });
  40762. // Diff.
  40763. var toHighlight = [];
  40764. var toDownplay = [];
  40765. each$1(lastHighlights, function (batchItem, key) {
  40766. !newHighlights[key] && toDownplay.push(batchItem);
  40767. });
  40768. each$1(newHighlights, function (batchItem, key) {
  40769. !lastHighlights[key] && toHighlight.push(batchItem);
  40770. });
  40771. toDownplay.length && api.dispatchAction({
  40772. type: 'downplay', escapeConnect: true, batch: toDownplay
  40773. });
  40774. toHighlight.length && api.dispatchAction({
  40775. type: 'highlight', escapeConnect: true, batch: toHighlight
  40776. });
  40777. }
  40778. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  40779. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  40780. var inputAxisInfo = inputAxesInfo[i];
  40781. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  40782. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  40783. ) {
  40784. return inputAxisInfo;
  40785. }
  40786. }
  40787. }
  40788. function makeMapperParam(axisInfo) {
  40789. var axisModel = axisInfo.axis.model;
  40790. var item = {};
  40791. var dim = item.axisDim = axisInfo.axis.dim;
  40792. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  40793. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  40794. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  40795. return item;
  40796. }
  40797. function illegalPoint(point) {
  40798. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  40799. }
  40800. /*
  40801. * Licensed to the Apache Software Foundation (ASF) under one
  40802. * or more contributor license agreements. See the NOTICE file
  40803. * distributed with this work for additional information
  40804. * regarding copyright ownership. The ASF licenses this file
  40805. * to you under the Apache License, Version 2.0 (the
  40806. * "License"); you may not use this file except in compliance
  40807. * with the License. You may obtain a copy of the License at
  40808. *
  40809. * http://www.apache.org/licenses/LICENSE-2.0
  40810. *
  40811. * Unless required by applicable law or agreed to in writing,
  40812. * software distributed under the License is distributed on an
  40813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40814. * KIND, either express or implied. See the License for the
  40815. * specific language governing permissions and limitations
  40816. * under the License.
  40817. */
  40818. var AxisPointerModel = extendComponentModel({
  40819. type: 'axisPointer',
  40820. coordSysAxesInfo: null,
  40821. defaultOption: {
  40822. // 'auto' means that show when triggered by tooltip or handle.
  40823. show: 'auto',
  40824. // 'click' | 'mousemove' | 'none'
  40825. triggerOn: null, // set default in AxisPonterView.js
  40826. zlevel: 0,
  40827. z: 50,
  40828. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  40829. // axispointer triggered by tootip determine snap automatically,
  40830. // see `modelHelper`.
  40831. snap: false,
  40832. triggerTooltip: true,
  40833. value: null,
  40834. status: null, // Init value depends on whether handle is used.
  40835. // [group0, group1, ...]
  40836. // Each group can be: {
  40837. // mapper: function () {},
  40838. // singleTooltip: 'multiple', // 'multiple' or 'single'
  40839. // xAxisId: ...,
  40840. // yAxisName: ...,
  40841. // angleAxisIndex: ...
  40842. // }
  40843. // mapper: can be ignored.
  40844. // input: {axisInfo, value}
  40845. // output: {axisInfo, value}
  40846. link: [],
  40847. // Do not set 'auto' here, otherwise global animation: false
  40848. // will not effect at this axispointer.
  40849. animation: null,
  40850. animationDurationUpdate: 200,
  40851. lineStyle: {
  40852. color: '#aaa',
  40853. width: 1,
  40854. type: 'solid'
  40855. },
  40856. shadowStyle: {
  40857. color: 'rgba(150,150,150,0.3)'
  40858. },
  40859. label: {
  40860. show: true,
  40861. formatter: null, // string | Function
  40862. precision: 'auto', // Or a number like 0, 1, 2 ...
  40863. margin: 3,
  40864. color: '#fff',
  40865. padding: [5, 7, 5, 7],
  40866. backgroundColor: 'auto', // default: axis line color
  40867. borderColor: null,
  40868. borderWidth: 0,
  40869. shadowBlur: 3,
  40870. shadowColor: '#aaa'
  40871. // Considering applicability, common style should
  40872. // better not have shadowOffset.
  40873. // shadowOffsetX: 0,
  40874. // shadowOffsetY: 2
  40875. },
  40876. handle: {
  40877. show: false,
  40878. /* eslint-disable */
  40879. 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
  40880. /* eslint-enable */
  40881. size: 45,
  40882. // handle margin is from symbol center to axis, which is stable when circular move.
  40883. margin: 50,
  40884. // color: '#1b8bbd'
  40885. // color: '#2f4554'
  40886. color: '#333',
  40887. shadowBlur: 3,
  40888. shadowColor: '#aaa',
  40889. shadowOffsetX: 0,
  40890. shadowOffsetY: 2,
  40891. // For mobile performance
  40892. throttle: 40
  40893. }
  40894. }
  40895. });
  40896. /*
  40897. * Licensed to the Apache Software Foundation (ASF) under one
  40898. * or more contributor license agreements. See the NOTICE file
  40899. * distributed with this work for additional information
  40900. * regarding copyright ownership. The ASF licenses this file
  40901. * to you under the Apache License, Version 2.0 (the
  40902. * "License"); you may not use this file except in compliance
  40903. * with the License. You may obtain a copy of the License at
  40904. *
  40905. * http://www.apache.org/licenses/LICENSE-2.0
  40906. *
  40907. * Unless required by applicable law or agreed to in writing,
  40908. * software distributed under the License is distributed on an
  40909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40910. * KIND, either express or implied. See the License for the
  40911. * specific language governing permissions and limitations
  40912. * under the License.
  40913. */
  40914. var inner$8 = makeInner();
  40915. var each$8 = each$1;
  40916. /**
  40917. * @param {string} key
  40918. * @param {module:echarts/ExtensionAPI} api
  40919. * @param {Function} handler
  40920. * param: {string} currTrigger
  40921. * param: {Array.<number>} point
  40922. */
  40923. function register(key, api, handler) {
  40924. if (env$1.node) {
  40925. return;
  40926. }
  40927. var zr = api.getZr();
  40928. inner$8(zr).records || (inner$8(zr).records = {});
  40929. initGlobalListeners(zr, api);
  40930. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  40931. record.handler = handler;
  40932. }
  40933. function initGlobalListeners(zr, api) {
  40934. if (inner$8(zr).initialized) {
  40935. return;
  40936. }
  40937. inner$8(zr).initialized = true;
  40938. useHandler('click', curry(doEnter, 'click'));
  40939. useHandler('mousemove', curry(doEnter, 'mousemove'));
  40940. // useHandler('mouseout', onLeave);
  40941. useHandler('globalout', onLeave);
  40942. function useHandler(eventType, cb) {
  40943. zr.on(eventType, function (e) {
  40944. var dis = makeDispatchAction(api);
  40945. each$8(inner$8(zr).records, function (record) {
  40946. record && cb(record, e, dis.dispatchAction);
  40947. });
  40948. dispatchTooltipFinally(dis.pendings, api);
  40949. });
  40950. }
  40951. }
  40952. function dispatchTooltipFinally(pendings, api) {
  40953. var showLen = pendings.showTip.length;
  40954. var hideLen = pendings.hideTip.length;
  40955. var actuallyPayload;
  40956. if (showLen) {
  40957. actuallyPayload = pendings.showTip[showLen - 1];
  40958. }
  40959. else if (hideLen) {
  40960. actuallyPayload = pendings.hideTip[hideLen - 1];
  40961. }
  40962. if (actuallyPayload) {
  40963. actuallyPayload.dispatchAction = null;
  40964. api.dispatchAction(actuallyPayload);
  40965. }
  40966. }
  40967. function onLeave(record, e, dispatchAction) {
  40968. record.handler('leave', null, dispatchAction);
  40969. }
  40970. function doEnter(currTrigger, record, e, dispatchAction) {
  40971. record.handler(currTrigger, e, dispatchAction);
  40972. }
  40973. function makeDispatchAction(api) {
  40974. var pendings = {
  40975. showTip: [],
  40976. hideTip: []
  40977. };
  40978. // FIXME
  40979. // better approach?
  40980. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  40981. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  40982. // So we have to add "final stage" to merge those dispatched actions.
  40983. var dispatchAction = function (payload) {
  40984. var pendingList = pendings[payload.type];
  40985. if (pendingList) {
  40986. pendingList.push(payload);
  40987. }
  40988. else {
  40989. payload.dispatchAction = dispatchAction;
  40990. api.dispatchAction(payload);
  40991. }
  40992. };
  40993. return {
  40994. dispatchAction: dispatchAction,
  40995. pendings: pendings
  40996. };
  40997. }
  40998. /**
  40999. * @param {string} key
  41000. * @param {module:echarts/ExtensionAPI} api
  41001. */
  41002. function unregister(key, api) {
  41003. if (env$1.node) {
  41004. return;
  41005. }
  41006. var zr = api.getZr();
  41007. var record = (inner$8(zr).records || {})[key];
  41008. if (record) {
  41009. inner$8(zr).records[key] = null;
  41010. }
  41011. }
  41012. /*
  41013. * Licensed to the Apache Software Foundation (ASF) under one
  41014. * or more contributor license agreements. See the NOTICE file
  41015. * distributed with this work for additional information
  41016. * regarding copyright ownership. The ASF licenses this file
  41017. * to you under the Apache License, Version 2.0 (the
  41018. * "License"); you may not use this file except in compliance
  41019. * with the License. You may obtain a copy of the License at
  41020. *
  41021. * http://www.apache.org/licenses/LICENSE-2.0
  41022. *
  41023. * Unless required by applicable law or agreed to in writing,
  41024. * software distributed under the License is distributed on an
  41025. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41026. * KIND, either express or implied. See the License for the
  41027. * specific language governing permissions and limitations
  41028. * under the License.
  41029. */
  41030. var AxisPointerView = extendComponentView({
  41031. type: 'axisPointer',
  41032. render: function (globalAxisPointerModel, ecModel, api) {
  41033. var globalTooltipModel = ecModel.getComponent('tooltip');
  41034. var triggerOn = globalAxisPointerModel.get('triggerOn')
  41035. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  41036. // Register global listener in AxisPointerView to enable
  41037. // AxisPointerView to be independent to Tooltip.
  41038. register(
  41039. 'axisPointer',
  41040. api,
  41041. function (currTrigger, e, dispatchAction) {
  41042. // If 'none', it is not controlled by mouse totally.
  41043. if (triggerOn !== 'none'
  41044. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  41045. ) {
  41046. dispatchAction({
  41047. type: 'updateAxisPointer',
  41048. currTrigger: currTrigger,
  41049. x: e && e.offsetX,
  41050. y: e && e.offsetY
  41051. });
  41052. }
  41053. }
  41054. );
  41055. },
  41056. /**
  41057. * @override
  41058. */
  41059. remove: function (ecModel, api) {
  41060. unregister(api.getZr(), 'axisPointer');
  41061. AxisPointerView.superApply(this._model, 'remove', arguments);
  41062. },
  41063. /**
  41064. * @override
  41065. */
  41066. dispose: function (ecModel, api) {
  41067. unregister('axisPointer', api);
  41068. AxisPointerView.superApply(this._model, 'dispose', arguments);
  41069. }
  41070. });
  41071. /*
  41072. * Licensed to the Apache Software Foundation (ASF) under one
  41073. * or more contributor license agreements. See the NOTICE file
  41074. * distributed with this work for additional information
  41075. * regarding copyright ownership. The ASF licenses this file
  41076. * to you under the Apache License, Version 2.0 (the
  41077. * "License"); you may not use this file except in compliance
  41078. * with the License. You may obtain a copy of the License at
  41079. *
  41080. * http://www.apache.org/licenses/LICENSE-2.0
  41081. *
  41082. * Unless required by applicable law or agreed to in writing,
  41083. * software distributed under the License is distributed on an
  41084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41085. * KIND, either express or implied. See the License for the
  41086. * specific language governing permissions and limitations
  41087. * under the License.
  41088. */
  41089. var inner$9 = makeInner();
  41090. var clone$4 = clone;
  41091. var bind$1 = bind;
  41092. /**
  41093. * Base axis pointer class in 2D.
  41094. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  41095. */
  41096. function BaseAxisPointer() {
  41097. }
  41098. BaseAxisPointer.prototype = {
  41099. /**
  41100. * @private
  41101. */
  41102. _group: null,
  41103. /**
  41104. * @private
  41105. */
  41106. _lastGraphicKey: null,
  41107. /**
  41108. * @private
  41109. */
  41110. _handle: null,
  41111. /**
  41112. * @private
  41113. */
  41114. _dragging: false,
  41115. /**
  41116. * @private
  41117. */
  41118. _lastValue: null,
  41119. /**
  41120. * @private
  41121. */
  41122. _lastStatus: null,
  41123. /**
  41124. * @private
  41125. */
  41126. _payloadInfo: null,
  41127. /**
  41128. * In px, arbitrary value. Do not set too small,
  41129. * no animation is ok for most cases.
  41130. * @protected
  41131. */
  41132. animationThreshold: 15,
  41133. /**
  41134. * @implement
  41135. */
  41136. render: function (axisModel, axisPointerModel, api, forceRender) {
  41137. var value = axisPointerModel.get('value');
  41138. var status = axisPointerModel.get('status');
  41139. // Bind them to `this`, not in closure, otherwise they will not
  41140. // be replaced when user calling setOption in not merge mode.
  41141. this._axisModel = axisModel;
  41142. this._axisPointerModel = axisPointerModel;
  41143. this._api = api;
  41144. // Optimize: `render` will be called repeatly during mouse move.
  41145. // So it is power consuming if performing `render` each time,
  41146. // especially on mobile device.
  41147. if (!forceRender
  41148. && this._lastValue === value
  41149. && this._lastStatus === status
  41150. ) {
  41151. return;
  41152. }
  41153. this._lastValue = value;
  41154. this._lastStatus = status;
  41155. var group = this._group;
  41156. var handle = this._handle;
  41157. if (!status || status === 'hide') {
  41158. // Do not clear here, for animation better.
  41159. group && group.hide();
  41160. handle && handle.hide();
  41161. return;
  41162. }
  41163. group && group.show();
  41164. handle && handle.show();
  41165. // Otherwise status is 'show'
  41166. var elOption = {};
  41167. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  41168. // Enable change axis pointer type.
  41169. var graphicKey = elOption.graphicKey;
  41170. if (graphicKey !== this._lastGraphicKey) {
  41171. this.clear(api);
  41172. }
  41173. this._lastGraphicKey = graphicKey;
  41174. var moveAnimation = this._moveAnimation =
  41175. this.determineAnimation(axisModel, axisPointerModel);
  41176. if (!group) {
  41177. group = this._group = new Group();
  41178. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  41179. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  41180. api.getZr().add(group);
  41181. }
  41182. else {
  41183. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  41184. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  41185. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  41186. }
  41187. updateMandatoryProps(group, axisPointerModel, true);
  41188. this._renderHandle(value);
  41189. },
  41190. /**
  41191. * @implement
  41192. */
  41193. remove: function (api) {
  41194. this.clear(api);
  41195. },
  41196. /**
  41197. * @implement
  41198. */
  41199. dispose: function (api) {
  41200. this.clear(api);
  41201. },
  41202. /**
  41203. * @protected
  41204. */
  41205. determineAnimation: function (axisModel, axisPointerModel) {
  41206. var animation = axisPointerModel.get('animation');
  41207. var axis = axisModel.axis;
  41208. var isCategoryAxis = axis.type === 'category';
  41209. var useSnap = axisPointerModel.get('snap');
  41210. // Value axis without snap always do not snap.
  41211. if (!useSnap && !isCategoryAxis) {
  41212. return false;
  41213. }
  41214. if (animation === 'auto' || animation == null) {
  41215. var animationThreshold = this.animationThreshold;
  41216. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  41217. return true;
  41218. }
  41219. // It is important to auto animation when snap used. Consider if there is
  41220. // a dataZoom, animation will be disabled when too many points exist, while
  41221. // it will be enabled for better visual effect when little points exist.
  41222. if (useSnap) {
  41223. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  41224. var axisExtent = axis.getExtent();
  41225. // Approximate band width
  41226. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  41227. }
  41228. return false;
  41229. }
  41230. return animation === true;
  41231. },
  41232. /**
  41233. * add {pointer, label, graphicKey} to elOption
  41234. * @protected
  41235. */
  41236. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41237. // Shoule be implemenented by sub-class.
  41238. },
  41239. /**
  41240. * @protected
  41241. */
  41242. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  41243. var pointerOption = elOption.pointer;
  41244. if (pointerOption) {
  41245. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  41246. clone$4(elOption.pointer)
  41247. );
  41248. group.add(pointerEl);
  41249. }
  41250. },
  41251. /**
  41252. * @protected
  41253. */
  41254. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  41255. if (elOption.label) {
  41256. var labelEl = inner$9(group).labelEl = new Rect(
  41257. clone$4(elOption.label)
  41258. );
  41259. group.add(labelEl);
  41260. updateLabelShowHide(labelEl, axisPointerModel);
  41261. }
  41262. },
  41263. /**
  41264. * @protected
  41265. */
  41266. updatePointerEl: function (group, elOption, updateProps$$1) {
  41267. var pointerEl = inner$9(group).pointerEl;
  41268. if (pointerEl && elOption.pointer) {
  41269. pointerEl.setStyle(elOption.pointer.style);
  41270. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  41271. }
  41272. },
  41273. /**
  41274. * @protected
  41275. */
  41276. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  41277. var labelEl = inner$9(group).labelEl;
  41278. if (labelEl) {
  41279. labelEl.setStyle(elOption.label.style);
  41280. updateProps$$1(labelEl, {
  41281. // Consider text length change in vertical axis, animation should
  41282. // be used on shape, otherwise the effect will be weird.
  41283. shape: elOption.label.shape,
  41284. position: elOption.label.position
  41285. });
  41286. updateLabelShowHide(labelEl, axisPointerModel);
  41287. }
  41288. },
  41289. /**
  41290. * @private
  41291. */
  41292. _renderHandle: function (value) {
  41293. if (this._dragging || !this.updateHandleTransform) {
  41294. return;
  41295. }
  41296. var axisPointerModel = this._axisPointerModel;
  41297. var zr = this._api.getZr();
  41298. var handle = this._handle;
  41299. var handleModel = axisPointerModel.getModel('handle');
  41300. var status = axisPointerModel.get('status');
  41301. if (!handleModel.get('show') || !status || status === 'hide') {
  41302. handle && zr.remove(handle);
  41303. this._handle = null;
  41304. return;
  41305. }
  41306. var isInit;
  41307. if (!this._handle) {
  41308. isInit = true;
  41309. handle = this._handle = createIcon(
  41310. handleModel.get('icon'),
  41311. {
  41312. cursor: 'move',
  41313. draggable: true,
  41314. onmousemove: function (e) {
  41315. // Fot mobile devicem, prevent screen slider on the button.
  41316. stop(e.event);
  41317. },
  41318. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  41319. drift: bind$1(this._onHandleDragMove, this),
  41320. ondragend: bind$1(this._onHandleDragEnd, this)
  41321. }
  41322. );
  41323. zr.add(handle);
  41324. }
  41325. updateMandatoryProps(handle, axisPointerModel, false);
  41326. // update style
  41327. var includeStyles = [
  41328. 'color', 'borderColor', 'borderWidth', 'opacity',
  41329. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  41330. ];
  41331. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  41332. // update position
  41333. var handleSize = handleModel.get('size');
  41334. if (!isArray(handleSize)) {
  41335. handleSize = [handleSize, handleSize];
  41336. }
  41337. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  41338. createOrUpdate(
  41339. this,
  41340. '_doDispatchAxisPointer',
  41341. handleModel.get('throttle') || 0,
  41342. 'fixRate'
  41343. );
  41344. this._moveHandleToValue(value, isInit);
  41345. },
  41346. /**
  41347. * @private
  41348. */
  41349. _moveHandleToValue: function (value, isInit) {
  41350. updateProps$1(
  41351. this._axisPointerModel,
  41352. !isInit && this._moveAnimation,
  41353. this._handle,
  41354. getHandleTransProps(this.getHandleTransform(
  41355. value, this._axisModel, this._axisPointerModel
  41356. ))
  41357. );
  41358. },
  41359. /**
  41360. * @private
  41361. */
  41362. _onHandleDragMove: function (dx, dy) {
  41363. var handle = this._handle;
  41364. if (!handle) {
  41365. return;
  41366. }
  41367. this._dragging = true;
  41368. // Persistent for throttle.
  41369. var trans = this.updateHandleTransform(
  41370. getHandleTransProps(handle),
  41371. [dx, dy],
  41372. this._axisModel,
  41373. this._axisPointerModel
  41374. );
  41375. this._payloadInfo = trans;
  41376. handle.stopAnimation();
  41377. handle.attr(getHandleTransProps(trans));
  41378. inner$9(handle).lastProp = null;
  41379. this._doDispatchAxisPointer();
  41380. },
  41381. /**
  41382. * Throttled method.
  41383. * @private
  41384. */
  41385. _doDispatchAxisPointer: function () {
  41386. var handle = this._handle;
  41387. if (!handle) {
  41388. return;
  41389. }
  41390. var payloadInfo = this._payloadInfo;
  41391. var axisModel = this._axisModel;
  41392. this._api.dispatchAction({
  41393. type: 'updateAxisPointer',
  41394. x: payloadInfo.cursorPoint[0],
  41395. y: payloadInfo.cursorPoint[1],
  41396. tooltipOption: payloadInfo.tooltipOption,
  41397. axesInfo: [{
  41398. axisDim: axisModel.axis.dim,
  41399. axisIndex: axisModel.componentIndex
  41400. }]
  41401. });
  41402. },
  41403. /**
  41404. * @private
  41405. */
  41406. _onHandleDragEnd: function (moveAnimation) {
  41407. this._dragging = false;
  41408. var handle = this._handle;
  41409. if (!handle) {
  41410. return;
  41411. }
  41412. var value = this._axisPointerModel.get('value');
  41413. // Consider snap or categroy axis, handle may be not consistent with
  41414. // axisPointer. So move handle to align the exact value position when
  41415. // drag ended.
  41416. this._moveHandleToValue(value);
  41417. // For the effect: tooltip will be shown when finger holding on handle
  41418. // button, and will be hidden after finger left handle button.
  41419. this._api.dispatchAction({
  41420. type: 'hideTip'
  41421. });
  41422. },
  41423. /**
  41424. * Should be implemenented by sub-class if support `handle`.
  41425. * @protected
  41426. * @param {number} value
  41427. * @param {module:echarts/model/Model} axisModel
  41428. * @param {module:echarts/model/Model} axisPointerModel
  41429. * @return {Object} {position: [x, y], rotation: 0}
  41430. */
  41431. getHandleTransform: null,
  41432. /**
  41433. * * Should be implemenented by sub-class if support `handle`.
  41434. * @protected
  41435. * @param {Object} transform {position, rotation}
  41436. * @param {Array.<number>} delta [dx, dy]
  41437. * @param {module:echarts/model/Model} axisModel
  41438. * @param {module:echarts/model/Model} axisPointerModel
  41439. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  41440. */
  41441. updateHandleTransform: null,
  41442. /**
  41443. * @private
  41444. */
  41445. clear: function (api) {
  41446. this._lastValue = null;
  41447. this._lastStatus = null;
  41448. var zr = api.getZr();
  41449. var group = this._group;
  41450. var handle = this._handle;
  41451. if (zr && group) {
  41452. this._lastGraphicKey = null;
  41453. group && zr.remove(group);
  41454. handle && zr.remove(handle);
  41455. this._group = null;
  41456. this._handle = null;
  41457. this._payloadInfo = null;
  41458. }
  41459. },
  41460. /**
  41461. * @protected
  41462. */
  41463. doClear: function () {
  41464. // Implemented by sub-class if necessary.
  41465. },
  41466. /**
  41467. * @protected
  41468. * @param {Array.<number>} xy
  41469. * @param {Array.<number>} wh
  41470. * @param {number} [xDimIndex=0] or 1
  41471. */
  41472. buildLabel: function (xy, wh, xDimIndex) {
  41473. xDimIndex = xDimIndex || 0;
  41474. return {
  41475. x: xy[xDimIndex],
  41476. y: xy[1 - xDimIndex],
  41477. width: wh[xDimIndex],
  41478. height: wh[1 - xDimIndex]
  41479. };
  41480. }
  41481. };
  41482. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  41483. function updateProps$1(animationModel, moveAnimation, el, props) {
  41484. // Animation optimize.
  41485. if (!propsEqual(inner$9(el).lastProp, props)) {
  41486. inner$9(el).lastProp = props;
  41487. moveAnimation
  41488. ? updateProps(el, props, animationModel)
  41489. : (el.stopAnimation(), el.attr(props));
  41490. }
  41491. }
  41492. function propsEqual(lastProps, newProps) {
  41493. if (isObject$1(lastProps) && isObject$1(newProps)) {
  41494. var equals = true;
  41495. each$1(newProps, function (item, key) {
  41496. equals = equals && propsEqual(lastProps[key], item);
  41497. });
  41498. return !!equals;
  41499. }
  41500. else {
  41501. return lastProps === newProps;
  41502. }
  41503. }
  41504. function updateLabelShowHide(labelEl, axisPointerModel) {
  41505. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  41506. }
  41507. function getHandleTransProps(trans) {
  41508. return {
  41509. position: trans.position.slice(),
  41510. rotation: trans.rotation || 0
  41511. };
  41512. }
  41513. function updateMandatoryProps(group, axisPointerModel, silent) {
  41514. var z = axisPointerModel.get('z');
  41515. var zlevel = axisPointerModel.get('zlevel');
  41516. group && group.traverse(function (el) {
  41517. if (el.type !== 'group') {
  41518. z != null && (el.z = z);
  41519. zlevel != null && (el.zlevel = zlevel);
  41520. el.silent = silent;
  41521. }
  41522. });
  41523. }
  41524. enableClassExtend(BaseAxisPointer);
  41525. /*
  41526. * Licensed to the Apache Software Foundation (ASF) under one
  41527. * or more contributor license agreements. See the NOTICE file
  41528. * distributed with this work for additional information
  41529. * regarding copyright ownership. The ASF licenses this file
  41530. * to you under the Apache License, Version 2.0 (the
  41531. * "License"); you may not use this file except in compliance
  41532. * with the License. You may obtain a copy of the License at
  41533. *
  41534. * http://www.apache.org/licenses/LICENSE-2.0
  41535. *
  41536. * Unless required by applicable law or agreed to in writing,
  41537. * software distributed under the License is distributed on an
  41538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41539. * KIND, either express or implied. See the License for the
  41540. * specific language governing permissions and limitations
  41541. * under the License.
  41542. */
  41543. /**
  41544. * @param {module:echarts/model/Model} axisPointerModel
  41545. */
  41546. function buildElStyle(axisPointerModel) {
  41547. var axisPointerType = axisPointerModel.get('type');
  41548. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  41549. var style;
  41550. if (axisPointerType === 'line') {
  41551. style = styleModel.getLineStyle();
  41552. style.fill = null;
  41553. }
  41554. else if (axisPointerType === 'shadow') {
  41555. style = styleModel.getAreaStyle();
  41556. style.stroke = null;
  41557. }
  41558. return style;
  41559. }
  41560. /**
  41561. * @param {Function} labelPos {align, verticalAlign, position}
  41562. */
  41563. function buildLabelElOption(
  41564. elOption, axisModel, axisPointerModel, api, labelPos
  41565. ) {
  41566. var value = axisPointerModel.get('value');
  41567. var text = getValueLabel(
  41568. value, axisModel.axis, axisModel.ecModel,
  41569. axisPointerModel.get('seriesDataIndices'),
  41570. {
  41571. precision: axisPointerModel.get('label.precision'),
  41572. formatter: axisPointerModel.get('label.formatter')
  41573. }
  41574. );
  41575. var labelModel = axisPointerModel.getModel('label');
  41576. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  41577. var font = labelModel.getFont();
  41578. var textRect = getBoundingRect(text, font);
  41579. var position = labelPos.position;
  41580. var width = textRect.width + paddings[1] + paddings[3];
  41581. var height = textRect.height + paddings[0] + paddings[2];
  41582. // Adjust by align.
  41583. var align = labelPos.align;
  41584. align === 'right' && (position[0] -= width);
  41585. align === 'center' && (position[0] -= width / 2);
  41586. var verticalAlign = labelPos.verticalAlign;
  41587. verticalAlign === 'bottom' && (position[1] -= height);
  41588. verticalAlign === 'middle' && (position[1] -= height / 2);
  41589. // Not overflow ec container
  41590. confineInContainer(position, width, height, api);
  41591. var bgColor = labelModel.get('backgroundColor');
  41592. if (!bgColor || bgColor === 'auto') {
  41593. bgColor = axisModel.get('axisLine.lineStyle.color');
  41594. }
  41595. elOption.label = {
  41596. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  41597. position: position.slice(),
  41598. // TODO: rich
  41599. style: {
  41600. text: text,
  41601. textFont: font,
  41602. textFill: labelModel.getTextColor(),
  41603. textPosition: 'inside',
  41604. textPadding: paddings,
  41605. fill: bgColor,
  41606. stroke: labelModel.get('borderColor') || 'transparent',
  41607. lineWidth: labelModel.get('borderWidth') || 0,
  41608. shadowBlur: labelModel.get('shadowBlur'),
  41609. shadowColor: labelModel.get('shadowColor'),
  41610. shadowOffsetX: labelModel.get('shadowOffsetX'),
  41611. shadowOffsetY: labelModel.get('shadowOffsetY')
  41612. },
  41613. // Lable should be over axisPointer.
  41614. z2: 10
  41615. };
  41616. }
  41617. // Do not overflow ec container
  41618. function confineInContainer(position, width, height, api) {
  41619. var viewWidth = api.getWidth();
  41620. var viewHeight = api.getHeight();
  41621. position[0] = Math.min(position[0] + width, viewWidth) - width;
  41622. position[1] = Math.min(position[1] + height, viewHeight) - height;
  41623. position[0] = Math.max(position[0], 0);
  41624. position[1] = Math.max(position[1], 0);
  41625. }
  41626. /**
  41627. * @param {number} value
  41628. * @param {module:echarts/coord/Axis} axis
  41629. * @param {module:echarts/model/Global} ecModel
  41630. * @param {Object} opt
  41631. * @param {Array.<Object>} seriesDataIndices
  41632. * @param {number|string} opt.precision 'auto' or a number
  41633. * @param {string|Function} opt.formatter label formatter
  41634. */
  41635. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  41636. value = axis.scale.parse(value);
  41637. var text = axis.scale.getLabel(
  41638. // If `precision` is set, width can be fixed (like '12.00500'), which
  41639. // helps to debounce when when moving label.
  41640. value, {precision: opt.precision}
  41641. );
  41642. var formatter = opt.formatter;
  41643. if (formatter) {
  41644. var params = {
  41645. value: getAxisRawValue(axis, value),
  41646. axisDimension: axis.dim,
  41647. axisIndex: axis.index,
  41648. seriesData: []
  41649. };
  41650. each$1(seriesDataIndices, function (idxItem) {
  41651. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  41652. var dataIndex = idxItem.dataIndexInside;
  41653. var dataParams = series && series.getDataParams(dataIndex);
  41654. dataParams && params.seriesData.push(dataParams);
  41655. });
  41656. if (isString(formatter)) {
  41657. text = formatter.replace('{value}', text);
  41658. }
  41659. else if (isFunction$1(formatter)) {
  41660. text = formatter(params);
  41661. }
  41662. }
  41663. return text;
  41664. }
  41665. /**
  41666. * @param {module:echarts/coord/Axis} axis
  41667. * @param {number} value
  41668. * @param {Object} layoutInfo {
  41669. * rotation, position, labelOffset, labelDirection, labelMargin
  41670. * }
  41671. */
  41672. function getTransformedPosition(axis, value, layoutInfo) {
  41673. var transform = create$1();
  41674. rotate(transform, transform, layoutInfo.rotation);
  41675. translate(transform, transform, layoutInfo.position);
  41676. return applyTransform$1([
  41677. axis.dataToCoord(value),
  41678. (layoutInfo.labelOffset || 0)
  41679. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  41680. ], transform);
  41681. }
  41682. function buildCartesianSingleLabelElOption(
  41683. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  41684. ) {
  41685. var textLayout = AxisBuilder.innerTextLayout(
  41686. layoutInfo.rotation, 0, layoutInfo.labelDirection
  41687. );
  41688. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  41689. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  41690. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  41691. align: textLayout.textAlign,
  41692. verticalAlign: textLayout.textVerticalAlign
  41693. });
  41694. }
  41695. /**
  41696. * @param {Array.<number>} p1
  41697. * @param {Array.<number>} p2
  41698. * @param {number} [xDimIndex=0] or 1
  41699. */
  41700. function makeLineShape(p1, p2, xDimIndex) {
  41701. xDimIndex = xDimIndex || 0;
  41702. return {
  41703. x1: p1[xDimIndex],
  41704. y1: p1[1 - xDimIndex],
  41705. x2: p2[xDimIndex],
  41706. y2: p2[1 - xDimIndex]
  41707. };
  41708. }
  41709. /**
  41710. * @param {Array.<number>} xy
  41711. * @param {Array.<number>} wh
  41712. * @param {number} [xDimIndex=0] or 1
  41713. */
  41714. function makeRectShape(xy, wh, xDimIndex) {
  41715. xDimIndex = xDimIndex || 0;
  41716. return {
  41717. x: xy[xDimIndex],
  41718. y: xy[1 - xDimIndex],
  41719. width: wh[xDimIndex],
  41720. height: wh[1 - xDimIndex]
  41721. };
  41722. }
  41723. /*
  41724. * Licensed to the Apache Software Foundation (ASF) under one
  41725. * or more contributor license agreements. See the NOTICE file
  41726. * distributed with this work for additional information
  41727. * regarding copyright ownership. The ASF licenses this file
  41728. * to you under the Apache License, Version 2.0 (the
  41729. * "License"); you may not use this file except in compliance
  41730. * with the License. You may obtain a copy of the License at
  41731. *
  41732. * http://www.apache.org/licenses/LICENSE-2.0
  41733. *
  41734. * Unless required by applicable law or agreed to in writing,
  41735. * software distributed under the License is distributed on an
  41736. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41737. * KIND, either express or implied. See the License for the
  41738. * specific language governing permissions and limitations
  41739. * under the License.
  41740. */
  41741. var CartesianAxisPointer = BaseAxisPointer.extend({
  41742. /**
  41743. * @override
  41744. */
  41745. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41746. var axis = axisModel.axis;
  41747. var grid = axis.grid;
  41748. var axisPointerType = axisPointerModel.get('type');
  41749. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41750. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  41751. if (axisPointerType && axisPointerType !== 'none') {
  41752. var elStyle = buildElStyle(axisPointerModel);
  41753. var pointerOption = pointerShapeBuilder[axisPointerType](
  41754. axis, pixelValue, otherExtent
  41755. );
  41756. pointerOption.style = elStyle;
  41757. elOption.graphicKey = pointerOption.type;
  41758. elOption.pointer = pointerOption;
  41759. }
  41760. var layoutInfo = layout$1(grid.model, axisModel);
  41761. buildCartesianSingleLabelElOption(
  41762. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  41763. );
  41764. },
  41765. /**
  41766. * @override
  41767. */
  41768. getHandleTransform: function (value, axisModel, axisPointerModel) {
  41769. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  41770. labelInside: false
  41771. });
  41772. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  41773. return {
  41774. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  41775. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  41776. };
  41777. },
  41778. /**
  41779. * @override
  41780. */
  41781. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  41782. var axis = axisModel.axis;
  41783. var grid = axis.grid;
  41784. var axisExtent = axis.getGlobalExtent(true);
  41785. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  41786. var dimIndex = axis.dim === 'x' ? 0 : 1;
  41787. var currPosition = transform.position;
  41788. currPosition[dimIndex] += delta[dimIndex];
  41789. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  41790. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  41791. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  41792. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  41793. cursorPoint[dimIndex] = currPosition[dimIndex];
  41794. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  41795. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  41796. return {
  41797. position: currPosition,
  41798. rotation: transform.rotation,
  41799. cursorPoint: cursorPoint,
  41800. tooltipOption: tooltipOptions[dimIndex]
  41801. };
  41802. }
  41803. });
  41804. function getCartesian(grid, axis) {
  41805. var opt = {};
  41806. opt[axis.dim + 'AxisIndex'] = axis.index;
  41807. return grid.getCartesian(opt);
  41808. }
  41809. var pointerShapeBuilder = {
  41810. line: function (axis, pixelValue, otherExtent) {
  41811. var targetShape = makeLineShape(
  41812. [pixelValue, otherExtent[0]],
  41813. [pixelValue, otherExtent[1]],
  41814. getAxisDimIndex(axis)
  41815. );
  41816. return {
  41817. type: 'Line',
  41818. subPixelOptimize: true,
  41819. shape: targetShape
  41820. };
  41821. },
  41822. shadow: function (axis, pixelValue, otherExtent) {
  41823. var bandWidth = Math.max(1, axis.getBandWidth());
  41824. var span = otherExtent[1] - otherExtent[0];
  41825. return {
  41826. type: 'Rect',
  41827. shape: makeRectShape(
  41828. [pixelValue - bandWidth / 2, otherExtent[0]],
  41829. [bandWidth, span],
  41830. getAxisDimIndex(axis)
  41831. )
  41832. };
  41833. }
  41834. };
  41835. function getAxisDimIndex(axis) {
  41836. return axis.dim === 'x' ? 0 : 1;
  41837. }
  41838. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  41839. /*
  41840. * Licensed to the Apache Software Foundation (ASF) under one
  41841. * or more contributor license agreements. See the NOTICE file
  41842. * distributed with this work for additional information
  41843. * regarding copyright ownership. The ASF licenses this file
  41844. * to you under the Apache License, Version 2.0 (the
  41845. * "License"); you may not use this file except in compliance
  41846. * with the License. You may obtain a copy of the License at
  41847. *
  41848. * http://www.apache.org/licenses/LICENSE-2.0
  41849. *
  41850. * Unless required by applicable law or agreed to in writing,
  41851. * software distributed under the License is distributed on an
  41852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41853. * KIND, either express or implied. See the License for the
  41854. * specific language governing permissions and limitations
  41855. * under the License.
  41856. */
  41857. // CartesianAxisPointer is not supposed to be required here. But consider
  41858. // echarts.simple.js and online build tooltip, which only require gridSimple,
  41859. // CartesianAxisPointer should be able to required somewhere.
  41860. registerPreprocessor(function (option) {
  41861. // Always has a global axisPointerModel for default setting.
  41862. if (option) {
  41863. (!option.axisPointer || option.axisPointer.length === 0)
  41864. && (option.axisPointer = {});
  41865. var link = option.axisPointer.link;
  41866. // Normalize to array to avoid object mergin. But if link
  41867. // is not set, remain null/undefined, otherwise it will
  41868. // override existent link setting.
  41869. if (link && !isArray(link)) {
  41870. option.axisPointer.link = [link];
  41871. }
  41872. }
  41873. });
  41874. // This process should proformed after coordinate systems created
  41875. // and series data processed. So put it on statistic processing stage.
  41876. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  41877. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  41878. // allAxesInfo should be updated when setOption performed.
  41879. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  41880. collect(ecModel, api);
  41881. });
  41882. // Broadcast to all views.
  41883. registerAction({
  41884. type: 'updateAxisPointer',
  41885. event: 'updateAxisPointer',
  41886. update: ':updateAxisPointer'
  41887. }, axisTrigger);
  41888. /*
  41889. * Licensed to the Apache Software Foundation (ASF) under one
  41890. * or more contributor license agreements. See the NOTICE file
  41891. * distributed with this work for additional information
  41892. * regarding copyright ownership. The ASF licenses this file
  41893. * to you under the Apache License, Version 2.0 (the
  41894. * "License"); you may not use this file except in compliance
  41895. * with the License. You may obtain a copy of the License at
  41896. *
  41897. * http://www.apache.org/licenses/LICENSE-2.0
  41898. *
  41899. * Unless required by applicable law or agreed to in writing,
  41900. * software distributed under the License is distributed on an
  41901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41902. * KIND, either express or implied. See the License for the
  41903. * specific language governing permissions and limitations
  41904. * under the License.
  41905. */
  41906. extendComponentModel({
  41907. type: 'tooltip',
  41908. dependencies: ['axisPointer'],
  41909. defaultOption: {
  41910. zlevel: 0,
  41911. z: 60,
  41912. show: true,
  41913. // tooltip主体内容
  41914. showContent: true,
  41915. // 'trigger' only works on coordinate system.
  41916. // 'item' | 'axis' | 'none'
  41917. trigger: 'item',
  41918. // 'click' | 'mousemove' | 'none'
  41919. triggerOn: 'mousemove|click',
  41920. alwaysShowContent: false,
  41921. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  41922. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  41923. // 'auto': use html by default, and use non-html if `document` is not defined
  41924. // 'html': use html for tooltip
  41925. // 'richText': use canvas, svg, and etc. for tooltip
  41926. // 位置 {Array} | {Function}
  41927. // position: null
  41928. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  41929. // align: null,
  41930. // verticalAlign: null,
  41931. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  41932. confine: false,
  41933. // 内容格式器:{string}(Template) ¦ {Function}
  41934. // formatter: null
  41935. showDelay: 0,
  41936. // 隐藏延迟,单位ms
  41937. hideDelay: 100,
  41938. // 动画变换时间,单位s
  41939. transitionDuration: 0.4,
  41940. enterable: false,
  41941. // 提示背景颜色,默认为透明度为0.7的黑色
  41942. backgroundColor: 'rgba(50,50,50,0.7)',
  41943. // 提示边框颜色
  41944. borderColor: '#333',
  41945. // 提示边框圆角,单位px,默认为4
  41946. borderRadius: 4,
  41947. // 提示边框线宽,单位px,默认为0(无边框)
  41948. borderWidth: 0,
  41949. // 提示内边距,单位px,默认各方向内边距为5,
  41950. // 接受数组分别设定上右下左边距,同css
  41951. padding: 5,
  41952. // Extra css text
  41953. extraCssText: '',
  41954. // 坐标轴指示器,坐标轴触发有效
  41955. axisPointer: {
  41956. // 默认为直线
  41957. // 可选为:'line' | 'shadow' | 'cross'
  41958. type: 'line',
  41959. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  41960. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  41961. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  41962. // 极坐标系会默认选择 angle 轴
  41963. axis: 'auto',
  41964. animation: 'auto',
  41965. animationDurationUpdate: 200,
  41966. animationEasingUpdate: 'exponentialOut',
  41967. crossStyle: {
  41968. color: '#999',
  41969. width: 1,
  41970. type: 'dashed',
  41971. // TODO formatter
  41972. textStyle: {}
  41973. }
  41974. // lineStyle and shadowStyle should not be specified here,
  41975. // otherwise it will always override those styles on option.axisPointer.
  41976. },
  41977. textStyle: {
  41978. color: '#fff',
  41979. fontSize: 14
  41980. }
  41981. }
  41982. });
  41983. /*
  41984. * Licensed to the Apache Software Foundation (ASF) under one
  41985. * or more contributor license agreements. See the NOTICE file
  41986. * distributed with this work for additional information
  41987. * regarding copyright ownership. The ASF licenses this file
  41988. * to you under the Apache License, Version 2.0 (the
  41989. * "License"); you may not use this file except in compliance
  41990. * with the License. You may obtain a copy of the License at
  41991. *
  41992. * http://www.apache.org/licenses/LICENSE-2.0
  41993. *
  41994. * Unless required by applicable law or agreed to in writing,
  41995. * software distributed under the License is distributed on an
  41996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41997. * KIND, either express or implied. See the License for the
  41998. * specific language governing permissions and limitations
  41999. * under the License.
  42000. */
  42001. var each$10 = each$1;
  42002. var toCamelCase$1 = toCamelCase;
  42003. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  42004. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  42005. /**
  42006. * @param {number} duration
  42007. * @return {string}
  42008. * @inner
  42009. */
  42010. function assembleTransition(duration) {
  42011. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  42012. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  42013. + 'top ' + duration + 's ' + transitionCurve;
  42014. return map(vendors, function (vendorPrefix) {
  42015. return vendorPrefix + 'transition:' + transitionText;
  42016. }).join(';');
  42017. }
  42018. /**
  42019. * @param {Object} textStyle
  42020. * @return {string}
  42021. * @inner
  42022. */
  42023. function assembleFont(textStyleModel) {
  42024. var cssText = [];
  42025. var fontSize = textStyleModel.get('fontSize');
  42026. var color = textStyleModel.getTextColor();
  42027. color && cssText.push('color:' + color);
  42028. cssText.push('font:' + textStyleModel.getFont());
  42029. fontSize
  42030. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  42031. each$10(['decoration', 'align'], function (name) {
  42032. var val = textStyleModel.get(name);
  42033. val && cssText.push('text-' + name + ':' + val);
  42034. });
  42035. return cssText.join(';');
  42036. }
  42037. /**
  42038. * @param {Object} tooltipModel
  42039. * @return {string}
  42040. * @inner
  42041. */
  42042. function assembleCssText(tooltipModel) {
  42043. var cssText = [];
  42044. var transitionDuration = tooltipModel.get('transitionDuration');
  42045. var backgroundColor = tooltipModel.get('backgroundColor');
  42046. var textStyleModel = tooltipModel.getModel('textStyle');
  42047. var padding = tooltipModel.get('padding');
  42048. // Animation transition. Do not animate when transitionDuration is 0.
  42049. transitionDuration
  42050. && cssText.push(assembleTransition(transitionDuration));
  42051. if (backgroundColor) {
  42052. if (env$1.canvasSupported) {
  42053. cssText.push('background-Color:' + backgroundColor);
  42054. }
  42055. else {
  42056. // for ie
  42057. cssText.push(
  42058. 'background-Color:#' + toHex(backgroundColor)
  42059. );
  42060. cssText.push('filter:alpha(opacity=70)');
  42061. }
  42062. }
  42063. // Border style
  42064. each$10(['width', 'color', 'radius'], function (name) {
  42065. var borderName = 'border-' + name;
  42066. var camelCase = toCamelCase$1(borderName);
  42067. var val = tooltipModel.get(camelCase);
  42068. val != null
  42069. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  42070. });
  42071. // Text style
  42072. cssText.push(assembleFont(textStyleModel));
  42073. // Padding
  42074. if (padding != null) {
  42075. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  42076. }
  42077. return cssText.join(';') + ';';
  42078. }
  42079. /**
  42080. * @alias module:echarts/component/tooltip/TooltipContent
  42081. * @constructor
  42082. */
  42083. function TooltipContent(container, api) {
  42084. if (env$1.wxa) {
  42085. return null;
  42086. }
  42087. var el = document.createElement('div');
  42088. var zr = this._zr = api.getZr();
  42089. this.el = el;
  42090. this._x = api.getWidth() / 2;
  42091. this._y = api.getHeight() / 2;
  42092. container.appendChild(el);
  42093. this._container = container;
  42094. this._show = false;
  42095. /**
  42096. * @private
  42097. */
  42098. this._hideTimeout;
  42099. // FIXME
  42100. // Is it needed to trigger zr event manually if
  42101. // the browser do not support `pointer-events: none`.
  42102. var self = this;
  42103. el.onmouseenter = function () {
  42104. // clear the timeout in hideLater and keep showing tooltip
  42105. if (self._enterable) {
  42106. clearTimeout(self._hideTimeout);
  42107. self._show = true;
  42108. }
  42109. self._inContent = true;
  42110. };
  42111. el.onmousemove = function (e) {
  42112. e = e || window.event;
  42113. if (!self._enterable) {
  42114. // `pointer-events: none` is set to tooltip content div
  42115. // if `enterable` is set as `false`, and `el.onmousemove`
  42116. // can not be triggered. But in browser that do not
  42117. // support `pointer-events`, we need to do this:
  42118. // Try trigger zrender event to avoid mouse
  42119. // in and out shape too frequently
  42120. var handler = zr.handler;
  42121. normalizeEvent(container, e, true);
  42122. handler.dispatch('mousemove', e);
  42123. }
  42124. };
  42125. el.onmouseleave = function () {
  42126. if (self._enterable) {
  42127. if (self._show) {
  42128. self.hideLater(self._hideDelay);
  42129. }
  42130. }
  42131. self._inContent = false;
  42132. };
  42133. }
  42134. TooltipContent.prototype = {
  42135. constructor: TooltipContent,
  42136. /**
  42137. * @private
  42138. * @type {boolean}
  42139. */
  42140. _enterable: true,
  42141. /**
  42142. * Update when tooltip is rendered
  42143. */
  42144. update: function () {
  42145. // FIXME
  42146. // Move this logic to ec main?
  42147. var container = this._container;
  42148. var stl = container.currentStyle
  42149. || document.defaultView.getComputedStyle(container);
  42150. var domStyle = container.style;
  42151. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  42152. domStyle.position = 'relative';
  42153. }
  42154. // Hide the tooltip
  42155. // PENDING
  42156. // this.hide();
  42157. },
  42158. show: function (tooltipModel) {
  42159. clearTimeout(this._hideTimeout);
  42160. var el = this.el;
  42161. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  42162. // Because of the reason described in:
  42163. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  42164. // we should set initial value to `left` and `top`.
  42165. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  42166. + (tooltipModel.get('extraCssText') || '');
  42167. el.style.display = el.innerHTML ? 'block' : 'none';
  42168. // If mouse occsionally move over the tooltip, a mouseout event will be
  42169. // triggered by canvas, and cuase some unexpectable result like dragging
  42170. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  42171. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  42172. // scenario.
  42173. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  42174. this._show = true;
  42175. },
  42176. setContent: function (content) {
  42177. this.el.innerHTML = content == null ? '' : content;
  42178. },
  42179. setEnterable: function (enterable) {
  42180. this._enterable = enterable;
  42181. },
  42182. getSize: function () {
  42183. var el = this.el;
  42184. return [el.clientWidth, el.clientHeight];
  42185. },
  42186. moveTo: function (x, y) {
  42187. // xy should be based on canvas root. But tooltipContent is
  42188. // the sibling of canvas root. So padding of ec container
  42189. // should be considered here.
  42190. var zr = this._zr;
  42191. var viewportRootOffset;
  42192. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  42193. x += viewportRootOffset.offsetLeft;
  42194. y += viewportRootOffset.offsetTop;
  42195. }
  42196. var style = this.el.style;
  42197. style.left = x + 'px';
  42198. style.top = y + 'px';
  42199. this._x = x;
  42200. this._y = y;
  42201. },
  42202. hide: function () {
  42203. this.el.style.display = 'none';
  42204. this._show = false;
  42205. },
  42206. hideLater: function (time) {
  42207. if (this._show && !(this._inContent && this._enterable)) {
  42208. if (time) {
  42209. this._hideDelay = time;
  42210. // Set show false to avoid invoke hideLater mutiple times
  42211. this._show = false;
  42212. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42213. }
  42214. else {
  42215. this.hide();
  42216. }
  42217. }
  42218. },
  42219. isShow: function () {
  42220. return this._show;
  42221. },
  42222. getOuterSize: function () {
  42223. var width = this.el.clientWidth;
  42224. var height = this.el.clientHeight;
  42225. // Consider browser compatibility.
  42226. // IE8 does not support getComputedStyle.
  42227. if (document.defaultView && document.defaultView.getComputedStyle) {
  42228. var stl = document.defaultView.getComputedStyle(this.el);
  42229. if (stl) {
  42230. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  42231. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  42232. }
  42233. }
  42234. return {width: width, height: height};
  42235. }
  42236. };
  42237. /*
  42238. * Licensed to the Apache Software Foundation (ASF) under one
  42239. * or more contributor license agreements. See the NOTICE file
  42240. * distributed with this work for additional information
  42241. * regarding copyright ownership. The ASF licenses this file
  42242. * to you under the Apache License, Version 2.0 (the
  42243. * "License"); you may not use this file except in compliance
  42244. * with the License. You may obtain a copy of the License at
  42245. *
  42246. * http://www.apache.org/licenses/LICENSE-2.0
  42247. *
  42248. * Unless required by applicable law or agreed to in writing,
  42249. * software distributed under the License is distributed on an
  42250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42251. * KIND, either express or implied. See the License for the
  42252. * specific language governing permissions and limitations
  42253. * under the License.
  42254. */
  42255. // import Group from 'zrender/src/container/Group';
  42256. /**
  42257. * @alias module:echarts/component/tooltip/TooltipRichContent
  42258. * @constructor
  42259. */
  42260. function TooltipRichContent(api) {
  42261. this._zr = api.getZr();
  42262. this._show = false;
  42263. /**
  42264. * @private
  42265. */
  42266. this._hideTimeout;
  42267. }
  42268. TooltipRichContent.prototype = {
  42269. constructor: TooltipRichContent,
  42270. /**
  42271. * @private
  42272. * @type {boolean}
  42273. */
  42274. _enterable: true,
  42275. /**
  42276. * Update when tooltip is rendered
  42277. */
  42278. update: function () {
  42279. // noop
  42280. },
  42281. show: function (tooltipModel) {
  42282. if (this._hideTimeout) {
  42283. clearTimeout(this._hideTimeout);
  42284. }
  42285. this.el.attr('show', true);
  42286. this._show = true;
  42287. },
  42288. /**
  42289. * Set tooltip content
  42290. *
  42291. * @param {string} content rich text string of content
  42292. * @param {Object} markerRich rich text style
  42293. * @param {Object} tooltipModel tooltip model
  42294. */
  42295. setContent: function (content, markerRich, tooltipModel) {
  42296. if (this.el) {
  42297. this._zr.remove(this.el);
  42298. }
  42299. var markers = {};
  42300. var text = content;
  42301. var prefix = '{marker';
  42302. var suffix = '|}';
  42303. var startId = text.indexOf(prefix);
  42304. while (startId >= 0) {
  42305. var endId = text.indexOf(suffix);
  42306. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  42307. if (name.indexOf('sub') > -1) {
  42308. markers['marker' + name] = {
  42309. textWidth: 4,
  42310. textHeight: 4,
  42311. textBorderRadius: 2,
  42312. textBackgroundColor: markerRich[name],
  42313. // TODO: textOffset is not implemented for rich text
  42314. textOffset: [3, 0]
  42315. };
  42316. }
  42317. else {
  42318. markers['marker' + name] = {
  42319. textWidth: 10,
  42320. textHeight: 10,
  42321. textBorderRadius: 5,
  42322. textBackgroundColor: markerRich[name]
  42323. };
  42324. }
  42325. text = text.substr(endId + 1);
  42326. startId = text.indexOf('{marker');
  42327. }
  42328. this.el = new Text({
  42329. style: {
  42330. rich: markers,
  42331. text: content,
  42332. textLineHeight: 20,
  42333. textBackgroundColor: tooltipModel.get('backgroundColor'),
  42334. textBorderRadius: tooltipModel.get('borderRadius'),
  42335. textFill: tooltipModel.get('textStyle.color'),
  42336. textPadding: tooltipModel.get('padding')
  42337. },
  42338. z: tooltipModel.get('z')
  42339. });
  42340. this._zr.add(this.el);
  42341. var self = this;
  42342. this.el.on('mouseover', function () {
  42343. // clear the timeout in hideLater and keep showing tooltip
  42344. if (self._enterable) {
  42345. clearTimeout(self._hideTimeout);
  42346. self._show = true;
  42347. }
  42348. self._inContent = true;
  42349. });
  42350. this.el.on('mouseout', function () {
  42351. if (self._enterable) {
  42352. if (self._show) {
  42353. self.hideLater(self._hideDelay);
  42354. }
  42355. }
  42356. self._inContent = false;
  42357. });
  42358. },
  42359. setEnterable: function (enterable) {
  42360. this._enterable = enterable;
  42361. },
  42362. getSize: function () {
  42363. var bounding = this.el.getBoundingRect();
  42364. return [bounding.width, bounding.height];
  42365. },
  42366. moveTo: function (x, y) {
  42367. if (this.el) {
  42368. this.el.attr('position', [x, y]);
  42369. }
  42370. },
  42371. hide: function () {
  42372. if (this.el) {
  42373. this.el.hide();
  42374. }
  42375. this._show = false;
  42376. },
  42377. hideLater: function (time) {
  42378. if (this._show && !(this._inContent && this._enterable)) {
  42379. if (time) {
  42380. this._hideDelay = time;
  42381. // Set show false to avoid invoke hideLater mutiple times
  42382. this._show = false;
  42383. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42384. }
  42385. else {
  42386. this.hide();
  42387. }
  42388. }
  42389. },
  42390. isShow: function () {
  42391. return this._show;
  42392. },
  42393. getOuterSize: function () {
  42394. var size = this.getSize();
  42395. return {
  42396. width: size[0],
  42397. height: size[1]
  42398. };
  42399. }
  42400. };
  42401. /*
  42402. * Licensed to the Apache Software Foundation (ASF) under one
  42403. * or more contributor license agreements. See the NOTICE file
  42404. * distributed with this work for additional information
  42405. * regarding copyright ownership. The ASF licenses this file
  42406. * to you under the Apache License, Version 2.0 (the
  42407. * "License"); you may not use this file except in compliance
  42408. * with the License. You may obtain a copy of the License at
  42409. *
  42410. * http://www.apache.org/licenses/LICENSE-2.0
  42411. *
  42412. * Unless required by applicable law or agreed to in writing,
  42413. * software distributed under the License is distributed on an
  42414. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42415. * KIND, either express or implied. See the License for the
  42416. * specific language governing permissions and limitations
  42417. * under the License.
  42418. */
  42419. var bind$2 = bind;
  42420. var each$9 = each$1;
  42421. var parsePercent$2 = parsePercent$1;
  42422. var proxyRect = new Rect({
  42423. shape: {x: -1, y: -1, width: 2, height: 2}
  42424. });
  42425. extendComponentView({
  42426. type: 'tooltip',
  42427. init: function (ecModel, api) {
  42428. if (env$1.node) {
  42429. return;
  42430. }
  42431. var tooltipModel = ecModel.getComponent('tooltip');
  42432. var renderMode = tooltipModel.get('renderMode');
  42433. this._renderMode = getTooltipRenderMode(renderMode);
  42434. var tooltipContent;
  42435. if (this._renderMode === 'html') {
  42436. tooltipContent = new TooltipContent(api.getDom(), api);
  42437. this._newLine = '<br/>';
  42438. }
  42439. else {
  42440. tooltipContent = new TooltipRichContent(api);
  42441. this._newLine = '\n';
  42442. }
  42443. this._tooltipContent = tooltipContent;
  42444. },
  42445. render: function (tooltipModel, ecModel, api) {
  42446. if (env$1.node) {
  42447. return;
  42448. }
  42449. // Reset
  42450. this.group.removeAll();
  42451. /**
  42452. * @private
  42453. * @type {module:echarts/component/tooltip/TooltipModel}
  42454. */
  42455. this._tooltipModel = tooltipModel;
  42456. /**
  42457. * @private
  42458. * @type {module:echarts/model/Global}
  42459. */
  42460. this._ecModel = ecModel;
  42461. /**
  42462. * @private
  42463. * @type {module:echarts/ExtensionAPI}
  42464. */
  42465. this._api = api;
  42466. /**
  42467. * Should be cleaned when render.
  42468. * @private
  42469. * @type {Array.<Array.<Object>>}
  42470. */
  42471. this._lastDataByCoordSys = null;
  42472. /**
  42473. * @private
  42474. * @type {boolean}
  42475. */
  42476. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42477. var tooltipContent = this._tooltipContent;
  42478. tooltipContent.update();
  42479. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  42480. this._initGlobalListener();
  42481. this._keepShow();
  42482. },
  42483. _initGlobalListener: function () {
  42484. var tooltipModel = this._tooltipModel;
  42485. var triggerOn = tooltipModel.get('triggerOn');
  42486. register(
  42487. 'itemTooltip',
  42488. this._api,
  42489. bind$2(function (currTrigger, e, dispatchAction) {
  42490. // If 'none', it is not controlled by mouse totally.
  42491. if (triggerOn !== 'none') {
  42492. if (triggerOn.indexOf(currTrigger) >= 0) {
  42493. this._tryShow(e, dispatchAction);
  42494. }
  42495. else if (currTrigger === 'leave') {
  42496. this._hide(dispatchAction);
  42497. }
  42498. }
  42499. }, this)
  42500. );
  42501. },
  42502. _keepShow: function () {
  42503. var tooltipModel = this._tooltipModel;
  42504. var ecModel = this._ecModel;
  42505. var api = this._api;
  42506. // Try to keep the tooltip show when refreshing
  42507. if (this._lastX != null
  42508. && this._lastY != null
  42509. // When user is willing to control tooltip totally using API,
  42510. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  42511. // which is not expected.
  42512. && tooltipModel.get('triggerOn') !== 'none'
  42513. ) {
  42514. var self = this;
  42515. clearTimeout(this._refreshUpdateTimeout);
  42516. this._refreshUpdateTimeout = setTimeout(function () {
  42517. // Show tip next tick after other charts are rendered
  42518. // In case highlight action has wrong result
  42519. // FIXME
  42520. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  42521. x: self._lastX,
  42522. y: self._lastY
  42523. });
  42524. });
  42525. }
  42526. },
  42527. /**
  42528. * Show tip manually by
  42529. * dispatchAction({
  42530. * type: 'showTip',
  42531. * x: 10,
  42532. * y: 10
  42533. * });
  42534. * Or
  42535. * dispatchAction({
  42536. * type: 'showTip',
  42537. * seriesIndex: 0,
  42538. * dataIndex or dataIndexInside or name
  42539. * });
  42540. *
  42541. * TODO Batch
  42542. */
  42543. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  42544. if (payload.from === this.uid || env$1.node) {
  42545. return;
  42546. }
  42547. var dispatchAction = makeDispatchAction$1(payload, api);
  42548. // Reset ticket
  42549. this._ticket = '';
  42550. // When triggered from axisPointer.
  42551. var dataByCoordSys = payload.dataByCoordSys;
  42552. if (payload.tooltip && payload.x != null && payload.y != null) {
  42553. var el = proxyRect;
  42554. el.position = [payload.x, payload.y];
  42555. el.update();
  42556. el.tooltip = payload.tooltip;
  42557. // Manually show tooltip while view is not using zrender elements.
  42558. this._tryShow({
  42559. offsetX: payload.x,
  42560. offsetY: payload.y,
  42561. target: el
  42562. }, dispatchAction);
  42563. }
  42564. else if (dataByCoordSys) {
  42565. this._tryShow({
  42566. offsetX: payload.x,
  42567. offsetY: payload.y,
  42568. position: payload.position,
  42569. event: {},
  42570. dataByCoordSys: payload.dataByCoordSys,
  42571. tooltipOption: payload.tooltipOption
  42572. }, dispatchAction);
  42573. }
  42574. else if (payload.seriesIndex != null) {
  42575. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  42576. return;
  42577. }
  42578. var pointInfo = findPointFromSeries(payload, ecModel);
  42579. var cx = pointInfo.point[0];
  42580. var cy = pointInfo.point[1];
  42581. if (cx != null && cy != null) {
  42582. this._tryShow({
  42583. offsetX: cx,
  42584. offsetY: cy,
  42585. position: payload.position,
  42586. target: pointInfo.el,
  42587. event: {}
  42588. }, dispatchAction);
  42589. }
  42590. }
  42591. else if (payload.x != null && payload.y != null) {
  42592. // FIXME
  42593. // should wrap dispatchAction like `axisPointer/globalListener` ?
  42594. api.dispatchAction({
  42595. type: 'updateAxisPointer',
  42596. x: payload.x,
  42597. y: payload.y
  42598. });
  42599. this._tryShow({
  42600. offsetX: payload.x,
  42601. offsetY: payload.y,
  42602. position: payload.position,
  42603. target: api.getZr().findHover(payload.x, payload.y).target,
  42604. event: {}
  42605. }, dispatchAction);
  42606. }
  42607. },
  42608. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  42609. var tooltipContent = this._tooltipContent;
  42610. if (!this._alwaysShowContent && this._tooltipModel) {
  42611. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  42612. }
  42613. this._lastX = this._lastY = null;
  42614. if (payload.from !== this.uid) {
  42615. this._hide(makeDispatchAction$1(payload, api));
  42616. }
  42617. },
  42618. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  42619. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  42620. // and tooltip.
  42621. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  42622. var seriesIndex = payload.seriesIndex;
  42623. var dataIndex = payload.dataIndex;
  42624. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  42625. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  42626. return;
  42627. }
  42628. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  42629. if (!seriesModel) {
  42630. return;
  42631. }
  42632. var data = seriesModel.getData();
  42633. var tooltipModel = buildTooltipModel([
  42634. data.getItemModel(dataIndex),
  42635. seriesModel,
  42636. (seriesModel.coordinateSystem || {}).model,
  42637. tooltipModel
  42638. ]);
  42639. if (tooltipModel.get('trigger') !== 'axis') {
  42640. return;
  42641. }
  42642. api.dispatchAction({
  42643. type: 'updateAxisPointer',
  42644. seriesIndex: seriesIndex,
  42645. dataIndex: dataIndex,
  42646. position: payload.position
  42647. });
  42648. return true;
  42649. },
  42650. _tryShow: function (e, dispatchAction) {
  42651. var el = e.target;
  42652. var tooltipModel = this._tooltipModel;
  42653. if (!tooltipModel) {
  42654. return;
  42655. }
  42656. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  42657. this._lastX = e.offsetX;
  42658. this._lastY = e.offsetY;
  42659. var dataByCoordSys = e.dataByCoordSys;
  42660. if (dataByCoordSys && dataByCoordSys.length) {
  42661. this._showAxisTooltip(dataByCoordSys, e);
  42662. }
  42663. // Always show item tooltip if mouse is on the element with dataIndex
  42664. else if (el && el.dataIndex != null) {
  42665. this._lastDataByCoordSys = null;
  42666. this._showSeriesItemTooltip(e, el, dispatchAction);
  42667. }
  42668. // Tooltip provided directly. Like legend.
  42669. else if (el && el.tooltip) {
  42670. this._lastDataByCoordSys = null;
  42671. this._showComponentItemTooltip(e, el, dispatchAction);
  42672. }
  42673. else {
  42674. this._lastDataByCoordSys = null;
  42675. this._hide(dispatchAction);
  42676. }
  42677. },
  42678. _showOrMove: function (tooltipModel, cb) {
  42679. // showDelay is used in this case: tooltip.enterable is set
  42680. // as true. User intent to move mouse into tooltip and click
  42681. // something. `showDelay` makes it easyer to enter the content
  42682. // but tooltip do not move immediately.
  42683. var delay = tooltipModel.get('showDelay');
  42684. cb = bind(cb, this);
  42685. clearTimeout(this._showTimout);
  42686. delay > 0
  42687. ? (this._showTimout = setTimeout(cb, delay))
  42688. : cb();
  42689. },
  42690. _showAxisTooltip: function (dataByCoordSys, e) {
  42691. var ecModel = this._ecModel;
  42692. var globalTooltipModel = this._tooltipModel;
  42693. var point = [e.offsetX, e.offsetY];
  42694. var singleDefaultHTML = [];
  42695. var singleParamsList = [];
  42696. var singleTooltipModel = buildTooltipModel([
  42697. e.tooltipOption,
  42698. globalTooltipModel
  42699. ]);
  42700. var renderMode = this._renderMode;
  42701. var newLine = this._newLine;
  42702. var markers = {};
  42703. each$9(dataByCoordSys, function (itemCoordSys) {
  42704. // var coordParamList = [];
  42705. // var coordDefaultHTML = [];
  42706. // var coordTooltipModel = buildTooltipModel([
  42707. // e.tooltipOption,
  42708. // itemCoordSys.tooltipOption,
  42709. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  42710. // globalTooltipModel
  42711. // ]);
  42712. // var displayMode = coordTooltipModel.get('displayMode');
  42713. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  42714. each$9(itemCoordSys.dataByAxis, function (item) {
  42715. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  42716. var axisValue = item.value;
  42717. var seriesDefaultHTML = [];
  42718. if (!axisModel || axisValue == null) {
  42719. return;
  42720. }
  42721. var valueLabel = getValueLabel(
  42722. axisValue, axisModel.axis, ecModel,
  42723. item.seriesDataIndices,
  42724. item.valueLabelOpt
  42725. );
  42726. each$1(item.seriesDataIndices, function (idxItem) {
  42727. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  42728. var dataIndex = idxItem.dataIndexInside;
  42729. var dataParams = series && series.getDataParams(dataIndex);
  42730. dataParams.axisDim = item.axisDim;
  42731. dataParams.axisIndex = item.axisIndex;
  42732. dataParams.axisType = item.axisType;
  42733. dataParams.axisId = item.axisId;
  42734. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  42735. dataParams.axisValueLabel = valueLabel;
  42736. if (dataParams) {
  42737. singleParamsList.push(dataParams);
  42738. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  42739. var html;
  42740. if (isObject$1(seriesTooltip)) {
  42741. html = seriesTooltip.html;
  42742. var newMarkers = seriesTooltip.markers;
  42743. merge(markers, newMarkers);
  42744. }
  42745. else {
  42746. html = seriesTooltip;
  42747. }
  42748. seriesDefaultHTML.push(html);
  42749. }
  42750. });
  42751. // Default tooltip content
  42752. // FIXME
  42753. // (1) shold be the first data which has name?
  42754. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  42755. var firstLine = valueLabel;
  42756. if (renderMode !== 'html') {
  42757. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  42758. }
  42759. else {
  42760. singleDefaultHTML.push(
  42761. (firstLine ? encodeHTML(firstLine) + newLine : '')
  42762. + seriesDefaultHTML.join(newLine)
  42763. );
  42764. }
  42765. });
  42766. }, this);
  42767. // In most case, the second axis is shown upper than the first one.
  42768. singleDefaultHTML.reverse();
  42769. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  42770. var positionExpr = e.position;
  42771. this._showOrMove(singleTooltipModel, function () {
  42772. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  42773. this._updatePosition(
  42774. singleTooltipModel,
  42775. positionExpr,
  42776. point[0], point[1],
  42777. this._tooltipContent,
  42778. singleParamsList
  42779. );
  42780. }
  42781. else {
  42782. this._showTooltipContent(
  42783. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  42784. point[0], point[1], positionExpr, undefined, markers
  42785. );
  42786. }
  42787. });
  42788. // Do not trigger events here, because this branch only be entered
  42789. // from dispatchAction.
  42790. },
  42791. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  42792. var ecModel = this._ecModel;
  42793. // Use dataModel in element if possible
  42794. // Used when mouseover on a element like markPoint or edge
  42795. // In which case, the data is not main data in series.
  42796. var seriesIndex = el.seriesIndex;
  42797. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  42798. // For example, graph link.
  42799. var dataModel = el.dataModel || seriesModel;
  42800. var dataIndex = el.dataIndex;
  42801. var dataType = el.dataType;
  42802. var data = dataModel.getData();
  42803. var tooltipModel = buildTooltipModel([
  42804. data.getItemModel(dataIndex),
  42805. dataModel,
  42806. seriesModel && (seriesModel.coordinateSystem || {}).model,
  42807. this._tooltipModel
  42808. ]);
  42809. var tooltipTrigger = tooltipModel.get('trigger');
  42810. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  42811. return;
  42812. }
  42813. var params = dataModel.getDataParams(dataIndex, dataType);
  42814. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  42815. var defaultHtml;
  42816. var markers;
  42817. if (isObject$1(seriesTooltip)) {
  42818. defaultHtml = seriesTooltip.html;
  42819. markers = seriesTooltip.markers;
  42820. }
  42821. else {
  42822. defaultHtml = seriesTooltip;
  42823. markers = null;
  42824. }
  42825. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  42826. this._showOrMove(tooltipModel, function () {
  42827. this._showTooltipContent(
  42828. tooltipModel, defaultHtml, params, asyncTicket,
  42829. e.offsetX, e.offsetY, e.position, e.target, markers
  42830. );
  42831. });
  42832. // FIXME
  42833. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  42834. dispatchAction({
  42835. type: 'showTip',
  42836. dataIndexInside: dataIndex,
  42837. dataIndex: data.getRawIndex(dataIndex),
  42838. seriesIndex: seriesIndex,
  42839. from: this.uid
  42840. });
  42841. },
  42842. _showComponentItemTooltip: function (e, el, dispatchAction) {
  42843. var tooltipOpt = el.tooltip;
  42844. if (typeof tooltipOpt === 'string') {
  42845. var content = tooltipOpt;
  42846. tooltipOpt = {
  42847. content: content,
  42848. // Fixed formatter
  42849. formatter: content
  42850. };
  42851. }
  42852. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  42853. var defaultHtml = subTooltipModel.get('content');
  42854. var asyncTicket = Math.random();
  42855. // Do not check whether `trigger` is 'none' here, because `trigger`
  42856. // only works on cooridinate system. In fact, we have not found case
  42857. // that requires setting `trigger` nothing on component yet.
  42858. this._showOrMove(subTooltipModel, function () {
  42859. this._showTooltipContent(
  42860. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  42861. asyncTicket, e.offsetX, e.offsetY, e.position, el
  42862. );
  42863. });
  42864. // If not dispatch showTip, tip may be hide triggered by axis.
  42865. dispatchAction({
  42866. type: 'showTip',
  42867. from: this.uid
  42868. });
  42869. },
  42870. _showTooltipContent: function (
  42871. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  42872. ) {
  42873. // Reset ticket
  42874. this._ticket = '';
  42875. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  42876. return;
  42877. }
  42878. var tooltipContent = this._tooltipContent;
  42879. var formatter = tooltipModel.get('formatter');
  42880. positionExpr = positionExpr || tooltipModel.get('position');
  42881. var html = defaultHtml;
  42882. if (formatter && typeof formatter === 'string') {
  42883. html = formatTpl(formatter, params, true);
  42884. }
  42885. else if (typeof formatter === 'function') {
  42886. var callback = bind$2(function (cbTicket, html) {
  42887. if (cbTicket === this._ticket) {
  42888. tooltipContent.setContent(html, markers, tooltipModel);
  42889. this._updatePosition(
  42890. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  42891. );
  42892. }
  42893. }, this);
  42894. this._ticket = asyncTicket;
  42895. html = formatter(params, asyncTicket, callback);
  42896. }
  42897. tooltipContent.setContent(html, markers, tooltipModel);
  42898. tooltipContent.show(tooltipModel);
  42899. this._updatePosition(
  42900. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  42901. );
  42902. },
  42903. /**
  42904. * @param {string|Function|Array.<number>|Object} positionExpr
  42905. * @param {number} x Mouse x
  42906. * @param {number} y Mouse y
  42907. * @param {boolean} confine Whether confine tooltip content in view rect.
  42908. * @param {Object|<Array.<Object>} params
  42909. * @param {module:zrender/Element} el target element
  42910. * @param {module:echarts/ExtensionAPI} api
  42911. * @return {Array.<number>}
  42912. */
  42913. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  42914. var viewWidth = this._api.getWidth();
  42915. var viewHeight = this._api.getHeight();
  42916. positionExpr = positionExpr || tooltipModel.get('position');
  42917. var contentSize = content.getSize();
  42918. var align = tooltipModel.get('align');
  42919. var vAlign = tooltipModel.get('verticalAlign');
  42920. var rect = el && el.getBoundingRect().clone();
  42921. el && rect.applyTransform(el.transform);
  42922. if (typeof positionExpr === 'function') {
  42923. // Callback of position can be an array or a string specify the position
  42924. positionExpr = positionExpr([x, y], params, content.el, rect, {
  42925. viewSize: [viewWidth, viewHeight],
  42926. contentSize: contentSize.slice()
  42927. });
  42928. }
  42929. if (isArray(positionExpr)) {
  42930. x = parsePercent$2(positionExpr[0], viewWidth);
  42931. y = parsePercent$2(positionExpr[1], viewHeight);
  42932. }
  42933. else if (isObject$1(positionExpr)) {
  42934. positionExpr.width = contentSize[0];
  42935. positionExpr.height = contentSize[1];
  42936. var layoutRect = getLayoutRect(
  42937. positionExpr, {width: viewWidth, height: viewHeight}
  42938. );
  42939. x = layoutRect.x;
  42940. y = layoutRect.y;
  42941. align = null;
  42942. // When positionExpr is left/top/right/bottom,
  42943. // align and verticalAlign will not work.
  42944. vAlign = null;
  42945. }
  42946. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  42947. else if (typeof positionExpr === 'string' && el) {
  42948. var pos = calcTooltipPosition(
  42949. positionExpr, rect, contentSize
  42950. );
  42951. x = pos[0];
  42952. y = pos[1];
  42953. }
  42954. else {
  42955. var pos = refixTooltipPosition(
  42956. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  42957. );
  42958. x = pos[0];
  42959. y = pos[1];
  42960. }
  42961. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  42962. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  42963. if (tooltipModel.get('confine')) {
  42964. var pos = confineTooltipPosition(
  42965. x, y, content, viewWidth, viewHeight
  42966. );
  42967. x = pos[0];
  42968. y = pos[1];
  42969. }
  42970. content.moveTo(x, y);
  42971. },
  42972. // FIXME
  42973. // Should we remove this but leave this to user?
  42974. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  42975. var lastCoordSys = this._lastDataByCoordSys;
  42976. var contentNotChanged = !!lastCoordSys
  42977. && lastCoordSys.length === dataByCoordSys.length;
  42978. contentNotChanged && each$9(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  42979. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  42980. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  42981. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  42982. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  42983. contentNotChanged && each$9(lastDataByAxis, function (lastItem, indexAxis) {
  42984. var thisItem = thisDataByAxis[indexAxis] || {};
  42985. var lastIndices = lastItem.seriesDataIndices || [];
  42986. var newIndices = thisItem.seriesDataIndices || [];
  42987. contentNotChanged
  42988. &= lastItem.value === thisItem.value
  42989. && lastItem.axisType === thisItem.axisType
  42990. && lastItem.axisId === thisItem.axisId
  42991. && lastIndices.length === newIndices.length;
  42992. contentNotChanged && each$9(lastIndices, function (lastIdxItem, j) {
  42993. var newIdxItem = newIndices[j];
  42994. contentNotChanged
  42995. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  42996. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  42997. });
  42998. });
  42999. });
  43000. this._lastDataByCoordSys = dataByCoordSys;
  43001. return !!contentNotChanged;
  43002. },
  43003. _hide: function (dispatchAction) {
  43004. // Do not directly hideLater here, because this behavior may be prevented
  43005. // in dispatchAction when showTip is dispatched.
  43006. // FIXME
  43007. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  43008. this._lastDataByCoordSys = null;
  43009. dispatchAction({
  43010. type: 'hideTip',
  43011. from: this.uid
  43012. });
  43013. },
  43014. dispose: function (ecModel, api) {
  43015. if (env$1.node) {
  43016. return;
  43017. }
  43018. this._tooltipContent.hide();
  43019. unregister('itemTooltip', api);
  43020. }
  43021. });
  43022. /**
  43023. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  43024. * From top to bottom. (the last one should be globalTooltipModel);
  43025. */
  43026. function buildTooltipModel(modelCascade) {
  43027. var resultModel = modelCascade.pop();
  43028. while (modelCascade.length) {
  43029. var tooltipOpt = modelCascade.pop();
  43030. if (tooltipOpt) {
  43031. if (Model.isInstance(tooltipOpt)) {
  43032. tooltipOpt = tooltipOpt.get('tooltip', true);
  43033. }
  43034. // In each data item tooltip can be simply write:
  43035. // {
  43036. // value: 10,
  43037. // tooltip: 'Something you need to know'
  43038. // }
  43039. if (typeof tooltipOpt === 'string') {
  43040. tooltipOpt = {formatter: tooltipOpt};
  43041. }
  43042. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  43043. }
  43044. }
  43045. return resultModel;
  43046. }
  43047. function makeDispatchAction$1(payload, api) {
  43048. return payload.dispatchAction || bind(api.dispatchAction, api);
  43049. }
  43050. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  43051. var size = content.getOuterSize();
  43052. var width = size.width;
  43053. var height = size.height;
  43054. if (gapH != null) {
  43055. if (x + width + gapH > viewWidth) {
  43056. x -= width + gapH;
  43057. }
  43058. else {
  43059. x += gapH;
  43060. }
  43061. }
  43062. if (gapV != null) {
  43063. if (y + height + gapV > viewHeight) {
  43064. y -= height + gapV;
  43065. }
  43066. else {
  43067. y += gapV;
  43068. }
  43069. }
  43070. return [x, y];
  43071. }
  43072. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  43073. var size = content.getOuterSize();
  43074. var width = size.width;
  43075. var height = size.height;
  43076. x = Math.min(x + width, viewWidth) - width;
  43077. y = Math.min(y + height, viewHeight) - height;
  43078. x = Math.max(x, 0);
  43079. y = Math.max(y, 0);
  43080. return [x, y];
  43081. }
  43082. function calcTooltipPosition(position, rect, contentSize) {
  43083. var domWidth = contentSize[0];
  43084. var domHeight = contentSize[1];
  43085. var gap = 5;
  43086. var x = 0;
  43087. var y = 0;
  43088. var rectWidth = rect.width;
  43089. var rectHeight = rect.height;
  43090. switch (position) {
  43091. case 'inside':
  43092. x = rect.x + rectWidth / 2 - domWidth / 2;
  43093. y = rect.y + rectHeight / 2 - domHeight / 2;
  43094. break;
  43095. case 'top':
  43096. x = rect.x + rectWidth / 2 - domWidth / 2;
  43097. y = rect.y - domHeight - gap;
  43098. break;
  43099. case 'bottom':
  43100. x = rect.x + rectWidth / 2 - domWidth / 2;
  43101. y = rect.y + rectHeight + gap;
  43102. break;
  43103. case 'left':
  43104. x = rect.x - domWidth - gap;
  43105. y = rect.y + rectHeight / 2 - domHeight / 2;
  43106. break;
  43107. case 'right':
  43108. x = rect.x + rectWidth + gap;
  43109. y = rect.y + rectHeight / 2 - domHeight / 2;
  43110. }
  43111. return [x, y];
  43112. }
  43113. function isCenterAlign(align) {
  43114. return align === 'center' || align === 'middle';
  43115. }
  43116. /*
  43117. * Licensed to the Apache Software Foundation (ASF) under one
  43118. * or more contributor license agreements. See the NOTICE file
  43119. * distributed with this work for additional information
  43120. * regarding copyright ownership. The ASF licenses this file
  43121. * to you under the Apache License, Version 2.0 (the
  43122. * "License"); you may not use this file except in compliance
  43123. * with the License. You may obtain a copy of the License at
  43124. *
  43125. * http://www.apache.org/licenses/LICENSE-2.0
  43126. *
  43127. * Unless required by applicable law or agreed to in writing,
  43128. * software distributed under the License is distributed on an
  43129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43130. * KIND, either express or implied. See the License for the
  43131. * specific language governing permissions and limitations
  43132. * under the License.
  43133. */
  43134. // FIXME Better way to pack data in graphic element
  43135. /**
  43136. * @action
  43137. * @property {string} type
  43138. * @property {number} seriesIndex
  43139. * @property {number} dataIndex
  43140. * @property {number} [x]
  43141. * @property {number} [y]
  43142. */
  43143. registerAction(
  43144. {
  43145. type: 'showTip',
  43146. event: 'showTip',
  43147. update: 'tooltip:manuallyShowTip'
  43148. },
  43149. // noop
  43150. function () {}
  43151. );
  43152. registerAction(
  43153. {
  43154. type: 'hideTip',
  43155. event: 'hideTip',
  43156. update: 'tooltip:manuallyHideTip'
  43157. },
  43158. // noop
  43159. function () {}
  43160. );
  43161. /*
  43162. * Licensed to the Apache Software Foundation (ASF) under one
  43163. * or more contributor license agreements. See the NOTICE file
  43164. * distributed with this work for additional information
  43165. * regarding copyright ownership. The ASF licenses this file
  43166. * to you under the Apache License, Version 2.0 (the
  43167. * "License"); you may not use this file except in compliance
  43168. * with the License. You may obtain a copy of the License at
  43169. *
  43170. * http://www.apache.org/licenses/LICENSE-2.0
  43171. *
  43172. * Unless required by applicable law or agreed to in writing,
  43173. * software distributed under the License is distributed on an
  43174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43175. * KIND, either express or implied. See the License for the
  43176. * specific language governing permissions and limitations
  43177. * under the License.
  43178. */
  43179. var langSelector = lang.legend.selector;
  43180. var defaultSelectorOption = {
  43181. all: {
  43182. type: 'all',
  43183. title: clone(langSelector.all)
  43184. },
  43185. inverse: {
  43186. type: 'inverse',
  43187. title: clone(langSelector.inverse)
  43188. }
  43189. };
  43190. var LegendModel = extendComponentModel({
  43191. type: 'legend.plain',
  43192. dependencies: ['series'],
  43193. layoutMode: {
  43194. type: 'box',
  43195. // legend.width/height are maxWidth/maxHeight actually,
  43196. // whereas realy width/height is calculated by its content.
  43197. // (Setting {left: 10, right: 10} does not make sense).
  43198. // So consider the case:
  43199. // `setOption({legend: {left: 10});`
  43200. // then `setOption({legend: {right: 10});`
  43201. // The previous `left` should be cleared by setting `ignoreSize`.
  43202. ignoreSize: true
  43203. },
  43204. init: function (option, parentModel, ecModel) {
  43205. this.mergeDefaultAndTheme(option, ecModel);
  43206. option.selected = option.selected || {};
  43207. this._updateSelector(option);
  43208. },
  43209. mergeOption: function (option) {
  43210. LegendModel.superCall(this, 'mergeOption', option);
  43211. this._updateSelector(option);
  43212. },
  43213. _updateSelector: function (option) {
  43214. var selector = option.selector;
  43215. if (selector === true) {
  43216. selector = option.selector = ['all', 'inverse'];
  43217. }
  43218. if (isArray(selector)) {
  43219. each$1(selector, function (item, index) {
  43220. isString(item) && (item = {type: item});
  43221. selector[index] = merge(item, defaultSelectorOption[item.type]);
  43222. });
  43223. }
  43224. },
  43225. optionUpdated: function () {
  43226. this._updateData(this.ecModel);
  43227. var legendData = this._data;
  43228. // If selectedMode is single, try to select one
  43229. if (legendData[0] && this.get('selectedMode') === 'single') {
  43230. var hasSelected = false;
  43231. // If has any selected in option.selected
  43232. for (var i = 0; i < legendData.length; i++) {
  43233. var name = legendData[i].get('name');
  43234. if (this.isSelected(name)) {
  43235. // Force to unselect others
  43236. this.select(name);
  43237. hasSelected = true;
  43238. break;
  43239. }
  43240. }
  43241. // Try select the first if selectedMode is single
  43242. !hasSelected && this.select(legendData[0].get('name'));
  43243. }
  43244. },
  43245. _updateData: function (ecModel) {
  43246. var potentialData = [];
  43247. var availableNames = [];
  43248. ecModel.eachRawSeries(function (seriesModel) {
  43249. var seriesName = seriesModel.name;
  43250. availableNames.push(seriesName);
  43251. var isPotential;
  43252. if (seriesModel.legendVisualProvider) {
  43253. var provider = seriesModel.legendVisualProvider;
  43254. var names = provider.getAllNames();
  43255. if (!ecModel.isSeriesFiltered(seriesModel)) {
  43256. availableNames = availableNames.concat(names);
  43257. }
  43258. if (names.length) {
  43259. potentialData = potentialData.concat(names);
  43260. }
  43261. else {
  43262. isPotential = true;
  43263. }
  43264. }
  43265. else {
  43266. isPotential = true;
  43267. }
  43268. if (isPotential && isNameSpecified(seriesModel)) {
  43269. potentialData.push(seriesModel.name);
  43270. }
  43271. });
  43272. /**
  43273. * @type {Array.<string>}
  43274. * @private
  43275. */
  43276. this._availableNames = availableNames;
  43277. // If legend.data not specified in option, use availableNames as data,
  43278. // which is convinient for user preparing option.
  43279. var rawData = this.get('data') || potentialData;
  43280. var legendData = map(rawData, function (dataItem) {
  43281. // Can be string or number
  43282. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  43283. dataItem = {
  43284. name: dataItem
  43285. };
  43286. }
  43287. return new Model(dataItem, this, this.ecModel);
  43288. }, this);
  43289. /**
  43290. * @type {Array.<module:echarts/model/Model>}
  43291. * @private
  43292. */
  43293. this._data = legendData;
  43294. },
  43295. /**
  43296. * @return {Array.<module:echarts/model/Model>}
  43297. */
  43298. getData: function () {
  43299. return this._data;
  43300. },
  43301. /**
  43302. * @param {string} name
  43303. */
  43304. select: function (name) {
  43305. var selected = this.option.selected;
  43306. var selectedMode = this.get('selectedMode');
  43307. if (selectedMode === 'single') {
  43308. var data = this._data;
  43309. each$1(data, function (dataItem) {
  43310. selected[dataItem.get('name')] = false;
  43311. });
  43312. }
  43313. selected[name] = true;
  43314. },
  43315. /**
  43316. * @param {string} name
  43317. */
  43318. unSelect: function (name) {
  43319. if (this.get('selectedMode') !== 'single') {
  43320. this.option.selected[name] = false;
  43321. }
  43322. },
  43323. /**
  43324. * @param {string} name
  43325. */
  43326. toggleSelected: function (name) {
  43327. var selected = this.option.selected;
  43328. // Default is true
  43329. if (!selected.hasOwnProperty(name)) {
  43330. selected[name] = true;
  43331. }
  43332. this[selected[name] ? 'unSelect' : 'select'](name);
  43333. },
  43334. allSelect: function () {
  43335. var data = this._data;
  43336. var selected = this.option.selected;
  43337. each$1(data, function (dataItem) {
  43338. selected[dataItem.get('name', true)] = true;
  43339. });
  43340. },
  43341. inverseSelect: function () {
  43342. var data = this._data;
  43343. var selected = this.option.selected;
  43344. each$1(data, function (dataItem) {
  43345. var name = dataItem.get('name', true);
  43346. // Initially, default value is true
  43347. if (!selected.hasOwnProperty(name)) {
  43348. selected[name] = true;
  43349. }
  43350. selected[name] = !selected[name];
  43351. });
  43352. },
  43353. /**
  43354. * @param {string} name
  43355. */
  43356. isSelected: function (name) {
  43357. var selected = this.option.selected;
  43358. return !(selected.hasOwnProperty(name) && !selected[name])
  43359. && indexOf(this._availableNames, name) >= 0;
  43360. },
  43361. getOrient: function () {
  43362. return this.get('orient') === 'vertical'
  43363. ? {index: 1, name: 'vertical'}
  43364. : {index: 0, name: 'horizontal'};
  43365. },
  43366. defaultOption: {
  43367. // 一级层叠
  43368. zlevel: 0,
  43369. // 二级层叠
  43370. z: 4,
  43371. show: true,
  43372. // 布局方式,默认为水平布局,可选为:
  43373. // 'horizontal' | 'vertical'
  43374. orient: 'horizontal',
  43375. left: 'center',
  43376. // right: 'center',
  43377. top: 0,
  43378. // bottom: null,
  43379. // 水平对齐
  43380. // 'auto' | 'left' | 'right'
  43381. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  43382. align: 'auto',
  43383. backgroundColor: 'rgba(0,0,0,0)',
  43384. // 图例边框颜色
  43385. borderColor: '#ccc',
  43386. borderRadius: 0,
  43387. // 图例边框线宽,单位px,默认为0(无边框)
  43388. borderWidth: 0,
  43389. // 图例内边距,单位px,默认各方向内边距为5,
  43390. // 接受数组分别设定上右下左边距,同css
  43391. padding: 5,
  43392. // 各个item之间的间隔,单位px,默认为10,
  43393. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  43394. itemGap: 10,
  43395. // the width of legend symbol
  43396. itemWidth: 25,
  43397. // the height of legend symbol
  43398. itemHeight: 14,
  43399. // the color of unselected legend symbol
  43400. inactiveColor: '#ccc',
  43401. // the borderColor of unselected legend symbol
  43402. inactiveBorderColor: '#ccc',
  43403. itemStyle: {
  43404. // the default borderWidth of legend symbol
  43405. borderWidth: 0
  43406. },
  43407. textStyle: {
  43408. // 图例文字颜色
  43409. color: '#333'
  43410. },
  43411. // formatter: '',
  43412. // 选择模式,默认开启图例开关
  43413. selectedMode: true,
  43414. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  43415. // selected: null,
  43416. // 图例内容(详见legend.data,数组中每一项代表一个item
  43417. // data: [],
  43418. // Usage:
  43419. // selector: [{type: 'all or inverse', title: xxx}]
  43420. // or
  43421. // selector: true
  43422. // or
  43423. // selector: ['all', 'inverse']
  43424. selector: false,
  43425. selectorLabel: {
  43426. show: true,
  43427. borderRadius: 10,
  43428. padding: [3, 5, 3, 5],
  43429. fontSize: 12,
  43430. fontFamily: ' sans-serif',
  43431. color: '#666',
  43432. borderWidth: 1,
  43433. borderColor: '#666'
  43434. },
  43435. emphasis: {
  43436. selectorLabel: {
  43437. show: true,
  43438. color: '#eee',
  43439. backgroundColor: '#666'
  43440. }
  43441. },
  43442. // Value can be 'start' or 'end'
  43443. selectorPosition: 'auto',
  43444. selectorItemGap: 7,
  43445. selectorButtonGap: 10,
  43446. // Tooltip 相关配置
  43447. tooltip: {
  43448. show: false
  43449. }
  43450. }
  43451. });
  43452. /*
  43453. * Licensed to the Apache Software Foundation (ASF) under one
  43454. * or more contributor license agreements. See the NOTICE file
  43455. * distributed with this work for additional information
  43456. * regarding copyright ownership. The ASF licenses this file
  43457. * to you under the Apache License, Version 2.0 (the
  43458. * "License"); you may not use this file except in compliance
  43459. * with the License. You may obtain a copy of the License at
  43460. *
  43461. * http://www.apache.org/licenses/LICENSE-2.0
  43462. *
  43463. * Unless required by applicable law or agreed to in writing,
  43464. * software distributed under the License is distributed on an
  43465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43466. * KIND, either express or implied. See the License for the
  43467. * specific language governing permissions and limitations
  43468. * under the License.
  43469. */
  43470. function legendSelectActionHandler(methodName, payload, ecModel) {
  43471. var selectedMap = {};
  43472. var isToggleSelect = methodName === 'toggleSelected';
  43473. var isSelected;
  43474. // Update all legend components
  43475. ecModel.eachComponent('legend', function (legendModel) {
  43476. if (isToggleSelect && isSelected != null) {
  43477. // Force other legend has same selected status
  43478. // Or the first is toggled to true and other are toggled to false
  43479. // In the case one legend has some item unSelected in option. And if other legend
  43480. // doesn't has the item, they will assume it is selected.
  43481. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  43482. }
  43483. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  43484. legendModel[methodName]();
  43485. }
  43486. else {
  43487. legendModel[methodName](payload.name);
  43488. isSelected = legendModel.isSelected(payload.name);
  43489. }
  43490. var legendData = legendModel.getData();
  43491. each$1(legendData, function (model) {
  43492. var name = model.get('name');
  43493. // Wrap element
  43494. if (name === '\n' || name === '') {
  43495. return;
  43496. }
  43497. var isItemSelected = legendModel.isSelected(name);
  43498. if (selectedMap.hasOwnProperty(name)) {
  43499. // Unselected if any legend is unselected
  43500. selectedMap[name] = selectedMap[name] && isItemSelected;
  43501. }
  43502. else {
  43503. selectedMap[name] = isItemSelected;
  43504. }
  43505. });
  43506. });
  43507. // Return the event explicitly
  43508. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  43509. ? {
  43510. selected: selectedMap
  43511. }
  43512. : {
  43513. name: payload.name,
  43514. selected: selectedMap
  43515. };
  43516. }
  43517. /**
  43518. * @event legendToggleSelect
  43519. * @type {Object}
  43520. * @property {string} type 'legendToggleSelect'
  43521. * @property {string} [from]
  43522. * @property {string} name Series name or data item name
  43523. */
  43524. registerAction(
  43525. 'legendToggleSelect', 'legendselectchanged',
  43526. curry(legendSelectActionHandler, 'toggleSelected')
  43527. );
  43528. registerAction(
  43529. 'legendAllSelect', 'legendselectall',
  43530. curry(legendSelectActionHandler, 'allSelect')
  43531. );
  43532. registerAction(
  43533. 'legendInverseSelect', 'legendinverseselect',
  43534. curry(legendSelectActionHandler, 'inverseSelect')
  43535. );
  43536. /**
  43537. * @event legendSelect
  43538. * @type {Object}
  43539. * @property {string} type 'legendSelect'
  43540. * @property {string} name Series name or data item name
  43541. */
  43542. registerAction(
  43543. 'legendSelect', 'legendselected',
  43544. curry(legendSelectActionHandler, 'select')
  43545. );
  43546. /**
  43547. * @event legendUnSelect
  43548. * @type {Object}
  43549. * @property {string} type 'legendUnSelect'
  43550. * @property {string} name Series name or data item name
  43551. */
  43552. registerAction(
  43553. 'legendUnSelect', 'legendunselected',
  43554. curry(legendSelectActionHandler, 'unSelect')
  43555. );
  43556. /*
  43557. * Licensed to the Apache Software Foundation (ASF) under one
  43558. * or more contributor license agreements. See the NOTICE file
  43559. * distributed with this work for additional information
  43560. * regarding copyright ownership. The ASF licenses this file
  43561. * to you under the Apache License, Version 2.0 (the
  43562. * "License"); you may not use this file except in compliance
  43563. * with the License. You may obtain a copy of the License at
  43564. *
  43565. * http://www.apache.org/licenses/LICENSE-2.0
  43566. *
  43567. * Unless required by applicable law or agreed to in writing,
  43568. * software distributed under the License is distributed on an
  43569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43570. * KIND, either express or implied. See the License for the
  43571. * specific language governing permissions and limitations
  43572. * under the License.
  43573. */
  43574. /**
  43575. * Layout list like component.
  43576. * It will box layout each items in group of component and then position the whole group in the viewport
  43577. * @param {module:zrender/group/Group} group
  43578. * @param {module:echarts/model/Component} componentModel
  43579. * @param {module:echarts/ExtensionAPI}
  43580. */
  43581. function layout$2(group, componentModel, api) {
  43582. var boxLayoutParams = componentModel.getBoxLayoutParams();
  43583. var padding = componentModel.get('padding');
  43584. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  43585. var rect = getLayoutRect(
  43586. boxLayoutParams,
  43587. viewportSize,
  43588. padding
  43589. );
  43590. box(
  43591. componentModel.get('orient'),
  43592. group,
  43593. componentModel.get('itemGap'),
  43594. rect.width,
  43595. rect.height
  43596. );
  43597. positionElement(
  43598. group,
  43599. boxLayoutParams,
  43600. viewportSize,
  43601. padding
  43602. );
  43603. }
  43604. function makeBackground(rect, componentModel) {
  43605. var padding = normalizeCssArray$1(
  43606. componentModel.get('padding')
  43607. );
  43608. var style = componentModel.getItemStyle(['color', 'opacity']);
  43609. style.fill = componentModel.get('backgroundColor');
  43610. var rect = new Rect({
  43611. shape: {
  43612. x: rect.x - padding[3],
  43613. y: rect.y - padding[0],
  43614. width: rect.width + padding[1] + padding[3],
  43615. height: rect.height + padding[0] + padding[2],
  43616. r: componentModel.get('borderRadius')
  43617. },
  43618. style: style,
  43619. silent: true,
  43620. z2: -1
  43621. });
  43622. // FIXME
  43623. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  43624. // and background rect when setting like `left: 0`, `top: 0`.
  43625. // graphic.subPixelOptimizeRect(rect);
  43626. return rect;
  43627. }
  43628. /*
  43629. * Licensed to the Apache Software Foundation (ASF) under one
  43630. * or more contributor license agreements. See the NOTICE file
  43631. * distributed with this work for additional information
  43632. * regarding copyright ownership. The ASF licenses this file
  43633. * to you under the Apache License, Version 2.0 (the
  43634. * "License"); you may not use this file except in compliance
  43635. * with the License. You may obtain a copy of the License at
  43636. *
  43637. * http://www.apache.org/licenses/LICENSE-2.0
  43638. *
  43639. * Unless required by applicable law or agreed to in writing,
  43640. * software distributed under the License is distributed on an
  43641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43642. * KIND, either express or implied. See the License for the
  43643. * specific language governing permissions and limitations
  43644. * under the License.
  43645. */
  43646. var curry$3 = curry;
  43647. var each$11 = each$1;
  43648. var Group$2 = Group;
  43649. var LegendView = extendComponentView({
  43650. type: 'legend.plain',
  43651. newlineDisabled: false,
  43652. /**
  43653. * @override
  43654. */
  43655. init: function () {
  43656. /**
  43657. * @private
  43658. * @type {module:zrender/container/Group}
  43659. */
  43660. this.group.add(this._contentGroup = new Group$2());
  43661. /**
  43662. * @private
  43663. * @type {module:zrender/Element}
  43664. */
  43665. this._backgroundEl;
  43666. /**
  43667. * @private
  43668. * @type {module:zrender/container/Group}
  43669. */
  43670. this.group.add(this._selectorGroup = new Group$2());
  43671. /**
  43672. * If first rendering, `contentGroup.position` is [0, 0], which
  43673. * does not make sense and may cause unexepcted animation if adopted.
  43674. * @private
  43675. * @type {boolean}
  43676. */
  43677. this._isFirstRender = true;
  43678. },
  43679. /**
  43680. * @protected
  43681. */
  43682. getContentGroup: function () {
  43683. return this._contentGroup;
  43684. },
  43685. /**
  43686. * @protected
  43687. */
  43688. getSelectorGroup: function () {
  43689. return this._selectorGroup;
  43690. },
  43691. /**
  43692. * @override
  43693. */
  43694. render: function (legendModel, ecModel, api) {
  43695. var isFirstRender = this._isFirstRender;
  43696. this._isFirstRender = false;
  43697. this.resetInner();
  43698. if (!legendModel.get('show', true)) {
  43699. return;
  43700. }
  43701. var itemAlign = legendModel.get('align');
  43702. var orient = legendModel.get('orient');
  43703. if (!itemAlign || itemAlign === 'auto') {
  43704. itemAlign = (
  43705. legendModel.get('left') === 'right'
  43706. && orient === 'vertical'
  43707. ) ? 'right' : 'left';
  43708. }
  43709. var selector = legendModel.get('selector', true);
  43710. var selectorPosition = legendModel.get('selectorPosition', true);
  43711. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  43712. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  43713. }
  43714. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  43715. // Perform layout.
  43716. var positionInfo = legendModel.getBoxLayoutParams();
  43717. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  43718. var padding = legendModel.get('padding');
  43719. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  43720. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  43721. // Place mainGroup, based on the calculated `mainRect`.
  43722. var layoutRect = getLayoutRect(
  43723. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  43724. viewportSize,
  43725. padding
  43726. );
  43727. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  43728. // Render background after group is layout.
  43729. this.group.add(
  43730. this._backgroundEl = makeBackground(mainRect, legendModel)
  43731. );
  43732. },
  43733. /**
  43734. * @protected
  43735. */
  43736. resetInner: function () {
  43737. this.getContentGroup().removeAll();
  43738. this._backgroundEl && this.group.remove(this._backgroundEl);
  43739. this.getSelectorGroup().removeAll();
  43740. },
  43741. /**
  43742. * @protected
  43743. */
  43744. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  43745. var contentGroup = this.getContentGroup();
  43746. var legendDrawnMap = createHashMap();
  43747. var selectMode = legendModel.get('selectedMode');
  43748. var excludeSeriesId = [];
  43749. ecModel.eachRawSeries(function (seriesModel) {
  43750. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  43751. });
  43752. each$11(legendModel.getData(), function (itemModel, dataIndex) {
  43753. var name = itemModel.get('name');
  43754. // Use empty string or \n as a newline string
  43755. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  43756. contentGroup.add(new Group$2({
  43757. newline: true
  43758. }));
  43759. return;
  43760. }
  43761. // Representitive series.
  43762. var seriesModel = ecModel.getSeriesByName(name)[0];
  43763. if (legendDrawnMap.get(name)) {
  43764. // Have been drawed
  43765. return;
  43766. }
  43767. // Legend to control series.
  43768. if (seriesModel) {
  43769. var data = seriesModel.getData();
  43770. var color = data.getVisual('color');
  43771. var borderColor = data.getVisual('borderColor');
  43772. // If color is a callback function
  43773. if (typeof color === 'function') {
  43774. // Use the first data
  43775. color = color(seriesModel.getDataParams(0));
  43776. }
  43777. // If borderColor is a callback function
  43778. if (typeof borderColor === 'function') {
  43779. // Use the first data
  43780. borderColor = borderColor(seriesModel.getDataParams(0));
  43781. }
  43782. // Using rect symbol defaultly
  43783. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  43784. var symbolType = data.getVisual('symbol');
  43785. var itemGroup = this._createItem(
  43786. name, dataIndex, itemModel, legendModel,
  43787. legendSymbolType, symbolType,
  43788. itemAlign, color, borderColor,
  43789. selectMode
  43790. );
  43791. itemGroup.on('click', curry$3(dispatchSelectAction, name, null, api, excludeSeriesId))
  43792. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  43793. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  43794. legendDrawnMap.set(name, true);
  43795. }
  43796. else {
  43797. // Legend to control data. In pie and funnel.
  43798. ecModel.eachRawSeries(function (seriesModel) {
  43799. // In case multiple series has same data name
  43800. if (legendDrawnMap.get(name)) {
  43801. return;
  43802. }
  43803. if (seriesModel.legendVisualProvider) {
  43804. var provider = seriesModel.legendVisualProvider;
  43805. if (!provider.containName(name)) {
  43806. return;
  43807. }
  43808. var idx = provider.indexOfName(name);
  43809. var color = provider.getItemVisual(idx, 'color');
  43810. var borderColor = provider.getItemVisual(idx, 'borderColor');
  43811. var legendSymbolType = 'roundRect';
  43812. var itemGroup = this._createItem(
  43813. name, dataIndex, itemModel, legendModel,
  43814. legendSymbolType, null,
  43815. itemAlign, color, borderColor,
  43816. selectMode
  43817. );
  43818. // FIXME: consider different series has items with the same name.
  43819. itemGroup.on('click', curry$3(dispatchSelectAction, null, name, api, excludeSeriesId))
  43820. // Should not specify the series name, consider legend controls
  43821. // more than one pie series.
  43822. .on('mouseover', curry$3(dispatchHighlightAction, null, name, api, excludeSeriesId))
  43823. .on('mouseout', curry$3(dispatchDownplayAction, null, name, api, excludeSeriesId));
  43824. legendDrawnMap.set(name, true);
  43825. }
  43826. }, this);
  43827. }
  43828. if (__DEV__) {
  43829. if (!legendDrawnMap.get(name)) {
  43830. console.warn(
  43831. name + ' series not exists. Legend data should be same with series name or data name.'
  43832. );
  43833. }
  43834. }
  43835. }, this);
  43836. if (selector) {
  43837. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  43838. }
  43839. },
  43840. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  43841. var selectorGroup = this.getSelectorGroup();
  43842. each$11(selector, function (selectorItem) {
  43843. createSelectorButton(selectorItem);
  43844. });
  43845. function createSelectorButton(selectorItem) {
  43846. var type = selectorItem.type;
  43847. var labelText = new Text({
  43848. style: {
  43849. x: 0,
  43850. y: 0,
  43851. align: 'center',
  43852. verticalAlign: 'middle'
  43853. },
  43854. onclick: function () {
  43855. api.dispatchAction({
  43856. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  43857. });
  43858. }
  43859. });
  43860. selectorGroup.add(labelText);
  43861. var labelModel = legendModel.getModel('selectorLabel');
  43862. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  43863. setLabelStyle(
  43864. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  43865. {
  43866. defaultText: selectorItem.title,
  43867. isRectText: false
  43868. }
  43869. );
  43870. setHoverStyle(labelText);
  43871. }
  43872. },
  43873. _createItem: function (
  43874. name, dataIndex, itemModel, legendModel,
  43875. legendSymbolType, symbolType,
  43876. itemAlign, color, borderColor, selectMode
  43877. ) {
  43878. var itemWidth = legendModel.get('itemWidth');
  43879. var itemHeight = legendModel.get('itemHeight');
  43880. var inactiveColor = legendModel.get('inactiveColor');
  43881. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  43882. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  43883. var legendModelItemStyle = legendModel.getModel('itemStyle');
  43884. var isSelected = legendModel.isSelected(name);
  43885. var itemGroup = new Group$2();
  43886. var textStyleModel = itemModel.getModel('textStyle');
  43887. var itemIcon = itemModel.get('icon');
  43888. var tooltipModel = itemModel.getModel('tooltip');
  43889. var legendGlobalTooltipModel = tooltipModel.parentModel;
  43890. // Use user given icon first
  43891. legendSymbolType = itemIcon || legendSymbolType;
  43892. var legendSymbol = createSymbol(
  43893. legendSymbolType,
  43894. 0,
  43895. 0,
  43896. itemWidth,
  43897. itemHeight,
  43898. isSelected ? color : inactiveColor,
  43899. // symbolKeepAspect default true for legend
  43900. symbolKeepAspect == null ? true : symbolKeepAspect
  43901. );
  43902. itemGroup.add(
  43903. setSymbolStyle(
  43904. legendSymbol, legendSymbolType, legendModelItemStyle,
  43905. borderColor, inactiveBorderColor, isSelected
  43906. )
  43907. );
  43908. // Compose symbols
  43909. // PENDING
  43910. if (!itemIcon && symbolType
  43911. // At least show one symbol, can't be all none
  43912. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  43913. ) {
  43914. var size = itemHeight * 0.8;
  43915. if (symbolType === 'none') {
  43916. symbolType = 'circle';
  43917. }
  43918. var legendSymbolCenter = createSymbol(
  43919. symbolType,
  43920. (itemWidth - size) / 2,
  43921. (itemHeight - size) / 2,
  43922. size,
  43923. size,
  43924. isSelected ? color : inactiveColor,
  43925. // symbolKeepAspect default true for legend
  43926. symbolKeepAspect == null ? true : symbolKeepAspect
  43927. );
  43928. // Put symbol in the center
  43929. itemGroup.add(
  43930. setSymbolStyle(
  43931. legendSymbolCenter, symbolType, legendModelItemStyle,
  43932. borderColor, inactiveBorderColor, isSelected
  43933. )
  43934. );
  43935. }
  43936. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  43937. var textAlign = itemAlign;
  43938. var formatter = legendModel.get('formatter');
  43939. var content = name;
  43940. if (typeof formatter === 'string' && formatter) {
  43941. content = formatter.replace('{name}', name != null ? name : '');
  43942. }
  43943. else if (typeof formatter === 'function') {
  43944. content = formatter(name);
  43945. }
  43946. itemGroup.add(new Text({
  43947. style: setTextStyle({}, textStyleModel, {
  43948. text: content,
  43949. x: textX,
  43950. y: itemHeight / 2,
  43951. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  43952. textAlign: textAlign,
  43953. textVerticalAlign: 'middle'
  43954. })
  43955. }));
  43956. // Add a invisible rect to increase the area of mouse hover
  43957. var hitRect = new Rect({
  43958. shape: itemGroup.getBoundingRect(),
  43959. invisible: true,
  43960. tooltip: tooltipModel.get('show') ? extend({
  43961. content: name,
  43962. // Defaul formatter
  43963. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  43964. return name;
  43965. },
  43966. formatterParams: {
  43967. componentType: 'legend',
  43968. legendIndex: legendModel.componentIndex,
  43969. name: name,
  43970. $vars: ['name']
  43971. }
  43972. }, tooltipModel.option) : null
  43973. });
  43974. itemGroup.add(hitRect);
  43975. itemGroup.eachChild(function (child) {
  43976. child.silent = true;
  43977. });
  43978. hitRect.silent = !selectMode;
  43979. this.getContentGroup().add(itemGroup);
  43980. setHoverStyle(itemGroup);
  43981. itemGroup.__legendDataIndex = dataIndex;
  43982. return itemGroup;
  43983. },
  43984. /**
  43985. * @protected
  43986. */
  43987. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  43988. var contentGroup = this.getContentGroup();
  43989. var selectorGroup = this.getSelectorGroup();
  43990. // Place items in contentGroup.
  43991. box(
  43992. legendModel.get('orient'),
  43993. contentGroup,
  43994. legendModel.get('itemGap'),
  43995. maxSize.width,
  43996. maxSize.height
  43997. );
  43998. var contentRect = contentGroup.getBoundingRect();
  43999. var contentPos = [-contentRect.x, -contentRect.y];
  44000. if (selector) {
  44001. // Place buttons in selectorGroup
  44002. box(
  44003. // Buttons in selectorGroup always layout horizontally
  44004. 'horizontal',
  44005. selectorGroup,
  44006. legendModel.get('selectorItemGap', true)
  44007. );
  44008. var selectorRect = selectorGroup.getBoundingRect();
  44009. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44010. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44011. var orientIdx = legendModel.getOrient().index;
  44012. var wh = orientIdx === 0 ? 'width' : 'height';
  44013. var hw = orientIdx === 0 ? 'height' : 'width';
  44014. var yx = orientIdx === 0 ? 'y' : 'x';
  44015. if (selectorPosition === 'end') {
  44016. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  44017. }
  44018. else {
  44019. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  44020. }
  44021. //Always align selector to content as 'middle'
  44022. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  44023. selectorGroup.attr('position', selectorPos);
  44024. contentGroup.attr('position', contentPos);
  44025. var mainRect = {x: 0, y: 0};
  44026. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  44027. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  44028. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  44029. return mainRect;
  44030. }
  44031. else {
  44032. contentGroup.attr('position', contentPos);
  44033. return this.group.getBoundingRect();
  44034. }
  44035. },
  44036. /**
  44037. * @protected
  44038. */
  44039. remove: function () {
  44040. this.getContentGroup().removeAll();
  44041. this._isFirstRender = true;
  44042. }
  44043. });
  44044. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  44045. var itemStyle;
  44046. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  44047. itemStyle = legendModelItemStyle.getItemStyle();
  44048. symbol.style.stroke = borderColor;
  44049. if (!isSelected) {
  44050. itemStyle.stroke = inactiveBorderColor;
  44051. }
  44052. }
  44053. else {
  44054. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  44055. }
  44056. return symbol.setStyle(itemStyle);
  44057. }
  44058. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  44059. // downplay before unselect
  44060. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  44061. api.dispatchAction({
  44062. type: 'legendToggleSelect',
  44063. name: seriesName != null ? seriesName : dataName
  44064. });
  44065. // highlight after select
  44066. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  44067. }
  44068. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  44069. // If element hover will move to a hoverLayer.
  44070. var el = api.getZr().storage.getDisplayList()[0];
  44071. if (!(el && el.useHoverLayer)) {
  44072. api.dispatchAction({
  44073. type: 'highlight',
  44074. seriesName: seriesName,
  44075. name: dataName,
  44076. excludeSeriesId: excludeSeriesId
  44077. });
  44078. }
  44079. }
  44080. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  44081. // If element hover will move to a hoverLayer.
  44082. var el = api.getZr().storage.getDisplayList()[0];
  44083. if (!(el && el.useHoverLayer)) {
  44084. api.dispatchAction({
  44085. type: 'downplay',
  44086. seriesName: seriesName,
  44087. name: dataName,
  44088. excludeSeriesId: excludeSeriesId
  44089. });
  44090. }
  44091. }
  44092. /*
  44093. * Licensed to the Apache Software Foundation (ASF) under one
  44094. * or more contributor license agreements. See the NOTICE file
  44095. * distributed with this work for additional information
  44096. * regarding copyright ownership. The ASF licenses this file
  44097. * to you under the Apache License, Version 2.0 (the
  44098. * "License"); you may not use this file except in compliance
  44099. * with the License. You may obtain a copy of the License at
  44100. *
  44101. * http://www.apache.org/licenses/LICENSE-2.0
  44102. *
  44103. * Unless required by applicable law or agreed to in writing,
  44104. * software distributed under the License is distributed on an
  44105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44106. * KIND, either express or implied. See the License for the
  44107. * specific language governing permissions and limitations
  44108. * under the License.
  44109. */
  44110. var legendFilter = function (ecModel) {
  44111. var legendModels = ecModel.findComponents({
  44112. mainType: 'legend'
  44113. });
  44114. if (legendModels && legendModels.length) {
  44115. ecModel.filterSeries(function (series) {
  44116. // If in any legend component the status is not selected.
  44117. // Because in legend series is assumed selected when it is not in the legend data.
  44118. for (var i = 0; i < legendModels.length; i++) {
  44119. if (!legendModels[i].isSelected(series.name)) {
  44120. return false;
  44121. }
  44122. }
  44123. return true;
  44124. });
  44125. }
  44126. };
  44127. /*
  44128. * Licensed to the Apache Software Foundation (ASF) under one
  44129. * or more contributor license agreements. See the NOTICE file
  44130. * distributed with this work for additional information
  44131. * regarding copyright ownership. The ASF licenses this file
  44132. * to you under the Apache License, Version 2.0 (the
  44133. * "License"); you may not use this file except in compliance
  44134. * with the License. You may obtain a copy of the License at
  44135. *
  44136. * http://www.apache.org/licenses/LICENSE-2.0
  44137. *
  44138. * Unless required by applicable law or agreed to in writing,
  44139. * software distributed under the License is distributed on an
  44140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44141. * KIND, either express or implied. See the License for the
  44142. * specific language governing permissions and limitations
  44143. * under the License.
  44144. */
  44145. // Do not contain scrollable legend, for sake of file size.
  44146. // Series Filter
  44147. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  44148. ComponentModel.registerSubTypeDefaulter('legend', function () {
  44149. // Default 'plain' when no type specified.
  44150. return 'plain';
  44151. });
  44152. /*
  44153. * Licensed to the Apache Software Foundation (ASF) under one
  44154. * or more contributor license agreements. See the NOTICE file
  44155. * distributed with this work for additional information
  44156. * regarding copyright ownership. The ASF licenses this file
  44157. * to you under the Apache License, Version 2.0 (the
  44158. * "License"); you may not use this file except in compliance
  44159. * with the License. You may obtain a copy of the License at
  44160. *
  44161. * http://www.apache.org/licenses/LICENSE-2.0
  44162. *
  44163. * Unless required by applicable law or agreed to in writing,
  44164. * software distributed under the License is distributed on an
  44165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44166. * KIND, either express or implied. See the License for the
  44167. * specific language governing permissions and limitations
  44168. * under the License.
  44169. */
  44170. var ScrollableLegendModel = LegendModel.extend({
  44171. type: 'legend.scroll',
  44172. /**
  44173. * @param {number} scrollDataIndex
  44174. */
  44175. setScrollDataIndex: function (scrollDataIndex) {
  44176. this.option.scrollDataIndex = scrollDataIndex;
  44177. },
  44178. defaultOption: {
  44179. scrollDataIndex: 0,
  44180. pageButtonItemGap: 5,
  44181. pageButtonGap: null,
  44182. pageButtonPosition: 'end', // 'start' or 'end'
  44183. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  44184. pageIcons: {
  44185. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  44186. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  44187. },
  44188. pageIconColor: '#2f4554',
  44189. pageIconInactiveColor: '#aaa',
  44190. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  44191. pageTextStyle: {
  44192. color: '#333'
  44193. },
  44194. animationDurationUpdate: 800
  44195. },
  44196. /**
  44197. * @override
  44198. */
  44199. init: function (option, parentModel, ecModel, extraOpt) {
  44200. var inputPositionParams = getLayoutParams(option);
  44201. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  44202. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  44203. },
  44204. /**
  44205. * @override
  44206. */
  44207. mergeOption: function (option, extraOpt) {
  44208. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  44209. mergeAndNormalizeLayoutParams(this, this.option, option);
  44210. }
  44211. });
  44212. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  44213. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  44214. var orient = legendModel.getOrient();
  44215. var ignoreSize = [1, 1];
  44216. ignoreSize[orient.index] = 0;
  44217. mergeLayoutParam(target, raw, {
  44218. type: 'box', ignoreSize: ignoreSize
  44219. });
  44220. }
  44221. /*
  44222. * Licensed to the Apache Software Foundation (ASF) under one
  44223. * or more contributor license agreements. See the NOTICE file
  44224. * distributed with this work for additional information
  44225. * regarding copyright ownership. The ASF licenses this file
  44226. * to you under the Apache License, Version 2.0 (the
  44227. * "License"); you may not use this file except in compliance
  44228. * with the License. You may obtain a copy of the License at
  44229. *
  44230. * http://www.apache.org/licenses/LICENSE-2.0
  44231. *
  44232. * Unless required by applicable law or agreed to in writing,
  44233. * software distributed under the License is distributed on an
  44234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44235. * KIND, either express or implied. See the License for the
  44236. * specific language governing permissions and limitations
  44237. * under the License.
  44238. */
  44239. /**
  44240. * Separate legend and scrollable legend to reduce package size.
  44241. */
  44242. var Group$3 = Group;
  44243. var WH = ['width', 'height'];
  44244. var XY = ['x', 'y'];
  44245. var ScrollableLegendView = LegendView.extend({
  44246. type: 'legend.scroll',
  44247. newlineDisabled: true,
  44248. init: function () {
  44249. ScrollableLegendView.superCall(this, 'init');
  44250. /**
  44251. * @private
  44252. * @type {number} For `scroll`.
  44253. */
  44254. this._currentIndex = 0;
  44255. /**
  44256. * @private
  44257. * @type {module:zrender/container/Group}
  44258. */
  44259. this.group.add(this._containerGroup = new Group$3());
  44260. this._containerGroup.add(this.getContentGroup());
  44261. /**
  44262. * @private
  44263. * @type {module:zrender/container/Group}
  44264. */
  44265. this.group.add(this._controllerGroup = new Group$3());
  44266. /**
  44267. *
  44268. * @private
  44269. */
  44270. this._showController;
  44271. },
  44272. /**
  44273. * @override
  44274. */
  44275. resetInner: function () {
  44276. ScrollableLegendView.superCall(this, 'resetInner');
  44277. this._controllerGroup.removeAll();
  44278. this._containerGroup.removeClipPath();
  44279. this._containerGroup.__rectSize = null;
  44280. },
  44281. /**
  44282. * @override
  44283. */
  44284. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44285. var me = this;
  44286. // Render content items.
  44287. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  44288. legendModel, ecModel, api, selector, orient, selectorPosition);
  44289. var controllerGroup = this._controllerGroup;
  44290. // FIXME: support be 'auto' adapt to size number text length,
  44291. // e.g., '3/12345' should not overlap with the control arrow button.
  44292. var pageIconSize = legendModel.get('pageIconSize', true);
  44293. if (!isArray(pageIconSize)) {
  44294. pageIconSize = [pageIconSize, pageIconSize];
  44295. }
  44296. createPageButton('pagePrev', 0);
  44297. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  44298. controllerGroup.add(new Text({
  44299. name: 'pageText',
  44300. style: {
  44301. textFill: pageTextStyleModel.getTextColor(),
  44302. font: pageTextStyleModel.getFont(),
  44303. textVerticalAlign: 'middle',
  44304. textAlign: 'center'
  44305. },
  44306. silent: true
  44307. }));
  44308. createPageButton('pageNext', 1);
  44309. function createPageButton(name, iconIdx) {
  44310. var pageDataIndexName = name + 'DataIndex';
  44311. var icon = createIcon(
  44312. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  44313. {
  44314. // Buttons will be created in each render, so we do not need
  44315. // to worry about avoiding using legendModel kept in scope.
  44316. onclick: bind(
  44317. me._pageGo, me, pageDataIndexName, legendModel, api
  44318. )
  44319. },
  44320. {
  44321. x: -pageIconSize[0] / 2,
  44322. y: -pageIconSize[1] / 2,
  44323. width: pageIconSize[0],
  44324. height: pageIconSize[1]
  44325. }
  44326. );
  44327. icon.name = name;
  44328. controllerGroup.add(icon);
  44329. }
  44330. },
  44331. /**
  44332. * @override
  44333. */
  44334. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44335. var selectorGroup = this.getSelectorGroup();
  44336. var orientIdx = legendModel.getOrient().index;
  44337. var wh = WH[orientIdx];
  44338. var xy = XY[orientIdx];
  44339. var hw = WH[1 - orientIdx];
  44340. var yx = XY[1 - orientIdx];
  44341. selector && box(
  44342. // Buttons in selectorGroup always layout horizontally
  44343. 'horizontal',
  44344. selectorGroup,
  44345. legendModel.get('selectorItemGap', true)
  44346. );
  44347. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44348. var selectorRect = selectorGroup.getBoundingRect();
  44349. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44350. var processMaxSize = clone(maxSize);
  44351. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  44352. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  44353. processMaxSize, orientIdx, wh, hw, yx
  44354. );
  44355. if (selector) {
  44356. if (selectorPosition === 'end') {
  44357. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  44358. }
  44359. else {
  44360. var offset = selectorRect[wh] + selectorButtonGap;
  44361. selectorPos[orientIdx] -= offset;
  44362. mainRect[xy] -= offset;
  44363. }
  44364. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  44365. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  44366. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  44367. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  44368. selectorGroup.attr('position', selectorPos);
  44369. }
  44370. return mainRect;
  44371. },
  44372. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  44373. var contentGroup = this.getContentGroup();
  44374. var containerGroup = this._containerGroup;
  44375. var controllerGroup = this._controllerGroup;
  44376. // Place items in contentGroup.
  44377. box(
  44378. legendModel.get('orient'),
  44379. contentGroup,
  44380. legendModel.get('itemGap'),
  44381. !orientIdx ? null : maxSize.width,
  44382. orientIdx ? null : maxSize.height
  44383. );
  44384. box(
  44385. // Buttons in controller are layout always horizontally.
  44386. 'horizontal',
  44387. controllerGroup,
  44388. legendModel.get('pageButtonItemGap', true)
  44389. );
  44390. var contentRect = contentGroup.getBoundingRect();
  44391. var controllerRect = controllerGroup.getBoundingRect();
  44392. var showController = this._showController = contentRect[wh] > maxSize[wh];
  44393. var contentPos = [-contentRect.x, -contentRect.y];
  44394. // Remain contentPos when scroll animation perfroming.
  44395. // If first rendering, `contentGroup.position` is [0, 0], which
  44396. // does not make sense and may cause unexepcted animation if adopted.
  44397. if (!isFirstRender) {
  44398. contentPos[orientIdx] = contentGroup.position[orientIdx];
  44399. }
  44400. // Layout container group based on 0.
  44401. var containerPos = [0, 0];
  44402. var controllerPos = [-controllerRect.x, -controllerRect.y];
  44403. var pageButtonGap = retrieve2(
  44404. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  44405. );
  44406. // Place containerGroup and controllerGroup and contentGroup.
  44407. if (showController) {
  44408. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  44409. // controller is on the right / bottom.
  44410. if (pageButtonPosition === 'end') {
  44411. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  44412. }
  44413. // controller is on the left / top.
  44414. else {
  44415. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  44416. }
  44417. }
  44418. // Always align controller to content as 'middle'.
  44419. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  44420. contentGroup.attr('position', contentPos);
  44421. containerGroup.attr('position', containerPos);
  44422. controllerGroup.attr('position', controllerPos);
  44423. // Calculate `mainRect` and set `clipPath`.
  44424. // mainRect should not be calculated by `this.group.getBoundingRect()`
  44425. // for sake of the overflow.
  44426. var mainRect = {x: 0, y: 0};
  44427. // Consider content may be overflow (should be clipped).
  44428. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  44429. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  44430. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  44431. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  44432. containerGroup.__rectSize = maxSize[wh];
  44433. if (showController) {
  44434. var clipShape = {x: 0, y: 0};
  44435. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  44436. clipShape[hw] = mainRect[hw];
  44437. containerGroup.setClipPath(new Rect({shape: clipShape}));
  44438. // Consider content may be larger than container, container rect
  44439. // can not be obtained from `containerGroup.getBoundingRect()`.
  44440. containerGroup.__rectSize = clipShape[wh];
  44441. }
  44442. else {
  44443. // Do not remove or ignore controller. Keep them set as placeholders.
  44444. controllerGroup.eachChild(function (child) {
  44445. child.attr({invisible: true, silent: true});
  44446. });
  44447. }
  44448. // Content translate animation.
  44449. var pageInfo = this._getPageInfo(legendModel);
  44450. pageInfo.pageIndex != null && updateProps(
  44451. contentGroup,
  44452. {position: pageInfo.contentPosition},
  44453. // When switch from "show controller" to "not show controller", view should be
  44454. // updated immediately without animation, otherwise causes weird effect.
  44455. showController ? legendModel : false
  44456. );
  44457. this._updatePageInfoView(legendModel, pageInfo);
  44458. return mainRect;
  44459. },
  44460. _pageGo: function (to, legendModel, api) {
  44461. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  44462. scrollDataIndex != null && api.dispatchAction({
  44463. type: 'legendScroll',
  44464. scrollDataIndex: scrollDataIndex,
  44465. legendId: legendModel.id
  44466. });
  44467. },
  44468. _updatePageInfoView: function (legendModel, pageInfo) {
  44469. var controllerGroup = this._controllerGroup;
  44470. each$1(['pagePrev', 'pageNext'], function (name) {
  44471. var canJump = pageInfo[name + 'DataIndex'] != null;
  44472. var icon = controllerGroup.childOfName(name);
  44473. if (icon) {
  44474. icon.setStyle(
  44475. 'fill',
  44476. canJump
  44477. ? legendModel.get('pageIconColor', true)
  44478. : legendModel.get('pageIconInactiveColor', true)
  44479. );
  44480. icon.cursor = canJump ? 'pointer' : 'default';
  44481. }
  44482. });
  44483. var pageText = controllerGroup.childOfName('pageText');
  44484. var pageFormatter = legendModel.get('pageFormatter');
  44485. var pageIndex = pageInfo.pageIndex;
  44486. var current = pageIndex != null ? pageIndex + 1 : 0;
  44487. var total = pageInfo.pageCount;
  44488. pageText && pageFormatter && pageText.setStyle(
  44489. 'text',
  44490. isString(pageFormatter)
  44491. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  44492. : pageFormatter({current: current, total: total})
  44493. );
  44494. },
  44495. /**
  44496. * @param {module:echarts/model/Model} legendModel
  44497. * @return {Object} {
  44498. * contentPosition: Array.<number>, null when data item not found.
  44499. * pageIndex: number, null when data item not found.
  44500. * pageCount: number, always be a number, can be 0.
  44501. * pagePrevDataIndex: number, null when no previous page.
  44502. * pageNextDataIndex: number, null when no next page.
  44503. * }
  44504. */
  44505. _getPageInfo: function (legendModel) {
  44506. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  44507. var contentGroup = this.getContentGroup();
  44508. var containerRectSize = this._containerGroup.__rectSize;
  44509. var orientIdx = legendModel.getOrient().index;
  44510. var wh = WH[orientIdx];
  44511. var xy = XY[orientIdx];
  44512. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  44513. var children = contentGroup.children();
  44514. var targetItem = children[targetItemIndex];
  44515. var itemCount = children.length;
  44516. var pCount = !itemCount ? 0 : 1;
  44517. var result = {
  44518. contentPosition: contentGroup.position.slice(),
  44519. pageCount: pCount,
  44520. pageIndex: pCount - 1,
  44521. pagePrevDataIndex: null,
  44522. pageNextDataIndex: null
  44523. };
  44524. if (!targetItem) {
  44525. return result;
  44526. }
  44527. var targetItemInfo = getItemInfo(targetItem);
  44528. result.contentPosition[orientIdx] = -targetItemInfo.s;
  44529. // Strategy:
  44530. // (1) Always align based on the left/top most item.
  44531. // (2) It is user-friendly that the last item shown in the
  44532. // current window is shown at the begining of next window.
  44533. // Otherwise if half of the last item is cut by the window,
  44534. // it will have no chance to display entirely.
  44535. // (3) Consider that item size probably be different, we
  44536. // have calculate pageIndex by size rather than item index,
  44537. // and we can not get page index directly by division.
  44538. // (4) The window is to narrow to contain more than
  44539. // one item, we should make sure that the page can be fliped.
  44540. for (var i = targetItemIndex + 1,
  44541. winStartItemInfo = targetItemInfo,
  44542. winEndItemInfo = targetItemInfo,
  44543. currItemInfo = null;
  44544. i <= itemCount;
  44545. ++i
  44546. ) {
  44547. currItemInfo = getItemInfo(children[i]);
  44548. if (
  44549. // Half of the last item is out of the window.
  44550. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  44551. // If the current item does not intersect with the window, the new page
  44552. // can be started at the current item or the last item.
  44553. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  44554. ) {
  44555. if (winEndItemInfo.i > winStartItemInfo.i) {
  44556. winStartItemInfo = winEndItemInfo;
  44557. }
  44558. else { // e.g., when page size is smaller than item size.
  44559. winStartItemInfo = currItemInfo;
  44560. }
  44561. if (winStartItemInfo) {
  44562. if (result.pageNextDataIndex == null) {
  44563. result.pageNextDataIndex = winStartItemInfo.i;
  44564. }
  44565. ++result.pageCount;
  44566. }
  44567. }
  44568. winEndItemInfo = currItemInfo;
  44569. }
  44570. for (var i = targetItemIndex - 1,
  44571. winStartItemInfo = targetItemInfo,
  44572. winEndItemInfo = targetItemInfo,
  44573. currItemInfo = null;
  44574. i >= -1;
  44575. --i
  44576. ) {
  44577. currItemInfo = getItemInfo(children[i]);
  44578. if (
  44579. // If the the end item does not intersect with the window started
  44580. // from the current item, a page can be settled.
  44581. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  44582. // e.g., when page size is smaller than item size.
  44583. && winStartItemInfo.i < winEndItemInfo.i
  44584. ) {
  44585. winEndItemInfo = winStartItemInfo;
  44586. if (result.pagePrevDataIndex == null) {
  44587. result.pagePrevDataIndex = winStartItemInfo.i;
  44588. }
  44589. ++result.pageCount;
  44590. ++result.pageIndex;
  44591. }
  44592. winStartItemInfo = currItemInfo;
  44593. }
  44594. return result;
  44595. function getItemInfo(el) {
  44596. if (el) {
  44597. var itemRect = el.getBoundingRect();
  44598. var start = itemRect[xy] + el.position[orientIdx];
  44599. return {
  44600. s: start,
  44601. e: start + itemRect[wh],
  44602. i: el.__legendDataIndex
  44603. };
  44604. }
  44605. }
  44606. function intersect(itemInfo, winStart) {
  44607. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  44608. }
  44609. },
  44610. _findTargetItemIndex: function (targetDataIndex) {
  44611. var index;
  44612. var contentGroup = this.getContentGroup();
  44613. var defaultIndex;
  44614. if (this._showController) {
  44615. contentGroup.eachChild(function (child, idx) {
  44616. var legendDataIdx = child.__legendDataIndex;
  44617. // FIXME
  44618. // If the given targetDataIndex (from model) is illegal,
  44619. // we use defualtIndex. But the index on the legend model and
  44620. // action payload is still illegal. That case will not be
  44621. // changed until some scenario requires.
  44622. if (defaultIndex == null && legendDataIdx != null) {
  44623. defaultIndex = idx;
  44624. }
  44625. if (legendDataIdx === targetDataIndex) {
  44626. index = idx;
  44627. }
  44628. });
  44629. }
  44630. return index != null ? index : defaultIndex;
  44631. }
  44632. });
  44633. /*
  44634. * Licensed to the Apache Software Foundation (ASF) under one
  44635. * or more contributor license agreements. See the NOTICE file
  44636. * distributed with this work for additional information
  44637. * regarding copyright ownership. The ASF licenses this file
  44638. * to you under the Apache License, Version 2.0 (the
  44639. * "License"); you may not use this file except in compliance
  44640. * with the License. You may obtain a copy of the License at
  44641. *
  44642. * http://www.apache.org/licenses/LICENSE-2.0
  44643. *
  44644. * Unless required by applicable law or agreed to in writing,
  44645. * software distributed under the License is distributed on an
  44646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44647. * KIND, either express or implied. See the License for the
  44648. * specific language governing permissions and limitations
  44649. * under the License.
  44650. */
  44651. /**
  44652. * @event legendScroll
  44653. * @type {Object}
  44654. * @property {string} type 'legendScroll'
  44655. * @property {string} scrollDataIndex
  44656. */
  44657. registerAction(
  44658. 'legendScroll', 'legendscroll',
  44659. function (payload, ecModel) {
  44660. var scrollDataIndex = payload.scrollDataIndex;
  44661. scrollDataIndex != null && ecModel.eachComponent(
  44662. {mainType: 'legend', subType: 'scroll', query: payload},
  44663. function (legendModel) {
  44664. legendModel.setScrollDataIndex(scrollDataIndex);
  44665. }
  44666. );
  44667. }
  44668. );
  44669. /*
  44670. * Licensed to the Apache Software Foundation (ASF) under one
  44671. * or more contributor license agreements. See the NOTICE file
  44672. * distributed with this work for additional information
  44673. * regarding copyright ownership. The ASF licenses this file
  44674. * to you under the Apache License, Version 2.0 (the
  44675. * "License"); you may not use this file except in compliance
  44676. * with the License. You may obtain a copy of the License at
  44677. *
  44678. * http://www.apache.org/licenses/LICENSE-2.0
  44679. *
  44680. * Unless required by applicable law or agreed to in writing,
  44681. * software distributed under the License is distributed on an
  44682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44683. * KIND, either express or implied. See the License for the
  44684. * specific language governing permissions and limitations
  44685. * under the License.
  44686. */
  44687. /**
  44688. * Legend component entry file8
  44689. */
  44690. /*
  44691. * Licensed to the Apache Software Foundation (ASF) under one
  44692. * or more contributor license agreements. See the NOTICE file
  44693. * distributed with this work for additional information
  44694. * regarding copyright ownership. The ASF licenses this file
  44695. * to you under the Apache License, Version 2.0 (the
  44696. * "License"); you may not use this file except in compliance
  44697. * with the License. You may obtain a copy of the License at
  44698. *
  44699. * http://www.apache.org/licenses/LICENSE-2.0
  44700. *
  44701. * Unless required by applicable law or agreed to in writing,
  44702. * software distributed under the License is distributed on an
  44703. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44704. * KIND, either express or implied. See the License for the
  44705. * specific language governing permissions and limitations
  44706. * under the License.
  44707. */
  44708. /*
  44709. * Licensed to the Apache Software Foundation (ASF) under one
  44710. * or more contributor license agreements. See the NOTICE file
  44711. * distributed with this work for additional information
  44712. * regarding copyright ownership. The ASF licenses this file
  44713. * to you under the Apache License, Version 2.0 (the
  44714. * "License"); you may not use this file except in compliance
  44715. * with the License. You may obtain a copy of the License at
  44716. *
  44717. * http://www.apache.org/licenses/LICENSE-2.0
  44718. *
  44719. * Unless required by applicable law or agreed to in writing,
  44720. * software distributed under the License is distributed on an
  44721. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44722. * KIND, either express or implied. See the License for the
  44723. * specific language governing permissions and limitations
  44724. * under the License.
  44725. */
  44726. // Model
  44727. extendComponentModel({
  44728. type: 'title',
  44729. layoutMode: {type: 'box', ignoreSize: true},
  44730. defaultOption: {
  44731. // 一级层叠
  44732. zlevel: 0,
  44733. // 二级层叠
  44734. z: 6,
  44735. show: true,
  44736. text: '',
  44737. // 超链接跳转
  44738. // link: null,
  44739. // 仅支持self | blank
  44740. target: 'blank',
  44741. subtext: '',
  44742. // 超链接跳转
  44743. // sublink: null,
  44744. // 仅支持self | blank
  44745. subtarget: 'blank',
  44746. // 'center' ¦ 'left' ¦ 'right'
  44747. // ¦ {number}(x坐标,单位px)
  44748. left: 0,
  44749. // 'top' ¦ 'bottom' ¦ 'center'
  44750. // ¦ {number}(y坐标,单位px)
  44751. top: 0,
  44752. // 水平对齐
  44753. // 'auto' | 'left' | 'right' | 'center'
  44754. // 默认根据 left 的位置判断是左对齐还是右对齐
  44755. // textAlign: null
  44756. //
  44757. // 垂直对齐
  44758. // 'auto' | 'top' | 'bottom' | 'middle'
  44759. // 默认根据 top 位置判断是上对齐还是下对齐
  44760. // textVerticalAlign: null
  44761. // textBaseline: null // The same as textVerticalAlign.
  44762. backgroundColor: 'rgba(0,0,0,0)',
  44763. // 标题边框颜色
  44764. borderColor: '#ccc',
  44765. // 标题边框线宽,单位px,默认为0(无边框)
  44766. borderWidth: 0,
  44767. // 标题内边距,单位px,默认各方向内边距为5,
  44768. // 接受数组分别设定上右下左边距,同css
  44769. padding: 5,
  44770. // 主副标题纵向间隔,单位px,默认为10,
  44771. itemGap: 10,
  44772. textStyle: {
  44773. fontSize: 18,
  44774. fontWeight: 'bolder',
  44775. color: '#333'
  44776. },
  44777. subtextStyle: {
  44778. color: '#aaa'
  44779. }
  44780. }
  44781. });
  44782. // View
  44783. extendComponentView({
  44784. type: 'title',
  44785. render: function (titleModel, ecModel, api) {
  44786. this.group.removeAll();
  44787. if (!titleModel.get('show')) {
  44788. return;
  44789. }
  44790. var group = this.group;
  44791. var textStyleModel = titleModel.getModel('textStyle');
  44792. var subtextStyleModel = titleModel.getModel('subtextStyle');
  44793. var textAlign = titleModel.get('textAlign');
  44794. var textVerticalAlign = retrieve2(
  44795. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  44796. );
  44797. var textEl = new Text({
  44798. style: setTextStyle({}, textStyleModel, {
  44799. text: titleModel.get('text'),
  44800. textFill: textStyleModel.getTextColor()
  44801. }, {disableBox: true}),
  44802. z2: 10
  44803. });
  44804. var textRect = textEl.getBoundingRect();
  44805. var subText = titleModel.get('subtext');
  44806. var subTextEl = new Text({
  44807. style: setTextStyle({}, subtextStyleModel, {
  44808. text: subText,
  44809. textFill: subtextStyleModel.getTextColor(),
  44810. y: textRect.height + titleModel.get('itemGap'),
  44811. textVerticalAlign: 'top'
  44812. }, {disableBox: true}),
  44813. z2: 10
  44814. });
  44815. var link = titleModel.get('link');
  44816. var sublink = titleModel.get('sublink');
  44817. var triggerEvent = titleModel.get('triggerEvent', true);
  44818. textEl.silent = !link && !triggerEvent;
  44819. subTextEl.silent = !sublink && !triggerEvent;
  44820. if (link) {
  44821. textEl.on('click', function () {
  44822. window.open(link, '_' + titleModel.get('target'));
  44823. });
  44824. }
  44825. if (sublink) {
  44826. subTextEl.on('click', function () {
  44827. window.open(sublink, '_' + titleModel.get('subtarget'));
  44828. });
  44829. }
  44830. textEl.eventData = subTextEl.eventData = triggerEvent
  44831. ? {
  44832. componentType: 'title',
  44833. componentIndex: titleModel.componentIndex
  44834. }
  44835. : null;
  44836. group.add(textEl);
  44837. subText && group.add(subTextEl);
  44838. // If no subText, but add subTextEl, there will be an empty line.
  44839. var groupRect = group.getBoundingRect();
  44840. var layoutOption = titleModel.getBoxLayoutParams();
  44841. layoutOption.width = groupRect.width;
  44842. layoutOption.height = groupRect.height;
  44843. var layoutRect = getLayoutRect(
  44844. layoutOption, {
  44845. width: api.getWidth(),
  44846. height: api.getHeight()
  44847. }, titleModel.get('padding')
  44848. );
  44849. // Adjust text align based on position
  44850. if (!textAlign) {
  44851. // Align left if title is on the left. center and right is same
  44852. textAlign = titleModel.get('left') || titleModel.get('right');
  44853. if (textAlign === 'middle') {
  44854. textAlign = 'center';
  44855. }
  44856. // Adjust layout by text align
  44857. if (textAlign === 'right') {
  44858. layoutRect.x += layoutRect.width;
  44859. }
  44860. else if (textAlign === 'center') {
  44861. layoutRect.x += layoutRect.width / 2;
  44862. }
  44863. }
  44864. if (!textVerticalAlign) {
  44865. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  44866. if (textVerticalAlign === 'center') {
  44867. textVerticalAlign = 'middle';
  44868. }
  44869. if (textVerticalAlign === 'bottom') {
  44870. layoutRect.y += layoutRect.height;
  44871. }
  44872. else if (textVerticalAlign === 'middle') {
  44873. layoutRect.y += layoutRect.height / 2;
  44874. }
  44875. textVerticalAlign = textVerticalAlign || 'top';
  44876. }
  44877. group.attr('position', [layoutRect.x, layoutRect.y]);
  44878. var alignStyle = {
  44879. textAlign: textAlign,
  44880. textVerticalAlign: textVerticalAlign
  44881. };
  44882. textEl.setStyle(alignStyle);
  44883. subTextEl.setStyle(alignStyle);
  44884. // Render background
  44885. // Get groupRect again because textAlign has been changed
  44886. groupRect = group.getBoundingRect();
  44887. var padding = layoutRect.margin;
  44888. var style = titleModel.getItemStyle(['color', 'opacity']);
  44889. style.fill = titleModel.get('backgroundColor');
  44890. var rect = new Rect({
  44891. shape: {
  44892. x: groupRect.x - padding[3],
  44893. y: groupRect.y - padding[0],
  44894. width: groupRect.width + padding[1] + padding[3],
  44895. height: groupRect.height + padding[0] + padding[2],
  44896. r: titleModel.get('borderRadius')
  44897. },
  44898. style: style,
  44899. subPixelOptimize: true,
  44900. silent: true
  44901. });
  44902. group.add(rect);
  44903. }
  44904. });
  44905. /*
  44906. * Licensed to the Apache Software Foundation (ASF) under one
  44907. * or more contributor license agreements. See the NOTICE file
  44908. * distributed with this work for additional information
  44909. * regarding copyright ownership. The ASF licenses this file
  44910. * to you under the Apache License, Version 2.0 (the
  44911. * "License"); you may not use this file except in compliance
  44912. * with the License. You may obtain a copy of the License at
  44913. *
  44914. * http://www.apache.org/licenses/LICENSE-2.0
  44915. *
  44916. * Unless required by applicable law or agreed to in writing,
  44917. * software distributed under the License is distributed on an
  44918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44919. * KIND, either express or implied. See the License for the
  44920. * specific language governing permissions and limitations
  44921. * under the License.
  44922. */
  44923. var addCommas$1 = addCommas;
  44924. var encodeHTML$1 = encodeHTML;
  44925. function fillLabel(opt) {
  44926. defaultEmphasis(opt, 'label', ['show']);
  44927. }
  44928. var MarkerModel = extendComponentModel({
  44929. type: 'marker',
  44930. dependencies: ['series', 'grid', 'polar', 'geo'],
  44931. /**
  44932. * @overrite
  44933. */
  44934. init: function (option, parentModel, ecModel) {
  44935. if (__DEV__) {
  44936. if (this.type === 'marker') {
  44937. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  44938. }
  44939. }
  44940. this.mergeDefaultAndTheme(option, ecModel);
  44941. this._mergeOption(option, ecModel, false, true);
  44942. },
  44943. /**
  44944. * @return {boolean}
  44945. */
  44946. isAnimationEnabled: function () {
  44947. if (env$1.node) {
  44948. return false;
  44949. }
  44950. var hostSeries = this.__hostSeries;
  44951. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  44952. },
  44953. /**
  44954. * @overrite
  44955. */
  44956. mergeOption: function (newOpt, ecModel) {
  44957. this._mergeOption(newOpt, ecModel, false, false);
  44958. },
  44959. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  44960. var MarkerModel = this.constructor;
  44961. var modelPropName = this.mainType + 'Model';
  44962. if (!createdBySelf) {
  44963. ecModel.eachSeries(function (seriesModel) {
  44964. var markerOpt = seriesModel.get(this.mainType, true);
  44965. var markerModel = seriesModel[modelPropName];
  44966. if (!markerOpt || !markerOpt.data) {
  44967. seriesModel[modelPropName] = null;
  44968. return;
  44969. }
  44970. if (!markerModel) {
  44971. if (isInit) {
  44972. // Default label emphasis `position` and `show`
  44973. fillLabel(markerOpt);
  44974. }
  44975. each$1(markerOpt.data, function (item) {
  44976. // FIXME Overwrite fillLabel method ?
  44977. if (item instanceof Array) {
  44978. fillLabel(item[0]);
  44979. fillLabel(item[1]);
  44980. }
  44981. else {
  44982. fillLabel(item);
  44983. }
  44984. });
  44985. markerModel = new MarkerModel(
  44986. markerOpt, this, ecModel
  44987. );
  44988. extend(markerModel, {
  44989. mainType: this.mainType,
  44990. // Use the same series index and name
  44991. seriesIndex: seriesModel.seriesIndex,
  44992. name: seriesModel.name,
  44993. createdBySelf: true
  44994. });
  44995. markerModel.__hostSeries = seriesModel;
  44996. }
  44997. else {
  44998. markerModel._mergeOption(markerOpt, ecModel, true);
  44999. }
  45000. seriesModel[modelPropName] = markerModel;
  45001. }, this);
  45002. }
  45003. },
  45004. formatTooltip: function (dataIndex) {
  45005. var data = this.getData();
  45006. var value = this.getRawValue(dataIndex);
  45007. var formattedValue = isArray(value)
  45008. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  45009. var name = data.getName(dataIndex);
  45010. var html = encodeHTML$1(this.name);
  45011. if (value != null || name) {
  45012. html += '<br />';
  45013. }
  45014. if (name) {
  45015. html += encodeHTML$1(name);
  45016. if (value != null) {
  45017. html += ' : ';
  45018. }
  45019. }
  45020. if (value != null) {
  45021. html += encodeHTML$1(formattedValue);
  45022. }
  45023. return html;
  45024. },
  45025. getData: function () {
  45026. return this._data;
  45027. },
  45028. setData: function (data) {
  45029. this._data = data;
  45030. }
  45031. });
  45032. mixin(MarkerModel, dataFormatMixin);
  45033. /*
  45034. * Licensed to the Apache Software Foundation (ASF) under one
  45035. * or more contributor license agreements. See the NOTICE file
  45036. * distributed with this work for additional information
  45037. * regarding copyright ownership. The ASF licenses this file
  45038. * to you under the Apache License, Version 2.0 (the
  45039. * "License"); you may not use this file except in compliance
  45040. * with the License. You may obtain a copy of the License at
  45041. *
  45042. * http://www.apache.org/licenses/LICENSE-2.0
  45043. *
  45044. * Unless required by applicable law or agreed to in writing,
  45045. * software distributed under the License is distributed on an
  45046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45047. * KIND, either express or implied. See the License for the
  45048. * specific language governing permissions and limitations
  45049. * under the License.
  45050. */
  45051. MarkerModel.extend({
  45052. type: 'markPoint',
  45053. defaultOption: {
  45054. zlevel: 0,
  45055. z: 5,
  45056. symbol: 'pin',
  45057. symbolSize: 50,
  45058. //symbolRotate: 0,
  45059. //symbolOffset: [0, 0]
  45060. tooltip: {
  45061. trigger: 'item'
  45062. },
  45063. label: {
  45064. show: true,
  45065. position: 'inside'
  45066. },
  45067. itemStyle: {
  45068. borderWidth: 2
  45069. },
  45070. emphasis: {
  45071. label: {
  45072. show: true
  45073. }
  45074. }
  45075. }
  45076. });
  45077. /*
  45078. * Licensed to the Apache Software Foundation (ASF) under one
  45079. * or more contributor license agreements. See the NOTICE file
  45080. * distributed with this work for additional information
  45081. * regarding copyright ownership. The ASF licenses this file
  45082. * to you under the Apache License, Version 2.0 (the
  45083. * "License"); you may not use this file except in compliance
  45084. * with the License. You may obtain a copy of the License at
  45085. *
  45086. * http://www.apache.org/licenses/LICENSE-2.0
  45087. *
  45088. * Unless required by applicable law or agreed to in writing,
  45089. * software distributed under the License is distributed on an
  45090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45091. * KIND, either express or implied. See the License for the
  45092. * specific language governing permissions and limitations
  45093. * under the License.
  45094. */
  45095. var indexOf$1 = indexOf;
  45096. function hasXOrY(item) {
  45097. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  45098. }
  45099. function hasXAndY(item) {
  45100. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  45101. }
  45102. // Make it simple, do not visit all stacked value to count precision.
  45103. // function getPrecision(data, valueAxisDim, dataIndex) {
  45104. // var precision = -1;
  45105. // var stackedDim = data.mapDimension(valueAxisDim);
  45106. // do {
  45107. // precision = Math.max(
  45108. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  45109. // precision
  45110. // );
  45111. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  45112. // if (stackedOnSeries) {
  45113. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  45114. // data = stackedOnSeries.getData();
  45115. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  45116. // stackedDim = data.getCalculationInfo('stackedDimension');
  45117. // }
  45118. // else {
  45119. // data = null;
  45120. // }
  45121. // } while (data);
  45122. // return precision;
  45123. // }
  45124. function markerTypeCalculatorWithExtent(
  45125. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  45126. ) {
  45127. var coordArr = [];
  45128. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  45129. var calcDataDim = stacked
  45130. ? data.getCalculationInfo('stackResultDimension')
  45131. : targetDataDim;
  45132. var value = numCalculate(data, calcDataDim, mlType);
  45133. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  45134. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  45135. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  45136. // Make it simple, do not visit all stacked value to count precision.
  45137. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  45138. precision = Math.min(precision, 20);
  45139. if (precision >= 0) {
  45140. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  45141. }
  45142. return coordArr;
  45143. }
  45144. var curry$4 = curry;
  45145. // TODO Specified percent
  45146. var markerTypeCalculator = {
  45147. /**
  45148. * @method
  45149. * @param {module:echarts/data/List} data
  45150. * @param {string} baseAxisDim
  45151. * @param {string} valueAxisDim
  45152. */
  45153. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  45154. /**
  45155. * @method
  45156. * @param {module:echarts/data/List} data
  45157. * @param {string} baseAxisDim
  45158. * @param {string} valueAxisDim
  45159. */
  45160. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  45161. /**
  45162. * @method
  45163. * @param {module:echarts/data/List} data
  45164. * @param {string} baseAxisDim
  45165. * @param {string} valueAxisDim
  45166. */
  45167. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  45168. };
  45169. /**
  45170. * Transform markPoint data item to format used in List by do the following
  45171. * 1. Calculate statistic like `max`, `min`, `average`
  45172. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  45173. * @param {module:echarts/model/Series} seriesModel
  45174. * @param {module:echarts/coord/*} [coordSys]
  45175. * @param {Object} item
  45176. * @return {Object}
  45177. */
  45178. function dataTransform(seriesModel, item) {
  45179. var data = seriesModel.getData();
  45180. var coordSys = seriesModel.coordinateSystem;
  45181. // 1. If not specify the position with pixel directly
  45182. // 2. If `coord` is not a data array. Which uses `xAxis`,
  45183. // `yAxis` to specify the coord on each dimension
  45184. // parseFloat first because item.x and item.y can be percent string like '20%'
  45185. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  45186. var dims = coordSys.dimensions;
  45187. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  45188. // Clone the option
  45189. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  45190. item = clone(item);
  45191. if (item.type
  45192. && markerTypeCalculator[item.type]
  45193. && axisInfo.baseAxis && axisInfo.valueAxis
  45194. ) {
  45195. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  45196. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  45197. item.coord = markerTypeCalculator[item.type](
  45198. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  45199. otherCoordIndex, targetCoordIndex
  45200. );
  45201. // Force to use the value of calculated value.
  45202. item.value = item.coord[targetCoordIndex];
  45203. }
  45204. else {
  45205. // FIXME Only has one of xAxis and yAxis.
  45206. var coord = [
  45207. item.xAxis != null ? item.xAxis : item.radiusAxis,
  45208. item.yAxis != null ? item.yAxis : item.angleAxis
  45209. ];
  45210. // Each coord support max, min, average
  45211. for (var i = 0; i < 2; i++) {
  45212. if (markerTypeCalculator[coord[i]]) {
  45213. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  45214. }
  45215. }
  45216. item.coord = coord;
  45217. }
  45218. }
  45219. return item;
  45220. }
  45221. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  45222. var ret = {};
  45223. if (item.valueIndex != null || item.valueDim != null) {
  45224. ret.valueDataDim = item.valueIndex != null
  45225. ? data.getDimension(item.valueIndex) : item.valueDim;
  45226. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  45227. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  45228. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45229. }
  45230. else {
  45231. ret.baseAxis = seriesModel.getBaseAxis();
  45232. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  45233. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45234. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  45235. }
  45236. return ret;
  45237. }
  45238. function dataDimToCoordDim(seriesModel, dataDim) {
  45239. var data = seriesModel.getData();
  45240. var dimensions = data.dimensions;
  45241. dataDim = data.getDimension(dataDim);
  45242. for (var i = 0; i < dimensions.length; i++) {
  45243. var dimItem = data.getDimensionInfo(dimensions[i]);
  45244. if (dimItem.name === dataDim) {
  45245. return dimItem.coordDim;
  45246. }
  45247. }
  45248. }
  45249. /**
  45250. * Filter data which is out of coordinateSystem range
  45251. * [dataFilter description]
  45252. * @param {module:echarts/coord/*} [coordSys]
  45253. * @param {Object} item
  45254. * @return {boolean}
  45255. */
  45256. function dataFilter$1(coordSys, item) {
  45257. // Alwalys return true if there is no coordSys
  45258. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  45259. ? coordSys.containData(item.coord) : true;
  45260. }
  45261. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  45262. // x, y, radius, angle
  45263. if (dimIndex < 2) {
  45264. return item.coord && item.coord[dimIndex];
  45265. }
  45266. return item.value;
  45267. }
  45268. function numCalculate(data, valueDataDim, type) {
  45269. if (type === 'average') {
  45270. var sum = 0;
  45271. var count = 0;
  45272. data.each(valueDataDim, function (val, idx) {
  45273. if (!isNaN(val)) {
  45274. sum += val;
  45275. count++;
  45276. }
  45277. });
  45278. return sum / count;
  45279. }
  45280. else if (type === 'median') {
  45281. return data.getMedian(valueDataDim);
  45282. }
  45283. else {
  45284. // max & min
  45285. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  45286. }
  45287. }
  45288. /*
  45289. * Licensed to the Apache Software Foundation (ASF) under one
  45290. * or more contributor license agreements. See the NOTICE file
  45291. * distributed with this work for additional information
  45292. * regarding copyright ownership. The ASF licenses this file
  45293. * to you under the Apache License, Version 2.0 (the
  45294. * "License"); you may not use this file except in compliance
  45295. * with the License. You may obtain a copy of the License at
  45296. *
  45297. * http://www.apache.org/licenses/LICENSE-2.0
  45298. *
  45299. * Unless required by applicable law or agreed to in writing,
  45300. * software distributed under the License is distributed on an
  45301. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45302. * KIND, either express or implied. See the License for the
  45303. * specific language governing permissions and limitations
  45304. * under the License.
  45305. */
  45306. var MarkerView = extendComponentView({
  45307. type: 'marker',
  45308. init: function () {
  45309. /**
  45310. * Markline grouped by series
  45311. * @private
  45312. * @type {module:zrender/core/util.HashMap}
  45313. */
  45314. this.markerGroupMap = createHashMap();
  45315. },
  45316. render: function (markerModel, ecModel, api) {
  45317. var markerGroupMap = this.markerGroupMap;
  45318. markerGroupMap.each(function (item) {
  45319. item.__keep = false;
  45320. });
  45321. var markerModelKey = this.type + 'Model';
  45322. ecModel.eachSeries(function (seriesModel) {
  45323. var markerModel = seriesModel[markerModelKey];
  45324. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  45325. }, this);
  45326. markerGroupMap.each(function (item) {
  45327. !item.__keep && this.group.remove(item.group);
  45328. }, this);
  45329. },
  45330. renderSeries: function () {}
  45331. });
  45332. /*
  45333. * Licensed to the Apache Software Foundation (ASF) under one
  45334. * or more contributor license agreements. See the NOTICE file
  45335. * distributed with this work for additional information
  45336. * regarding copyright ownership. The ASF licenses this file
  45337. * to you under the Apache License, Version 2.0 (the
  45338. * "License"); you may not use this file except in compliance
  45339. * with the License. You may obtain a copy of the License at
  45340. *
  45341. * http://www.apache.org/licenses/LICENSE-2.0
  45342. *
  45343. * Unless required by applicable law or agreed to in writing,
  45344. * software distributed under the License is distributed on an
  45345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45346. * KIND, either express or implied. See the License for the
  45347. * specific language governing permissions and limitations
  45348. * under the License.
  45349. */
  45350. function updateMarkerLayout(mpData, seriesModel, api) {
  45351. var coordSys = seriesModel.coordinateSystem;
  45352. mpData.each(function (idx) {
  45353. var itemModel = mpData.getItemModel(idx);
  45354. var point;
  45355. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  45356. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  45357. if (!isNaN(xPx) && !isNaN(yPx)) {
  45358. point = [xPx, yPx];
  45359. }
  45360. // Chart like bar may have there own marker positioning logic
  45361. else if (seriesModel.getMarkerPosition) {
  45362. // Use the getMarkerPoisition
  45363. point = seriesModel.getMarkerPosition(
  45364. mpData.getValues(mpData.dimensions, idx)
  45365. );
  45366. }
  45367. else if (coordSys) {
  45368. var x = mpData.get(coordSys.dimensions[0], idx);
  45369. var y = mpData.get(coordSys.dimensions[1], idx);
  45370. point = coordSys.dataToPoint([x, y]);
  45371. }
  45372. // Use x, y if has any
  45373. if (!isNaN(xPx)) {
  45374. point[0] = xPx;
  45375. }
  45376. if (!isNaN(yPx)) {
  45377. point[1] = yPx;
  45378. }
  45379. mpData.setItemLayout(idx, point);
  45380. });
  45381. }
  45382. MarkerView.extend({
  45383. type: 'markPoint',
  45384. // updateLayout: function (markPointModel, ecModel, api) {
  45385. // ecModel.eachSeries(function (seriesModel) {
  45386. // var mpModel = seriesModel.markPointModel;
  45387. // if (mpModel) {
  45388. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45389. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45390. // }
  45391. // }, this);
  45392. // },
  45393. updateTransform: function (markPointModel, ecModel, api) {
  45394. ecModel.eachSeries(function (seriesModel) {
  45395. var mpModel = seriesModel.markPointModel;
  45396. if (mpModel) {
  45397. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45398. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45399. }
  45400. }, this);
  45401. },
  45402. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  45403. var coordSys = seriesModel.coordinateSystem;
  45404. var seriesId = seriesModel.id;
  45405. var seriesData = seriesModel.getData();
  45406. var symbolDrawMap = this.markerGroupMap;
  45407. var symbolDraw = symbolDrawMap.get(seriesId)
  45408. || symbolDrawMap.set(seriesId, new SymbolDraw());
  45409. var mpData = createList$1(coordSys, seriesModel, mpModel);
  45410. // FIXME
  45411. mpModel.setData(mpData);
  45412. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45413. mpData.each(function (idx) {
  45414. var itemModel = mpData.getItemModel(idx);
  45415. var symbol = itemModel.getShallow('symbol');
  45416. var symbolSize = itemModel.getShallow('symbolSize');
  45417. var isFnSymbol = isFunction$1(symbol);
  45418. var isFnSymbolSize = isFunction$1(symbolSize);
  45419. if (isFnSymbol || isFnSymbolSize) {
  45420. var rawIdx = mpModel.getRawValue(idx);
  45421. var dataParams = mpModel.getDataParams(idx);
  45422. if (isFnSymbol) {
  45423. symbol = symbol(rawIdx, dataParams);
  45424. }
  45425. if (isFnSymbolSize) {
  45426. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  45427. symbolSize = symbolSize(rawIdx, dataParams);
  45428. }
  45429. }
  45430. mpData.setItemVisual(idx, {
  45431. symbol: symbol,
  45432. symbolSize: symbolSize,
  45433. color: itemModel.get('itemStyle.color')
  45434. || seriesData.getVisual('color')
  45435. });
  45436. });
  45437. // TODO Text are wrong
  45438. symbolDraw.updateData(mpData);
  45439. this.group.add(symbolDraw.group);
  45440. // Set host model for tooltip
  45441. // FIXME
  45442. mpData.eachItemGraphicEl(function (el) {
  45443. el.traverse(function (child) {
  45444. child.dataModel = mpModel;
  45445. });
  45446. });
  45447. symbolDraw.__keep = true;
  45448. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  45449. }
  45450. });
  45451. /**
  45452. * @inner
  45453. * @param {module:echarts/coord/*} [coordSys]
  45454. * @param {module:echarts/model/Series} seriesModel
  45455. * @param {module:echarts/model/Model} mpModel
  45456. */
  45457. function createList$1(coordSys, seriesModel, mpModel) {
  45458. var coordDimsInfos;
  45459. if (coordSys) {
  45460. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  45461. var info = seriesModel.getData().getDimensionInfo(
  45462. seriesModel.getData().mapDimension(coordDim)
  45463. ) || {};
  45464. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  45465. return defaults({name: coordDim}, info);
  45466. });
  45467. }
  45468. else {
  45469. coordDimsInfos = [{
  45470. name: 'value',
  45471. type: 'float'
  45472. }];
  45473. }
  45474. var mpData = new List(coordDimsInfos, mpModel);
  45475. var dataOpt = map(mpModel.get('data'), curry(
  45476. dataTransform, seriesModel
  45477. ));
  45478. if (coordSys) {
  45479. dataOpt = filter(
  45480. dataOpt, curry(dataFilter$1, coordSys)
  45481. );
  45482. }
  45483. mpData.initData(dataOpt, null,
  45484. coordSys ? dimValueGetter : function (item) {
  45485. return item.value;
  45486. }
  45487. );
  45488. return mpData;
  45489. }
  45490. /*
  45491. * Licensed to the Apache Software Foundation (ASF) under one
  45492. * or more contributor license agreements. See the NOTICE file
  45493. * distributed with this work for additional information
  45494. * regarding copyright ownership. The ASF licenses this file
  45495. * to you under the Apache License, Version 2.0 (the
  45496. * "License"); you may not use this file except in compliance
  45497. * with the License. You may obtain a copy of the License at
  45498. *
  45499. * http://www.apache.org/licenses/LICENSE-2.0
  45500. *
  45501. * Unless required by applicable law or agreed to in writing,
  45502. * software distributed under the License is distributed on an
  45503. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45504. * KIND, either express or implied. See the License for the
  45505. * specific language governing permissions and limitations
  45506. * under the License.
  45507. */
  45508. // HINT Markpoint can't be used too much
  45509. registerPreprocessor(function (opt) {
  45510. // Make sure markPoint component is enabled
  45511. opt.markPoint = opt.markPoint || {};
  45512. });
  45513. /*
  45514. * Licensed to the Apache Software Foundation (ASF) under one
  45515. * or more contributor license agreements. See the NOTICE file
  45516. * distributed with this work for additional information
  45517. * regarding copyright ownership. The ASF licenses this file
  45518. * to you under the Apache License, Version 2.0 (the
  45519. * "License"); you may not use this file except in compliance
  45520. * with the License. You may obtain a copy of the License at
  45521. *
  45522. * http://www.apache.org/licenses/LICENSE-2.0
  45523. *
  45524. * Unless required by applicable law or agreed to in writing,
  45525. * software distributed under the License is distributed on an
  45526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45527. * KIND, either express or implied. See the License for the
  45528. * specific language governing permissions and limitations
  45529. * under the License.
  45530. */
  45531. MarkerModel.extend({
  45532. type: 'markLine',
  45533. defaultOption: {
  45534. zlevel: 0,
  45535. z: 5,
  45536. symbol: ['circle', 'arrow'],
  45537. symbolSize: [8, 16],
  45538. //symbolRotate: 0,
  45539. precision: 2,
  45540. tooltip: {
  45541. trigger: 'item'
  45542. },
  45543. label: {
  45544. show: true,
  45545. position: 'end'
  45546. },
  45547. lineStyle: {
  45548. type: 'dashed'
  45549. },
  45550. emphasis: {
  45551. label: {
  45552. show: true
  45553. },
  45554. lineStyle: {
  45555. width: 3
  45556. }
  45557. },
  45558. animationEasing: 'linear'
  45559. }
  45560. });
  45561. /*
  45562. * Licensed to the Apache Software Foundation (ASF) under one
  45563. * or more contributor license agreements. See the NOTICE file
  45564. * distributed with this work for additional information
  45565. * regarding copyright ownership. The ASF licenses this file
  45566. * to you under the Apache License, Version 2.0 (the
  45567. * "License"); you may not use this file except in compliance
  45568. * with the License. You may obtain a copy of the License at
  45569. *
  45570. * http://www.apache.org/licenses/LICENSE-2.0
  45571. *
  45572. * Unless required by applicable law or agreed to in writing,
  45573. * software distributed under the License is distributed on an
  45574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45575. * KIND, either express or implied. See the License for the
  45576. * specific language governing permissions and limitations
  45577. * under the License.
  45578. */
  45579. /**
  45580. * Line path for bezier and straight line draw
  45581. */
  45582. var straightLineProto = Line.prototype;
  45583. var bezierCurveProto = BezierCurve.prototype;
  45584. function isLine(shape) {
  45585. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  45586. }
  45587. var LinePath = extendShape({
  45588. type: 'ec-line',
  45589. style: {
  45590. stroke: '#000',
  45591. fill: null
  45592. },
  45593. shape: {
  45594. x1: 0,
  45595. y1: 0,
  45596. x2: 0,
  45597. y2: 0,
  45598. percent: 1,
  45599. cpx1: null,
  45600. cpy1: null
  45601. },
  45602. buildPath: function (ctx, shape) {
  45603. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  45604. },
  45605. _buildPathLine: straightLineProto.buildPath,
  45606. _buildPathCurve: bezierCurveProto.buildPath,
  45607. pointAt: function (t) {
  45608. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  45609. },
  45610. _pointAtLine: straightLineProto.pointAt,
  45611. _pointAtCurve: bezierCurveProto.pointAt,
  45612. tangentAt: function (t) {
  45613. var shape = this.shape;
  45614. var p = isLine(shape)
  45615. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  45616. : this._tangentAtCurve(t);
  45617. return normalize(p, p);
  45618. },
  45619. _tangentAtCurve: bezierCurveProto.tangentAt
  45620. });
  45621. /*
  45622. * Licensed to the Apache Software Foundation (ASF) under one
  45623. * or more contributor license agreements. See the NOTICE file
  45624. * distributed with this work for additional information
  45625. * regarding copyright ownership. The ASF licenses this file
  45626. * to you under the Apache License, Version 2.0 (the
  45627. * "License"); you may not use this file except in compliance
  45628. * with the License. You may obtain a copy of the License at
  45629. *
  45630. * http://www.apache.org/licenses/LICENSE-2.0
  45631. *
  45632. * Unless required by applicable law or agreed to in writing,
  45633. * software distributed under the License is distributed on an
  45634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45635. * KIND, either express or implied. See the License for the
  45636. * specific language governing permissions and limitations
  45637. * under the License.
  45638. */
  45639. /**
  45640. * @module echarts/chart/helper/Line
  45641. */
  45642. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  45643. function makeSymbolTypeKey(symbolCategory) {
  45644. return '_' + symbolCategory + 'Type';
  45645. }
  45646. /**
  45647. * @inner
  45648. */
  45649. function createSymbol$1(name, lineData, idx) {
  45650. var color = lineData.getItemVisual(idx, 'color');
  45651. var symbolType = lineData.getItemVisual(idx, name);
  45652. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  45653. if (!symbolType || symbolType === 'none') {
  45654. return;
  45655. }
  45656. if (!isArray(symbolSize)) {
  45657. symbolSize = [symbolSize, symbolSize];
  45658. }
  45659. var symbolPath = createSymbol(
  45660. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  45661. symbolSize[0], symbolSize[1], color
  45662. );
  45663. symbolPath.name = name;
  45664. return symbolPath;
  45665. }
  45666. function createLine(points) {
  45667. var line = new LinePath({
  45668. name: 'line',
  45669. subPixelOptimize: true
  45670. });
  45671. setLinePoints(line.shape, points);
  45672. return line;
  45673. }
  45674. function setLinePoints(targetShape, points) {
  45675. targetShape.x1 = points[0][0];
  45676. targetShape.y1 = points[0][1];
  45677. targetShape.x2 = points[1][0];
  45678. targetShape.y2 = points[1][1];
  45679. targetShape.percent = 1;
  45680. var cp1 = points[2];
  45681. if (cp1) {
  45682. targetShape.cpx1 = cp1[0];
  45683. targetShape.cpy1 = cp1[1];
  45684. }
  45685. else {
  45686. targetShape.cpx1 = NaN;
  45687. targetShape.cpy1 = NaN;
  45688. }
  45689. }
  45690. function updateSymbolAndLabelBeforeLineUpdate() {
  45691. var lineGroup = this;
  45692. var symbolFrom = lineGroup.childOfName('fromSymbol');
  45693. var symbolTo = lineGroup.childOfName('toSymbol');
  45694. var label = lineGroup.childOfName('label');
  45695. // Quick reject
  45696. if (!symbolFrom && !symbolTo && label.ignore) {
  45697. return;
  45698. }
  45699. var invScale = 1;
  45700. var parentNode = this.parent;
  45701. while (parentNode) {
  45702. if (parentNode.scale) {
  45703. invScale /= parentNode.scale[0];
  45704. }
  45705. parentNode = parentNode.parent;
  45706. }
  45707. var line = lineGroup.childOfName('line');
  45708. // If line not changed
  45709. // FIXME Parent scale changed
  45710. if (!this.__dirty && !line.__dirty) {
  45711. return;
  45712. }
  45713. var percent = line.shape.percent;
  45714. var fromPos = line.pointAt(0);
  45715. var toPos = line.pointAt(percent);
  45716. var d = sub([], toPos, fromPos);
  45717. normalize(d, d);
  45718. if (symbolFrom) {
  45719. symbolFrom.attr('position', fromPos);
  45720. var tangent = line.tangentAt(0);
  45721. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  45722. tangent[1], tangent[0]
  45723. ));
  45724. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  45725. }
  45726. if (symbolTo) {
  45727. symbolTo.attr('position', toPos);
  45728. var tangent = line.tangentAt(1);
  45729. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  45730. tangent[1], tangent[0]
  45731. ));
  45732. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  45733. }
  45734. if (!label.ignore) {
  45735. label.attr('position', toPos);
  45736. var textPosition;
  45737. var textAlign;
  45738. var textVerticalAlign;
  45739. var distance$$1 = 5 * invScale;
  45740. // End
  45741. if (label.__position === 'end') {
  45742. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  45743. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  45744. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  45745. }
  45746. // Middle
  45747. else if (label.__position === 'middle') {
  45748. var halfPercent = percent / 2;
  45749. var tangent = line.tangentAt(halfPercent);
  45750. var n = [tangent[1], -tangent[0]];
  45751. var cp = line.pointAt(halfPercent);
  45752. if (n[1] > 0) {
  45753. n[0] = -n[0];
  45754. n[1] = -n[1];
  45755. }
  45756. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  45757. textAlign = 'center';
  45758. textVerticalAlign = 'bottom';
  45759. var rotation = -Math.atan2(tangent[1], tangent[0]);
  45760. if (toPos[0] < fromPos[0]) {
  45761. rotation = Math.PI + rotation;
  45762. }
  45763. label.attr('rotation', rotation);
  45764. }
  45765. // Start
  45766. else {
  45767. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  45768. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  45769. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  45770. }
  45771. label.attr({
  45772. style: {
  45773. // Use the user specified text align and baseline first
  45774. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  45775. textAlign: label.__textAlign || textAlign
  45776. },
  45777. position: textPosition,
  45778. scale: [invScale, invScale]
  45779. });
  45780. }
  45781. }
  45782. /**
  45783. * @constructor
  45784. * @extends {module:zrender/graphic/Group}
  45785. * @alias {module:echarts/chart/helper/Line}
  45786. */
  45787. function Line$1(lineData, idx, seriesScope) {
  45788. Group.call(this);
  45789. this._createLine(lineData, idx, seriesScope);
  45790. }
  45791. var lineProto = Line$1.prototype;
  45792. // Update symbol position and rotation
  45793. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  45794. lineProto._createLine = function (lineData, idx, seriesScope) {
  45795. var seriesModel = lineData.hostModel;
  45796. var linePoints = lineData.getItemLayout(idx);
  45797. var line = createLine(linePoints);
  45798. line.shape.percent = 0;
  45799. initProps(line, {
  45800. shape: {
  45801. percent: 1
  45802. }
  45803. }, seriesModel, idx);
  45804. this.add(line);
  45805. var label = new Text({
  45806. name: 'label',
  45807. // FIXME
  45808. // Temporary solution for `focusNodeAdjacency`.
  45809. // line label do not use the opacity of lineStyle.
  45810. lineLabelOriginalOpacity: 1
  45811. });
  45812. this.add(label);
  45813. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45814. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  45815. // symbols must added after line to make sure
  45816. // it will be updated after line#update.
  45817. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  45818. this.add(symbol);
  45819. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  45820. }, this);
  45821. this._updateCommonStl(lineData, idx, seriesScope);
  45822. };
  45823. lineProto.updateData = function (lineData, idx, seriesScope) {
  45824. var seriesModel = lineData.hostModel;
  45825. var line = this.childOfName('line');
  45826. var linePoints = lineData.getItemLayout(idx);
  45827. var target = {
  45828. shape: {}
  45829. };
  45830. setLinePoints(target.shape, linePoints);
  45831. updateProps(line, target, seriesModel, idx);
  45832. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45833. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  45834. var key = makeSymbolTypeKey(symbolCategory);
  45835. // Symbol changed
  45836. if (this[key] !== symbolType) {
  45837. this.remove(this.childOfName(symbolCategory));
  45838. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  45839. this.add(symbol);
  45840. }
  45841. this[key] = symbolType;
  45842. }, this);
  45843. this._updateCommonStl(lineData, idx, seriesScope);
  45844. };
  45845. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  45846. var seriesModel = lineData.hostModel;
  45847. var line = this.childOfName('line');
  45848. var lineStyle = seriesScope && seriesScope.lineStyle;
  45849. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  45850. var labelModel = seriesScope && seriesScope.labelModel;
  45851. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  45852. // Optimization for large dataset
  45853. if (!seriesScope || lineData.hasItemOption) {
  45854. var itemModel = lineData.getItemModel(idx);
  45855. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  45856. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  45857. labelModel = itemModel.getModel('label');
  45858. hoverLabelModel = itemModel.getModel('emphasis.label');
  45859. }
  45860. var visualColor = lineData.getItemVisual(idx, 'color');
  45861. var visualOpacity = retrieve3(
  45862. lineData.getItemVisual(idx, 'opacity'),
  45863. lineStyle.opacity,
  45864. 1
  45865. );
  45866. line.useStyle(defaults(
  45867. {
  45868. strokeNoScale: true,
  45869. fill: 'none',
  45870. stroke: visualColor,
  45871. opacity: visualOpacity
  45872. },
  45873. lineStyle
  45874. ));
  45875. line.hoverStyle = hoverLineStyle;
  45876. // Update symbol
  45877. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  45878. var symbol = this.childOfName(symbolCategory);
  45879. if (symbol) {
  45880. symbol.setColor(visualColor);
  45881. symbol.setStyle({
  45882. opacity: visualOpacity
  45883. });
  45884. }
  45885. }, this);
  45886. var showLabel = labelModel.getShallow('show');
  45887. var hoverShowLabel = hoverLabelModel.getShallow('show');
  45888. var label = this.childOfName('label');
  45889. var defaultLabelColor;
  45890. var baseText;
  45891. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  45892. if (showLabel || hoverShowLabel) {
  45893. defaultLabelColor = visualColor || '#000';
  45894. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  45895. if (baseText == null) {
  45896. var rawVal = seriesModel.getRawValue(idx);
  45897. baseText = rawVal == null
  45898. ? lineData.getName(idx)
  45899. : isFinite(rawVal)
  45900. ? round$1(rawVal)
  45901. : rawVal;
  45902. }
  45903. }
  45904. var normalText = showLabel ? baseText : null;
  45905. var emphasisText = hoverShowLabel
  45906. ? retrieve2(
  45907. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  45908. baseText
  45909. )
  45910. : null;
  45911. var labelStyle = label.style;
  45912. // Always set `textStyle` even if `normalStyle.text` is null, because default
  45913. // values have to be set on `normalStyle`.
  45914. if (normalText != null || emphasisText != null) {
  45915. setTextStyle(label.style, labelModel, {
  45916. text: normalText
  45917. }, {
  45918. autoColor: defaultLabelColor
  45919. });
  45920. label.__textAlign = labelStyle.textAlign;
  45921. label.__verticalAlign = labelStyle.textVerticalAlign;
  45922. // 'start', 'middle', 'end'
  45923. label.__position = labelModel.get('position') || 'middle';
  45924. }
  45925. if (emphasisText != null) {
  45926. // Only these properties supported in this emphasis style here.
  45927. label.hoverStyle = {
  45928. text: emphasisText,
  45929. textFill: hoverLabelModel.getTextColor(true),
  45930. // For merging hover style to normal style, do not use
  45931. // `hoverLabelModel.getFont()` here.
  45932. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  45933. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  45934. fontSize: hoverLabelModel.getShallow('fontSize'),
  45935. fontFamily: hoverLabelModel.getShallow('fontFamily')
  45936. };
  45937. }
  45938. else {
  45939. label.hoverStyle = {
  45940. text: null
  45941. };
  45942. }
  45943. label.ignore = !showLabel && !hoverShowLabel;
  45944. setHoverStyle(this);
  45945. };
  45946. lineProto.highlight = function () {
  45947. this.trigger('emphasis');
  45948. };
  45949. lineProto.downplay = function () {
  45950. this.trigger('normal');
  45951. };
  45952. lineProto.updateLayout = function (lineData, idx) {
  45953. this.setLinePoints(lineData.getItemLayout(idx));
  45954. };
  45955. lineProto.setLinePoints = function (points) {
  45956. var linePath = this.childOfName('line');
  45957. setLinePoints(linePath.shape, points);
  45958. linePath.dirty();
  45959. };
  45960. inherits(Line$1, Group);
  45961. /*
  45962. * Licensed to the Apache Software Foundation (ASF) under one
  45963. * or more contributor license agreements. See the NOTICE file
  45964. * distributed with this work for additional information
  45965. * regarding copyright ownership. The ASF licenses this file
  45966. * to you under the Apache License, Version 2.0 (the
  45967. * "License"); you may not use this file except in compliance
  45968. * with the License. You may obtain a copy of the License at
  45969. *
  45970. * http://www.apache.org/licenses/LICENSE-2.0
  45971. *
  45972. * Unless required by applicable law or agreed to in writing,
  45973. * software distributed under the License is distributed on an
  45974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45975. * KIND, either express or implied. See the License for the
  45976. * specific language governing permissions and limitations
  45977. * under the License.
  45978. */
  45979. /**
  45980. * @module echarts/chart/helper/LineDraw
  45981. */
  45982. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  45983. /**
  45984. * @alias module:echarts/component/marker/LineDraw
  45985. * @constructor
  45986. */
  45987. function LineDraw(ctor) {
  45988. this._ctor = ctor || Line$1;
  45989. this.group = new Group();
  45990. }
  45991. var lineDrawProto = LineDraw.prototype;
  45992. lineDrawProto.isPersistent = function () {
  45993. return true;
  45994. };
  45995. /**
  45996. * @param {module:echarts/data/List} lineData
  45997. */
  45998. lineDrawProto.updateData = function (lineData) {
  45999. var lineDraw = this;
  46000. var group = lineDraw.group;
  46001. var oldLineData = lineDraw._lineData;
  46002. lineDraw._lineData = lineData;
  46003. // There is no oldLineData only when first rendering or switching from
  46004. // stream mode to normal mode, where previous elements should be removed.
  46005. if (!oldLineData) {
  46006. group.removeAll();
  46007. }
  46008. var seriesScope = makeSeriesScope$1(lineData);
  46009. lineData.diff(oldLineData)
  46010. .add(function (idx) {
  46011. doAdd(lineDraw, lineData, idx, seriesScope);
  46012. })
  46013. .update(function (newIdx, oldIdx) {
  46014. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  46015. })
  46016. .remove(function (idx) {
  46017. group.remove(oldLineData.getItemGraphicEl(idx));
  46018. })
  46019. .execute();
  46020. };
  46021. function doAdd(lineDraw, lineData, idx, seriesScope) {
  46022. var itemLayout = lineData.getItemLayout(idx);
  46023. if (!lineNeedsDraw(itemLayout)) {
  46024. return;
  46025. }
  46026. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  46027. lineData.setItemGraphicEl(idx, el);
  46028. lineDraw.group.add(el);
  46029. }
  46030. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  46031. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  46032. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  46033. lineDraw.group.remove(itemEl);
  46034. return;
  46035. }
  46036. if (!itemEl) {
  46037. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  46038. }
  46039. else {
  46040. itemEl.updateData(newLineData, newIdx, seriesScope);
  46041. }
  46042. newLineData.setItemGraphicEl(newIdx, itemEl);
  46043. lineDraw.group.add(itemEl);
  46044. }
  46045. lineDrawProto.updateLayout = function () {
  46046. var lineData = this._lineData;
  46047. // Do not support update layout in incremental mode.
  46048. if (!lineData) {
  46049. return;
  46050. }
  46051. lineData.eachItemGraphicEl(function (el, idx) {
  46052. el.updateLayout(lineData, idx);
  46053. }, this);
  46054. };
  46055. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  46056. this._seriesScope = makeSeriesScope$1(lineData);
  46057. this._lineData = null;
  46058. this.group.removeAll();
  46059. };
  46060. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  46061. function updateIncrementalAndHover(el) {
  46062. if (!el.isGroup) {
  46063. el.incremental = el.useHoverLayer = true;
  46064. }
  46065. }
  46066. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  46067. var itemLayout = lineData.getItemLayout(idx);
  46068. if (lineNeedsDraw(itemLayout)) {
  46069. var el = new this._ctor(lineData, idx, this._seriesScope);
  46070. el.traverse(updateIncrementalAndHover);
  46071. this.group.add(el);
  46072. lineData.setItemGraphicEl(idx, el);
  46073. }
  46074. }
  46075. };
  46076. function makeSeriesScope$1(lineData) {
  46077. var hostModel = lineData.hostModel;
  46078. return {
  46079. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  46080. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  46081. labelModel: hostModel.getModel('label'),
  46082. hoverLabelModel: hostModel.getModel('emphasis.label')
  46083. };
  46084. }
  46085. lineDrawProto.remove = function () {
  46086. this._clearIncremental();
  46087. this._incremental = null;
  46088. this.group.removeAll();
  46089. };
  46090. lineDrawProto._clearIncremental = function () {
  46091. var incremental = this._incremental;
  46092. if (incremental) {
  46093. incremental.clearDisplaybles();
  46094. }
  46095. };
  46096. function isPointNaN(pt) {
  46097. return isNaN(pt[0]) || isNaN(pt[1]);
  46098. }
  46099. function lineNeedsDraw(pts) {
  46100. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  46101. }
  46102. /*
  46103. * Licensed to the Apache Software Foundation (ASF) under one
  46104. * or more contributor license agreements. See the NOTICE file
  46105. * distributed with this work for additional information
  46106. * regarding copyright ownership. The ASF licenses this file
  46107. * to you under the Apache License, Version 2.0 (the
  46108. * "License"); you may not use this file except in compliance
  46109. * with the License. You may obtain a copy of the License at
  46110. *
  46111. * http://www.apache.org/licenses/LICENSE-2.0
  46112. *
  46113. * Unless required by applicable law or agreed to in writing,
  46114. * software distributed under the License is distributed on an
  46115. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46116. * KIND, either express or implied. See the License for the
  46117. * specific language governing permissions and limitations
  46118. * under the License.
  46119. */
  46120. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  46121. var data = seriesModel.getData();
  46122. // Special type markLine like 'min', 'max', 'average', 'median'
  46123. var mlType = item.type;
  46124. if (!isArray(item)
  46125. && (
  46126. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  46127. // In case
  46128. // data: [{
  46129. // yAxis: 10
  46130. // }]
  46131. || (item.xAxis != null || item.yAxis != null)
  46132. )
  46133. ) {
  46134. var valueAxis;
  46135. var value;
  46136. if (item.yAxis != null || item.xAxis != null) {
  46137. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  46138. value = retrieve(item.yAxis, item.xAxis);
  46139. }
  46140. else {
  46141. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  46142. valueAxis = axisInfo.valueAxis;
  46143. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  46144. value = numCalculate(data, valueDataDim, mlType);
  46145. }
  46146. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  46147. var baseIndex = 1 - valueIndex;
  46148. var mlFrom = clone(item);
  46149. var mlTo = {};
  46150. mlFrom.type = null;
  46151. mlFrom.coord = [];
  46152. mlTo.coord = [];
  46153. mlFrom.coord[baseIndex] = -Infinity;
  46154. mlTo.coord[baseIndex] = Infinity;
  46155. var precision = mlModel.get('precision');
  46156. if (precision >= 0 && typeof value === 'number') {
  46157. value = +value.toFixed(Math.min(precision, 20));
  46158. }
  46159. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  46160. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  46161. type: mlType,
  46162. valueIndex: item.valueIndex,
  46163. // Force to use the value of calculated value.
  46164. value: value
  46165. }];
  46166. }
  46167. item = [
  46168. dataTransform(seriesModel, item[0]),
  46169. dataTransform(seriesModel, item[1]),
  46170. extend({}, item[2])
  46171. ];
  46172. // Avoid line data type is extended by from(to) data type
  46173. item[2].type = item[2].type || '';
  46174. // Merge from option and to option into line option
  46175. merge(item[2], item[0]);
  46176. merge(item[2], item[1]);
  46177. return item;
  46178. };
  46179. function isInifinity(val) {
  46180. return !isNaN(val) && !isFinite(val);
  46181. }
  46182. // If a markLine has one dim
  46183. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  46184. var otherDimIndex = 1 - dimIndex;
  46185. var dimName = coordSys.dimensions[dimIndex];
  46186. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  46187. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  46188. }
  46189. function markLineFilter(coordSys, item) {
  46190. if (coordSys.type === 'cartesian2d') {
  46191. var fromCoord = item[0].coord;
  46192. var toCoord = item[1].coord;
  46193. // In case
  46194. // {
  46195. // markLine: {
  46196. // data: [{ yAxis: 2 }]
  46197. // }
  46198. // }
  46199. if (
  46200. fromCoord && toCoord
  46201. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  46202. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  46203. ) {
  46204. return true;
  46205. }
  46206. }
  46207. return dataFilter$1(coordSys, item[0])
  46208. && dataFilter$1(coordSys, item[1]);
  46209. }
  46210. function updateSingleMarkerEndLayout(
  46211. data, idx, isFrom, seriesModel, api
  46212. ) {
  46213. var coordSys = seriesModel.coordinateSystem;
  46214. var itemModel = data.getItemModel(idx);
  46215. var point;
  46216. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  46217. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  46218. if (!isNaN(xPx) && !isNaN(yPx)) {
  46219. point = [xPx, yPx];
  46220. }
  46221. else {
  46222. // Chart like bar may have there own marker positioning logic
  46223. if (seriesModel.getMarkerPosition) {
  46224. // Use the getMarkerPoisition
  46225. point = seriesModel.getMarkerPosition(
  46226. data.getValues(data.dimensions, idx)
  46227. );
  46228. }
  46229. else {
  46230. var dims = coordSys.dimensions;
  46231. var x = data.get(dims[0], idx);
  46232. var y = data.get(dims[1], idx);
  46233. point = coordSys.dataToPoint([x, y]);
  46234. }
  46235. // Expand line to the edge of grid if value on one axis is Inifnity
  46236. // In case
  46237. // markLine: {
  46238. // data: [{
  46239. // yAxis: 2
  46240. // // or
  46241. // type: 'average'
  46242. // }]
  46243. // }
  46244. if (coordSys.type === 'cartesian2d') {
  46245. var xAxis = coordSys.getAxis('x');
  46246. var yAxis = coordSys.getAxis('y');
  46247. var dims = coordSys.dimensions;
  46248. if (isInifinity(data.get(dims[0], idx))) {
  46249. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  46250. }
  46251. else if (isInifinity(data.get(dims[1], idx))) {
  46252. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  46253. }
  46254. }
  46255. // Use x, y if has any
  46256. if (!isNaN(xPx)) {
  46257. point[0] = xPx;
  46258. }
  46259. if (!isNaN(yPx)) {
  46260. point[1] = yPx;
  46261. }
  46262. }
  46263. data.setItemLayout(idx, point);
  46264. }
  46265. MarkerView.extend({
  46266. type: 'markLine',
  46267. // updateLayout: function (markLineModel, ecModel, api) {
  46268. // ecModel.eachSeries(function (seriesModel) {
  46269. // var mlModel = seriesModel.markLineModel;
  46270. // if (mlModel) {
  46271. // var mlData = mlModel.getData();
  46272. // var fromData = mlModel.__from;
  46273. // var toData = mlModel.__to;
  46274. // // Update visual and layout of from symbol and to symbol
  46275. // fromData.each(function (idx) {
  46276. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46277. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46278. // });
  46279. // // Update layout of line
  46280. // mlData.each(function (idx) {
  46281. // mlData.setItemLayout(idx, [
  46282. // fromData.getItemLayout(idx),
  46283. // toData.getItemLayout(idx)
  46284. // ]);
  46285. // });
  46286. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  46287. // }
  46288. // }, this);
  46289. // },
  46290. updateTransform: function (markLineModel, ecModel, api) {
  46291. ecModel.eachSeries(function (seriesModel) {
  46292. var mlModel = seriesModel.markLineModel;
  46293. if (mlModel) {
  46294. var mlData = mlModel.getData();
  46295. var fromData = mlModel.__from;
  46296. var toData = mlModel.__to;
  46297. // Update visual and layout of from symbol and to symbol
  46298. fromData.each(function (idx) {
  46299. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46300. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46301. });
  46302. // Update layout of line
  46303. mlData.each(function (idx) {
  46304. mlData.setItemLayout(idx, [
  46305. fromData.getItemLayout(idx),
  46306. toData.getItemLayout(idx)
  46307. ]);
  46308. });
  46309. this.markerGroupMap.get(seriesModel.id).updateLayout();
  46310. }
  46311. }, this);
  46312. },
  46313. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  46314. var coordSys = seriesModel.coordinateSystem;
  46315. var seriesId = seriesModel.id;
  46316. var seriesData = seriesModel.getData();
  46317. var lineDrawMap = this.markerGroupMap;
  46318. var lineDraw = lineDrawMap.get(seriesId)
  46319. || lineDrawMap.set(seriesId, new LineDraw());
  46320. this.group.add(lineDraw.group);
  46321. var mlData = createList$2(coordSys, seriesModel, mlModel);
  46322. var fromData = mlData.from;
  46323. var toData = mlData.to;
  46324. var lineData = mlData.line;
  46325. mlModel.__from = fromData;
  46326. mlModel.__to = toData;
  46327. // Line data for tooltip and formatter
  46328. mlModel.setData(lineData);
  46329. var symbolType = mlModel.get('symbol');
  46330. var symbolSize = mlModel.get('symbolSize');
  46331. if (!isArray(symbolType)) {
  46332. symbolType = [symbolType, symbolType];
  46333. }
  46334. if (typeof symbolSize === 'number') {
  46335. symbolSize = [symbolSize, symbolSize];
  46336. }
  46337. // Update visual and layout of from symbol and to symbol
  46338. mlData.from.each(function (idx) {
  46339. updateDataVisualAndLayout(fromData, idx, true);
  46340. updateDataVisualAndLayout(toData, idx, false);
  46341. });
  46342. // Update visual and layout of line
  46343. lineData.each(function (idx) {
  46344. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  46345. lineData.setItemVisual(idx, {
  46346. color: lineColor || fromData.getItemVisual(idx, 'color')
  46347. });
  46348. lineData.setItemLayout(idx, [
  46349. fromData.getItemLayout(idx),
  46350. toData.getItemLayout(idx)
  46351. ]);
  46352. lineData.setItemVisual(idx, {
  46353. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  46354. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  46355. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  46356. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  46357. });
  46358. });
  46359. lineDraw.updateData(lineData);
  46360. // Set host model for tooltip
  46361. // FIXME
  46362. mlData.line.eachItemGraphicEl(function (el, idx) {
  46363. el.traverse(function (child) {
  46364. child.dataModel = mlModel;
  46365. });
  46366. });
  46367. function updateDataVisualAndLayout(data, idx, isFrom) {
  46368. var itemModel = data.getItemModel(idx);
  46369. updateSingleMarkerEndLayout(
  46370. data, idx, isFrom, seriesModel, api
  46371. );
  46372. data.setItemVisual(idx, {
  46373. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  46374. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  46375. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  46376. });
  46377. }
  46378. lineDraw.__keep = true;
  46379. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  46380. }
  46381. });
  46382. /**
  46383. * @inner
  46384. * @param {module:echarts/coord/*} coordSys
  46385. * @param {module:echarts/model/Series} seriesModel
  46386. * @param {module:echarts/model/Model} mpModel
  46387. */
  46388. function createList$2(coordSys, seriesModel, mlModel) {
  46389. var coordDimsInfos;
  46390. if (coordSys) {
  46391. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46392. var info = seriesModel.getData().getDimensionInfo(
  46393. seriesModel.getData().mapDimension(coordDim)
  46394. ) || {};
  46395. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46396. return defaults({name: coordDim}, info);
  46397. });
  46398. }
  46399. else {
  46400. coordDimsInfos = [{
  46401. name: 'value',
  46402. type: 'float'
  46403. }];
  46404. }
  46405. var fromData = new List(coordDimsInfos, mlModel);
  46406. var toData = new List(coordDimsInfos, mlModel);
  46407. // No dimensions
  46408. var lineData = new List([], mlModel);
  46409. var optData = map(mlModel.get('data'), curry(
  46410. markLineTransform, seriesModel, coordSys, mlModel
  46411. ));
  46412. if (coordSys) {
  46413. optData = filter(
  46414. optData, curry(markLineFilter, coordSys)
  46415. );
  46416. }
  46417. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  46418. return item.value;
  46419. };
  46420. fromData.initData(
  46421. map(optData, function (item) {
  46422. return item[0];
  46423. }),
  46424. null,
  46425. dimValueGetter$$1
  46426. );
  46427. toData.initData(
  46428. map(optData, function (item) {
  46429. return item[1];
  46430. }),
  46431. null,
  46432. dimValueGetter$$1
  46433. );
  46434. lineData.initData(
  46435. map(optData, function (item) {
  46436. return item[2];
  46437. })
  46438. );
  46439. lineData.hasItemOption = true;
  46440. return {
  46441. from: fromData,
  46442. to: toData,
  46443. line: lineData
  46444. };
  46445. }
  46446. /*
  46447. * Licensed to the Apache Software Foundation (ASF) under one
  46448. * or more contributor license agreements. See the NOTICE file
  46449. * distributed with this work for additional information
  46450. * regarding copyright ownership. The ASF licenses this file
  46451. * to you under the Apache License, Version 2.0 (the
  46452. * "License"); you may not use this file except in compliance
  46453. * with the License. You may obtain a copy of the License at
  46454. *
  46455. * http://www.apache.org/licenses/LICENSE-2.0
  46456. *
  46457. * Unless required by applicable law or agreed to in writing,
  46458. * software distributed under the License is distributed on an
  46459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46460. * KIND, either express or implied. See the License for the
  46461. * specific language governing permissions and limitations
  46462. * under the License.
  46463. */
  46464. registerPreprocessor(function (opt) {
  46465. // Make sure markLine component is enabled
  46466. opt.markLine = opt.markLine || {};
  46467. });
  46468. /*
  46469. * Licensed to the Apache Software Foundation (ASF) under one
  46470. * or more contributor license agreements. See the NOTICE file
  46471. * distributed with this work for additional information
  46472. * regarding copyright ownership. The ASF licenses this file
  46473. * to you under the Apache License, Version 2.0 (the
  46474. * "License"); you may not use this file except in compliance
  46475. * with the License. You may obtain a copy of the License at
  46476. *
  46477. * http://www.apache.org/licenses/LICENSE-2.0
  46478. *
  46479. * Unless required by applicable law or agreed to in writing,
  46480. * software distributed under the License is distributed on an
  46481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46482. * KIND, either express or implied. See the License for the
  46483. * specific language governing permissions and limitations
  46484. * under the License.
  46485. */
  46486. MarkerModel.extend({
  46487. type: 'markArea',
  46488. defaultOption: {
  46489. zlevel: 0,
  46490. // PENDING
  46491. z: 1,
  46492. tooltip: {
  46493. trigger: 'item'
  46494. },
  46495. // markArea should fixed on the coordinate system
  46496. animation: false,
  46497. label: {
  46498. show: true,
  46499. position: 'top'
  46500. },
  46501. itemStyle: {
  46502. // color and borderColor default to use color from series
  46503. // color: 'auto'
  46504. // borderColor: 'auto'
  46505. borderWidth: 0
  46506. },
  46507. emphasis: {
  46508. label: {
  46509. show: true,
  46510. position: 'top'
  46511. }
  46512. }
  46513. }
  46514. });
  46515. /*
  46516. * Licensed to the Apache Software Foundation (ASF) under one
  46517. * or more contributor license agreements. See the NOTICE file
  46518. * distributed with this work for additional information
  46519. * regarding copyright ownership. The ASF licenses this file
  46520. * to you under the Apache License, Version 2.0 (the
  46521. * "License"); you may not use this file except in compliance
  46522. * with the License. You may obtain a copy of the License at
  46523. *
  46524. * http://www.apache.org/licenses/LICENSE-2.0
  46525. *
  46526. * Unless required by applicable law or agreed to in writing,
  46527. * software distributed under the License is distributed on an
  46528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46529. * KIND, either express or implied. See the License for the
  46530. * specific language governing permissions and limitations
  46531. * under the License.
  46532. */
  46533. // TODO Better on polar
  46534. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  46535. var lt = dataTransform(seriesModel, item[0]);
  46536. var rb = dataTransform(seriesModel, item[1]);
  46537. var retrieve$$1 = retrieve;
  46538. // FIXME make sure lt is less than rb
  46539. var ltCoord = lt.coord;
  46540. var rbCoord = rb.coord;
  46541. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  46542. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  46543. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  46544. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  46545. // Merge option into one
  46546. var result = mergeAll([{}, lt, rb]);
  46547. result.coord = [
  46548. lt.coord, rb.coord
  46549. ];
  46550. result.x0 = lt.x;
  46551. result.y0 = lt.y;
  46552. result.x1 = rb.x;
  46553. result.y1 = rb.y;
  46554. return result;
  46555. };
  46556. function isInifinity$1(val) {
  46557. return !isNaN(val) && !isFinite(val);
  46558. }
  46559. // If a markArea has one dim
  46560. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  46561. var otherDimIndex = 1 - dimIndex;
  46562. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  46563. }
  46564. function markAreaFilter(coordSys, item) {
  46565. var fromCoord = item.coord[0];
  46566. var toCoord = item.coord[1];
  46567. if (coordSys.type === 'cartesian2d') {
  46568. // In case
  46569. // {
  46570. // markArea: {
  46571. // data: [{ yAxis: 2 }]
  46572. // }
  46573. // }
  46574. if (
  46575. fromCoord && toCoord
  46576. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  46577. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  46578. ) {
  46579. return true;
  46580. }
  46581. }
  46582. return dataFilter$1(coordSys, {
  46583. coord: fromCoord,
  46584. x: item.x0,
  46585. y: item.y0
  46586. })
  46587. || dataFilter$1(coordSys, {
  46588. coord: toCoord,
  46589. x: item.x1,
  46590. y: item.y1
  46591. });
  46592. }
  46593. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  46594. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  46595. var coordSys = seriesModel.coordinateSystem;
  46596. var itemModel = data.getItemModel(idx);
  46597. var point;
  46598. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  46599. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  46600. if (!isNaN(xPx) && !isNaN(yPx)) {
  46601. point = [xPx, yPx];
  46602. }
  46603. else {
  46604. // Chart like bar may have there own marker positioning logic
  46605. if (seriesModel.getMarkerPosition) {
  46606. // Use the getMarkerPoisition
  46607. point = seriesModel.getMarkerPosition(
  46608. data.getValues(dims, idx)
  46609. );
  46610. }
  46611. else {
  46612. var x = data.get(dims[0], idx);
  46613. var y = data.get(dims[1], idx);
  46614. var pt = [x, y];
  46615. coordSys.clampData && coordSys.clampData(pt, pt);
  46616. point = coordSys.dataToPoint(pt, true);
  46617. }
  46618. if (coordSys.type === 'cartesian2d') {
  46619. var xAxis = coordSys.getAxis('x');
  46620. var yAxis = coordSys.getAxis('y');
  46621. var x = data.get(dims[0], idx);
  46622. var y = data.get(dims[1], idx);
  46623. if (isInifinity$1(x)) {
  46624. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  46625. }
  46626. else if (isInifinity$1(y)) {
  46627. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  46628. }
  46629. }
  46630. // Use x, y if has any
  46631. if (!isNaN(xPx)) {
  46632. point[0] = xPx;
  46633. }
  46634. if (!isNaN(yPx)) {
  46635. point[1] = yPx;
  46636. }
  46637. }
  46638. return point;
  46639. }
  46640. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  46641. MarkerView.extend({
  46642. type: 'markArea',
  46643. // updateLayout: function (markAreaModel, ecModel, api) {
  46644. // ecModel.eachSeries(function (seriesModel) {
  46645. // var maModel = seriesModel.markAreaModel;
  46646. // if (maModel) {
  46647. // var areaData = maModel.getData();
  46648. // areaData.each(function (idx) {
  46649. // var points = zrUtil.map(dimPermutations, function (dim) {
  46650. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46651. // });
  46652. // // Layout
  46653. // areaData.setItemLayout(idx, points);
  46654. // var el = areaData.getItemGraphicEl(idx);
  46655. // el.setShape('points', points);
  46656. // });
  46657. // }
  46658. // }, this);
  46659. // },
  46660. updateTransform: function (markAreaModel, ecModel, api) {
  46661. ecModel.eachSeries(function (seriesModel) {
  46662. var maModel = seriesModel.markAreaModel;
  46663. if (maModel) {
  46664. var areaData = maModel.getData();
  46665. areaData.each(function (idx) {
  46666. var points = map(dimPermutations, function (dim) {
  46667. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46668. });
  46669. // Layout
  46670. areaData.setItemLayout(idx, points);
  46671. var el = areaData.getItemGraphicEl(idx);
  46672. el.setShape('points', points);
  46673. });
  46674. }
  46675. }, this);
  46676. },
  46677. renderSeries: function (seriesModel, maModel, ecModel, api) {
  46678. var coordSys = seriesModel.coordinateSystem;
  46679. var seriesId = seriesModel.id;
  46680. var seriesData = seriesModel.getData();
  46681. var areaGroupMap = this.markerGroupMap;
  46682. var polygonGroup = areaGroupMap.get(seriesId)
  46683. || areaGroupMap.set(seriesId, {group: new Group()});
  46684. this.group.add(polygonGroup.group);
  46685. polygonGroup.__keep = true;
  46686. var areaData = createList$3(coordSys, seriesModel, maModel);
  46687. // Line data for tooltip and formatter
  46688. maModel.setData(areaData);
  46689. // Update visual and layout of line
  46690. areaData.each(function (idx) {
  46691. // Layout
  46692. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  46693. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  46694. }));
  46695. // Visual
  46696. areaData.setItemVisual(idx, {
  46697. color: seriesData.getVisual('color')
  46698. });
  46699. });
  46700. areaData.diff(polygonGroup.__data)
  46701. .add(function (idx) {
  46702. var polygon = new Polygon({
  46703. shape: {
  46704. points: areaData.getItemLayout(idx)
  46705. }
  46706. });
  46707. areaData.setItemGraphicEl(idx, polygon);
  46708. polygonGroup.group.add(polygon);
  46709. })
  46710. .update(function (newIdx, oldIdx) {
  46711. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  46712. updateProps(polygon, {
  46713. shape: {
  46714. points: areaData.getItemLayout(newIdx)
  46715. }
  46716. }, maModel, newIdx);
  46717. polygonGroup.group.add(polygon);
  46718. areaData.setItemGraphicEl(newIdx, polygon);
  46719. })
  46720. .remove(function (idx) {
  46721. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  46722. polygonGroup.group.remove(polygon);
  46723. })
  46724. .execute();
  46725. areaData.eachItemGraphicEl(function (polygon, idx) {
  46726. var itemModel = areaData.getItemModel(idx);
  46727. var labelModel = itemModel.getModel('label');
  46728. var labelHoverModel = itemModel.getModel('emphasis.label');
  46729. var color = areaData.getItemVisual(idx, 'color');
  46730. polygon.useStyle(
  46731. defaults(
  46732. itemModel.getModel('itemStyle').getItemStyle(),
  46733. {
  46734. fill: modifyAlpha(color, 0.4),
  46735. stroke: color
  46736. }
  46737. )
  46738. );
  46739. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  46740. setLabelStyle(
  46741. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  46742. {
  46743. labelFetcher: maModel,
  46744. labelDataIndex: idx,
  46745. defaultText: areaData.getName(idx) || '',
  46746. isRectText: true,
  46747. autoColor: color
  46748. }
  46749. );
  46750. setHoverStyle(polygon, {});
  46751. polygon.dataModel = maModel;
  46752. });
  46753. polygonGroup.__data = areaData;
  46754. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  46755. }
  46756. });
  46757. /**
  46758. * @inner
  46759. * @param {module:echarts/coord/*} coordSys
  46760. * @param {module:echarts/model/Series} seriesModel
  46761. * @param {module:echarts/model/Model} mpModel
  46762. */
  46763. function createList$3(coordSys, seriesModel, maModel) {
  46764. var coordDimsInfos;
  46765. var areaData;
  46766. var dims = ['x0', 'y0', 'x1', 'y1'];
  46767. if (coordSys) {
  46768. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46769. var data = seriesModel.getData();
  46770. var info = data.getDimensionInfo(
  46771. data.mapDimension(coordDim)
  46772. ) || {};
  46773. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46774. return defaults({name: coordDim}, info);
  46775. });
  46776. areaData = new List(map(dims, function (dim, idx) {
  46777. return {
  46778. name: dim,
  46779. type: coordDimsInfos[idx % 2].type
  46780. };
  46781. }), maModel);
  46782. }
  46783. else {
  46784. coordDimsInfos = [{
  46785. name: 'value',
  46786. type: 'float'
  46787. }];
  46788. areaData = new List(coordDimsInfos, maModel);
  46789. }
  46790. var optData = map(maModel.get('data'), curry(
  46791. markAreaTransform, seriesModel, coordSys, maModel
  46792. ));
  46793. if (coordSys) {
  46794. optData = filter(
  46795. optData, curry(markAreaFilter, coordSys)
  46796. );
  46797. }
  46798. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  46799. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  46800. } : function (item) {
  46801. return item.value;
  46802. };
  46803. areaData.initData(optData, null, dimValueGetter$$1);
  46804. areaData.hasItemOption = true;
  46805. return areaData;
  46806. }
  46807. /*
  46808. * Licensed to the Apache Software Foundation (ASF) under one
  46809. * or more contributor license agreements. See the NOTICE file
  46810. * distributed with this work for additional information
  46811. * regarding copyright ownership. The ASF licenses this file
  46812. * to you under the Apache License, Version 2.0 (the
  46813. * "License"); you may not use this file except in compliance
  46814. * with the License. You may obtain a copy of the License at
  46815. *
  46816. * http://www.apache.org/licenses/LICENSE-2.0
  46817. *
  46818. * Unless required by applicable law or agreed to in writing,
  46819. * software distributed under the License is distributed on an
  46820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46821. * KIND, either express or implied. See the License for the
  46822. * specific language governing permissions and limitations
  46823. * under the License.
  46824. */
  46825. registerPreprocessor(function (opt) {
  46826. // Make sure markArea component is enabled
  46827. opt.markArea = opt.markArea || {};
  46828. });
  46829. /*
  46830. * Licensed to the Apache Software Foundation (ASF) under one
  46831. * or more contributor license agreements. See the NOTICE file
  46832. * distributed with this work for additional information
  46833. * regarding copyright ownership. The ASF licenses this file
  46834. * to you under the Apache License, Version 2.0 (the
  46835. * "License"); you may not use this file except in compliance
  46836. * with the License. You may obtain a copy of the License at
  46837. *
  46838. * http://www.apache.org/licenses/LICENSE-2.0
  46839. *
  46840. * Unless required by applicable law or agreed to in writing,
  46841. * software distributed under the License is distributed on an
  46842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46843. * KIND, either express or implied. See the License for the
  46844. * specific language governing permissions and limitations
  46845. * under the License.
  46846. */
  46847. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  46848. // Default 'slider' when no type specified.
  46849. return 'slider';
  46850. });
  46851. /*
  46852. * Licensed to the Apache Software Foundation (ASF) under one
  46853. * or more contributor license agreements. See the NOTICE file
  46854. * distributed with this work for additional information
  46855. * regarding copyright ownership. The ASF licenses this file
  46856. * to you under the Apache License, Version 2.0 (the
  46857. * "License"); you may not use this file except in compliance
  46858. * with the License. You may obtain a copy of the License at
  46859. *
  46860. * http://www.apache.org/licenses/LICENSE-2.0
  46861. *
  46862. * Unless required by applicable law or agreed to in writing,
  46863. * software distributed under the License is distributed on an
  46864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46865. * KIND, either express or implied. See the License for the
  46866. * specific language governing permissions and limitations
  46867. * under the License.
  46868. */
  46869. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  46870. // Supported coords.
  46871. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  46872. /**
  46873. * @param {string} coordType
  46874. * @return {boolean}
  46875. */
  46876. function isCoordSupported(coordType) {
  46877. return indexOf(COORDS, coordType) >= 0;
  46878. }
  46879. /**
  46880. * Create "each" method to iterate names.
  46881. *
  46882. * @pubilc
  46883. * @param {Array.<string>} names
  46884. * @param {Array.<string>=} attrs
  46885. * @return {Function}
  46886. */
  46887. function createNameEach(names, attrs) {
  46888. names = names.slice();
  46889. var capitalNames = map(names, capitalFirst);
  46890. attrs = (attrs || []).slice();
  46891. var capitalAttrs = map(attrs, capitalFirst);
  46892. return function (callback, context) {
  46893. each$1(names, function (name, index) {
  46894. var nameObj = {name: name, capital: capitalNames[index]};
  46895. for (var j = 0; j < attrs.length; j++) {
  46896. nameObj[attrs[j]] = name + capitalAttrs[j];
  46897. }
  46898. callback.call(context, nameObj);
  46899. });
  46900. };
  46901. }
  46902. /**
  46903. * Iterate each dimension name.
  46904. *
  46905. * @public
  46906. * @param {Function} callback The parameter is like:
  46907. * {
  46908. * name: 'angle',
  46909. * capital: 'Angle',
  46910. * axis: 'angleAxis',
  46911. * axisIndex: 'angleAixs',
  46912. * index: 'angleIndex'
  46913. * }
  46914. * @param {Object} context
  46915. */
  46916. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  46917. /**
  46918. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  46919. * dataZoomModels and 'links' make up one or more graphics.
  46920. * This function finds the graphic where the source dataZoomModel is in.
  46921. *
  46922. * @public
  46923. * @param {Function} forEachNode Node iterator.
  46924. * @param {Function} forEachEdgeType edgeType iterator
  46925. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  46926. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  46927. */
  46928. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  46929. return function (sourceNode) {
  46930. var result = {
  46931. nodes: [],
  46932. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  46933. };
  46934. forEachEdgeType(function (edgeType) {
  46935. result.records[edgeType.name] = {};
  46936. });
  46937. if (!sourceNode) {
  46938. return result;
  46939. }
  46940. absorb(sourceNode, result);
  46941. var existsLink;
  46942. do {
  46943. existsLink = false;
  46944. forEachNode(processSingleNode);
  46945. }
  46946. while (existsLink);
  46947. function processSingleNode(node) {
  46948. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  46949. absorb(node, result);
  46950. existsLink = true;
  46951. }
  46952. }
  46953. return result;
  46954. };
  46955. function isNodeAbsorded(node, result) {
  46956. return indexOf(result.nodes, node) >= 0;
  46957. }
  46958. function isLinked(node, result) {
  46959. var hasLink = false;
  46960. forEachEdgeType(function (edgeType) {
  46961. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  46962. result.records[edgeType.name][edgeId] && (hasLink = true);
  46963. });
  46964. });
  46965. return hasLink;
  46966. }
  46967. function absorb(node, result) {
  46968. result.nodes.push(node);
  46969. forEachEdgeType(function (edgeType) {
  46970. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  46971. result.records[edgeType.name][edgeId] = true;
  46972. });
  46973. });
  46974. }
  46975. }
  46976. /*
  46977. * Licensed to the Apache Software Foundation (ASF) under one
  46978. * or more contributor license agreements. See the NOTICE file
  46979. * distributed with this work for additional information
  46980. * regarding copyright ownership. The ASF licenses this file
  46981. * to you under the Apache License, Version 2.0 (the
  46982. * "License"); you may not use this file except in compliance
  46983. * with the License. You may obtain a copy of the License at
  46984. *
  46985. * http://www.apache.org/licenses/LICENSE-2.0
  46986. *
  46987. * Unless required by applicable law or agreed to in writing,
  46988. * software distributed under the License is distributed on an
  46989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46990. * KIND, either express or implied. See the License for the
  46991. * specific language governing permissions and limitations
  46992. * under the License.
  46993. */
  46994. /**
  46995. * Calculate slider move result.
  46996. * Usage:
  46997. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  46998. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  46999. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47000. *
  47001. * @param {number} delta Move length.
  47002. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47003. * handleEnds will be modified in this method.
  47004. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47005. * extent[0] should less or equals than extent[1].
  47006. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  47007. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47008. * If not set, handle0 and cross handle1. If set as a non-negative
  47009. * number (including `0`), handles will push each other when reaching
  47010. * the minSpan.
  47011. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47012. * @return {Array.<number>} The input handleEnds.
  47013. */
  47014. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47015. delta = delta || 0;
  47016. var extentSpan = extent[1] - extent[0];
  47017. // Notice maxSpan and minSpan can be null/undefined.
  47018. if (minSpan != null) {
  47019. minSpan = restrict(minSpan, [0, extentSpan]);
  47020. }
  47021. if (maxSpan != null) {
  47022. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47023. }
  47024. if (handleIndex === 'all') {
  47025. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47026. handleSpan = restrict(handleSpan, [0, extentSpan]);
  47027. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  47028. handleIndex = 0;
  47029. }
  47030. handleEnds[0] = restrict(handleEnds[0], extent);
  47031. handleEnds[1] = restrict(handleEnds[1], extent);
  47032. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47033. handleEnds[handleIndex] += delta;
  47034. // Restrict in extent.
  47035. var extentMinSpan = minSpan || 0;
  47036. var realExtent = extent.slice();
  47037. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47038. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  47039. // Expand span.
  47040. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47041. if (minSpan != null && (
  47042. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47043. )) {
  47044. // If minSpan exists, 'cross' is forbidden.
  47045. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47046. }
  47047. // Shrink span.
  47048. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47049. if (maxSpan != null && currDistSign.span > maxSpan) {
  47050. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47051. }
  47052. return handleEnds;
  47053. };
  47054. function getSpanSign(handleEnds, handleIndex) {
  47055. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47056. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47057. // is at left of handleEnds[1] for non-cross case.
  47058. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47059. }
  47060. function restrict(value, extend) {
  47061. return Math.min(
  47062. extend[1] != null ? extend[1] : Infinity,
  47063. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  47064. );
  47065. }
  47066. /*
  47067. * Licensed to the Apache Software Foundation (ASF) under one
  47068. * or more contributor license agreements. See the NOTICE file
  47069. * distributed with this work for additional information
  47070. * regarding copyright ownership. The ASF licenses this file
  47071. * to you under the Apache License, Version 2.0 (the
  47072. * "License"); you may not use this file except in compliance
  47073. * with the License. You may obtain a copy of the License at
  47074. *
  47075. * http://www.apache.org/licenses/LICENSE-2.0
  47076. *
  47077. * Unless required by applicable law or agreed to in writing,
  47078. * software distributed under the License is distributed on an
  47079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47080. * KIND, either express or implied. See the License for the
  47081. * specific language governing permissions and limitations
  47082. * under the License.
  47083. */
  47084. var each$13 = each$1;
  47085. var asc$1 = asc;
  47086. /**
  47087. * Operate single axis.
  47088. * One axis can only operated by one axis operator.
  47089. * Different dataZoomModels may be defined to operate the same axis.
  47090. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  47091. * So dataZoomModels share one axisProxy in that case.
  47092. *
  47093. * @class
  47094. */
  47095. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  47096. /**
  47097. * @private
  47098. * @type {string}
  47099. */
  47100. this._dimName = dimName;
  47101. /**
  47102. * @private
  47103. */
  47104. this._axisIndex = axisIndex;
  47105. /**
  47106. * @private
  47107. * @type {Array.<number>}
  47108. */
  47109. this._valueWindow;
  47110. /**
  47111. * @private
  47112. * @type {Array.<number>}
  47113. */
  47114. this._percentWindow;
  47115. /**
  47116. * @private
  47117. * @type {Array.<number>}
  47118. */
  47119. this._dataExtent;
  47120. /**
  47121. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  47122. * @private
  47123. * @type {Object}
  47124. */
  47125. this._minMaxSpan;
  47126. /**
  47127. * @readOnly
  47128. * @type {module: echarts/model/Global}
  47129. */
  47130. this.ecModel = ecModel;
  47131. /**
  47132. * @private
  47133. * @type {module: echarts/component/dataZoom/DataZoomModel}
  47134. */
  47135. this._dataZoomModel = dataZoomModel;
  47136. // /**
  47137. // * @readOnly
  47138. // * @private
  47139. // */
  47140. // this.hasSeriesStacked;
  47141. };
  47142. AxisProxy.prototype = {
  47143. constructor: AxisProxy,
  47144. /**
  47145. * Whether the axisProxy is hosted by dataZoomModel.
  47146. *
  47147. * @public
  47148. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47149. * @return {boolean}
  47150. */
  47151. hostedBy: function (dataZoomModel) {
  47152. return this._dataZoomModel === dataZoomModel;
  47153. },
  47154. /**
  47155. * @return {Array.<number>} Value can only be NaN or finite value.
  47156. */
  47157. getDataValueWindow: function () {
  47158. return this._valueWindow.slice();
  47159. },
  47160. /**
  47161. * @return {Array.<number>}
  47162. */
  47163. getDataPercentWindow: function () {
  47164. return this._percentWindow.slice();
  47165. },
  47166. /**
  47167. * @public
  47168. * @param {number} axisIndex
  47169. * @return {Array} seriesModels
  47170. */
  47171. getTargetSeriesModels: function () {
  47172. var seriesModels = [];
  47173. var ecModel = this.ecModel;
  47174. ecModel.eachSeries(function (seriesModel) {
  47175. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  47176. var dimName = this._dimName;
  47177. var axisModel = ecModel.queryComponents({
  47178. mainType: dimName + 'Axis',
  47179. index: seriesModel.get(dimName + 'AxisIndex'),
  47180. id: seriesModel.get(dimName + 'AxisId')
  47181. })[0];
  47182. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  47183. seriesModels.push(seriesModel);
  47184. }
  47185. }
  47186. }, this);
  47187. return seriesModels;
  47188. },
  47189. getAxisModel: function () {
  47190. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  47191. },
  47192. getOtherAxisModel: function () {
  47193. var axisDim = this._dimName;
  47194. var ecModel = this.ecModel;
  47195. var axisModel = this.getAxisModel();
  47196. var isCartesian = axisDim === 'x' || axisDim === 'y';
  47197. var otherAxisDim;
  47198. var coordSysIndexName;
  47199. if (isCartesian) {
  47200. coordSysIndexName = 'gridIndex';
  47201. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  47202. }
  47203. else {
  47204. coordSysIndexName = 'polarIndex';
  47205. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  47206. }
  47207. var foundOtherAxisModel;
  47208. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  47209. if ((otherAxisModel.get(coordSysIndexName) || 0)
  47210. === (axisModel.get(coordSysIndexName) || 0)
  47211. ) {
  47212. foundOtherAxisModel = otherAxisModel;
  47213. }
  47214. });
  47215. return foundOtherAxisModel;
  47216. },
  47217. getMinMaxSpan: function () {
  47218. return clone(this._minMaxSpan);
  47219. },
  47220. /**
  47221. * Only calculate by given range and this._dataExtent, do not change anything.
  47222. *
  47223. * @param {Object} opt
  47224. * @param {number} [opt.start]
  47225. * @param {number} [opt.end]
  47226. * @param {number} [opt.startValue]
  47227. * @param {number} [opt.endValue]
  47228. */
  47229. calculateDataWindow: function (opt) {
  47230. var dataExtent = this._dataExtent;
  47231. var axisModel = this.getAxisModel();
  47232. var scale = axisModel.axis.scale;
  47233. var rangePropMode = this._dataZoomModel.getRangePropMode();
  47234. var percentExtent = [0, 100];
  47235. var percentWindow = [];
  47236. var valueWindow = [];
  47237. var hasPropModeValue;
  47238. each$13(['start', 'end'], function (prop, idx) {
  47239. var boundPercent = opt[prop];
  47240. var boundValue = opt[prop + 'Value'];
  47241. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  47242. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  47243. // but not min/max of axis, which will be calculated by data window then).
  47244. // The former one is suitable for cases that a dataZoom component controls multiple
  47245. // axes with different unit or extent, and the latter one is suitable for accurate
  47246. // zoom by pixel (e.g., in dataZoomSelect).
  47247. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  47248. // only when setOption or dispatchAction, otherwise it remains its original value.
  47249. // (Why not only record `percentProp` and always map to `valueProp`? Because
  47250. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  47251. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  47252. // data extent. All of values that are overflow the `dataExtent` will be calculated
  47253. // to percent '100%').
  47254. if (rangePropMode[idx] === 'percent') {
  47255. boundPercent == null && (boundPercent = percentExtent[idx]);
  47256. // Use scale.parse to math round for category or time axis.
  47257. boundValue = scale.parse(linearMap(
  47258. boundPercent, percentExtent, dataExtent
  47259. ));
  47260. }
  47261. else {
  47262. hasPropModeValue = true;
  47263. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  47264. // Calculating `percent` from `value` may be not accurate, because
  47265. // This calculation can not be inversed, because all of values that
  47266. // are overflow the `dataExtent` will be calculated to percent '100%'
  47267. boundPercent = linearMap(
  47268. boundValue, dataExtent, percentExtent
  47269. );
  47270. }
  47271. // valueWindow[idx] = round(boundValue);
  47272. // percentWindow[idx] = round(boundPercent);
  47273. valueWindow[idx] = boundValue;
  47274. percentWindow[idx] = boundPercent;
  47275. });
  47276. asc$1(valueWindow);
  47277. asc$1(percentWindow);
  47278. // The windows from user calling of `dispatchAction` might be out of the extent,
  47279. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  47280. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47281. // where API is able to initialize/modify the window size even though `zoomLock`
  47282. // specified.
  47283. var spans = this._minMaxSpan;
  47284. hasPropModeValue
  47285. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  47286. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47287. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47288. var suffix = toValue ? 'Span' : 'ValueSpan';
  47289. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47290. for (var i = 0; i < 2; i++) {
  47291. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47292. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47293. }
  47294. }
  47295. return {
  47296. valueWindow: valueWindow,
  47297. percentWindow: percentWindow
  47298. };
  47299. },
  47300. /**
  47301. * Notice: reset should not be called before series.restoreData() called,
  47302. * so it is recommanded to be called in "process stage" but not "model init
  47303. * stage".
  47304. *
  47305. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47306. */
  47307. reset: function (dataZoomModel) {
  47308. if (dataZoomModel !== this._dataZoomModel) {
  47309. return;
  47310. }
  47311. var targetSeries = this.getTargetSeriesModels();
  47312. // Culculate data window and data extent, and record them.
  47313. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47314. // this.hasSeriesStacked = false;
  47315. // each(targetSeries, function (series) {
  47316. // var data = series.getData();
  47317. // var dataDim = data.mapDimension(this._dimName);
  47318. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  47319. // if (stackedDimension && stackedDimension === dataDim) {
  47320. // this.hasSeriesStacked = true;
  47321. // }
  47322. // }, this);
  47323. // `calculateDataWindow` uses min/maxSpan.
  47324. setMinMaxSpan(this);
  47325. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47326. this._valueWindow = dataWindow.valueWindow;
  47327. this._percentWindow = dataWindow.percentWindow;
  47328. // Update axis setting then.
  47329. setAxisModel(this);
  47330. },
  47331. /**
  47332. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47333. */
  47334. restore: function (dataZoomModel) {
  47335. if (dataZoomModel !== this._dataZoomModel) {
  47336. return;
  47337. }
  47338. this._valueWindow = this._percentWindow = null;
  47339. setAxisModel(this, true);
  47340. },
  47341. /**
  47342. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47343. */
  47344. filterData: function (dataZoomModel, api) {
  47345. if (dataZoomModel !== this._dataZoomModel) {
  47346. return;
  47347. }
  47348. var axisDim = this._dimName;
  47349. var seriesModels = this.getTargetSeriesModels();
  47350. var filterMode = dataZoomModel.get('filterMode');
  47351. var valueWindow = this._valueWindow;
  47352. if (filterMode === 'none') {
  47353. return;
  47354. }
  47355. // FIXME
  47356. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47357. // with NaN data, NaN will be filtered and stack will be wrong.
  47358. // So we need to force the mode to be set empty.
  47359. // In fect, it is not a big deal that do not support filterMode-'filter'
  47360. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  47361. // selection" some day, which might need "adapt to data extent on the
  47362. // otherAxis", which is disabled by filterMode-'empty'.
  47363. // But currently, stack has been fixed to based on value but not index,
  47364. // so this is not an issue any more.
  47365. // var otherAxisModel = this.getOtherAxisModel();
  47366. // if (dataZoomModel.get('$fromToolbox')
  47367. // && otherAxisModel
  47368. // && otherAxisModel.hasSeriesStacked
  47369. // ) {
  47370. // filterMode = 'empty';
  47371. // }
  47372. // TODO
  47373. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  47374. each$13(seriesModels, function (seriesModel) {
  47375. var seriesData = seriesModel.getData();
  47376. var dataDims = seriesData.mapDimension(axisDim, true);
  47377. if (!dataDims.length) {
  47378. return;
  47379. }
  47380. if (filterMode === 'weakFilter') {
  47381. seriesData.filterSelf(function (dataIndex) {
  47382. var leftOut;
  47383. var rightOut;
  47384. var hasValue;
  47385. for (var i = 0; i < dataDims.length; i++) {
  47386. var value = seriesData.get(dataDims[i], dataIndex);
  47387. var thisHasValue = !isNaN(value);
  47388. var thisLeftOut = value < valueWindow[0];
  47389. var thisRightOut = value > valueWindow[1];
  47390. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  47391. return true;
  47392. }
  47393. thisHasValue && (hasValue = true);
  47394. thisLeftOut && (leftOut = true);
  47395. thisRightOut && (rightOut = true);
  47396. }
  47397. // If both left out and right out, do not filter.
  47398. return hasValue && leftOut && rightOut;
  47399. });
  47400. }
  47401. else {
  47402. each$13(dataDims, function (dim) {
  47403. if (filterMode === 'empty') {
  47404. seriesModel.setData(
  47405. seriesData = seriesData.map(dim, function (value) {
  47406. return !isInWindow(value) ? NaN : value;
  47407. })
  47408. );
  47409. }
  47410. else {
  47411. var range = {};
  47412. range[dim] = valueWindow;
  47413. // console.time('select');
  47414. seriesData.selectRange(range);
  47415. // console.timeEnd('select');
  47416. }
  47417. });
  47418. }
  47419. each$13(dataDims, function (dim) {
  47420. seriesData.setApproximateExtent(valueWindow, dim);
  47421. });
  47422. });
  47423. function isInWindow(value) {
  47424. return value >= valueWindow[0] && value <= valueWindow[1];
  47425. }
  47426. }
  47427. };
  47428. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  47429. var dataExtent = [Infinity, -Infinity];
  47430. each$13(seriesModels, function (seriesModel) {
  47431. var seriesData = seriesModel.getData();
  47432. if (seriesData) {
  47433. each$13(seriesData.mapDimension(axisDim, true), function (dim) {
  47434. var seriesExtent = seriesData.getApproximateExtent(dim);
  47435. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  47436. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  47437. });
  47438. }
  47439. });
  47440. if (dataExtent[1] < dataExtent[0]) {
  47441. dataExtent = [NaN, NaN];
  47442. }
  47443. // It is important to get "consistent" extent when more then one axes is
  47444. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  47445. // when zooming. But it is difficult to know what is "consistent", considering
  47446. // axes have different type or even different meanings (For example, two
  47447. // time axes are used to compare data of the same date in different years).
  47448. // So basically dataZoom just obtains extent by series.data (in category axis
  47449. // extent can be obtained from axis.data).
  47450. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  47451. // consistent.
  47452. fixExtentByAxis(axisProxy, dataExtent);
  47453. return dataExtent;
  47454. }
  47455. function fixExtentByAxis(axisProxy, dataExtent) {
  47456. var axisModel = axisProxy.getAxisModel();
  47457. var min = axisModel.getMin(true);
  47458. // For category axis, if min/max/scale are not set, extent is determined
  47459. // by axis.data by default.
  47460. var isCategoryAxis = axisModel.get('type') === 'category';
  47461. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  47462. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  47463. dataExtent[0] = min;
  47464. }
  47465. else if (isCategoryAxis) {
  47466. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  47467. }
  47468. var max = axisModel.getMax(true);
  47469. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  47470. dataExtent[1] = max;
  47471. }
  47472. else if (isCategoryAxis) {
  47473. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  47474. }
  47475. if (!axisModel.get('scale', true)) {
  47476. dataExtent[0] > 0 && (dataExtent[0] = 0);
  47477. dataExtent[1] < 0 && (dataExtent[1] = 0);
  47478. }
  47479. // For value axis, if min/max/scale are not set, we just use the extent obtained
  47480. // by series data, which may be a little different from the extent calculated by
  47481. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  47482. // little when zooming. So it will not be fixed until some users require it strongly.
  47483. return dataExtent;
  47484. }
  47485. function setAxisModel(axisProxy, isRestore) {
  47486. var axisModel = axisProxy.getAxisModel();
  47487. var percentWindow = axisProxy._percentWindow;
  47488. var valueWindow = axisProxy._valueWindow;
  47489. if (!percentWindow) {
  47490. return;
  47491. }
  47492. // [0, 500]: arbitrary value, guess axis extent.
  47493. var precision = getPixelPrecision(valueWindow, [0, 500]);
  47494. precision = Math.min(precision, 20);
  47495. // isRestore or isFull
  47496. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  47497. axisModel.setRange(
  47498. useOrigin ? null : +valueWindow[0].toFixed(precision),
  47499. useOrigin ? null : +valueWindow[1].toFixed(precision)
  47500. );
  47501. }
  47502. function setMinMaxSpan(axisProxy) {
  47503. var minMaxSpan = axisProxy._minMaxSpan = {};
  47504. var dataZoomModel = axisProxy._dataZoomModel;
  47505. var dataExtent = axisProxy._dataExtent;
  47506. each$13(['min', 'max'], function (minMax) {
  47507. var percentSpan = dataZoomModel.get(minMax + 'Span');
  47508. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  47509. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  47510. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  47511. if (valueSpan != null) {
  47512. percentSpan = linearMap(
  47513. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  47514. );
  47515. }
  47516. else if (percentSpan != null) {
  47517. valueSpan = linearMap(
  47518. percentSpan, [0, 100], dataExtent, true
  47519. ) - dataExtent[0];
  47520. }
  47521. minMaxSpan[minMax + 'Span'] = percentSpan;
  47522. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  47523. });
  47524. }
  47525. /*
  47526. * Licensed to the Apache Software Foundation (ASF) under one
  47527. * or more contributor license agreements. See the NOTICE file
  47528. * distributed with this work for additional information
  47529. * regarding copyright ownership. The ASF licenses this file
  47530. * to you under the Apache License, Version 2.0 (the
  47531. * "License"); you may not use this file except in compliance
  47532. * with the License. You may obtain a copy of the License at
  47533. *
  47534. * http://www.apache.org/licenses/LICENSE-2.0
  47535. *
  47536. * Unless required by applicable law or agreed to in writing,
  47537. * software distributed under the License is distributed on an
  47538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47539. * KIND, either express or implied. See the License for the
  47540. * specific language governing permissions and limitations
  47541. * under the License.
  47542. */
  47543. var each$12 = each$1;
  47544. var eachAxisDim = eachAxisDim$1;
  47545. var DataZoomModel = extendComponentModel({
  47546. type: 'dataZoom',
  47547. dependencies: [
  47548. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  47549. ],
  47550. /**
  47551. * @protected
  47552. */
  47553. defaultOption: {
  47554. zlevel: 0,
  47555. z: 4, // Higher than normal component (z: 2).
  47556. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  47557. xAxisIndex: null, // Default the first horizontal category axis.
  47558. yAxisIndex: null, // Default the first vertical category axis.
  47559. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  47560. // 'filter': data items which are out of window will be removed. This option is
  47561. // applicable when filtering outliers. For each data item, it will be
  47562. // filtered if one of the relevant dimensions is out of the window.
  47563. // 'weakFilter': data items which are out of window will be removed. This option
  47564. // is applicable when filtering outliers. For each data item, it will be
  47565. // filtered only if all of the relevant dimensions are out of the same
  47566. // side of the window.
  47567. // 'empty': data items which are out of window will be set to empty.
  47568. // This option is applicable when user should not neglect
  47569. // that there are some data items out of window.
  47570. // 'none': Do not filter.
  47571. // Taking line chart as an example, line will be broken in
  47572. // the filtered points when filterModel is set to 'empty', but
  47573. // be connected when set to 'filter'.
  47574. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  47575. // default 100. Do not throttle when use null/undefined.
  47576. // If animation === true and animationDurationUpdate > 0,
  47577. // default value is 100, otherwise 20.
  47578. start: 0, // Start percent. 0 ~ 100
  47579. end: 100, // End percent. 0 ~ 100
  47580. startValue: null, // Start value. If startValue specified, start is ignored.
  47581. endValue: null, // End value. If endValue specified, end is ignored.
  47582. minSpan: null, // 0 ~ 100
  47583. maxSpan: null, // 0 ~ 100
  47584. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  47585. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  47586. rangeMode: null // Array, can be 'value' or 'percent'.
  47587. },
  47588. /**
  47589. * @override
  47590. */
  47591. init: function (option, parentModel, ecModel) {
  47592. /**
  47593. * key like x_0, y_1
  47594. * @private
  47595. * @type {Object}
  47596. */
  47597. this._dataIntervalByAxis = {};
  47598. /**
  47599. * @private
  47600. */
  47601. this._dataInfo = {};
  47602. /**
  47603. * key like x_0, y_1
  47604. * @private
  47605. */
  47606. this._axisProxies = {};
  47607. /**
  47608. * @readOnly
  47609. */
  47610. this.textStyleModel;
  47611. /**
  47612. * @private
  47613. */
  47614. this._autoThrottle = true;
  47615. /**
  47616. * It is `[rangeModeForMin, rangeModeForMax]`.
  47617. * The optional values for `rangeMode`:
  47618. * + `'value'` mode: the axis extent will always be determined by
  47619. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  47620. * how data like and how `axis.min` and `axis.max` are.
  47621. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  47622. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  47623. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  47624. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  47625. *
  47626. * For example, when users are using dynamic data (update data periodically via `setOption`),
  47627. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  47628. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  47629. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  47630. *
  47631. * @private
  47632. */
  47633. this._rangePropMode = ['percent', 'percent'];
  47634. var inputRawOption = retrieveRawOption(option);
  47635. /**
  47636. * Suppose a "main process" start at the point that model prepared (that is,
  47637. * model initialized or merged or method called in `action`).
  47638. * We should keep the `main process` idempotent, that is, given a set of values
  47639. * on `option`, we get the same result.
  47640. *
  47641. * But sometimes, values on `option` will be updated for providing users
  47642. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  47643. * should not be the base/input of the `main process`.
  47644. *
  47645. * So in that case we should save and keep the input of the `main process`
  47646. * separately, called `settledOption`.
  47647. *
  47648. * For example, consider the case:
  47649. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  47650. * where the original input `option.startValue`, `option.endValue` are earsed by
  47651. * calculated value.
  47652. * (Step)2) click the legend to hide and show a series,
  47653. * where the new range is calculated by the earsed `startValue` and `endValue`,
  47654. * which brings incorrect result.
  47655. *
  47656. * @readOnly
  47657. */
  47658. this.settledOption = inputRawOption;
  47659. this.mergeDefaultAndTheme(option, ecModel);
  47660. this.doInit(inputRawOption);
  47661. },
  47662. /**
  47663. * @override
  47664. */
  47665. mergeOption: function (newOption) {
  47666. var inputRawOption = retrieveRawOption(newOption);
  47667. //FIX #2591
  47668. merge(this.option, newOption, true);
  47669. merge(this.settledOption, inputRawOption, true);
  47670. this.doInit(inputRawOption);
  47671. },
  47672. /**
  47673. * @protected
  47674. */
  47675. doInit: function (inputRawOption) {
  47676. var thisOption = this.option;
  47677. // Disable realtime view update if canvas is not supported.
  47678. if (!env$1.canvasSupported) {
  47679. thisOption.realtime = false;
  47680. }
  47681. this._setDefaultThrottle(inputRawOption);
  47682. updateRangeUse(this, inputRawOption);
  47683. var settledOption = this.settledOption;
  47684. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  47685. // start/end has higher priority over startValue/endValue if they
  47686. // both set, but we should make chart.setOption({endValue: 1000})
  47687. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  47688. if (this._rangePropMode[index] === 'value') {
  47689. thisOption[names[0]] = settledOption[names[0]] = null;
  47690. }
  47691. // Otherwise do nothing and use the merge result.
  47692. }, this);
  47693. this.textStyleModel = this.getModel('textStyle');
  47694. this._resetTarget();
  47695. this._giveAxisProxies();
  47696. },
  47697. /**
  47698. * @private
  47699. */
  47700. _giveAxisProxies: function () {
  47701. var axisProxies = this._axisProxies;
  47702. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  47703. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  47704. // If exists, share axisProxy with other dataZoomModels.
  47705. var axisProxy = axisModel.__dzAxisProxy || (
  47706. // Use the first dataZoomModel as the main model of axisProxy.
  47707. axisModel.__dzAxisProxy = new AxisProxy(
  47708. dimNames.name, axisIndex, this, ecModel
  47709. )
  47710. );
  47711. // FIXME
  47712. // dispose __dzAxisProxy
  47713. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  47714. }, this);
  47715. },
  47716. /**
  47717. * @private
  47718. */
  47719. _resetTarget: function () {
  47720. var thisOption = this.option;
  47721. var autoMode = this._judgeAutoMode();
  47722. eachAxisDim(function (dimNames) {
  47723. var axisIndexName = dimNames.axisIndex;
  47724. thisOption[axisIndexName] = normalizeToArray(
  47725. thisOption[axisIndexName]
  47726. );
  47727. }, this);
  47728. if (autoMode === 'axisIndex') {
  47729. this._autoSetAxisIndex();
  47730. }
  47731. else if (autoMode === 'orient') {
  47732. this._autoSetOrient();
  47733. }
  47734. },
  47735. /**
  47736. * @private
  47737. */
  47738. _judgeAutoMode: function () {
  47739. // Auto set only works for setOption at the first time.
  47740. // The following is user's reponsibility. So using merged
  47741. // option is OK.
  47742. var thisOption = this.option;
  47743. var hasIndexSpecified = false;
  47744. eachAxisDim(function (dimNames) {
  47745. // When user set axisIndex as a empty array, we think that user specify axisIndex
  47746. // but do not want use auto mode. Because empty array may be encountered when
  47747. // some error occured.
  47748. if (thisOption[dimNames.axisIndex] != null) {
  47749. hasIndexSpecified = true;
  47750. }
  47751. }, this);
  47752. var orient = thisOption.orient;
  47753. if (orient == null && hasIndexSpecified) {
  47754. return 'orient';
  47755. }
  47756. else if (!hasIndexSpecified) {
  47757. if (orient == null) {
  47758. thisOption.orient = 'horizontal';
  47759. }
  47760. return 'axisIndex';
  47761. }
  47762. },
  47763. /**
  47764. * @private
  47765. */
  47766. _autoSetAxisIndex: function () {
  47767. var autoAxisIndex = true;
  47768. var orient = this.get('orient', true);
  47769. var thisOption = this.option;
  47770. var dependentModels = this.dependentModels;
  47771. if (autoAxisIndex) {
  47772. // Find axis that parallel to dataZoom as default.
  47773. var dimName = orient === 'vertical' ? 'y' : 'x';
  47774. if (dependentModels[dimName + 'Axis'].length) {
  47775. thisOption[dimName + 'AxisIndex'] = [0];
  47776. autoAxisIndex = false;
  47777. }
  47778. else {
  47779. each$12(dependentModels.singleAxis, function (singleAxisModel) {
  47780. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  47781. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  47782. autoAxisIndex = false;
  47783. }
  47784. });
  47785. }
  47786. }
  47787. if (autoAxisIndex) {
  47788. // Find the first category axis as default. (consider polar)
  47789. eachAxisDim(function (dimNames) {
  47790. if (!autoAxisIndex) {
  47791. return;
  47792. }
  47793. var axisIndices = [];
  47794. var axisModels = this.dependentModels[dimNames.axis];
  47795. if (axisModels.length && !axisIndices.length) {
  47796. for (var i = 0, len = axisModels.length; i < len; i++) {
  47797. if (axisModels[i].get('type') === 'category') {
  47798. axisIndices.push(i);
  47799. }
  47800. }
  47801. }
  47802. thisOption[dimNames.axisIndex] = axisIndices;
  47803. if (axisIndices.length) {
  47804. autoAxisIndex = false;
  47805. }
  47806. }, this);
  47807. }
  47808. if (autoAxisIndex) {
  47809. // FIXME
  47810. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  47811. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  47812. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  47813. // dataZoom component auto adopts series that reference to
  47814. // both xAxis and yAxis which type is 'value'.
  47815. this.ecModel.eachSeries(function (seriesModel) {
  47816. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  47817. eachAxisDim(function (dimNames) {
  47818. var axisIndices = thisOption[dimNames.axisIndex];
  47819. var axisIndex = seriesModel.get(dimNames.axisIndex);
  47820. var axisId = seriesModel.get(dimNames.axisId);
  47821. var axisModel = seriesModel.ecModel.queryComponents({
  47822. mainType: dimNames.axis,
  47823. index: axisIndex,
  47824. id: axisId
  47825. })[0];
  47826. if (__DEV__) {
  47827. if (!axisModel) {
  47828. throw new Error(
  47829. dimNames.axis + ' "' + retrieve(
  47830. axisIndex,
  47831. axisId,
  47832. 0
  47833. ) + '" not found'
  47834. );
  47835. }
  47836. }
  47837. axisIndex = axisModel.componentIndex;
  47838. if (indexOf(axisIndices, axisIndex) < 0) {
  47839. axisIndices.push(axisIndex);
  47840. }
  47841. });
  47842. }
  47843. }, this);
  47844. }
  47845. },
  47846. /**
  47847. * @private
  47848. */
  47849. _autoSetOrient: function () {
  47850. var dim;
  47851. // Find the first axis
  47852. this.eachTargetAxis(function (dimNames) {
  47853. !dim && (dim = dimNames.name);
  47854. }, this);
  47855. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  47856. },
  47857. /**
  47858. * @private
  47859. */
  47860. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  47861. // FIXME
  47862. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  47863. // 例如series.type === scatter时。
  47864. var is = true;
  47865. eachAxisDim(function (dimNames) {
  47866. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  47867. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  47868. if (!axisModel || axisModel.get('type') !== axisType) {
  47869. is = false;
  47870. }
  47871. }, this);
  47872. return is;
  47873. },
  47874. /**
  47875. * @private
  47876. */
  47877. _setDefaultThrottle: function (inputRawOption) {
  47878. // When first time user set throttle, auto throttle ends.
  47879. if (inputRawOption.hasOwnProperty('throttle')) {
  47880. this._autoThrottle = false;
  47881. }
  47882. if (this._autoThrottle) {
  47883. var globalOption = this.ecModel.option;
  47884. this.option.throttle = (
  47885. globalOption.animation && globalOption.animationDurationUpdate > 0
  47886. ) ? 100 : 20;
  47887. }
  47888. },
  47889. /**
  47890. * @public
  47891. */
  47892. getFirstTargetAxisModel: function () {
  47893. var firstAxisModel;
  47894. eachAxisDim(function (dimNames) {
  47895. if (firstAxisModel == null) {
  47896. var indices = this.get(dimNames.axisIndex);
  47897. if (indices.length) {
  47898. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  47899. }
  47900. }
  47901. }, this);
  47902. return firstAxisModel;
  47903. },
  47904. /**
  47905. * @public
  47906. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  47907. */
  47908. eachTargetAxis: function (callback, context) {
  47909. var ecModel = this.ecModel;
  47910. eachAxisDim(function (dimNames) {
  47911. each$12(
  47912. this.get(dimNames.axisIndex),
  47913. function (axisIndex) {
  47914. callback.call(context, dimNames, axisIndex, this, ecModel);
  47915. },
  47916. this
  47917. );
  47918. }, this);
  47919. },
  47920. /**
  47921. * @param {string} dimName
  47922. * @param {number} axisIndex
  47923. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  47924. */
  47925. getAxisProxy: function (dimName, axisIndex) {
  47926. return this._axisProxies[dimName + '_' + axisIndex];
  47927. },
  47928. /**
  47929. * @param {string} dimName
  47930. * @param {number} axisIndex
  47931. * @return {module:echarts/model/Model} If not found, return null/undefined.
  47932. */
  47933. getAxisModel: function (dimName, axisIndex) {
  47934. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  47935. return axisProxy && axisProxy.getAxisModel();
  47936. },
  47937. /**
  47938. * If not specified, set to undefined.
  47939. *
  47940. * @public
  47941. * @param {Object} opt
  47942. * @param {number} [opt.start]
  47943. * @param {number} [opt.end]
  47944. * @param {number} [opt.startValue]
  47945. * @param {number} [opt.endValue]
  47946. */
  47947. setRawRange: function (opt) {
  47948. var thisOption = this.option;
  47949. var settledOption = this.settledOption;
  47950. each$12([['start', 'startValue'], ['end', 'endValue']], function (names) {
  47951. // Consider the pair <start, startValue>:
  47952. // If one has value and the other one is `null/undefined`, we both set them
  47953. // to `settledOption`. This strategy enables the feature to clear the original
  47954. // value in `settledOption` to `null/undefined`.
  47955. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  47956. // and keep `settledOption` with the original value. This strategy enables users to
  47957. // only set <end or endValue> but not set <start or startValue> when calling
  47958. // `dispatchAction`.
  47959. // The pair <end, endValue> is treated in the same way.
  47960. if (opt[names[0]] != null || opt[names[1]] != null) {
  47961. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  47962. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  47963. }
  47964. }, this);
  47965. updateRangeUse(this, opt);
  47966. },
  47967. /**
  47968. * @public
  47969. * @param {Object} opt
  47970. * @param {number} [opt.start]
  47971. * @param {number} [opt.end]
  47972. * @param {number} [opt.startValue]
  47973. * @param {number} [opt.endValue]
  47974. */
  47975. setCalculatedRange: function (opt) {
  47976. var option = this.option;
  47977. each$12(['start', 'startValue', 'end', 'endValue'], function (name) {
  47978. option[name] = opt[name];
  47979. });
  47980. },
  47981. /**
  47982. * @public
  47983. * @return {Array.<number>} [startPercent, endPercent]
  47984. */
  47985. getPercentRange: function () {
  47986. var axisProxy = this.findRepresentativeAxisProxy();
  47987. if (axisProxy) {
  47988. return axisProxy.getDataPercentWindow();
  47989. }
  47990. },
  47991. /**
  47992. * @public
  47993. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  47994. *
  47995. * @param {string} [axisDimName]
  47996. * @param {number} [axisIndex]
  47997. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  47998. */
  47999. getValueRange: function (axisDimName, axisIndex) {
  48000. if (axisDimName == null && axisIndex == null) {
  48001. var axisProxy = this.findRepresentativeAxisProxy();
  48002. if (axisProxy) {
  48003. return axisProxy.getDataValueWindow();
  48004. }
  48005. }
  48006. else {
  48007. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  48008. }
  48009. },
  48010. /**
  48011. * @public
  48012. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  48013. * corresponding to the axisModel
  48014. * @return {module:echarts/component/dataZoom/AxisProxy}
  48015. */
  48016. findRepresentativeAxisProxy: function (axisModel) {
  48017. if (axisModel) {
  48018. return axisModel.__dzAxisProxy;
  48019. }
  48020. // Find the first hosted axisProxy
  48021. var axisProxies = this._axisProxies;
  48022. for (var key in axisProxies) {
  48023. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  48024. return axisProxies[key];
  48025. }
  48026. }
  48027. // If no hosted axis find not hosted axisProxy.
  48028. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  48029. // and the option.start or option.end settings are different. The percentRange
  48030. // should follow axisProxy.
  48031. // (We encounter this problem in toolbox data zoom.)
  48032. for (var key in axisProxies) {
  48033. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  48034. return axisProxies[key];
  48035. }
  48036. }
  48037. },
  48038. /**
  48039. * @return {Array.<string>}
  48040. */
  48041. getRangePropMode: function () {
  48042. return this._rangePropMode.slice();
  48043. }
  48044. });
  48045. /**
  48046. * Retrieve the those raw params from option, which will be cached separately.
  48047. * becasue they will be overwritten by normalized/calculated values in the main
  48048. * process.
  48049. */
  48050. function retrieveRawOption(option) {
  48051. var ret = {};
  48052. each$12(
  48053. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  48054. function (name) {
  48055. option.hasOwnProperty(name) && (ret[name] = option[name]);
  48056. }
  48057. );
  48058. return ret;
  48059. }
  48060. function updateRangeUse(dataZoomModel, inputRawOption) {
  48061. var rangePropMode = dataZoomModel._rangePropMode;
  48062. var rangeModeInOption = dataZoomModel.get('rangeMode');
  48063. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48064. var percentSpecified = inputRawOption[names[0]] != null;
  48065. var valueSpecified = inputRawOption[names[1]] != null;
  48066. if (percentSpecified && !valueSpecified) {
  48067. rangePropMode[index] = 'percent';
  48068. }
  48069. else if (!percentSpecified && valueSpecified) {
  48070. rangePropMode[index] = 'value';
  48071. }
  48072. else if (rangeModeInOption) {
  48073. rangePropMode[index] = rangeModeInOption[index];
  48074. }
  48075. else if (percentSpecified) { // percentSpecified && valueSpecified
  48076. rangePropMode[index] = 'percent';
  48077. }
  48078. // else remain its original setting.
  48079. });
  48080. }
  48081. /*
  48082. * Licensed to the Apache Software Foundation (ASF) under one
  48083. * or more contributor license agreements. See the NOTICE file
  48084. * distributed with this work for additional information
  48085. * regarding copyright ownership. The ASF licenses this file
  48086. * to you under the Apache License, Version 2.0 (the
  48087. * "License"); you may not use this file except in compliance
  48088. * with the License. You may obtain a copy of the License at
  48089. *
  48090. * http://www.apache.org/licenses/LICENSE-2.0
  48091. *
  48092. * Unless required by applicable law or agreed to in writing,
  48093. * software distributed under the License is distributed on an
  48094. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48095. * KIND, either express or implied. See the License for the
  48096. * specific language governing permissions and limitations
  48097. * under the License.
  48098. */
  48099. var DataZoomView = Component$1.extend({
  48100. type: 'dataZoom',
  48101. render: function (dataZoomModel, ecModel, api, payload) {
  48102. this.dataZoomModel = dataZoomModel;
  48103. this.ecModel = ecModel;
  48104. this.api = api;
  48105. },
  48106. /**
  48107. * Find the first target coordinate system.
  48108. *
  48109. * @protected
  48110. * @return {Object} {
  48111. * grid: [
  48112. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  48113. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  48114. * ...
  48115. * ], // cartesians must not be null/undefined.
  48116. * polar: [
  48117. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  48118. * ...
  48119. * ], // polars must not be null/undefined.
  48120. * singleAxis: [
  48121. * {model: coord0, axisModels: [], coordIndex: 0}
  48122. * ]
  48123. */
  48124. getTargetCoordInfo: function () {
  48125. var dataZoomModel = this.dataZoomModel;
  48126. var ecModel = this.ecModel;
  48127. var coordSysLists = {};
  48128. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48129. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  48130. if (axisModel) {
  48131. var coordModel = axisModel.getCoordSysModel();
  48132. coordModel && save(
  48133. coordModel,
  48134. axisModel,
  48135. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  48136. coordModel.componentIndex
  48137. );
  48138. }
  48139. }, this);
  48140. function save(coordModel, axisModel, store, coordIndex) {
  48141. var item;
  48142. for (var i = 0; i < store.length; i++) {
  48143. if (store[i].model === coordModel) {
  48144. item = store[i];
  48145. break;
  48146. }
  48147. }
  48148. if (!item) {
  48149. store.push(item = {
  48150. model: coordModel, axisModels: [], coordIndex: coordIndex
  48151. });
  48152. }
  48153. item.axisModels.push(axisModel);
  48154. }
  48155. return coordSysLists;
  48156. }
  48157. });
  48158. /*
  48159. * Licensed to the Apache Software Foundation (ASF) under one
  48160. * or more contributor license agreements. See the NOTICE file
  48161. * distributed with this work for additional information
  48162. * regarding copyright ownership. The ASF licenses this file
  48163. * to you under the Apache License, Version 2.0 (the
  48164. * "License"); you may not use this file except in compliance
  48165. * with the License. You may obtain a copy of the License at
  48166. *
  48167. * http://www.apache.org/licenses/LICENSE-2.0
  48168. *
  48169. * Unless required by applicable law or agreed to in writing,
  48170. * software distributed under the License is distributed on an
  48171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48172. * KIND, either express or implied. See the License for the
  48173. * specific language governing permissions and limitations
  48174. * under the License.
  48175. */
  48176. var SliderZoomModel = DataZoomModel.extend({
  48177. type: 'dataZoom.slider',
  48178. layoutMode: 'box',
  48179. /**
  48180. * @protected
  48181. */
  48182. defaultOption: {
  48183. show: true,
  48184. // ph => placeholder. Using placehoder here because
  48185. // deault value can only be drived in view stage.
  48186. right: 'ph', // Default align to grid rect.
  48187. top: 'ph', // Default align to grid rect.
  48188. width: 'ph', // Default align to grid rect.
  48189. height: 'ph', // Default align to grid rect.
  48190. left: null, // Default align to grid rect.
  48191. bottom: null, // Default align to grid rect.
  48192. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  48193. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  48194. // highest priority, remain for compatibility of
  48195. // previous version, but not recommended any more.
  48196. dataBackground: {
  48197. lineStyle: {
  48198. color: '#2f4554',
  48199. width: 0.5,
  48200. opacity: 0.3
  48201. },
  48202. areaStyle: {
  48203. color: 'rgba(47,69,84,0.3)',
  48204. opacity: 0.3
  48205. }
  48206. },
  48207. borderColor: '#ddd', // border color of the box. For compatibility,
  48208. // if dataBackgroundColor is set, borderColor
  48209. // is ignored.
  48210. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  48211. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  48212. // 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',
  48213. /* eslint-disable */
  48214. 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',
  48215. /* eslint-enable */
  48216. // Percent of the slider height
  48217. handleSize: '100%',
  48218. handleStyle: {
  48219. color: '#a7b7cc'
  48220. },
  48221. labelPrecision: null,
  48222. labelFormatter: null,
  48223. showDetail: true,
  48224. showDataShadow: 'auto', // Default auto decision.
  48225. realtime: true,
  48226. zoomLock: false, // Whether disable zoom.
  48227. textStyle: {
  48228. color: '#333'
  48229. }
  48230. }
  48231. });
  48232. /*
  48233. * Licensed to the Apache Software Foundation (ASF) under one
  48234. * or more contributor license agreements. See the NOTICE file
  48235. * distributed with this work for additional information
  48236. * regarding copyright ownership. The ASF licenses this file
  48237. * to you under the Apache License, Version 2.0 (the
  48238. * "License"); you may not use this file except in compliance
  48239. * with the License. You may obtain a copy of the License at
  48240. *
  48241. * http://www.apache.org/licenses/LICENSE-2.0
  48242. *
  48243. * Unless required by applicable law or agreed to in writing,
  48244. * software distributed under the License is distributed on an
  48245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48246. * KIND, either express or implied. See the License for the
  48247. * specific language governing permissions and limitations
  48248. * under the License.
  48249. */
  48250. var Rect$1 = Rect;
  48251. var linearMap$1 = linearMap;
  48252. var asc$2 = asc;
  48253. var bind$3 = bind;
  48254. var each$14 = each$1;
  48255. // Constants
  48256. var DEFAULT_LOCATION_EDGE_GAP = 7;
  48257. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  48258. var DEFAULT_FILLER_SIZE = 30;
  48259. var HORIZONTAL = 'horizontal';
  48260. var VERTICAL = 'vertical';
  48261. var LABEL_GAP = 5;
  48262. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  48263. var SliderZoomView = DataZoomView.extend({
  48264. type: 'dataZoom.slider',
  48265. init: function (ecModel, api) {
  48266. /**
  48267. * @private
  48268. * @type {Object}
  48269. */
  48270. this._displayables = {};
  48271. /**
  48272. * @private
  48273. * @type {string}
  48274. */
  48275. this._orient;
  48276. /**
  48277. * [0, 100]
  48278. * @private
  48279. */
  48280. this._range;
  48281. /**
  48282. * [coord of the first handle, coord of the second handle]
  48283. * @private
  48284. */
  48285. this._handleEnds;
  48286. /**
  48287. * [length, thick]
  48288. * @private
  48289. * @type {Array.<number>}
  48290. */
  48291. this._size;
  48292. /**
  48293. * @private
  48294. * @type {number}
  48295. */
  48296. this._handleWidth;
  48297. /**
  48298. * @private
  48299. * @type {number}
  48300. */
  48301. this._handleHeight;
  48302. /**
  48303. * @private
  48304. */
  48305. this._location;
  48306. /**
  48307. * @private
  48308. */
  48309. this._dragging;
  48310. /**
  48311. * @private
  48312. */
  48313. this._dataShadowInfo;
  48314. this.api = api;
  48315. },
  48316. /**
  48317. * @override
  48318. */
  48319. render: function (dataZoomModel, ecModel, api, payload) {
  48320. SliderZoomView.superApply(this, 'render', arguments);
  48321. createOrUpdate(
  48322. this,
  48323. '_dispatchZoomAction',
  48324. this.dataZoomModel.get('throttle'),
  48325. 'fixRate'
  48326. );
  48327. this._orient = dataZoomModel.get('orient');
  48328. if (this.dataZoomModel.get('show') === false) {
  48329. this.group.removeAll();
  48330. return;
  48331. }
  48332. // Notice: this._resetInterval() should not be executed when payload.type
  48333. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  48334. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  48335. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  48336. this._buildView();
  48337. }
  48338. this._updateView();
  48339. },
  48340. /**
  48341. * @override
  48342. */
  48343. remove: function () {
  48344. SliderZoomView.superApply(this, 'remove', arguments);
  48345. clear(this, '_dispatchZoomAction');
  48346. },
  48347. /**
  48348. * @override
  48349. */
  48350. dispose: function () {
  48351. SliderZoomView.superApply(this, 'dispose', arguments);
  48352. clear(this, '_dispatchZoomAction');
  48353. },
  48354. _buildView: function () {
  48355. var thisGroup = this.group;
  48356. thisGroup.removeAll();
  48357. this._resetLocation();
  48358. this._resetInterval();
  48359. var barGroup = this._displayables.barGroup = new Group();
  48360. this._renderBackground();
  48361. this._renderHandle();
  48362. this._renderDataShadow();
  48363. thisGroup.add(barGroup);
  48364. this._positionGroup();
  48365. },
  48366. /**
  48367. * @private
  48368. */
  48369. _resetLocation: function () {
  48370. var dataZoomModel = this.dataZoomModel;
  48371. var api = this.api;
  48372. // If some of x/y/width/height are not specified,
  48373. // auto-adapt according to target grid.
  48374. var coordRect = this._findCoordRect();
  48375. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  48376. // Default align by coordinate system rect.
  48377. var positionInfo = this._orient === HORIZONTAL
  48378. ? {
  48379. // Why using 'right', because right should be used in vertical,
  48380. // and it is better to be consistent for dealing with position param merge.
  48381. right: ecSize.width - coordRect.x - coordRect.width,
  48382. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  48383. width: coordRect.width,
  48384. height: DEFAULT_FILLER_SIZE
  48385. }
  48386. : { // vertical
  48387. right: DEFAULT_LOCATION_EDGE_GAP,
  48388. top: coordRect.y,
  48389. width: DEFAULT_FILLER_SIZE,
  48390. height: coordRect.height
  48391. };
  48392. // Do not write back to option and replace value 'ph', because
  48393. // the 'ph' value should be recalculated when resize.
  48394. var layoutParams = getLayoutParams(dataZoomModel.option);
  48395. // Replace the placeholder value.
  48396. each$1(['right', 'top', 'width', 'height'], function (name) {
  48397. if (layoutParams[name] === 'ph') {
  48398. layoutParams[name] = positionInfo[name];
  48399. }
  48400. });
  48401. var layoutRect = getLayoutRect(
  48402. layoutParams,
  48403. ecSize,
  48404. dataZoomModel.padding
  48405. );
  48406. this._location = {x: layoutRect.x, y: layoutRect.y};
  48407. this._size = [layoutRect.width, layoutRect.height];
  48408. this._orient === VERTICAL && this._size.reverse();
  48409. },
  48410. /**
  48411. * @private
  48412. */
  48413. _positionGroup: function () {
  48414. var thisGroup = this.group;
  48415. var location = this._location;
  48416. var orient = this._orient;
  48417. // Just use the first axis to determine mapping.
  48418. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  48419. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  48420. var barGroup = this._displayables.barGroup;
  48421. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  48422. // Transform barGroup.
  48423. barGroup.attr(
  48424. (orient === HORIZONTAL && !inverse)
  48425. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  48426. : (orient === HORIZONTAL && inverse)
  48427. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  48428. : (orient === VERTICAL && !inverse)
  48429. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  48430. // Dont use Math.PI, considering shadow direction.
  48431. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  48432. );
  48433. // Position barGroup
  48434. var rect = thisGroup.getBoundingRect([barGroup]);
  48435. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  48436. },
  48437. /**
  48438. * @private
  48439. */
  48440. _getViewExtent: function () {
  48441. return [0, this._size[0]];
  48442. },
  48443. _renderBackground: function () {
  48444. var dataZoomModel = this.dataZoomModel;
  48445. var size = this._size;
  48446. var barGroup = this._displayables.barGroup;
  48447. barGroup.add(new Rect$1({
  48448. silent: true,
  48449. shape: {
  48450. x: 0, y: 0, width: size[0], height: size[1]
  48451. },
  48452. style: {
  48453. fill: dataZoomModel.get('backgroundColor')
  48454. },
  48455. z2: -40
  48456. }));
  48457. // Click panel, over shadow, below handles.
  48458. barGroup.add(new Rect$1({
  48459. shape: {
  48460. x: 0, y: 0, width: size[0], height: size[1]
  48461. },
  48462. style: {
  48463. fill: 'transparent'
  48464. },
  48465. z2: 0,
  48466. onclick: bind(this._onClickPanelClick, this)
  48467. }));
  48468. },
  48469. _renderDataShadow: function () {
  48470. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  48471. if (!info) {
  48472. return;
  48473. }
  48474. var size = this._size;
  48475. var seriesModel = info.series;
  48476. var data = seriesModel.getRawData();
  48477. var otherDim = seriesModel.getShadowDim
  48478. ? seriesModel.getShadowDim() // @see candlestick
  48479. : info.otherDim;
  48480. if (otherDim == null) {
  48481. return;
  48482. }
  48483. var otherDataExtent = data.getDataExtent(otherDim);
  48484. // Nice extent.
  48485. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  48486. otherDataExtent = [
  48487. otherDataExtent[0] - otherOffset,
  48488. otherDataExtent[1] + otherOffset
  48489. ];
  48490. var otherShadowExtent = [0, size[1]];
  48491. var thisShadowExtent = [0, size[0]];
  48492. var areaPoints = [[size[0], 0], [0, 0]];
  48493. var linePoints = [];
  48494. var step = thisShadowExtent[1] / (data.count() - 1);
  48495. var thisCoord = 0;
  48496. // Optimize for large data shadow
  48497. var stride = Math.round(data.count() / size[0]);
  48498. var lastIsEmpty;
  48499. data.each([otherDim], function (value, index) {
  48500. if (stride > 0 && (index % stride)) {
  48501. thisCoord += step;
  48502. return;
  48503. }
  48504. // FIXME
  48505. // Should consider axis.min/axis.max when drawing dataShadow.
  48506. // FIXME
  48507. // 应该使用统一的空判断?还是在list里进行空判断?
  48508. var isEmpty = value == null || isNaN(value) || value === '';
  48509. // See #4235.
  48510. var otherCoord = isEmpty
  48511. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  48512. // Attempt to draw data shadow precisely when there are empty value.
  48513. if (isEmpty && !lastIsEmpty && index) {
  48514. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  48515. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  48516. }
  48517. else if (!isEmpty && lastIsEmpty) {
  48518. areaPoints.push([thisCoord, 0]);
  48519. linePoints.push([thisCoord, 0]);
  48520. }
  48521. areaPoints.push([thisCoord, otherCoord]);
  48522. linePoints.push([thisCoord, otherCoord]);
  48523. thisCoord += step;
  48524. lastIsEmpty = isEmpty;
  48525. });
  48526. var dataZoomModel = this.dataZoomModel;
  48527. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  48528. this._displayables.barGroup.add(new Polygon({
  48529. shape: {points: areaPoints},
  48530. style: defaults(
  48531. {fill: dataZoomModel.get('dataBackgroundColor')},
  48532. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  48533. ),
  48534. silent: true,
  48535. z2: -20
  48536. }));
  48537. this._displayables.barGroup.add(new Polyline({
  48538. shape: {points: linePoints},
  48539. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  48540. silent: true,
  48541. z2: -19
  48542. }));
  48543. },
  48544. _prepareDataShadowInfo: function () {
  48545. var dataZoomModel = this.dataZoomModel;
  48546. var showDataShadow = dataZoomModel.get('showDataShadow');
  48547. if (showDataShadow === false) {
  48548. return;
  48549. }
  48550. // Find a representative series.
  48551. var result;
  48552. var ecModel = this.ecModel;
  48553. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48554. var seriesModels = dataZoomModel
  48555. .getAxisProxy(dimNames.name, axisIndex)
  48556. .getTargetSeriesModels();
  48557. each$1(seriesModels, function (seriesModel) {
  48558. if (result) {
  48559. return;
  48560. }
  48561. if (showDataShadow !== true && indexOf(
  48562. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  48563. ) < 0
  48564. ) {
  48565. return;
  48566. }
  48567. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  48568. var otherDim = getOtherDim(dimNames.name);
  48569. var otherAxisInverse;
  48570. var coordSys = seriesModel.coordinateSystem;
  48571. if (otherDim != null && coordSys.getOtherAxis) {
  48572. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  48573. }
  48574. otherDim = seriesModel.getData().mapDimension(otherDim);
  48575. result = {
  48576. thisAxis: thisAxis,
  48577. series: seriesModel,
  48578. thisDim: dimNames.name,
  48579. otherDim: otherDim,
  48580. otherAxisInverse: otherAxisInverse
  48581. };
  48582. }, this);
  48583. }, this);
  48584. return result;
  48585. },
  48586. _renderHandle: function () {
  48587. var displaybles = this._displayables;
  48588. var handles = displaybles.handles = [];
  48589. var handleLabels = displaybles.handleLabels = [];
  48590. var barGroup = this._displayables.barGroup;
  48591. var size = this._size;
  48592. var dataZoomModel = this.dataZoomModel;
  48593. barGroup.add(displaybles.filler = new Rect$1({
  48594. draggable: true,
  48595. cursor: getCursor(this._orient),
  48596. drift: bind$3(this._onDragMove, this, 'all'),
  48597. ondragstart: bind$3(this._showDataInfo, this, true),
  48598. ondragend: bind$3(this._onDragEnd, this),
  48599. onmouseover: bind$3(this._showDataInfo, this, true),
  48600. onmouseout: bind$3(this._showDataInfo, this, false),
  48601. style: {
  48602. fill: dataZoomModel.get('fillerColor'),
  48603. textPosition: 'inside'
  48604. }
  48605. }));
  48606. // Frame border.
  48607. barGroup.add(new Rect$1({
  48608. silent: true,
  48609. subPixelOptimize: true,
  48610. shape: {
  48611. x: 0,
  48612. y: 0,
  48613. width: size[0],
  48614. height: size[1]
  48615. },
  48616. style: {
  48617. stroke: dataZoomModel.get('dataBackgroundColor')
  48618. || dataZoomModel.get('borderColor'),
  48619. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  48620. fill: 'rgba(0,0,0,0)'
  48621. }
  48622. }));
  48623. each$14([0, 1], function (handleIndex) {
  48624. var path = createIcon(
  48625. dataZoomModel.get('handleIcon'),
  48626. {
  48627. cursor: getCursor(this._orient),
  48628. draggable: true,
  48629. drift: bind$3(this._onDragMove, this, handleIndex),
  48630. ondragend: bind$3(this._onDragEnd, this),
  48631. onmouseover: bind$3(this._showDataInfo, this, true),
  48632. onmouseout: bind$3(this._showDataInfo, this, false)
  48633. },
  48634. {x: -1, y: 0, width: 2, height: 2}
  48635. );
  48636. var bRect = path.getBoundingRect();
  48637. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  48638. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  48639. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  48640. var handleColor = dataZoomModel.get('handleColor');
  48641. // Compatitable with previous version
  48642. if (handleColor != null) {
  48643. path.style.fill = handleColor;
  48644. }
  48645. barGroup.add(handles[handleIndex] = path);
  48646. var textStyleModel = dataZoomModel.textStyleModel;
  48647. this.group.add(
  48648. handleLabels[handleIndex] = new Text({
  48649. silent: true,
  48650. invisible: true,
  48651. style: {
  48652. x: 0, y: 0, text: '',
  48653. textVerticalAlign: 'middle',
  48654. textAlign: 'center',
  48655. textFill: textStyleModel.getTextColor(),
  48656. textFont: textStyleModel.getFont()
  48657. },
  48658. z2: 10
  48659. }));
  48660. }, this);
  48661. },
  48662. /**
  48663. * @private
  48664. */
  48665. _resetInterval: function () {
  48666. var range = this._range = this.dataZoomModel.getPercentRange();
  48667. var viewExtent = this._getViewExtent();
  48668. this._handleEnds = [
  48669. linearMap$1(range[0], [0, 100], viewExtent, true),
  48670. linearMap$1(range[1], [0, 100], viewExtent, true)
  48671. ];
  48672. },
  48673. /**
  48674. * @private
  48675. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  48676. * @param {number} delta
  48677. * @return {boolean} changed
  48678. */
  48679. _updateInterval: function (handleIndex, delta) {
  48680. var dataZoomModel = this.dataZoomModel;
  48681. var handleEnds = this._handleEnds;
  48682. var viewExtend = this._getViewExtent();
  48683. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  48684. var percentExtent = [0, 100];
  48685. sliderMove(
  48686. delta,
  48687. handleEnds,
  48688. viewExtend,
  48689. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  48690. minMaxSpan.minSpan != null
  48691. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  48692. minMaxSpan.maxSpan != null
  48693. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  48694. );
  48695. var lastRange = this._range;
  48696. var range = this._range = asc$2([
  48697. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  48698. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  48699. ]);
  48700. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  48701. },
  48702. /**
  48703. * @private
  48704. */
  48705. _updateView: function (nonRealtime) {
  48706. var displaybles = this._displayables;
  48707. var handleEnds = this._handleEnds;
  48708. var handleInterval = asc$2(handleEnds.slice());
  48709. var size = this._size;
  48710. each$14([0, 1], function (handleIndex) {
  48711. // Handles
  48712. var handle = displaybles.handles[handleIndex];
  48713. var handleHeight = this._handleHeight;
  48714. handle.attr({
  48715. scale: [handleHeight / 2, handleHeight / 2],
  48716. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  48717. });
  48718. }, this);
  48719. // Filler
  48720. displaybles.filler.setShape({
  48721. x: handleInterval[0],
  48722. y: 0,
  48723. width: handleInterval[1] - handleInterval[0],
  48724. height: size[1]
  48725. });
  48726. this._updateDataInfo(nonRealtime);
  48727. },
  48728. /**
  48729. * @private
  48730. */
  48731. _updateDataInfo: function (nonRealtime) {
  48732. var dataZoomModel = this.dataZoomModel;
  48733. var displaybles = this._displayables;
  48734. var handleLabels = displaybles.handleLabels;
  48735. var orient = this._orient;
  48736. var labelTexts = ['', ''];
  48737. // FIXME
  48738. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  48739. if (dataZoomModel.get('showDetail')) {
  48740. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  48741. if (axisProxy) {
  48742. var axis = axisProxy.getAxisModel().axis;
  48743. var range = this._range;
  48744. var dataInterval = nonRealtime
  48745. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  48746. ? axisProxy.calculateDataWindow({
  48747. start: range[0], end: range[1]
  48748. }).valueWindow
  48749. : axisProxy.getDataValueWindow();
  48750. labelTexts = [
  48751. this._formatLabel(dataInterval[0], axis),
  48752. this._formatLabel(dataInterval[1], axis)
  48753. ];
  48754. }
  48755. }
  48756. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  48757. setLabel.call(this, 0);
  48758. setLabel.call(this, 1);
  48759. function setLabel(handleIndex) {
  48760. // Label
  48761. // Text should not transform by barGroup.
  48762. // Ignore handlers transform
  48763. var barTransform = getTransform(
  48764. displaybles.handles[handleIndex].parent, this.group
  48765. );
  48766. var direction = transformDirection(
  48767. handleIndex === 0 ? 'right' : 'left', barTransform
  48768. );
  48769. var offset = this._handleWidth / 2 + LABEL_GAP;
  48770. var textPoint = applyTransform$1(
  48771. [
  48772. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  48773. this._size[1] / 2
  48774. ],
  48775. barTransform
  48776. );
  48777. handleLabels[handleIndex].setStyle({
  48778. x: textPoint[0],
  48779. y: textPoint[1],
  48780. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  48781. textAlign: orient === HORIZONTAL ? direction : 'center',
  48782. text: labelTexts[handleIndex]
  48783. });
  48784. }
  48785. },
  48786. /**
  48787. * @private
  48788. */
  48789. _formatLabel: function (value, axis) {
  48790. var dataZoomModel = this.dataZoomModel;
  48791. var labelFormatter = dataZoomModel.get('labelFormatter');
  48792. var labelPrecision = dataZoomModel.get('labelPrecision');
  48793. if (labelPrecision == null || labelPrecision === 'auto') {
  48794. labelPrecision = axis.getPixelPrecision();
  48795. }
  48796. var valueStr = (value == null || isNaN(value))
  48797. ? ''
  48798. // FIXME Glue code
  48799. : (axis.type === 'category' || axis.type === 'time')
  48800. ? axis.scale.getLabel(Math.round(value))
  48801. // param of toFixed should less then 20.
  48802. : value.toFixed(Math.min(labelPrecision, 20));
  48803. return isFunction$1(labelFormatter)
  48804. ? labelFormatter(value, valueStr)
  48805. : isString(labelFormatter)
  48806. ? labelFormatter.replace('{value}', valueStr)
  48807. : valueStr;
  48808. },
  48809. /**
  48810. * @private
  48811. * @param {boolean} showOrHide true: show, false: hide
  48812. */
  48813. _showDataInfo: function (showOrHide) {
  48814. // Always show when drgging.
  48815. showOrHide = this._dragging || showOrHide;
  48816. var handleLabels = this._displayables.handleLabels;
  48817. handleLabels[0].attr('invisible', !showOrHide);
  48818. handleLabels[1].attr('invisible', !showOrHide);
  48819. },
  48820. _onDragMove: function (handleIndex, dx, dy, event) {
  48821. this._dragging = true;
  48822. // For mobile device, prevent screen slider on the button.
  48823. stop(event.event);
  48824. // Transform dx, dy to bar coordination.
  48825. var barTransform = this._displayables.barGroup.getLocalTransform();
  48826. var vertex = applyTransform$1([dx, dy], barTransform, true);
  48827. var changed = this._updateInterval(handleIndex, vertex[0]);
  48828. var realtime = this.dataZoomModel.get('realtime');
  48829. this._updateView(!realtime);
  48830. // Avoid dispatch dataZoom repeatly but range not changed,
  48831. // which cause bad visual effect when progressive enabled.
  48832. changed && realtime && this._dispatchZoomAction();
  48833. },
  48834. _onDragEnd: function () {
  48835. this._dragging = false;
  48836. this._showDataInfo(false);
  48837. // While in realtime mode and stream mode, dispatch action when
  48838. // drag end will cause the whole view rerender, which is unnecessary.
  48839. var realtime = this.dataZoomModel.get('realtime');
  48840. !realtime && this._dispatchZoomAction();
  48841. },
  48842. _onClickPanelClick: function (e) {
  48843. var size = this._size;
  48844. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  48845. if (localPoint[0] < 0 || localPoint[0] > size[0]
  48846. || localPoint[1] < 0 || localPoint[1] > size[1]
  48847. ) {
  48848. return;
  48849. }
  48850. var handleEnds = this._handleEnds;
  48851. var center = (handleEnds[0] + handleEnds[1]) / 2;
  48852. var changed = this._updateInterval('all', localPoint[0] - center);
  48853. this._updateView();
  48854. changed && this._dispatchZoomAction();
  48855. },
  48856. /**
  48857. * This action will be throttled.
  48858. * @private
  48859. */
  48860. _dispatchZoomAction: function () {
  48861. var range = this._range;
  48862. this.api.dispatchAction({
  48863. type: 'dataZoom',
  48864. from: this.uid,
  48865. dataZoomId: this.dataZoomModel.id,
  48866. start: range[0],
  48867. end: range[1]
  48868. });
  48869. },
  48870. /**
  48871. * @private
  48872. */
  48873. _findCoordRect: function () {
  48874. // Find the grid coresponding to the first axis referred by dataZoom.
  48875. var rect;
  48876. each$14(this.getTargetCoordInfo(), function (coordInfoList) {
  48877. if (!rect && coordInfoList.length) {
  48878. var coordSys = coordInfoList[0].model.coordinateSystem;
  48879. rect = coordSys.getRect && coordSys.getRect();
  48880. }
  48881. });
  48882. if (!rect) {
  48883. var width = this.api.getWidth();
  48884. var height = this.api.getHeight();
  48885. rect = {
  48886. x: width * 0.2,
  48887. y: height * 0.2,
  48888. width: width * 0.6,
  48889. height: height * 0.6
  48890. };
  48891. }
  48892. return rect;
  48893. }
  48894. });
  48895. function getOtherDim(thisDim) {
  48896. // FIXME
  48897. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  48898. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  48899. return map$$1[thisDim];
  48900. }
  48901. function getCursor(orient) {
  48902. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  48903. }
  48904. /*
  48905. * Licensed to the Apache Software Foundation (ASF) under one
  48906. * or more contributor license agreements. See the NOTICE file
  48907. * distributed with this work for additional information
  48908. * regarding copyright ownership. The ASF licenses this file
  48909. * to you under the Apache License, Version 2.0 (the
  48910. * "License"); you may not use this file except in compliance
  48911. * with the License. You may obtain a copy of the License at
  48912. *
  48913. * http://www.apache.org/licenses/LICENSE-2.0
  48914. *
  48915. * Unless required by applicable law or agreed to in writing,
  48916. * software distributed under the License is distributed on an
  48917. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48918. * KIND, either express or implied. See the License for the
  48919. * specific language governing permissions and limitations
  48920. * under the License.
  48921. */
  48922. registerProcessor({
  48923. // `dataZoomProcessor` will only be performed in needed series. Consider if
  48924. // there is a line series and a pie series, it is better not to update the
  48925. // line series if only pie series is needed to be updated.
  48926. getTargetSeries: function (ecModel) {
  48927. var seriesModelMap = createHashMap();
  48928. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48929. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48930. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  48931. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  48932. seriesModelMap.set(seriesModel.uid, seriesModel);
  48933. });
  48934. });
  48935. });
  48936. return seriesModelMap;
  48937. },
  48938. modifyOutputEnd: true,
  48939. // Consider appendData, where filter should be performed. Because data process is
  48940. // in block mode currently, it is not need to worry about that the overallProgress
  48941. // execute every frame.
  48942. overallReset: function (ecModel, api) {
  48943. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48944. // We calculate window and reset axis here but not in model
  48945. // init stage and not after action dispatch handler, because
  48946. // reset should be called after seriesData.restoreData.
  48947. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48948. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  48949. });
  48950. // Caution: data zoom filtering is order sensitive when using
  48951. // percent range and no min/max/scale set on axis.
  48952. // For example, we have dataZoom definition:
  48953. // [
  48954. // {xAxisIndex: 0, start: 30, end: 70},
  48955. // {yAxisIndex: 0, start: 20, end: 80}
  48956. // ]
  48957. // In this case, [20, 80] of y-dataZoom should be based on data
  48958. // that have filtered by x-dataZoom using range of [30, 70],
  48959. // but should not be based on full raw data. Thus sliding
  48960. // x-dataZoom will change both ranges of xAxis and yAxis,
  48961. // while sliding y-dataZoom will only change the range of yAxis.
  48962. // So we should filter x-axis after reset x-axis immediately,
  48963. // and then reset y-axis and filter y-axis.
  48964. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  48965. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  48966. });
  48967. });
  48968. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  48969. // Fullfill all of the range props so that user
  48970. // is able to get them from chart.getOption().
  48971. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  48972. var percentRange = axisProxy.getDataPercentWindow();
  48973. var valueRange = axisProxy.getDataValueWindow();
  48974. dataZoomModel.setCalculatedRange({
  48975. start: percentRange[0],
  48976. end: percentRange[1],
  48977. startValue: valueRange[0],
  48978. endValue: valueRange[1]
  48979. });
  48980. });
  48981. }
  48982. });
  48983. /*
  48984. * Licensed to the Apache Software Foundation (ASF) under one
  48985. * or more contributor license agreements. See the NOTICE file
  48986. * distributed with this work for additional information
  48987. * regarding copyright ownership. The ASF licenses this file
  48988. * to you under the Apache License, Version 2.0 (the
  48989. * "License"); you may not use this file except in compliance
  48990. * with the License. You may obtain a copy of the License at
  48991. *
  48992. * http://www.apache.org/licenses/LICENSE-2.0
  48993. *
  48994. * Unless required by applicable law or agreed to in writing,
  48995. * software distributed under the License is distributed on an
  48996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48997. * KIND, either express or implied. See the License for the
  48998. * specific language governing permissions and limitations
  48999. * under the License.
  49000. */
  49001. registerAction('dataZoom', function (payload, ecModel) {
  49002. var linkedNodesFinder = createLinkedNodesFinder(
  49003. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  49004. eachAxisDim$1,
  49005. function (model, dimNames) {
  49006. return model.get(dimNames.axisIndex);
  49007. }
  49008. );
  49009. var effectedModels = [];
  49010. ecModel.eachComponent(
  49011. {mainType: 'dataZoom', query: payload},
  49012. function (model, index) {
  49013. effectedModels.push.apply(
  49014. effectedModels, linkedNodesFinder(model).nodes
  49015. );
  49016. }
  49017. );
  49018. each$1(effectedModels, function (dataZoomModel, index) {
  49019. dataZoomModel.setRawRange({
  49020. start: payload.start,
  49021. end: payload.end,
  49022. startValue: payload.startValue,
  49023. endValue: payload.endValue
  49024. });
  49025. });
  49026. });
  49027. /*
  49028. * Licensed to the Apache Software Foundation (ASF) under one
  49029. * or more contributor license agreements. See the NOTICE file
  49030. * distributed with this work for additional information
  49031. * regarding copyright ownership. The ASF licenses this file
  49032. * to you under the Apache License, Version 2.0 (the
  49033. * "License"); you may not use this file except in compliance
  49034. * with the License. You may obtain a copy of the License at
  49035. *
  49036. * http://www.apache.org/licenses/LICENSE-2.0
  49037. *
  49038. * Unless required by applicable law or agreed to in writing,
  49039. * software distributed under the License is distributed on an
  49040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49041. * KIND, either express or implied. See the License for the
  49042. * specific language governing permissions and limitations
  49043. * under the License.
  49044. */
  49045. /*
  49046. * Licensed to the Apache Software Foundation (ASF) under one
  49047. * or more contributor license agreements. See the NOTICE file
  49048. * distributed with this work for additional information
  49049. * regarding copyright ownership. The ASF licenses this file
  49050. * to you under the Apache License, Version 2.0 (the
  49051. * "License"); you may not use this file except in compliance
  49052. * with the License. You may obtain a copy of the License at
  49053. *
  49054. * http://www.apache.org/licenses/LICENSE-2.0
  49055. *
  49056. * Unless required by applicable law or agreed to in writing,
  49057. * software distributed under the License is distributed on an
  49058. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49059. * KIND, either express or implied. See the License for the
  49060. * specific language governing permissions and limitations
  49061. * under the License.
  49062. */
  49063. DataZoomModel.extend({
  49064. type: 'dataZoom.inside',
  49065. /**
  49066. * @protected
  49067. */
  49068. defaultOption: {
  49069. disabled: false, // Whether disable this inside zoom.
  49070. zoomLock: false, // Whether disable zoom but only pan.
  49071. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49072. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49073. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49074. preventDefaultMouseMove: true
  49075. }
  49076. });
  49077. /*
  49078. * Licensed to the Apache Software Foundation (ASF) under one
  49079. * or more contributor license agreements. See the NOTICE file
  49080. * distributed with this work for additional information
  49081. * regarding copyright ownership. The ASF licenses this file
  49082. * to you under the Apache License, Version 2.0 (the
  49083. * "License"); you may not use this file except in compliance
  49084. * with the License. You may obtain a copy of the License at
  49085. *
  49086. * http://www.apache.org/licenses/LICENSE-2.0
  49087. *
  49088. * Unless required by applicable law or agreed to in writing,
  49089. * software distributed under the License is distributed on an
  49090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49091. * KIND, either express or implied. See the License for the
  49092. * specific language governing permissions and limitations
  49093. * under the License.
  49094. */
  49095. var ATTR$1 = '\0_ec_interaction_mutex';
  49096. function take(zr, resourceKey, userKey) {
  49097. var store = getStore(zr);
  49098. store[resourceKey] = userKey;
  49099. }
  49100. function release(zr, resourceKey, userKey) {
  49101. var store = getStore(zr);
  49102. var uKey = store[resourceKey];
  49103. if (uKey === userKey) {
  49104. store[resourceKey] = null;
  49105. }
  49106. }
  49107. function isTaken(zr, resourceKey) {
  49108. return !!getStore(zr)[resourceKey];
  49109. }
  49110. function getStore(zr) {
  49111. return zr[ATTR$1] || (zr[ATTR$1] = {});
  49112. }
  49113. /**
  49114. * payload: {
  49115. * type: 'takeGlobalCursor',
  49116. * key: 'dataZoomSelect', or 'brush', or ...,
  49117. * If no userKey, release global cursor.
  49118. * }
  49119. */
  49120. registerAction(
  49121. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  49122. function () {}
  49123. );
  49124. /*
  49125. * Licensed to the Apache Software Foundation (ASF) under one
  49126. * or more contributor license agreements. See the NOTICE file
  49127. * distributed with this work for additional information
  49128. * regarding copyright ownership. The ASF licenses this file
  49129. * to you under the Apache License, Version 2.0 (the
  49130. * "License"); you may not use this file except in compliance
  49131. * with the License. You may obtain a copy of the License at
  49132. *
  49133. * http://www.apache.org/licenses/LICENSE-2.0
  49134. *
  49135. * Unless required by applicable law or agreed to in writing,
  49136. * software distributed under the License is distributed on an
  49137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49138. * KIND, either express or implied. See the License for the
  49139. * specific language governing permissions and limitations
  49140. * under the License.
  49141. */
  49142. /**
  49143. * @alias module:echarts/component/helper/RoamController
  49144. * @constructor
  49145. * @mixin {module:zrender/mixin/Eventful}
  49146. *
  49147. * @param {module:zrender/zrender~ZRender} zr
  49148. */
  49149. function RoamController(zr) {
  49150. /**
  49151. * @type {Function}
  49152. */
  49153. this.pointerChecker;
  49154. /**
  49155. * @type {module:zrender}
  49156. */
  49157. this._zr = zr;
  49158. /**
  49159. * @type {Object}
  49160. */
  49161. this._opt = {};
  49162. // Avoid two roamController bind the same handler
  49163. var bind$$1 = bind;
  49164. var mousedownHandler = bind$$1(mousedown, this);
  49165. var mousemoveHandler = bind$$1(mousemove, this);
  49166. var mouseupHandler = bind$$1(mouseup, this);
  49167. var mousewheelHandler = bind$$1(mousewheel, this);
  49168. var pinchHandler = bind$$1(pinch, this);
  49169. Eventful.call(this);
  49170. /**
  49171. * @param {Function} pointerChecker
  49172. * input: x, y
  49173. * output: boolean
  49174. */
  49175. this.setPointerChecker = function (pointerChecker) {
  49176. this.pointerChecker = pointerChecker;
  49177. };
  49178. /**
  49179. * Notice: only enable needed types. For example, if 'zoom'
  49180. * is not needed, 'zoom' should not be enabled, otherwise
  49181. * default mousewheel behaviour (scroll page) will be disabled.
  49182. *
  49183. * @param {boolean|string} [controlType=true] Specify the control type,
  49184. * which can be null/undefined or true/false
  49185. * or 'pan/move' or 'zoom'/'scale'
  49186. * @param {Object} [opt]
  49187. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49188. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49189. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49190. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  49191. */
  49192. this.enable = function (controlType, opt) {
  49193. // Disable previous first
  49194. this.disable();
  49195. this._opt = defaults(clone(opt) || {}, {
  49196. zoomOnMouseWheel: true,
  49197. moveOnMouseMove: true,
  49198. // By default, wheel do not trigger move.
  49199. moveOnMouseWheel: false,
  49200. preventDefaultMouseMove: true
  49201. });
  49202. if (controlType == null) {
  49203. controlType = true;
  49204. }
  49205. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  49206. zr.on('mousedown', mousedownHandler);
  49207. zr.on('mousemove', mousemoveHandler);
  49208. zr.on('mouseup', mouseupHandler);
  49209. }
  49210. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  49211. zr.on('mousewheel', mousewheelHandler);
  49212. zr.on('pinch', pinchHandler);
  49213. }
  49214. };
  49215. this.disable = function () {
  49216. zr.off('mousedown', mousedownHandler);
  49217. zr.off('mousemove', mousemoveHandler);
  49218. zr.off('mouseup', mouseupHandler);
  49219. zr.off('mousewheel', mousewheelHandler);
  49220. zr.off('pinch', pinchHandler);
  49221. };
  49222. this.dispose = this.disable;
  49223. this.isDragging = function () {
  49224. return this._dragging;
  49225. };
  49226. this.isPinching = function () {
  49227. return this._pinching;
  49228. };
  49229. }
  49230. mixin(RoamController, Eventful);
  49231. function mousedown(e) {
  49232. if (isMiddleOrRightButtonOnMouseUpDown(e)
  49233. || (e.target && e.target.draggable)
  49234. ) {
  49235. return;
  49236. }
  49237. var x = e.offsetX;
  49238. var y = e.offsetY;
  49239. // Only check on mosedown, but not mousemove.
  49240. // Mouse can be out of target when mouse moving.
  49241. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  49242. this._x = x;
  49243. this._y = y;
  49244. this._dragging = true;
  49245. }
  49246. }
  49247. function mousemove(e) {
  49248. if (!this._dragging
  49249. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  49250. || e.gestureEvent === 'pinch'
  49251. || isTaken(this._zr, 'globalPan')
  49252. ) {
  49253. return;
  49254. }
  49255. var x = e.offsetX;
  49256. var y = e.offsetY;
  49257. var oldX = this._x;
  49258. var oldY = this._y;
  49259. var dx = x - oldX;
  49260. var dy = y - oldY;
  49261. this._x = x;
  49262. this._y = y;
  49263. this._opt.preventDefaultMouseMove && stop(e.event);
  49264. trigger(this, 'pan', 'moveOnMouseMove', e, {
  49265. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  49266. });
  49267. }
  49268. function mouseup(e) {
  49269. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  49270. this._dragging = false;
  49271. }
  49272. }
  49273. function mousewheel(e) {
  49274. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  49275. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  49276. var wheelDelta = e.wheelDelta;
  49277. var absWheelDeltaDelta = Math.abs(wheelDelta);
  49278. var originX = e.offsetX;
  49279. var originY = e.offsetY;
  49280. // wheelDelta maybe -0 in chrome mac.
  49281. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  49282. return;
  49283. }
  49284. // If both `shouldZoom` and `shouldMove` is true, trigger
  49285. // their event both, and the final behavior is determined
  49286. // by event listener themselves.
  49287. if (shouldZoom) {
  49288. // Convenience:
  49289. // Mac and VM Windows on Mac: scroll up: zoom out.
  49290. // Windows: scroll up: zoom in.
  49291. // FIXME: Should do more test in different environment.
  49292. // wheelDelta is too complicated in difference nvironment
  49293. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  49294. // although it has been normallized by zrender.
  49295. // wheelDelta of mouse wheel is bigger than touch pad.
  49296. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  49297. var scale = wheelDelta > 0 ? factor : 1 / factor;
  49298. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  49299. scale: scale, originX: originX, originY: originY
  49300. });
  49301. }
  49302. if (shouldMove) {
  49303. // FIXME: Should do more test in different environment.
  49304. var absDelta = Math.abs(wheelDelta);
  49305. // wheelDelta of mouse wheel is bigger than touch pad.
  49306. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  49307. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  49308. scrollDelta: scrollDelta, originX: originX, originY: originY
  49309. });
  49310. }
  49311. }
  49312. function pinch(e) {
  49313. if (isTaken(this._zr, 'globalPan')) {
  49314. return;
  49315. }
  49316. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  49317. checkPointerAndTrigger(this, 'zoom', null, e, {
  49318. scale: scale, originX: e.pinchX, originY: e.pinchY
  49319. });
  49320. }
  49321. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49322. if (controller.pointerChecker
  49323. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  49324. ) {
  49325. // When mouse is out of roamController rect,
  49326. // default befavoius should not be be disabled, otherwise
  49327. // page sliding is disabled, contrary to expectation.
  49328. stop(e.event);
  49329. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  49330. }
  49331. }
  49332. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49333. // Also provide behavior checker for event listener, for some case that
  49334. // multiple components share one listener.
  49335. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  49336. controller.trigger(eventName, contollerEvent);
  49337. }
  49338. // settings: {
  49339. // zoomOnMouseWheel
  49340. // moveOnMouseMove
  49341. // moveOnMouseWheel
  49342. // }
  49343. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49344. function isAvailableBehavior(behaviorToCheck, e, settings) {
  49345. var setting = settings[behaviorToCheck];
  49346. return !behaviorToCheck || (
  49347. setting && (!isString(setting) || e.event[setting + 'Key'])
  49348. );
  49349. }
  49350. /*
  49351. * Licensed to the Apache Software Foundation (ASF) under one
  49352. * or more contributor license agreements. See the NOTICE file
  49353. * distributed with this work for additional information
  49354. * regarding copyright ownership. The ASF licenses this file
  49355. * to you under the Apache License, Version 2.0 (the
  49356. * "License"); you may not use this file except in compliance
  49357. * with the License. You may obtain a copy of the License at
  49358. *
  49359. * http://www.apache.org/licenses/LICENSE-2.0
  49360. *
  49361. * Unless required by applicable law or agreed to in writing,
  49362. * software distributed under the License is distributed on an
  49363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49364. * KIND, either express or implied. See the License for the
  49365. * specific language governing permissions and limitations
  49366. * under the License.
  49367. */
  49368. // Only create one roam controller for each coordinate system.
  49369. // one roam controller might be refered by two inside data zoom
  49370. // components (for example, one for x and one for y). When user
  49371. // pan or zoom, only dispatch one action for those data zoom
  49372. // components.
  49373. var ATTR = '\0_ec_dataZoom_roams';
  49374. /**
  49375. * @public
  49376. * @param {module:echarts/ExtensionAPI} api
  49377. * @param {Object} dataZoomInfo
  49378. * @param {string} dataZoomInfo.coordId
  49379. * @param {Function} dataZoomInfo.containsPoint
  49380. * @param {Array.<string>} dataZoomInfo.allCoordIds
  49381. * @param {string} dataZoomInfo.dataZoomId
  49382. * @param {Object} dataZoomInfo.getRange
  49383. * @param {Function} dataZoomInfo.getRange.pan
  49384. * @param {Function} dataZoomInfo.getRange.zoom
  49385. * @param {Function} dataZoomInfo.getRange.scrollMove
  49386. * @param {boolean} dataZoomInfo.dataZoomModel
  49387. */
  49388. function register$1(api, dataZoomInfo) {
  49389. var store = giveStore(api);
  49390. var theDataZoomId = dataZoomInfo.dataZoomId;
  49391. var theCoordId = dataZoomInfo.coordId;
  49392. // Do clean when a dataZoom changes its target coordnate system.
  49393. // Avoid memory leak, dispose all not-used-registered.
  49394. each$1(store, function (record, coordId) {
  49395. var dataZoomInfos = record.dataZoomInfos;
  49396. if (dataZoomInfos[theDataZoomId]
  49397. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  49398. ) {
  49399. delete dataZoomInfos[theDataZoomId];
  49400. record.count--;
  49401. }
  49402. });
  49403. cleanStore(store);
  49404. var record = store[theCoordId];
  49405. // Create if needed.
  49406. if (!record) {
  49407. record = store[theCoordId] = {
  49408. coordId: theCoordId,
  49409. dataZoomInfos: {},
  49410. count: 0
  49411. };
  49412. record.controller = createController(api, record);
  49413. record.dispatchAction = curry(dispatchAction, api);
  49414. }
  49415. // Update reference of dataZoom.
  49416. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  49417. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  49418. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  49419. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  49420. // Consider resize, area should be always updated.
  49421. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  49422. // Update throttle.
  49423. createOrUpdate(
  49424. record,
  49425. 'dispatchAction',
  49426. dataZoomInfo.dataZoomModel.get('throttle', true),
  49427. 'fixRate'
  49428. );
  49429. }
  49430. /**
  49431. * @public
  49432. * @param {module:echarts/ExtensionAPI} api
  49433. * @param {string} dataZoomId
  49434. */
  49435. function unregister$1(api, dataZoomId) {
  49436. var store = giveStore(api);
  49437. each$1(store, function (record) {
  49438. record.controller.dispose();
  49439. var dataZoomInfos = record.dataZoomInfos;
  49440. if (dataZoomInfos[dataZoomId]) {
  49441. delete dataZoomInfos[dataZoomId];
  49442. record.count--;
  49443. }
  49444. });
  49445. cleanStore(store);
  49446. }
  49447. /**
  49448. * @public
  49449. */
  49450. function generateCoordId(coordModel) {
  49451. return coordModel.type + '\0_' + coordModel.id;
  49452. }
  49453. /**
  49454. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  49455. * @type {Array.<Object>}
  49456. */
  49457. function giveStore(api) {
  49458. // Mount store on zrender instance, so that we do not
  49459. // need to worry about dispose.
  49460. var zr = api.getZr();
  49461. return zr[ATTR] || (zr[ATTR] = {});
  49462. }
  49463. function createController(api, newRecord) {
  49464. var controller = new RoamController(api.getZr());
  49465. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  49466. controller.on(eventName, function (event) {
  49467. var batch = [];
  49468. each$1(newRecord.dataZoomInfos, function (info) {
  49469. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  49470. // moveOnMouseWheel, ...) enabled.
  49471. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  49472. return;
  49473. }
  49474. var method = (info.getRange || {})[eventName];
  49475. var range = method && method(newRecord.controller, event);
  49476. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  49477. dataZoomId: info.dataZoomId,
  49478. start: range[0],
  49479. end: range[1]
  49480. });
  49481. });
  49482. batch.length && newRecord.dispatchAction(batch);
  49483. });
  49484. });
  49485. return controller;
  49486. }
  49487. function cleanStore(store) {
  49488. each$1(store, function (record, coordId) {
  49489. if (!record.count) {
  49490. record.controller.dispose();
  49491. delete store[coordId];
  49492. }
  49493. });
  49494. }
  49495. /**
  49496. * This action will be throttled.
  49497. */
  49498. function dispatchAction(api, batch) {
  49499. api.dispatchAction({
  49500. type: 'dataZoom',
  49501. batch: batch
  49502. });
  49503. }
  49504. /**
  49505. * Merge roamController settings when multiple dataZooms share one roamController.
  49506. */
  49507. function mergeControllerParams(dataZoomInfos) {
  49508. var controlType;
  49509. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  49510. // as string, it is probably revert to reserved word by compress tool. See #7411.
  49511. var prefix = 'type_';
  49512. var typePriority = {
  49513. 'type_true': 2,
  49514. 'type_move': 1,
  49515. 'type_false': 0,
  49516. 'type_undefined': -1
  49517. };
  49518. var preventDefaultMouseMove = true;
  49519. each$1(dataZoomInfos, function (dataZoomInfo) {
  49520. var dataZoomModel = dataZoomInfo.dataZoomModel;
  49521. var oneType = dataZoomModel.get('disabled', true)
  49522. ? false
  49523. : dataZoomModel.get('zoomLock', true)
  49524. ? 'move'
  49525. : true;
  49526. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  49527. controlType = oneType;
  49528. }
  49529. // Prevent default move event by default. If one false, do not prevent. Otherwise
  49530. // users may be confused why it does not work when multiple insideZooms exist.
  49531. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  49532. });
  49533. return {
  49534. controlType: controlType,
  49535. opt: {
  49536. // RoamController will enable all of these functionalities,
  49537. // and the final behavior is determined by its event listener
  49538. // provided by each inside zoom.
  49539. zoomOnMouseWheel: true,
  49540. moveOnMouseMove: true,
  49541. moveOnMouseWheel: true,
  49542. preventDefaultMouseMove: !!preventDefaultMouseMove
  49543. }
  49544. };
  49545. }
  49546. /*
  49547. * Licensed to the Apache Software Foundation (ASF) under one
  49548. * or more contributor license agreements. See the NOTICE file
  49549. * distributed with this work for additional information
  49550. * regarding copyright ownership. The ASF licenses this file
  49551. * to you under the Apache License, Version 2.0 (the
  49552. * "License"); you may not use this file except in compliance
  49553. * with the License. You may obtain a copy of the License at
  49554. *
  49555. * http://www.apache.org/licenses/LICENSE-2.0
  49556. *
  49557. * Unless required by applicable law or agreed to in writing,
  49558. * software distributed under the License is distributed on an
  49559. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49560. * KIND, either express or implied. See the License for the
  49561. * specific language governing permissions and limitations
  49562. * under the License.
  49563. */
  49564. var bind$4 = bind;
  49565. var InsideZoomView = DataZoomView.extend({
  49566. type: 'dataZoom.inside',
  49567. /**
  49568. * @override
  49569. */
  49570. init: function (ecModel, api) {
  49571. /**
  49572. * 'throttle' is used in this.dispatchAction, so we save range
  49573. * to avoid missing some 'pan' info.
  49574. * @private
  49575. * @type {Array.<number>}
  49576. */
  49577. this._range;
  49578. },
  49579. /**
  49580. * @override
  49581. */
  49582. render: function (dataZoomModel, ecModel, api, payload) {
  49583. InsideZoomView.superApply(this, 'render', arguments);
  49584. // Hence the `throttle` util ensures to preserve command order,
  49585. // here simply updating range all the time will not cause missing
  49586. // any of the the roam change.
  49587. this._range = dataZoomModel.getPercentRange();
  49588. // Reset controllers.
  49589. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  49590. var allCoordIds = map(coordInfoList, function (coordInfo) {
  49591. return generateCoordId(coordInfo.model);
  49592. });
  49593. each$1(coordInfoList, function (coordInfo) {
  49594. var coordModel = coordInfo.model;
  49595. var getRange = {};
  49596. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  49597. getRange[eventName] = bind$4(roamHandlers[eventName], this, coordInfo, coordSysName);
  49598. }, this);
  49599. register$1(
  49600. api,
  49601. {
  49602. coordId: generateCoordId(coordModel),
  49603. allCoordIds: allCoordIds,
  49604. containsPoint: function (e, x, y) {
  49605. return coordModel.coordinateSystem.containPoint([x, y]);
  49606. },
  49607. dataZoomId: dataZoomModel.id,
  49608. dataZoomModel: dataZoomModel,
  49609. getRange: getRange
  49610. }
  49611. );
  49612. }, this);
  49613. }, this);
  49614. },
  49615. /**
  49616. * @override
  49617. */
  49618. dispose: function () {
  49619. unregister$1(this.api, this.dataZoomModel.id);
  49620. InsideZoomView.superApply(this, 'dispose', arguments);
  49621. this._range = null;
  49622. }
  49623. });
  49624. var roamHandlers = {
  49625. /**
  49626. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49627. */
  49628. zoom: function (coordInfo, coordSysName, controller, e) {
  49629. var lastRange = this._range;
  49630. var range = lastRange.slice();
  49631. // Calculate transform by the first axis.
  49632. var axisModel = coordInfo.axisModels[0];
  49633. if (!axisModel) {
  49634. return;
  49635. }
  49636. var directionInfo = getDirectionInfo[coordSysName](
  49637. null, [e.originX, e.originY], axisModel, controller, coordInfo
  49638. );
  49639. var percentPoint = (
  49640. directionInfo.signal > 0
  49641. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  49642. : (directionInfo.pixel - directionInfo.pixelStart)
  49643. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  49644. var scale = Math.max(1 / e.scale, 0);
  49645. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  49646. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  49647. // Restrict range.
  49648. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  49649. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  49650. this._range = range;
  49651. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  49652. return range;
  49653. }
  49654. },
  49655. /**
  49656. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49657. */
  49658. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  49659. var directionInfo = getDirectionInfo[coordSysName](
  49660. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  49661. );
  49662. return directionInfo.signal
  49663. * (range[1] - range[0])
  49664. * directionInfo.pixel / directionInfo.pixelLength;
  49665. }),
  49666. /**
  49667. * @this {module:echarts/component/dataZoom/InsideZoomView}
  49668. */
  49669. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  49670. var directionInfo = getDirectionInfo[coordSysName](
  49671. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  49672. );
  49673. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  49674. })
  49675. };
  49676. function makeMover(getPercentDelta) {
  49677. return function (coordInfo, coordSysName, controller, e) {
  49678. var lastRange = this._range;
  49679. var range = lastRange.slice();
  49680. // Calculate transform by the first axis.
  49681. var axisModel = coordInfo.axisModels[0];
  49682. if (!axisModel) {
  49683. return;
  49684. }
  49685. var percentDelta = getPercentDelta(
  49686. range, axisModel, coordInfo, coordSysName, controller, e
  49687. );
  49688. sliderMove(percentDelta, range, [0, 100], 'all');
  49689. this._range = range;
  49690. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  49691. return range;
  49692. }
  49693. };
  49694. }
  49695. var getDirectionInfo = {
  49696. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49697. var axis = axisModel.axis;
  49698. var ret = {};
  49699. var rect = coordInfo.model.coordinateSystem.getRect();
  49700. oldPoint = oldPoint || [0, 0];
  49701. if (axis.dim === 'x') {
  49702. ret.pixel = newPoint[0] - oldPoint[0];
  49703. ret.pixelLength = rect.width;
  49704. ret.pixelStart = rect.x;
  49705. ret.signal = axis.inverse ? 1 : -1;
  49706. }
  49707. else { // axis.dim === 'y'
  49708. ret.pixel = newPoint[1] - oldPoint[1];
  49709. ret.pixelLength = rect.height;
  49710. ret.pixelStart = rect.y;
  49711. ret.signal = axis.inverse ? -1 : 1;
  49712. }
  49713. return ret;
  49714. },
  49715. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49716. var axis = axisModel.axis;
  49717. var ret = {};
  49718. var polar = coordInfo.model.coordinateSystem;
  49719. var radiusExtent = polar.getRadiusAxis().getExtent();
  49720. var angleExtent = polar.getAngleAxis().getExtent();
  49721. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  49722. newPoint = polar.pointToCoord(newPoint);
  49723. if (axisModel.mainType === 'radiusAxis') {
  49724. ret.pixel = newPoint[0] - oldPoint[0];
  49725. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  49726. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  49727. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  49728. ret.pixelStart = radiusExtent[0];
  49729. ret.signal = axis.inverse ? 1 : -1;
  49730. }
  49731. else { // 'angleAxis'
  49732. ret.pixel = newPoint[1] - oldPoint[1];
  49733. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  49734. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  49735. ret.pixelLength = angleExtent[1] - angleExtent[0];
  49736. ret.pixelStart = angleExtent[0];
  49737. ret.signal = axis.inverse ? -1 : 1;
  49738. }
  49739. return ret;
  49740. },
  49741. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  49742. var axis = axisModel.axis;
  49743. var rect = coordInfo.model.coordinateSystem.getRect();
  49744. var ret = {};
  49745. oldPoint = oldPoint || [0, 0];
  49746. if (axis.orient === 'horizontal') {
  49747. ret.pixel = newPoint[0] - oldPoint[0];
  49748. ret.pixelLength = rect.width;
  49749. ret.pixelStart = rect.x;
  49750. ret.signal = axis.inverse ? 1 : -1;
  49751. }
  49752. else { // 'vertical'
  49753. ret.pixel = newPoint[1] - oldPoint[1];
  49754. ret.pixelLength = rect.height;
  49755. ret.pixelStart = rect.y;
  49756. ret.signal = axis.inverse ? -1 : 1;
  49757. }
  49758. return ret;
  49759. }
  49760. };
  49761. /*
  49762. * Licensed to the Apache Software Foundation (ASF) under one
  49763. * or more contributor license agreements. See the NOTICE file
  49764. * distributed with this work for additional information
  49765. * regarding copyright ownership. The ASF licenses this file
  49766. * to you under the Apache License, Version 2.0 (the
  49767. * "License"); you may not use this file except in compliance
  49768. * with the License. You may obtain a copy of the License at
  49769. *
  49770. * http://www.apache.org/licenses/LICENSE-2.0
  49771. *
  49772. * Unless required by applicable law or agreed to in writing,
  49773. * software distributed under the License is distributed on an
  49774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49775. * KIND, either express or implied. See the License for the
  49776. * specific language governing permissions and limitations
  49777. * under the License.
  49778. */
  49779. /*
  49780. * Licensed to the Apache Software Foundation (ASF) under one
  49781. * or more contributor license agreements. See the NOTICE file
  49782. * distributed with this work for additional information
  49783. * regarding copyright ownership. The ASF licenses this file
  49784. * to you under the Apache License, Version 2.0 (the
  49785. * "License"); you may not use this file except in compliance
  49786. * with the License. You may obtain a copy of the License at
  49787. *
  49788. * http://www.apache.org/licenses/LICENSE-2.0
  49789. *
  49790. * Unless required by applicable law or agreed to in writing,
  49791. * software distributed under the License is distributed on an
  49792. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49793. * KIND, either express or implied. See the License for the
  49794. * specific language governing permissions and limitations
  49795. * under the License.
  49796. */
  49797. // Do not include './dataZoomSelect',
  49798. // since it only work for toolbox dataZoom.
  49799. /*
  49800. * Licensed to the Apache Software Foundation (ASF) under one
  49801. * or more contributor license agreements. See the NOTICE file
  49802. * distributed with this work for additional information
  49803. * regarding copyright ownership. The ASF licenses this file
  49804. * to you under the Apache License, Version 2.0 (the
  49805. * "License"); you may not use this file except in compliance
  49806. * with the License. You may obtain a copy of the License at
  49807. *
  49808. * http://www.apache.org/licenses/LICENSE-2.0
  49809. *
  49810. * Unless required by applicable law or agreed to in writing,
  49811. * software distributed under the License is distributed on an
  49812. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49813. * KIND, either express or implied. See the License for the
  49814. * specific language governing permissions and limitations
  49815. * under the License.
  49816. */
  49817. var features = {};
  49818. function register$2(name, ctor) {
  49819. features[name] = ctor;
  49820. }
  49821. function get$1(name) {
  49822. return features[name];
  49823. }
  49824. /*
  49825. * Licensed to the Apache Software Foundation (ASF) under one
  49826. * or more contributor license agreements. See the NOTICE file
  49827. * distributed with this work for additional information
  49828. * regarding copyright ownership. The ASF licenses this file
  49829. * to you under the Apache License, Version 2.0 (the
  49830. * "License"); you may not use this file except in compliance
  49831. * with the License. You may obtain a copy of the License at
  49832. *
  49833. * http://www.apache.org/licenses/LICENSE-2.0
  49834. *
  49835. * Unless required by applicable law or agreed to in writing,
  49836. * software distributed under the License is distributed on an
  49837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49838. * KIND, either express or implied. See the License for the
  49839. * specific language governing permissions and limitations
  49840. * under the License.
  49841. */
  49842. var ToolboxModel = extendComponentModel({
  49843. type: 'toolbox',
  49844. layoutMode: {
  49845. type: 'box',
  49846. ignoreSize: true
  49847. },
  49848. optionUpdated: function () {
  49849. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  49850. each$1(this.option.feature, function (featureOpt, featureName) {
  49851. var Feature = get$1(featureName);
  49852. Feature && merge(featureOpt, Feature.defaultOption);
  49853. });
  49854. },
  49855. defaultOption: {
  49856. show: true,
  49857. z: 6,
  49858. zlevel: 0,
  49859. orient: 'horizontal',
  49860. left: 'right',
  49861. top: 'top',
  49862. // right
  49863. // bottom
  49864. backgroundColor: 'transparent',
  49865. borderColor: '#ccc',
  49866. borderRadius: 0,
  49867. borderWidth: 0,
  49868. padding: 5,
  49869. itemSize: 15,
  49870. itemGap: 8,
  49871. showTitle: true,
  49872. iconStyle: {
  49873. borderColor: '#666',
  49874. color: 'none'
  49875. },
  49876. emphasis: {
  49877. iconStyle: {
  49878. borderColor: '#3E98C5'
  49879. }
  49880. },
  49881. // textStyle: {},
  49882. // feature
  49883. tooltip: {
  49884. show: false
  49885. }
  49886. }
  49887. });
  49888. /*
  49889. * Licensed to the Apache Software Foundation (ASF) under one
  49890. * or more contributor license agreements. See the NOTICE file
  49891. * distributed with this work for additional information
  49892. * regarding copyright ownership. The ASF licenses this file
  49893. * to you under the Apache License, Version 2.0 (the
  49894. * "License"); you may not use this file except in compliance
  49895. * with the License. You may obtain a copy of the License at
  49896. *
  49897. * http://www.apache.org/licenses/LICENSE-2.0
  49898. *
  49899. * Unless required by applicable law or agreed to in writing,
  49900. * software distributed under the License is distributed on an
  49901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49902. * KIND, either express or implied. See the License for the
  49903. * specific language governing permissions and limitations
  49904. * under the License.
  49905. */
  49906. extendComponentView({
  49907. type: 'toolbox',
  49908. render: function (toolboxModel, ecModel, api, payload) {
  49909. var group = this.group;
  49910. group.removeAll();
  49911. if (!toolboxModel.get('show')) {
  49912. return;
  49913. }
  49914. var itemSize = +toolboxModel.get('itemSize');
  49915. var featureOpts = toolboxModel.get('feature') || {};
  49916. var features = this._features || (this._features = {});
  49917. var featureNames = [];
  49918. each$1(featureOpts, function (opt, name) {
  49919. featureNames.push(name);
  49920. });
  49921. (new DataDiffer(this._featureNames || [], featureNames))
  49922. .add(processFeature)
  49923. .update(processFeature)
  49924. .remove(curry(processFeature, null))
  49925. .execute();
  49926. // Keep for diff.
  49927. this._featureNames = featureNames;
  49928. function processFeature(newIndex, oldIndex) {
  49929. var featureName = featureNames[newIndex];
  49930. var oldName = featureNames[oldIndex];
  49931. var featureOpt = featureOpts[featureName];
  49932. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  49933. var feature;
  49934. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  49935. if (payload && payload.newTitle != null) {
  49936. featureOpt.title = payload.newTitle;
  49937. }
  49938. if (featureName && !oldName) { // Create
  49939. if (isUserFeatureName(featureName)) {
  49940. feature = {
  49941. model: featureModel,
  49942. onclick: featureModel.option.onclick,
  49943. featureName: featureName
  49944. };
  49945. }
  49946. else {
  49947. var Feature = get$1(featureName);
  49948. if (!Feature) {
  49949. return;
  49950. }
  49951. feature = new Feature(featureModel, ecModel, api);
  49952. }
  49953. features[featureName] = feature;
  49954. }
  49955. else {
  49956. feature = features[oldName];
  49957. // If feature does not exsit.
  49958. if (!feature) {
  49959. return;
  49960. }
  49961. feature.model = featureModel;
  49962. feature.ecModel = ecModel;
  49963. feature.api = api;
  49964. }
  49965. if (!featureName && oldName) {
  49966. feature.dispose && feature.dispose(ecModel, api);
  49967. return;
  49968. }
  49969. if (!featureModel.get('show') || feature.unusable) {
  49970. feature.remove && feature.remove(ecModel, api);
  49971. return;
  49972. }
  49973. createIconPaths(featureModel, feature, featureName);
  49974. featureModel.setIconStatus = function (iconName, status) {
  49975. var option = this.option;
  49976. var iconPaths = this.iconPaths;
  49977. option.iconStatus = option.iconStatus || {};
  49978. option.iconStatus[iconName] = status;
  49979. // FIXME
  49980. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  49981. };
  49982. if (feature.render) {
  49983. feature.render(featureModel, ecModel, api, payload);
  49984. }
  49985. }
  49986. function createIconPaths(featureModel, feature, featureName) {
  49987. var iconStyleModel = featureModel.getModel('iconStyle');
  49988. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  49989. // If one feature has mutiple icon. they are orginaized as
  49990. // {
  49991. // icon: {
  49992. // foo: '',
  49993. // bar: ''
  49994. // },
  49995. // title: {
  49996. // foo: '',
  49997. // bar: ''
  49998. // }
  49999. // }
  50000. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  50001. var titles = featureModel.get('title') || {};
  50002. if (typeof icons === 'string') {
  50003. var icon = icons;
  50004. var title = titles;
  50005. icons = {};
  50006. titles = {};
  50007. icons[featureName] = icon;
  50008. titles[featureName] = title;
  50009. }
  50010. var iconPaths = featureModel.iconPaths = {};
  50011. each$1(icons, function (iconStr, iconName) {
  50012. var path = createIcon(
  50013. iconStr,
  50014. {},
  50015. {
  50016. x: -itemSize / 2,
  50017. y: -itemSize / 2,
  50018. width: itemSize,
  50019. height: itemSize
  50020. }
  50021. );
  50022. path.setStyle(iconStyleModel.getItemStyle());
  50023. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50024. // Text position calculation
  50025. path.setStyle({
  50026. text: titles[iconName],
  50027. textAlign: iconStyleEmphasisModel.get('textAlign'),
  50028. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  50029. textPadding: iconStyleEmphasisModel.get('textPadding'),
  50030. textFill: null
  50031. });
  50032. var tooltipModel = toolboxModel.getModel('tooltip');
  50033. if (tooltipModel && tooltipModel.get('show')) {
  50034. path.attr('tooltip', extend({
  50035. content: titles[iconName],
  50036. formatter: tooltipModel.get('formatter', true)
  50037. || function () {
  50038. return titles[iconName];
  50039. },
  50040. formatterParams: {
  50041. componentType: 'toolbox',
  50042. name: iconName,
  50043. title: titles[iconName],
  50044. $vars: ['name', 'title']
  50045. },
  50046. position: tooltipModel.get('position', true) || 'bottom'
  50047. }, tooltipModel.option));
  50048. }
  50049. setHoverStyle(path);
  50050. if (toolboxModel.get('showTitle')) {
  50051. path.__title = titles[iconName];
  50052. path.on('mouseover', function () {
  50053. // Should not reuse above hoverStyle, which might be modified.
  50054. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50055. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  50056. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  50057. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  50058. path.setStyle({
  50059. textFill: iconStyleEmphasisModel.get('textFill')
  50060. || hoverStyle.fill || hoverStyle.stroke || '#000',
  50061. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  50062. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  50063. });
  50064. })
  50065. .on('mouseout', function () {
  50066. path.setStyle({
  50067. textFill: null,
  50068. textBackgroundColor: null
  50069. });
  50070. });
  50071. }
  50072. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  50073. group.add(path);
  50074. path.on('click', bind(
  50075. feature.onclick, feature, ecModel, api, iconName
  50076. ));
  50077. iconPaths[iconName] = path;
  50078. });
  50079. }
  50080. layout$2(group, toolboxModel, api);
  50081. // Render background after group is layout
  50082. // FIXME
  50083. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  50084. // Adjust icon title positions to avoid them out of screen
  50085. group.eachChild(function (icon) {
  50086. var titleText = icon.__title;
  50087. var hoverStyle = icon.hoverStyle;
  50088. // May be background element
  50089. if (hoverStyle && titleText) {
  50090. var rect = getBoundingRect(
  50091. titleText, makeFont(hoverStyle)
  50092. );
  50093. var offsetX = icon.position[0] + group.position[0];
  50094. var offsetY = icon.position[1] + group.position[1] + itemSize;
  50095. var needPutOnTop = false;
  50096. if (offsetY + rect.height > api.getHeight()) {
  50097. hoverStyle.textPosition = 'top';
  50098. needPutOnTop = true;
  50099. }
  50100. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  50101. if (offsetX + rect.width / 2 > api.getWidth()) {
  50102. hoverStyle.textPosition = ['100%', topOffset];
  50103. hoverStyle.textAlign = 'right';
  50104. }
  50105. else if (offsetX - rect.width / 2 < 0) {
  50106. hoverStyle.textPosition = [0, topOffset];
  50107. hoverStyle.textAlign = 'left';
  50108. }
  50109. }
  50110. });
  50111. },
  50112. updateView: function (toolboxModel, ecModel, api, payload) {
  50113. each$1(this._features, function (feature) {
  50114. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  50115. });
  50116. },
  50117. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  50118. // zrUtil.each(this._features, function (feature) {
  50119. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  50120. // });
  50121. // },
  50122. remove: function (ecModel, api) {
  50123. each$1(this._features, function (feature) {
  50124. feature.remove && feature.remove(ecModel, api);
  50125. });
  50126. this.group.removeAll();
  50127. },
  50128. dispose: function (ecModel, api) {
  50129. each$1(this._features, function (feature) {
  50130. feature.dispose && feature.dispose(ecModel, api);
  50131. });
  50132. }
  50133. });
  50134. function isUserFeatureName(featureName) {
  50135. return featureName.indexOf('my') === 0;
  50136. }
  50137. /*
  50138. * Licensed to the Apache Software Foundation (ASF) under one
  50139. * or more contributor license agreements. See the NOTICE file
  50140. * distributed with this work for additional information
  50141. * regarding copyright ownership. The ASF licenses this file
  50142. * to you under the Apache License, Version 2.0 (the
  50143. * "License"); you may not use this file except in compliance
  50144. * with the License. You may obtain a copy of the License at
  50145. *
  50146. * http://www.apache.org/licenses/LICENSE-2.0
  50147. *
  50148. * Unless required by applicable law or agreed to in writing,
  50149. * software distributed under the License is distributed on an
  50150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50151. * KIND, either express or implied. See the License for the
  50152. * specific language governing permissions and limitations
  50153. * under the License.
  50154. */
  50155. /* global Uint8Array */
  50156. var saveAsImageLang = lang.toolbox.saveAsImage;
  50157. function SaveAsImage(model) {
  50158. this.model = model;
  50159. }
  50160. SaveAsImage.defaultOption = {
  50161. show: true,
  50162. 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',
  50163. title: saveAsImageLang.title,
  50164. type: 'png',
  50165. // Default use option.backgroundColor
  50166. // backgroundColor: '#fff',
  50167. connectedBackgroundColor: '#fff',
  50168. name: '',
  50169. excludeComponents: ['toolbox'],
  50170. pixelRatio: 1,
  50171. lang: saveAsImageLang.lang.slice()
  50172. };
  50173. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  50174. var proto$2 = SaveAsImage.prototype;
  50175. proto$2.onclick = function (ecModel, api) {
  50176. var model = this.model;
  50177. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  50178. var type = model.get('type', true) || 'png';
  50179. var url = api.getConnectedDataURL({
  50180. type: type,
  50181. backgroundColor: model.get('backgroundColor', true)
  50182. || ecModel.get('backgroundColor') || '#fff',
  50183. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  50184. excludeComponents: model.get('excludeComponents'),
  50185. pixelRatio: model.get('pixelRatio')
  50186. });
  50187. // Chrome and Firefox
  50188. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  50189. var $a = document.createElement('a');
  50190. $a.download = title + '.' + type;
  50191. $a.target = '_blank';
  50192. $a.href = url;
  50193. var evt = new MouseEvent('click', {
  50194. view: window,
  50195. bubbles: true,
  50196. cancelable: false
  50197. });
  50198. $a.dispatchEvent(evt);
  50199. }
  50200. // IE
  50201. else {
  50202. if (window.navigator.msSaveOrOpenBlob) {
  50203. var bstr = atob(url.split(',')[1]);
  50204. var n = bstr.length;
  50205. var u8arr = new Uint8Array(n);
  50206. while (n--) {
  50207. u8arr[n] = bstr.charCodeAt(n);
  50208. }
  50209. var blob = new Blob([u8arr]);
  50210. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  50211. }
  50212. else {
  50213. var lang$$1 = model.get('lang');
  50214. var html = ''
  50215. + '<body style="margin:0;">'
  50216. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  50217. + '</body>';
  50218. var tab = window.open();
  50219. tab.document.write(html);
  50220. }
  50221. }
  50222. };
  50223. register$2(
  50224. 'saveAsImage', SaveAsImage
  50225. );
  50226. /*
  50227. * Licensed to the Apache Software Foundation (ASF) under one
  50228. * or more contributor license agreements. See the NOTICE file
  50229. * distributed with this work for additional information
  50230. * regarding copyright ownership. The ASF licenses this file
  50231. * to you under the Apache License, Version 2.0 (the
  50232. * "License"); you may not use this file except in compliance
  50233. * with the License. You may obtain a copy of the License at
  50234. *
  50235. * http://www.apache.org/licenses/LICENSE-2.0
  50236. *
  50237. * Unless required by applicable law or agreed to in writing,
  50238. * software distributed under the License is distributed on an
  50239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50240. * KIND, either express or implied. See the License for the
  50241. * specific language governing permissions and limitations
  50242. * under the License.
  50243. */
  50244. var magicTypeLang = lang.toolbox.magicType;
  50245. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  50246. function MagicType(model) {
  50247. this.model = model;
  50248. }
  50249. MagicType.defaultOption = {
  50250. show: true,
  50251. type: [],
  50252. // Icon group
  50253. icon: {
  50254. /* eslint-disable */
  50255. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  50256. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  50257. 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
  50258. /* eslint-enable */
  50259. },
  50260. // `line`, `bar`, `stack`, `tiled`
  50261. title: clone(magicTypeLang.title),
  50262. option: {},
  50263. seriesIndex: {}
  50264. };
  50265. var proto$3 = MagicType.prototype;
  50266. proto$3.getIcons = function () {
  50267. var model = this.model;
  50268. var availableIcons = model.get('icon');
  50269. var icons = {};
  50270. each$1(model.get('type'), function (type) {
  50271. if (availableIcons[type]) {
  50272. icons[type] = availableIcons[type];
  50273. }
  50274. });
  50275. return icons;
  50276. };
  50277. var seriesOptGenreator = {
  50278. 'line': function (seriesType, seriesId, seriesModel, model) {
  50279. if (seriesType === 'bar') {
  50280. return merge({
  50281. id: seriesId,
  50282. type: 'line',
  50283. // Preserve data related option
  50284. data: seriesModel.get('data'),
  50285. stack: seriesModel.get('stack'),
  50286. markPoint: seriesModel.get('markPoint'),
  50287. markLine: seriesModel.get('markLine')
  50288. }, model.get('option.line') || {}, true);
  50289. }
  50290. },
  50291. 'bar': function (seriesType, seriesId, seriesModel, model) {
  50292. if (seriesType === 'line') {
  50293. return merge({
  50294. id: seriesId,
  50295. type: 'bar',
  50296. // Preserve data related option
  50297. data: seriesModel.get('data'),
  50298. stack: seriesModel.get('stack'),
  50299. markPoint: seriesModel.get('markPoint'),
  50300. markLine: seriesModel.get('markLine')
  50301. }, model.get('option.bar') || {}, true);
  50302. }
  50303. },
  50304. 'stack': function (seriesType, seriesId, seriesModel, model) {
  50305. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  50306. if (seriesType === 'line' || seriesType === 'bar') {
  50307. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  50308. return merge({
  50309. id: seriesId,
  50310. stack: isStack ? '' : INNER_STACK_KEYWORD
  50311. }, model.get('option.stack') || {}, true);
  50312. }
  50313. }
  50314. };
  50315. var radioTypes = [
  50316. ['line', 'bar'],
  50317. ['stack']
  50318. ];
  50319. proto$3.onclick = function (ecModel, api, type) {
  50320. var model = this.model;
  50321. var seriesIndex = model.get('seriesIndex.' + type);
  50322. // Not supported magicType
  50323. if (!seriesOptGenreator[type]) {
  50324. return;
  50325. }
  50326. var newOption = {
  50327. series: []
  50328. };
  50329. var generateNewSeriesTypes = function (seriesModel) {
  50330. var seriesType = seriesModel.subType;
  50331. var seriesId = seriesModel.id;
  50332. var newSeriesOpt = seriesOptGenreator[type](
  50333. seriesType, seriesId, seriesModel, model
  50334. );
  50335. if (newSeriesOpt) {
  50336. // PENDING If merge original option?
  50337. defaults(newSeriesOpt, seriesModel.option);
  50338. newOption.series.push(newSeriesOpt);
  50339. }
  50340. // Modify boundaryGap
  50341. var coordSys = seriesModel.coordinateSystem;
  50342. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  50343. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  50344. if (categoryAxis) {
  50345. var axisDim = categoryAxis.dim;
  50346. var axisType = axisDim + 'Axis';
  50347. var axisModel = ecModel.queryComponents({
  50348. mainType: axisType,
  50349. index: seriesModel.get(name + 'Index'),
  50350. id: seriesModel.get(name + 'Id')
  50351. })[0];
  50352. var axisIndex = axisModel.componentIndex;
  50353. newOption[axisType] = newOption[axisType] || [];
  50354. for (var i = 0; i <= axisIndex; i++) {
  50355. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  50356. }
  50357. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  50358. }
  50359. }
  50360. };
  50361. each$1(radioTypes, function (radio) {
  50362. if (indexOf(radio, type) >= 0) {
  50363. each$1(radio, function (item) {
  50364. model.setIconStatus(item, 'normal');
  50365. });
  50366. }
  50367. });
  50368. model.setIconStatus(type, 'emphasis');
  50369. ecModel.eachComponent(
  50370. {
  50371. mainType: 'series',
  50372. query: seriesIndex == null ? null : {
  50373. seriesIndex: seriesIndex
  50374. }
  50375. }, generateNewSeriesTypes
  50376. );
  50377. var newTitle;
  50378. // Change title of stack
  50379. if (type === 'stack') {
  50380. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  50381. newTitle = isStack
  50382. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  50383. : clone(magicTypeLang.title);
  50384. }
  50385. api.dispatchAction({
  50386. type: 'changeMagicType',
  50387. currentType: type,
  50388. newOption: newOption,
  50389. newTitle: newTitle
  50390. });
  50391. };
  50392. registerAction({
  50393. type: 'changeMagicType',
  50394. event: 'magicTypeChanged',
  50395. update: 'prepareAndUpdate'
  50396. }, function (payload, ecModel) {
  50397. ecModel.mergeOption(payload.newOption);
  50398. });
  50399. register$2('magicType', MagicType);
  50400. /*
  50401. * Licensed to the Apache Software Foundation (ASF) under one
  50402. * or more contributor license agreements. See the NOTICE file
  50403. * distributed with this work for additional information
  50404. * regarding copyright ownership. The ASF licenses this file
  50405. * to you under the Apache License, Version 2.0 (the
  50406. * "License"); you may not use this file except in compliance
  50407. * with the License. You may obtain a copy of the License at
  50408. *
  50409. * http://www.apache.org/licenses/LICENSE-2.0
  50410. *
  50411. * Unless required by applicable law or agreed to in writing,
  50412. * software distributed under the License is distributed on an
  50413. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50414. * KIND, either express or implied. See the License for the
  50415. * specific language governing permissions and limitations
  50416. * under the License.
  50417. */
  50418. var dataViewLang = lang.toolbox.dataView;
  50419. var BLOCK_SPLITER = new Array(60).join('-');
  50420. var ITEM_SPLITER = '\t';
  50421. /**
  50422. * Group series into two types
  50423. * 1. on category axis, like line, bar
  50424. * 2. others, like scatter, pie
  50425. * @param {module:echarts/model/Global} ecModel
  50426. * @return {Object}
  50427. * @inner
  50428. */
  50429. function groupSeries(ecModel) {
  50430. var seriesGroupByCategoryAxis = {};
  50431. var otherSeries = [];
  50432. var meta = [];
  50433. ecModel.eachRawSeries(function (seriesModel) {
  50434. var coordSys = seriesModel.coordinateSystem;
  50435. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  50436. var baseAxis = coordSys.getBaseAxis();
  50437. if (baseAxis.type === 'category') {
  50438. var key = baseAxis.dim + '_' + baseAxis.index;
  50439. if (!seriesGroupByCategoryAxis[key]) {
  50440. seriesGroupByCategoryAxis[key] = {
  50441. categoryAxis: baseAxis,
  50442. valueAxis: coordSys.getOtherAxis(baseAxis),
  50443. series: []
  50444. };
  50445. meta.push({
  50446. axisDim: baseAxis.dim,
  50447. axisIndex: baseAxis.index
  50448. });
  50449. }
  50450. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  50451. }
  50452. else {
  50453. otherSeries.push(seriesModel);
  50454. }
  50455. }
  50456. else {
  50457. otherSeries.push(seriesModel);
  50458. }
  50459. });
  50460. return {
  50461. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  50462. other: otherSeries,
  50463. meta: meta
  50464. };
  50465. }
  50466. /**
  50467. * Assemble content of series on cateogory axis
  50468. * @param {Array.<module:echarts/model/Series>} series
  50469. * @return {string}
  50470. * @inner
  50471. */
  50472. function assembleSeriesWithCategoryAxis(series) {
  50473. var tables = [];
  50474. each$1(series, function (group, key) {
  50475. var categoryAxis = group.categoryAxis;
  50476. var valueAxis = group.valueAxis;
  50477. var valueAxisDim = valueAxis.dim;
  50478. var headers = [' '].concat(map(group.series, function (series) {
  50479. return series.name;
  50480. }));
  50481. var columns = [categoryAxis.model.getCategories()];
  50482. each$1(group.series, function (series) {
  50483. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  50484. return val;
  50485. }));
  50486. });
  50487. // Assemble table content
  50488. var lines = [headers.join(ITEM_SPLITER)];
  50489. for (var i = 0; i < columns[0].length; i++) {
  50490. var items = [];
  50491. for (var j = 0; j < columns.length; j++) {
  50492. items.push(columns[j][i]);
  50493. }
  50494. lines.push(items.join(ITEM_SPLITER));
  50495. }
  50496. tables.push(lines.join('\n'));
  50497. });
  50498. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  50499. }
  50500. /**
  50501. * Assemble content of other series
  50502. * @param {Array.<module:echarts/model/Series>} series
  50503. * @return {string}
  50504. * @inner
  50505. */
  50506. function assembleOtherSeries(series) {
  50507. return map(series, function (series) {
  50508. var data = series.getRawData();
  50509. var lines = [series.name];
  50510. var vals = [];
  50511. data.each(data.dimensions, function () {
  50512. var argLen = arguments.length;
  50513. var dataIndex = arguments[argLen - 1];
  50514. var name = data.getName(dataIndex);
  50515. for (var i = 0; i < argLen - 1; i++) {
  50516. vals[i] = arguments[i];
  50517. }
  50518. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  50519. });
  50520. return lines.join('\n');
  50521. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  50522. }
  50523. /**
  50524. * @param {module:echarts/model/Global}
  50525. * @return {Object}
  50526. * @inner
  50527. */
  50528. function getContentFromModel(ecModel) {
  50529. var result = groupSeries(ecModel);
  50530. return {
  50531. value: filter([
  50532. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  50533. assembleOtherSeries(result.other)
  50534. ], function (str) {
  50535. return str.replace(/[\n\t\s]/g, '');
  50536. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  50537. meta: result.meta
  50538. };
  50539. }
  50540. function trim$1(str) {
  50541. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  50542. }
  50543. /**
  50544. * If a block is tsv format
  50545. */
  50546. function isTSVFormat(block) {
  50547. // Simple method to find out if a block is tsv format
  50548. var firstLine = block.slice(0, block.indexOf('\n'));
  50549. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  50550. return true;
  50551. }
  50552. }
  50553. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  50554. /**
  50555. * @param {string} tsv
  50556. * @return {Object}
  50557. */
  50558. function parseTSVContents(tsv) {
  50559. var tsvLines = tsv.split(/\n+/g);
  50560. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  50561. var categories = [];
  50562. var series = map(headers, function (header) {
  50563. return {
  50564. name: header,
  50565. data: []
  50566. };
  50567. });
  50568. for (var i = 0; i < tsvLines.length; i++) {
  50569. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  50570. categories.push(items.shift());
  50571. for (var j = 0; j < items.length; j++) {
  50572. series[j] && (series[j].data[i] = items[j]);
  50573. }
  50574. }
  50575. return {
  50576. series: series,
  50577. categories: categories
  50578. };
  50579. }
  50580. /**
  50581. * @param {string} str
  50582. * @return {Array.<Object>}
  50583. * @inner
  50584. */
  50585. function parseListContents(str) {
  50586. var lines = str.split(/\n+/g);
  50587. var seriesName = trim$1(lines.shift());
  50588. var data = [];
  50589. for (var i = 0; i < lines.length; i++) {
  50590. var items = trim$1(lines[i]).split(itemSplitRegex);
  50591. var name = '';
  50592. var value;
  50593. var hasName = false;
  50594. if (isNaN(items[0])) { // First item is name
  50595. hasName = true;
  50596. name = items[0];
  50597. items = items.slice(1);
  50598. data[i] = {
  50599. name: name,
  50600. value: []
  50601. };
  50602. value = data[i].value;
  50603. }
  50604. else {
  50605. value = data[i] = [];
  50606. }
  50607. for (var j = 0; j < items.length; j++) {
  50608. value.push(+items[j]);
  50609. }
  50610. if (value.length === 1) {
  50611. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  50612. }
  50613. }
  50614. return {
  50615. name: seriesName,
  50616. data: data
  50617. };
  50618. }
  50619. /**
  50620. * @param {string} str
  50621. * @param {Array.<Object>} blockMetaList
  50622. * @return {Object}
  50623. * @inner
  50624. */
  50625. function parseContents(str, blockMetaList) {
  50626. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  50627. var newOption = {
  50628. series: []
  50629. };
  50630. each$1(blocks, function (block, idx) {
  50631. if (isTSVFormat(block)) {
  50632. var result = parseTSVContents(block);
  50633. var blockMeta = blockMetaList[idx];
  50634. var axisKey = blockMeta.axisDim + 'Axis';
  50635. if (blockMeta) {
  50636. newOption[axisKey] = newOption[axisKey] || [];
  50637. newOption[axisKey][blockMeta.axisIndex] = {
  50638. data: result.categories
  50639. };
  50640. newOption.series = newOption.series.concat(result.series);
  50641. }
  50642. }
  50643. else {
  50644. var result = parseListContents(block);
  50645. newOption.series.push(result);
  50646. }
  50647. });
  50648. return newOption;
  50649. }
  50650. /**
  50651. * @alias {module:echarts/component/toolbox/feature/DataView}
  50652. * @constructor
  50653. * @param {module:echarts/model/Model} model
  50654. */
  50655. function DataView(model) {
  50656. this._dom = null;
  50657. this.model = model;
  50658. }
  50659. DataView.defaultOption = {
  50660. show: true,
  50661. readOnly: false,
  50662. optionToContent: null,
  50663. contentToOption: null,
  50664. 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',
  50665. title: clone(dataViewLang.title),
  50666. lang: clone(dataViewLang.lang),
  50667. backgroundColor: '#fff',
  50668. textColor: '#000',
  50669. textareaColor: '#fff',
  50670. textareaBorderColor: '#333',
  50671. buttonColor: '#c23531',
  50672. buttonTextColor: '#fff'
  50673. };
  50674. DataView.prototype.onclick = function (ecModel, api) {
  50675. var container = api.getDom();
  50676. var model = this.model;
  50677. if (this._dom) {
  50678. container.removeChild(this._dom);
  50679. }
  50680. var root = document.createElement('div');
  50681. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  50682. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  50683. // Create elements
  50684. var header = document.createElement('h4');
  50685. var lang$$1 = model.get('lang') || [];
  50686. header.innerHTML = lang$$1[0] || model.get('title');
  50687. header.style.cssText = 'margin: 10px 20px;';
  50688. header.style.color = model.get('textColor');
  50689. var viewMain = document.createElement('div');
  50690. var textarea = document.createElement('textarea');
  50691. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  50692. var optionToContent = model.get('optionToContent');
  50693. var contentToOption = model.get('contentToOption');
  50694. var result = getContentFromModel(ecModel);
  50695. if (typeof optionToContent === 'function') {
  50696. var htmlOrDom = optionToContent(api.getOption());
  50697. if (typeof htmlOrDom === 'string') {
  50698. viewMain.innerHTML = htmlOrDom;
  50699. }
  50700. else if (isDom(htmlOrDom)) {
  50701. viewMain.appendChild(htmlOrDom);
  50702. }
  50703. }
  50704. else {
  50705. // Use default textarea
  50706. viewMain.appendChild(textarea);
  50707. textarea.readOnly = model.get('readOnly');
  50708. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  50709. textarea.style.color = model.get('textColor');
  50710. textarea.style.borderColor = model.get('textareaBorderColor');
  50711. textarea.style.backgroundColor = model.get('textareaColor');
  50712. textarea.value = result.value;
  50713. }
  50714. var blockMetaList = result.meta;
  50715. var buttonContainer = document.createElement('div');
  50716. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  50717. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  50718. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  50719. var closeButton = document.createElement('div');
  50720. var refreshButton = document.createElement('div');
  50721. buttonStyle += ';background-color:' + model.get('buttonColor');
  50722. buttonStyle += ';color:' + model.get('buttonTextColor');
  50723. var self = this;
  50724. function close() {
  50725. container.removeChild(root);
  50726. self._dom = null;
  50727. }
  50728. addEventListener(closeButton, 'click', close);
  50729. addEventListener(refreshButton, 'click', function () {
  50730. var newOption;
  50731. try {
  50732. if (typeof contentToOption === 'function') {
  50733. newOption = contentToOption(viewMain, api.getOption());
  50734. }
  50735. else {
  50736. newOption = parseContents(textarea.value, blockMetaList);
  50737. }
  50738. }
  50739. catch (e) {
  50740. close();
  50741. throw new Error('Data view format error ' + e);
  50742. }
  50743. if (newOption) {
  50744. api.dispatchAction({
  50745. type: 'changeDataView',
  50746. newOption: newOption
  50747. });
  50748. }
  50749. close();
  50750. });
  50751. closeButton.innerHTML = lang$$1[1];
  50752. refreshButton.innerHTML = lang$$1[2];
  50753. refreshButton.style.cssText = buttonStyle;
  50754. closeButton.style.cssText = buttonStyle;
  50755. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  50756. buttonContainer.appendChild(closeButton);
  50757. root.appendChild(header);
  50758. root.appendChild(viewMain);
  50759. root.appendChild(buttonContainer);
  50760. viewMain.style.height = (container.clientHeight - 80) + 'px';
  50761. container.appendChild(root);
  50762. this._dom = root;
  50763. };
  50764. DataView.prototype.remove = function (ecModel, api) {
  50765. this._dom && api.getDom().removeChild(this._dom);
  50766. };
  50767. DataView.prototype.dispose = function (ecModel, api) {
  50768. this.remove(ecModel, api);
  50769. };
  50770. /**
  50771. * @inner
  50772. */
  50773. function tryMergeDataOption(newData, originalData) {
  50774. return map(newData, function (newVal, idx) {
  50775. var original = originalData && originalData[idx];
  50776. if (isObject$1(original) && !isArray(original)) {
  50777. if (isObject$1(newVal) && !isArray(newVal)) {
  50778. newVal = newVal.value;
  50779. }
  50780. // Original data has option
  50781. return defaults({
  50782. value: newVal
  50783. }, original);
  50784. }
  50785. else {
  50786. return newVal;
  50787. }
  50788. });
  50789. }
  50790. register$2('dataView', DataView);
  50791. registerAction({
  50792. type: 'changeDataView',
  50793. event: 'dataViewChanged',
  50794. update: 'prepareAndUpdate'
  50795. }, function (payload, ecModel) {
  50796. var newSeriesOptList = [];
  50797. each$1(payload.newOption.series, function (seriesOpt) {
  50798. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  50799. if (!seriesModel) {
  50800. // New created series
  50801. // Geuss the series type
  50802. newSeriesOptList.push(extend({
  50803. // Default is scatter
  50804. type: 'scatter'
  50805. }, seriesOpt));
  50806. }
  50807. else {
  50808. var originalData = seriesModel.get('data');
  50809. newSeriesOptList.push({
  50810. name: seriesOpt.name,
  50811. data: tryMergeDataOption(seriesOpt.data, originalData)
  50812. });
  50813. }
  50814. });
  50815. ecModel.mergeOption(defaults({
  50816. series: newSeriesOptList
  50817. }, payload.newOption));
  50818. });
  50819. /*
  50820. * Licensed to the Apache Software Foundation (ASF) under one
  50821. * or more contributor license agreements. See the NOTICE file
  50822. * distributed with this work for additional information
  50823. * regarding copyright ownership. The ASF licenses this file
  50824. * to you under the Apache License, Version 2.0 (the
  50825. * "License"); you may not use this file except in compliance
  50826. * with the License. You may obtain a copy of the License at
  50827. *
  50828. * http://www.apache.org/licenses/LICENSE-2.0
  50829. *
  50830. * Unless required by applicable law or agreed to in writing,
  50831. * software distributed under the License is distributed on an
  50832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50833. * KIND, either express or implied. See the License for the
  50834. * specific language governing permissions and limitations
  50835. * under the License.
  50836. */
  50837. var curry$5 = curry;
  50838. var each$16 = each$1;
  50839. var map$2 = map;
  50840. var mathMin$5 = Math.min;
  50841. var mathMax$5 = Math.max;
  50842. var mathPow$2 = Math.pow;
  50843. var COVER_Z = 10000;
  50844. var UNSELECT_THRESHOLD = 6;
  50845. var MIN_RESIZE_LINE_WIDTH = 6;
  50846. var MUTEX_RESOURCE_KEY = 'globalPan';
  50847. var DIRECTION_MAP = {
  50848. w: [0, 0],
  50849. e: [0, 1],
  50850. n: [1, 0],
  50851. s: [1, 1]
  50852. };
  50853. var CURSOR_MAP = {
  50854. w: 'ew',
  50855. e: 'ew',
  50856. n: 'ns',
  50857. s: 'ns',
  50858. ne: 'nesw',
  50859. sw: 'nesw',
  50860. nw: 'nwse',
  50861. se: 'nwse'
  50862. };
  50863. var DEFAULT_BRUSH_OPT = {
  50864. brushStyle: {
  50865. lineWidth: 2,
  50866. stroke: 'rgba(0,0,0,0.3)',
  50867. fill: 'rgba(0,0,0,0.1)'
  50868. },
  50869. transformable: true,
  50870. brushMode: 'single',
  50871. removeOnClick: false
  50872. };
  50873. var baseUID = 0;
  50874. /**
  50875. * @alias module:echarts/component/helper/BrushController
  50876. * @constructor
  50877. * @mixin {module:zrender/mixin/Eventful}
  50878. * @event module:echarts/component/helper/BrushController#brush
  50879. * params:
  50880. * areas: Array.<Array>, coord relates to container group,
  50881. * If no container specified, to global.
  50882. * opt {
  50883. * isEnd: boolean,
  50884. * removeOnClick: boolean
  50885. * }
  50886. *
  50887. * @param {module:zrender/zrender~ZRender} zr
  50888. */
  50889. function BrushController(zr) {
  50890. if (__DEV__) {
  50891. assert$1(zr);
  50892. }
  50893. Eventful.call(this);
  50894. /**
  50895. * @type {module:zrender/zrender~ZRender}
  50896. * @private
  50897. */
  50898. this._zr = zr;
  50899. /**
  50900. * @type {module:zrender/container/Group}
  50901. * @readOnly
  50902. */
  50903. this.group = new Group();
  50904. /**
  50905. * Only for drawing (after enabledBrush).
  50906. * 'line', 'rect', 'polygon' or false
  50907. * If passing false/null/undefined, disable brush.
  50908. * If passing 'auto', determined by panel.defaultBrushType
  50909. * @private
  50910. * @type {string}
  50911. */
  50912. this._brushType;
  50913. /**
  50914. * Only for drawing (after enabledBrush).
  50915. *
  50916. * @private
  50917. * @type {Object}
  50918. */
  50919. this._brushOption;
  50920. /**
  50921. * @private
  50922. * @type {Object}
  50923. */
  50924. this._panels;
  50925. /**
  50926. * @private
  50927. * @type {Array.<nubmer>}
  50928. */
  50929. this._track = [];
  50930. /**
  50931. * @private
  50932. * @type {boolean}
  50933. */
  50934. this._dragging;
  50935. /**
  50936. * @private
  50937. * @type {Array}
  50938. */
  50939. this._covers = [];
  50940. /**
  50941. * @private
  50942. * @type {moudule:zrender/container/Group}
  50943. */
  50944. this._creatingCover;
  50945. /**
  50946. * `true` means global panel
  50947. * @private
  50948. * @type {module:zrender/container/Group|boolean}
  50949. */
  50950. this._creatingPanel;
  50951. /**
  50952. * @private
  50953. * @type {boolean}
  50954. */
  50955. this._enableGlobalPan;
  50956. /**
  50957. * @private
  50958. * @type {boolean}
  50959. */
  50960. if (__DEV__) {
  50961. this._mounted;
  50962. }
  50963. /**
  50964. * @private
  50965. * @type {string}
  50966. */
  50967. this._uid = 'brushController_' + baseUID++;
  50968. /**
  50969. * @private
  50970. * @type {Object}
  50971. */
  50972. this._handlers = {};
  50973. each$16(pointerHandlers, function (handler, eventName) {
  50974. this._handlers[eventName] = bind(handler, this);
  50975. }, this);
  50976. }
  50977. BrushController.prototype = {
  50978. constructor: BrushController,
  50979. /**
  50980. * If set to null/undefined/false, select disabled.
  50981. * @param {Object} brushOption
  50982. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  50983. * If passing false/null/undefined, disable brush.
  50984. * If passing 'auto', determined by panel.defaultBrushType.
  50985. * ('auto' can not be used in global panel)
  50986. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  50987. * @param {boolean} [brushOption.transformable=true]
  50988. * @param {boolean} [brushOption.removeOnClick=false]
  50989. * @param {Object} [brushOption.brushStyle]
  50990. * @param {number} [brushOption.brushStyle.width]
  50991. * @param {number} [brushOption.brushStyle.lineWidth]
  50992. * @param {string} [brushOption.brushStyle.stroke]
  50993. * @param {string} [brushOption.brushStyle.fill]
  50994. * @param {number} [brushOption.z]
  50995. */
  50996. enableBrush: function (brushOption) {
  50997. if (__DEV__) {
  50998. assert$1(this._mounted);
  50999. }
  51000. this._brushType && doDisableBrush(this);
  51001. brushOption.brushType && doEnableBrush(this, brushOption);
  51002. return this;
  51003. },
  51004. /**
  51005. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  51006. * Each items: {
  51007. * panelId, // mandatory.
  51008. * clipPath, // mandatory. function.
  51009. * isTargetByCursor, // mandatory. function.
  51010. * defaultBrushType, // optional, only used when brushType is 'auto'.
  51011. * getLinearBrushOtherExtent, // optional. function.
  51012. * }
  51013. */
  51014. setPanels: function (panelOpts) {
  51015. if (panelOpts && panelOpts.length) {
  51016. var panels = this._panels = {};
  51017. each$1(panelOpts, function (panelOpts) {
  51018. panels[panelOpts.panelId] = clone(panelOpts);
  51019. });
  51020. }
  51021. else {
  51022. this._panels = null;
  51023. }
  51024. return this;
  51025. },
  51026. /**
  51027. * @param {Object} [opt]
  51028. * @return {boolean} [opt.enableGlobalPan=false]
  51029. */
  51030. mount: function (opt) {
  51031. opt = opt || {};
  51032. if (__DEV__) {
  51033. this._mounted = true; // should be at first.
  51034. }
  51035. this._enableGlobalPan = opt.enableGlobalPan;
  51036. var thisGroup = this.group;
  51037. this._zr.add(thisGroup);
  51038. thisGroup.attr({
  51039. position: opt.position || [0, 0],
  51040. rotation: opt.rotation || 0,
  51041. scale: opt.scale || [1, 1]
  51042. });
  51043. this._transform = thisGroup.getLocalTransform();
  51044. return this;
  51045. },
  51046. eachCover: function (cb, context) {
  51047. each$16(this._covers, cb, context);
  51048. },
  51049. /**
  51050. * Update covers.
  51051. * @param {Array.<Object>} brushOptionList Like:
  51052. * [
  51053. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  51054. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  51055. * ...
  51056. * ]
  51057. * `brushType` is required in each cover info. (can not be 'auto')
  51058. * `id` is not mandatory.
  51059. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  51060. * If brushOptionList is null/undefined, all covers removed.
  51061. */
  51062. updateCovers: function (brushOptionList) {
  51063. if (__DEV__) {
  51064. assert$1(this._mounted);
  51065. }
  51066. brushOptionList = map(brushOptionList, function (brushOption) {
  51067. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51068. });
  51069. var tmpIdPrefix = '\0-brush-index-';
  51070. var oldCovers = this._covers;
  51071. var newCovers = this._covers = [];
  51072. var controller = this;
  51073. var creatingCover = this._creatingCover;
  51074. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  51075. .add(addOrUpdate)
  51076. .update(addOrUpdate)
  51077. .remove(remove)
  51078. .execute();
  51079. return this;
  51080. function getKey(brushOption, index) {
  51081. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  51082. + '-' + brushOption.brushType;
  51083. }
  51084. function oldGetKey(cover, index) {
  51085. return getKey(cover.__brushOption, index);
  51086. }
  51087. function addOrUpdate(newIndex, oldIndex) {
  51088. var newBrushOption = brushOptionList[newIndex];
  51089. // Consider setOption in event listener of brushSelect,
  51090. // where updating cover when creating should be forbiden.
  51091. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  51092. newCovers[newIndex] = oldCovers[oldIndex];
  51093. }
  51094. else {
  51095. var cover = newCovers[newIndex] = oldIndex != null
  51096. ? (
  51097. oldCovers[oldIndex].__brushOption = newBrushOption,
  51098. oldCovers[oldIndex]
  51099. )
  51100. : endCreating(controller, createCover(controller, newBrushOption));
  51101. updateCoverAfterCreation(controller, cover);
  51102. }
  51103. }
  51104. function remove(oldIndex) {
  51105. if (oldCovers[oldIndex] !== creatingCover) {
  51106. controller.group.remove(oldCovers[oldIndex]);
  51107. }
  51108. }
  51109. },
  51110. unmount: function () {
  51111. if (__DEV__) {
  51112. if (!this._mounted) {
  51113. return;
  51114. }
  51115. }
  51116. this.enableBrush(false);
  51117. // container may 'removeAll' outside.
  51118. clearCovers(this);
  51119. this._zr.remove(this.group);
  51120. if (__DEV__) {
  51121. this._mounted = false; // should be at last.
  51122. }
  51123. return this;
  51124. },
  51125. dispose: function () {
  51126. this.unmount();
  51127. this.off();
  51128. }
  51129. };
  51130. mixin(BrushController, Eventful);
  51131. function doEnableBrush(controller, brushOption) {
  51132. var zr = controller._zr;
  51133. // Consider roam, which takes globalPan too.
  51134. if (!controller._enableGlobalPan) {
  51135. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51136. }
  51137. mountHandlers(zr, controller._handlers);
  51138. controller._brushType = brushOption.brushType;
  51139. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51140. }
  51141. function doDisableBrush(controller) {
  51142. var zr = controller._zr;
  51143. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51144. unmountHandlers(zr, controller._handlers);
  51145. controller._brushType = controller._brushOption = null;
  51146. }
  51147. function mountHandlers(zr, handlers) {
  51148. each$16(handlers, function (handler, eventName) {
  51149. zr.on(eventName, handler);
  51150. });
  51151. }
  51152. function unmountHandlers(zr, handlers) {
  51153. each$16(handlers, function (handler, eventName) {
  51154. zr.off(eventName, handler);
  51155. });
  51156. }
  51157. function createCover(controller, brushOption) {
  51158. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  51159. cover.__brushOption = brushOption;
  51160. updateZ$1(cover, brushOption);
  51161. controller.group.add(cover);
  51162. return cover;
  51163. }
  51164. function endCreating(controller, creatingCover) {
  51165. var coverRenderer = getCoverRenderer(creatingCover);
  51166. if (coverRenderer.endCreating) {
  51167. coverRenderer.endCreating(controller, creatingCover);
  51168. updateZ$1(creatingCover, creatingCover.__brushOption);
  51169. }
  51170. return creatingCover;
  51171. }
  51172. function updateCoverShape(controller, cover) {
  51173. var brushOption = cover.__brushOption;
  51174. getCoverRenderer(cover).updateCoverShape(
  51175. controller, cover, brushOption.range, brushOption
  51176. );
  51177. }
  51178. function updateZ$1(cover, brushOption) {
  51179. var z = brushOption.z;
  51180. z == null && (z = COVER_Z);
  51181. cover.traverse(function (el) {
  51182. el.z = z;
  51183. el.z2 = z; // Consider in given container.
  51184. });
  51185. }
  51186. function updateCoverAfterCreation(controller, cover) {
  51187. getCoverRenderer(cover).updateCommon(controller, cover);
  51188. updateCoverShape(controller, cover);
  51189. }
  51190. function getCoverRenderer(cover) {
  51191. return coverRenderers[cover.__brushOption.brushType];
  51192. }
  51193. // return target panel or `true` (means global panel)
  51194. function getPanelByPoint(controller, e, localCursorPoint) {
  51195. var panels = controller._panels;
  51196. if (!panels) {
  51197. return true; // Global panel
  51198. }
  51199. var panel;
  51200. var transform = controller._transform;
  51201. each$16(panels, function (pn) {
  51202. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  51203. });
  51204. return panel;
  51205. }
  51206. // Return a panel or true
  51207. function getPanelByCover(controller, cover) {
  51208. var panels = controller._panels;
  51209. if (!panels) {
  51210. return true; // Global panel
  51211. }
  51212. var panelId = cover.__brushOption.panelId;
  51213. // User may give cover without coord sys info,
  51214. // which is then treated as global panel.
  51215. return panelId != null ? panels[panelId] : true;
  51216. }
  51217. function clearCovers(controller) {
  51218. var covers = controller._covers;
  51219. var originalLength = covers.length;
  51220. each$16(covers, function (cover) {
  51221. controller.group.remove(cover);
  51222. }, controller);
  51223. covers.length = 0;
  51224. return !!originalLength;
  51225. }
  51226. function trigger$1(controller, opt) {
  51227. var areas = map$2(controller._covers, function (cover) {
  51228. var brushOption = cover.__brushOption;
  51229. var range = clone(brushOption.range);
  51230. return {
  51231. brushType: brushOption.brushType,
  51232. panelId: brushOption.panelId,
  51233. range: range
  51234. };
  51235. });
  51236. controller.trigger('brush', areas, {
  51237. isEnd: !!opt.isEnd,
  51238. removeOnClick: !!opt.removeOnClick
  51239. });
  51240. }
  51241. function shouldShowCover(controller) {
  51242. var track = controller._track;
  51243. if (!track.length) {
  51244. return false;
  51245. }
  51246. var p2 = track[track.length - 1];
  51247. var p1 = track[0];
  51248. var dx = p2[0] - p1[0];
  51249. var dy = p2[1] - p1[1];
  51250. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  51251. return dist > UNSELECT_THRESHOLD;
  51252. }
  51253. function getTrackEnds(track) {
  51254. var tail = track.length - 1;
  51255. tail < 0 && (tail = 0);
  51256. return [track[0], track[tail]];
  51257. }
  51258. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  51259. var cover = new Group();
  51260. cover.add(new Rect({
  51261. name: 'main',
  51262. style: makeStyle(brushOption),
  51263. silent: true,
  51264. draggable: true,
  51265. cursor: 'move',
  51266. drift: curry$5(doDrift, controller, cover, 'nswe'),
  51267. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51268. }));
  51269. each$16(
  51270. edgeNames,
  51271. function (name) {
  51272. cover.add(new Rect({
  51273. name: name,
  51274. style: {opacity: 0},
  51275. draggable: true,
  51276. silent: true,
  51277. invisible: true,
  51278. drift: curry$5(doDrift, controller, cover, name),
  51279. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51280. }));
  51281. }
  51282. );
  51283. return cover;
  51284. }
  51285. function updateBaseRect(controller, cover, localRange, brushOption) {
  51286. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  51287. var handleSize = mathMax$5(lineWidth, MIN_RESIZE_LINE_WIDTH);
  51288. var x = localRange[0][0];
  51289. var y = localRange[1][0];
  51290. var xa = x - lineWidth / 2;
  51291. var ya = y - lineWidth / 2;
  51292. var x2 = localRange[0][1];
  51293. var y2 = localRange[1][1];
  51294. var x2a = x2 - handleSize + lineWidth / 2;
  51295. var y2a = y2 - handleSize + lineWidth / 2;
  51296. var width = x2 - x;
  51297. var height = y2 - y;
  51298. var widtha = width + lineWidth;
  51299. var heighta = height + lineWidth;
  51300. updateRectShape(controller, cover, 'main', x, y, width, height);
  51301. if (brushOption.transformable) {
  51302. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51303. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51304. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51305. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51306. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51307. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51308. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51309. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51310. }
  51311. }
  51312. function updateCommon(controller, cover) {
  51313. var brushOption = cover.__brushOption;
  51314. var transformable = brushOption.transformable;
  51315. var mainEl = cover.childAt(0);
  51316. mainEl.useStyle(makeStyle(brushOption));
  51317. mainEl.attr({
  51318. silent: !transformable,
  51319. cursor: transformable ? 'move' : 'default'
  51320. });
  51321. each$16(
  51322. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  51323. function (name) {
  51324. var el = cover.childOfName(name);
  51325. var globalDir = getGlobalDirection(controller, name);
  51326. el && el.attr({
  51327. silent: !transformable,
  51328. invisible: !transformable,
  51329. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51330. });
  51331. }
  51332. );
  51333. }
  51334. function updateRectShape(controller, cover, name, x, y, w, h) {
  51335. var el = cover.childOfName(name);
  51336. el && el.setShape(pointsToRect(
  51337. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51338. ));
  51339. }
  51340. function makeStyle(brushOption) {
  51341. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51342. }
  51343. function formatRectRange(x, y, x2, y2) {
  51344. var min = [mathMin$5(x, x2), mathMin$5(y, y2)];
  51345. var max = [mathMax$5(x, x2), mathMax$5(y, y2)];
  51346. return [
  51347. [min[0], max[0]], // x range
  51348. [min[1], max[1]] // y range
  51349. ];
  51350. }
  51351. function getTransform$1(controller) {
  51352. return getTransform(controller.group);
  51353. }
  51354. function getGlobalDirection(controller, localDirection) {
  51355. if (localDirection.length > 1) {
  51356. localDirection = localDirection.split('');
  51357. var globalDir = [
  51358. getGlobalDirection(controller, localDirection[0]),
  51359. getGlobalDirection(controller, localDirection[1])
  51360. ];
  51361. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51362. return globalDir.join('');
  51363. }
  51364. else {
  51365. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  51366. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  51367. var globalDir = transformDirection(
  51368. map$$1[localDirection], getTransform$1(controller)
  51369. );
  51370. return inverseMap[globalDir];
  51371. }
  51372. }
  51373. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  51374. var brushOption = cover.__brushOption;
  51375. var rectRange = toRectRange(brushOption.range);
  51376. var localDelta = toLocalDelta(controller, dx, dy);
  51377. each$16(name.split(''), function (namePart) {
  51378. var ind = DIRECTION_MAP[namePart];
  51379. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51380. });
  51381. brushOption.range = fromRectRange(formatRectRange(
  51382. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  51383. ));
  51384. updateCoverAfterCreation(controller, cover);
  51385. trigger$1(controller, {isEnd: false});
  51386. }
  51387. function driftPolygon(controller, cover, dx, dy, e) {
  51388. var range = cover.__brushOption.range;
  51389. var localDelta = toLocalDelta(controller, dx, dy);
  51390. each$16(range, function (point) {
  51391. point[0] += localDelta[0];
  51392. point[1] += localDelta[1];
  51393. });
  51394. updateCoverAfterCreation(controller, cover);
  51395. trigger$1(controller, {isEnd: false});
  51396. }
  51397. function toLocalDelta(controller, dx, dy) {
  51398. var thisGroup = controller.group;
  51399. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51400. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51401. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51402. }
  51403. function clipByPanel(controller, cover, data) {
  51404. var panel = getPanelByCover(controller, cover);
  51405. return (panel && panel !== true)
  51406. ? panel.clipPath(data, controller._transform)
  51407. : clone(data);
  51408. }
  51409. function pointsToRect(points) {
  51410. var xmin = mathMin$5(points[0][0], points[1][0]);
  51411. var ymin = mathMin$5(points[0][1], points[1][1]);
  51412. var xmax = mathMax$5(points[0][0], points[1][0]);
  51413. var ymax = mathMax$5(points[0][1], points[1][1]);
  51414. return {
  51415. x: xmin,
  51416. y: ymin,
  51417. width: xmax - xmin,
  51418. height: ymax - ymin
  51419. };
  51420. }
  51421. function resetCursor(controller, e, localCursorPoint) {
  51422. if (
  51423. // Check active
  51424. !controller._brushType
  51425. // resetCursor should be always called when mouse is in zr area,
  51426. // but not called when mouse is out of zr area to avoid bad influence
  51427. // if `mousemove`, `mouseup` are triggered from `document` event.
  51428. || isOutsideZrArea(controller, e)
  51429. ) {
  51430. return;
  51431. }
  51432. var zr = controller._zr;
  51433. var covers = controller._covers;
  51434. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51435. // Check whether in covers.
  51436. if (!controller._dragging) {
  51437. for (var i = 0; i < covers.length; i++) {
  51438. var brushOption = covers[i].__brushOption;
  51439. if (currPanel
  51440. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  51441. && coverRenderers[brushOption.brushType].contain(
  51442. covers[i], localCursorPoint[0], localCursorPoint[1]
  51443. )
  51444. ) {
  51445. // Use cursor style set on cover.
  51446. return;
  51447. }
  51448. }
  51449. }
  51450. currPanel && zr.setCursorStyle('crosshair');
  51451. }
  51452. function preventDefault(e) {
  51453. var rawE = e.event;
  51454. rawE.preventDefault && rawE.preventDefault();
  51455. }
  51456. function mainShapeContain(cover, x, y) {
  51457. return cover.childOfName('main').contain(x, y);
  51458. }
  51459. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51460. var creatingCover = controller._creatingCover;
  51461. var panel = controller._creatingPanel;
  51462. var thisBrushOption = controller._brushOption;
  51463. var eventParams;
  51464. controller._track.push(localCursorPoint.slice());
  51465. if (shouldShowCover(controller) || creatingCover) {
  51466. if (panel && !creatingCover) {
  51467. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51468. var brushOption = clone(thisBrushOption);
  51469. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51470. brushOption.panelId = panel === true ? null : panel.panelId;
  51471. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51472. controller._covers.push(creatingCover);
  51473. }
  51474. if (creatingCover) {
  51475. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51476. var coverBrushOption = creatingCover.__brushOption;
  51477. coverBrushOption.range = coverRenderer.getCreatingRange(
  51478. clipByPanel(controller, creatingCover, controller._track)
  51479. );
  51480. if (isEnd) {
  51481. endCreating(controller, creatingCover);
  51482. coverRenderer.updateCommon(controller, creatingCover);
  51483. }
  51484. updateCoverShape(controller, creatingCover);
  51485. eventParams = {isEnd: isEnd};
  51486. }
  51487. }
  51488. else if (
  51489. isEnd
  51490. && thisBrushOption.brushMode === 'single'
  51491. && thisBrushOption.removeOnClick
  51492. ) {
  51493. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51494. // But a single click do not clear covers, because user may have casual
  51495. // clicks (for example, click on other component and do not expect covers
  51496. // disappear).
  51497. // Only some cover removed, trigger action, but not every click trigger action.
  51498. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51499. eventParams = {isEnd: isEnd, removeOnClick: true};
  51500. }
  51501. }
  51502. return eventParams;
  51503. }
  51504. function determineBrushType(brushType, panel) {
  51505. if (brushType === 'auto') {
  51506. if (__DEV__) {
  51507. assert$1(
  51508. panel && panel.defaultBrushType,
  51509. 'MUST have defaultBrushType when brushType is "atuo"'
  51510. );
  51511. }
  51512. return panel.defaultBrushType;
  51513. }
  51514. return brushType;
  51515. }
  51516. var pointerHandlers = {
  51517. mousedown: function (e) {
  51518. if (this._dragging) {
  51519. // In case some browser do not support globalOut,
  51520. // and release mose out side the browser.
  51521. handleDragEnd(this, e);
  51522. }
  51523. else if (!e.target || !e.target.draggable) {
  51524. preventDefault(e);
  51525. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51526. this._creatingCover = null;
  51527. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  51528. if (panel) {
  51529. this._dragging = true;
  51530. this._track = [localCursorPoint.slice()];
  51531. }
  51532. }
  51533. },
  51534. mousemove: function (e) {
  51535. var x = e.offsetX;
  51536. var y = e.offsetY;
  51537. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  51538. resetCursor(this, e, localCursorPoint);
  51539. if (this._dragging) {
  51540. preventDefault(e);
  51541. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  51542. eventParams && trigger$1(this, eventParams);
  51543. }
  51544. },
  51545. mouseup: function (e) {
  51546. handleDragEnd(this, e);
  51547. }
  51548. };
  51549. function handleDragEnd(controller, e) {
  51550. if (controller._dragging) {
  51551. preventDefault(e);
  51552. var x = e.offsetX;
  51553. var y = e.offsetY;
  51554. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  51555. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  51556. controller._dragging = false;
  51557. controller._track = [];
  51558. controller._creatingCover = null;
  51559. // trigger event shoule be at final, after procedure will be nested.
  51560. eventParams && trigger$1(controller, eventParams);
  51561. }
  51562. }
  51563. function isOutsideZrArea(controller, x, y) {
  51564. var zr = controller._zr;
  51565. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  51566. }
  51567. /**
  51568. * key: brushType
  51569. * @type {Object}
  51570. */
  51571. var coverRenderers = {
  51572. lineX: getLineRenderer(0),
  51573. lineY: getLineRenderer(1),
  51574. rect: {
  51575. createCover: function (controller, brushOption) {
  51576. return createBaseRectCover(
  51577. curry$5(
  51578. driftRect,
  51579. function (range) {
  51580. return range;
  51581. },
  51582. function (range) {
  51583. return range;
  51584. }
  51585. ),
  51586. controller,
  51587. brushOption,
  51588. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  51589. );
  51590. },
  51591. getCreatingRange: function (localTrack) {
  51592. var ends = getTrackEnds(localTrack);
  51593. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  51594. },
  51595. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51596. updateBaseRect(controller, cover, localRange, brushOption);
  51597. },
  51598. updateCommon: updateCommon,
  51599. contain: mainShapeContain
  51600. },
  51601. polygon: {
  51602. createCover: function (controller, brushOption) {
  51603. var cover = new Group();
  51604. // Do not use graphic.Polygon because graphic.Polyline do not close the
  51605. // border of the shape when drawing, which is a better experience for user.
  51606. cover.add(new Polyline({
  51607. name: 'main',
  51608. style: makeStyle(brushOption),
  51609. silent: true
  51610. }));
  51611. return cover;
  51612. },
  51613. getCreatingRange: function (localTrack) {
  51614. return localTrack;
  51615. },
  51616. endCreating: function (controller, cover) {
  51617. cover.remove(cover.childAt(0));
  51618. // Use graphic.Polygon close the shape.
  51619. cover.add(new Polygon({
  51620. name: 'main',
  51621. draggable: true,
  51622. drift: curry$5(driftPolygon, controller, cover),
  51623. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51624. }));
  51625. },
  51626. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51627. cover.childAt(0).setShape({
  51628. points: clipByPanel(controller, cover, localRange)
  51629. });
  51630. },
  51631. updateCommon: updateCommon,
  51632. contain: mainShapeContain
  51633. }
  51634. };
  51635. function getLineRenderer(xyIndex) {
  51636. return {
  51637. createCover: function (controller, brushOption) {
  51638. return createBaseRectCover(
  51639. curry$5(
  51640. driftRect,
  51641. function (range) {
  51642. var rectRange = [range, [0, 100]];
  51643. xyIndex && rectRange.reverse();
  51644. return rectRange;
  51645. },
  51646. function (rectRange) {
  51647. return rectRange[xyIndex];
  51648. }
  51649. ),
  51650. controller,
  51651. brushOption,
  51652. [['w', 'e'], ['n', 's']][xyIndex]
  51653. );
  51654. },
  51655. getCreatingRange: function (localTrack) {
  51656. var ends = getTrackEnds(localTrack);
  51657. var min = mathMin$5(ends[0][xyIndex], ends[1][xyIndex]);
  51658. var max = mathMax$5(ends[0][xyIndex], ends[1][xyIndex]);
  51659. return [min, max];
  51660. },
  51661. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51662. var otherExtent;
  51663. // If brushWidth not specified, fit the panel.
  51664. var panel = getPanelByCover(controller, cover);
  51665. if (panel !== true && panel.getLinearBrushOtherExtent) {
  51666. otherExtent = panel.getLinearBrushOtherExtent(
  51667. xyIndex, controller._transform
  51668. );
  51669. }
  51670. else {
  51671. var zr = controller._zr;
  51672. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  51673. }
  51674. var rectRange = [localRange, otherExtent];
  51675. xyIndex && rectRange.reverse();
  51676. updateBaseRect(controller, cover, rectRange, brushOption);
  51677. },
  51678. updateCommon: updateCommon,
  51679. contain: mainShapeContain
  51680. };
  51681. }
  51682. /*
  51683. * Licensed to the Apache Software Foundation (ASF) under one
  51684. * or more contributor license agreements. See the NOTICE file
  51685. * distributed with this work for additional information
  51686. * regarding copyright ownership. The ASF licenses this file
  51687. * to you under the Apache License, Version 2.0 (the
  51688. * "License"); you may not use this file except in compliance
  51689. * with the License. You may obtain a copy of the License at
  51690. *
  51691. * http://www.apache.org/licenses/LICENSE-2.0
  51692. *
  51693. * Unless required by applicable law or agreed to in writing,
  51694. * software distributed under the License is distributed on an
  51695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51696. * KIND, either express or implied. See the License for the
  51697. * specific language governing permissions and limitations
  51698. * under the License.
  51699. */
  51700. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  51701. /**
  51702. * Avoid that: mouse click on a elements that is over geo or graph,
  51703. * but roam is triggered.
  51704. */
  51705. function onIrrelevantElement(e, api, targetCoordSysModel) {
  51706. var model = api.getComponentByElement(e.topTarget);
  51707. // If model is axisModel, it works only if it is injected with coordinateSystem.
  51708. var coordSys = model && model.coordinateSystem;
  51709. return model
  51710. && model !== targetCoordSysModel
  51711. && !IRRELEVANT_EXCLUDES[model.mainType]
  51712. && (coordSys && coordSys.model !== targetCoordSysModel);
  51713. }
  51714. /*
  51715. * Licensed to the Apache Software Foundation (ASF) under one
  51716. * or more contributor license agreements. See the NOTICE file
  51717. * distributed with this work for additional information
  51718. * regarding copyright ownership. The ASF licenses this file
  51719. * to you under the Apache License, Version 2.0 (the
  51720. * "License"); you may not use this file except in compliance
  51721. * with the License. You may obtain a copy of the License at
  51722. *
  51723. * http://www.apache.org/licenses/LICENSE-2.0
  51724. *
  51725. * Unless required by applicable law or agreed to in writing,
  51726. * software distributed under the License is distributed on an
  51727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51728. * KIND, either express or implied. See the License for the
  51729. * specific language governing permissions and limitations
  51730. * under the License.
  51731. */
  51732. function makeRectPanelClipPath(rect) {
  51733. rect = normalizeRect(rect);
  51734. return function (localPoints, transform) {
  51735. return clipPointsByRect(localPoints, rect);
  51736. };
  51737. }
  51738. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  51739. rect = normalizeRect(rect);
  51740. return function (xyIndex) {
  51741. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  51742. var brushWidth = idx ? rect.width : rect.height;
  51743. var base = idx ? rect.x : rect.y;
  51744. return [base, base + (brushWidth || 0)];
  51745. };
  51746. }
  51747. function makeRectIsTargetByCursor(rect, api, targetModel) {
  51748. rect = normalizeRect(rect);
  51749. return function (e, localCursorPoint, transform) {
  51750. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  51751. && !onIrrelevantElement(e, api, targetModel);
  51752. };
  51753. }
  51754. // Consider width/height is negative.
  51755. function normalizeRect(rect) {
  51756. return BoundingRect.create(rect);
  51757. }
  51758. /*
  51759. * Licensed to the Apache Software Foundation (ASF) under one
  51760. * or more contributor license agreements. See the NOTICE file
  51761. * distributed with this work for additional information
  51762. * regarding copyright ownership. The ASF licenses this file
  51763. * to you under the Apache License, Version 2.0 (the
  51764. * "License"); you may not use this file except in compliance
  51765. * with the License. You may obtain a copy of the License at
  51766. *
  51767. * http://www.apache.org/licenses/LICENSE-2.0
  51768. *
  51769. * Unless required by applicable law or agreed to in writing,
  51770. * software distributed under the License is distributed on an
  51771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51772. * KIND, either express or implied. See the License for the
  51773. * specific language governing permissions and limitations
  51774. * under the License.
  51775. */
  51776. var each$17 = each$1;
  51777. var indexOf$2 = indexOf;
  51778. var curry$6 = curry;
  51779. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  51780. // FIXME
  51781. // how to genarialize to more coordinate systems.
  51782. var INCLUDE_FINDER_MAIN_TYPES = [
  51783. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  51784. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  51785. ];
  51786. /**
  51787. * [option in constructor]:
  51788. * {
  51789. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51790. * }
  51791. *
  51792. *
  51793. * [targetInfo]:
  51794. *
  51795. * There can be multiple axes in a single targetInfo. Consider the case
  51796. * of `grid` component, a targetInfo represents a grid which contains one or more
  51797. * cartesian and one or more axes. And consider the case of parallel system,
  51798. * which has multiple axes in a coordinate system.
  51799. * Can be {
  51800. * panelId: ...,
  51801. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  51802. * coordSyses: all cartesians.
  51803. * gridModel: <grid component>
  51804. * xAxes: correspond to coordSyses on index
  51805. * yAxes: correspond to coordSyses on index
  51806. * }
  51807. * or {
  51808. * panelId: ...,
  51809. * coordSys: <geo coord sys>
  51810. * coordSyses: [<geo coord sys>]
  51811. * geoModel: <geo component>
  51812. * }
  51813. *
  51814. *
  51815. * [panelOpt]:
  51816. *
  51817. * Make from targetInfo. Input to BrushController.
  51818. * {
  51819. * panelId: ...,
  51820. * rect: ...
  51821. * }
  51822. *
  51823. *
  51824. * [area]:
  51825. *
  51826. * Generated by BrushController or user input.
  51827. * {
  51828. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  51829. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  51830. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51831. * range: pixel range.
  51832. * coordRange: representitive coord range (the first one of coordRanges).
  51833. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  51834. * }
  51835. */
  51836. /**
  51837. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  51838. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  51839. * @param {module:echarts/model/Global} ecModel
  51840. * @param {Object} [opt]
  51841. * @param {Array.<string>} [opt.include] include coordinate system types.
  51842. */
  51843. function BrushTargetManager(option, ecModel, opt) {
  51844. /**
  51845. * @private
  51846. * @type {Array.<Object>}
  51847. */
  51848. var targetInfoList = this._targetInfoList = [];
  51849. var info = {};
  51850. var foundCpts = parseFinder$1(ecModel, option);
  51851. each$17(targetInfoBuilders, function (builder, type) {
  51852. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  51853. builder(foundCpts, targetInfoList, info);
  51854. }
  51855. });
  51856. }
  51857. var proto$5 = BrushTargetManager.prototype;
  51858. proto$5.setOutputRanges = function (areas, ecModel) {
  51859. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  51860. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  51861. // area.coordRange is the first of area.coordRanges
  51862. if (!area.coordRange) {
  51863. area.coordRange = coordRange;
  51864. // In 'category' axis, coord to pixel is not reversible, so we can not
  51865. // rebuild range by coordRange accrately, which may bring trouble when
  51866. // brushing only one item. So we use __rangeOffset to rebuilding range
  51867. // by coordRange. And this it only used in brush component so it is no
  51868. // need to be adapted to coordRanges.
  51869. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  51870. area.__rangeOffset = {
  51871. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  51872. xyMinMax: result.xyMinMax
  51873. };
  51874. }
  51875. });
  51876. };
  51877. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  51878. each$17(areas, function (area) {
  51879. var targetInfo = this.findTargetInfo(area, ecModel);
  51880. if (targetInfo && targetInfo !== true) {
  51881. each$1(
  51882. targetInfo.coordSyses,
  51883. function (coordSys) {
  51884. var result = coordConvert[area.brushType](1, coordSys, area.range);
  51885. cb(area, result.values, coordSys, ecModel);
  51886. }
  51887. );
  51888. }
  51889. }, this);
  51890. };
  51891. proto$5.setInputRanges = function (areas, ecModel) {
  51892. each$17(areas, function (area) {
  51893. var targetInfo = this.findTargetInfo(area, ecModel);
  51894. if (__DEV__) {
  51895. assert$1(
  51896. !targetInfo || targetInfo === true || area.coordRange,
  51897. 'coordRange must be specified when coord index specified.'
  51898. );
  51899. assert$1(
  51900. !targetInfo || targetInfo !== true || area.range,
  51901. 'range must be specified in global brush.'
  51902. );
  51903. }
  51904. area.range = area.range || [];
  51905. // convert coordRange to global range and set panelId.
  51906. if (targetInfo && targetInfo !== true) {
  51907. area.panelId = targetInfo.panelId;
  51908. // (1) area.range shoule always be calculate from coordRange but does
  51909. // not keep its original value, for the sake of the dataZoom scenario,
  51910. // where area.coordRange remains unchanged but area.range may be changed.
  51911. // (2) Only support converting one coordRange to pixel range in brush
  51912. // component. So do not consider `coordRanges`.
  51913. // (3) About __rangeOffset, see comment above.
  51914. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  51915. var rangeOffset = area.__rangeOffset;
  51916. area.range = rangeOffset
  51917. ? diffProcessor[area.brushType](
  51918. result.values,
  51919. rangeOffset.offset,
  51920. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  51921. )
  51922. : result.values;
  51923. }
  51924. }, this);
  51925. };
  51926. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  51927. return map(this._targetInfoList, function (targetInfo) {
  51928. var rect = targetInfo.getPanelRect();
  51929. return {
  51930. panelId: targetInfo.panelId,
  51931. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  51932. clipPath: makeRectPanelClipPath(rect),
  51933. isTargetByCursor: makeRectIsTargetByCursor(
  51934. rect, api, targetInfo.coordSysModel
  51935. ),
  51936. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  51937. };
  51938. });
  51939. };
  51940. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  51941. // Check whether area is bound in coord, and series do not belong to that coord.
  51942. // If do not do this check, some brush (like lineX) will controll all axes.
  51943. var targetInfo = this.findTargetInfo(area, ecModel);
  51944. return targetInfo === true || (
  51945. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  51946. );
  51947. };
  51948. /**
  51949. * If return Object, a coord found.
  51950. * If reutrn true, global found.
  51951. * Otherwise nothing found.
  51952. *
  51953. * @param {Object} area
  51954. * @param {Array} targetInfoList
  51955. * @return {Object|boolean}
  51956. */
  51957. proto$5.findTargetInfo = function (area, ecModel) {
  51958. var targetInfoList = this._targetInfoList;
  51959. var foundCpts = parseFinder$1(ecModel, area);
  51960. for (var i = 0; i < targetInfoList.length; i++) {
  51961. var targetInfo = targetInfoList[i];
  51962. var areaPanelId = area.panelId;
  51963. if (areaPanelId) {
  51964. if (targetInfo.panelId === areaPanelId) {
  51965. return targetInfo;
  51966. }
  51967. }
  51968. else {
  51969. for (var i = 0; i < targetInfoMatchers.length; i++) {
  51970. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  51971. return targetInfo;
  51972. }
  51973. }
  51974. }
  51975. }
  51976. return true;
  51977. };
  51978. function formatMinMax(minMax) {
  51979. minMax[0] > minMax[1] && minMax.reverse();
  51980. return minMax;
  51981. }
  51982. function parseFinder$1(ecModel, option) {
  51983. return parseFinder(
  51984. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  51985. );
  51986. }
  51987. var targetInfoBuilders = {
  51988. grid: function (foundCpts, targetInfoList) {
  51989. var xAxisModels = foundCpts.xAxisModels;
  51990. var yAxisModels = foundCpts.yAxisModels;
  51991. var gridModels = foundCpts.gridModels;
  51992. // Remove duplicated.
  51993. var gridModelMap = createHashMap();
  51994. var xAxesHas = {};
  51995. var yAxesHas = {};
  51996. if (!xAxisModels && !yAxisModels && !gridModels) {
  51997. return;
  51998. }
  51999. each$17(xAxisModels, function (axisModel) {
  52000. var gridModel = axisModel.axis.grid.model;
  52001. gridModelMap.set(gridModel.id, gridModel);
  52002. xAxesHas[gridModel.id] = true;
  52003. });
  52004. each$17(yAxisModels, function (axisModel) {
  52005. var gridModel = axisModel.axis.grid.model;
  52006. gridModelMap.set(gridModel.id, gridModel);
  52007. yAxesHas[gridModel.id] = true;
  52008. });
  52009. each$17(gridModels, function (gridModel) {
  52010. gridModelMap.set(gridModel.id, gridModel);
  52011. xAxesHas[gridModel.id] = true;
  52012. yAxesHas[gridModel.id] = true;
  52013. });
  52014. gridModelMap.each(function (gridModel) {
  52015. var grid = gridModel.coordinateSystem;
  52016. var cartesians = [];
  52017. each$17(grid.getCartesians(), function (cartesian, index) {
  52018. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  52019. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  52020. ) {
  52021. cartesians.push(cartesian);
  52022. }
  52023. });
  52024. targetInfoList.push({
  52025. panelId: 'grid--' + gridModel.id,
  52026. gridModel: gridModel,
  52027. coordSysModel: gridModel,
  52028. // Use the first one as the representitive coordSys.
  52029. coordSys: cartesians[0],
  52030. coordSyses: cartesians,
  52031. getPanelRect: panelRectBuilder.grid,
  52032. xAxisDeclared: xAxesHas[gridModel.id],
  52033. yAxisDeclared: yAxesHas[gridModel.id]
  52034. });
  52035. });
  52036. },
  52037. geo: function (foundCpts, targetInfoList) {
  52038. each$17(foundCpts.geoModels, function (geoModel) {
  52039. var coordSys = geoModel.coordinateSystem;
  52040. targetInfoList.push({
  52041. panelId: 'geo--' + geoModel.id,
  52042. geoModel: geoModel,
  52043. coordSysModel: geoModel,
  52044. coordSys: coordSys,
  52045. coordSyses: [coordSys],
  52046. getPanelRect: panelRectBuilder.geo
  52047. });
  52048. });
  52049. }
  52050. };
  52051. var targetInfoMatchers = [
  52052. // grid
  52053. function (foundCpts, targetInfo) {
  52054. var xAxisModel = foundCpts.xAxisModel;
  52055. var yAxisModel = foundCpts.yAxisModel;
  52056. var gridModel = foundCpts.gridModel;
  52057. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  52058. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  52059. return gridModel && gridModel === targetInfo.gridModel;
  52060. },
  52061. // geo
  52062. function (foundCpts, targetInfo) {
  52063. var geoModel = foundCpts.geoModel;
  52064. return geoModel && geoModel === targetInfo.geoModel;
  52065. }
  52066. ];
  52067. var panelRectBuilder = {
  52068. grid: function () {
  52069. // grid is not Transformable.
  52070. return this.coordSys.grid.getRect().clone();
  52071. },
  52072. geo: function () {
  52073. var coordSys = this.coordSys;
  52074. var rect = coordSys.getBoundingRect().clone();
  52075. // geo roam and zoom transform
  52076. rect.applyTransform(getTransform(coordSys));
  52077. return rect;
  52078. }
  52079. };
  52080. var coordConvert = {
  52081. lineX: curry$6(axisConvert, 0),
  52082. lineY: curry$6(axisConvert, 1),
  52083. rect: function (to, coordSys, rangeOrCoordRange) {
  52084. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  52085. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  52086. var values = [
  52087. formatMinMax([xminymin[0], xmaxymax[0]]),
  52088. formatMinMax([xminymin[1], xmaxymax[1]])
  52089. ];
  52090. return {values: values, xyMinMax: values};
  52091. },
  52092. polygon: function (to, coordSys, rangeOrCoordRange) {
  52093. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  52094. var values = map(rangeOrCoordRange, function (item) {
  52095. var p = coordSys[COORD_CONVERTS[to]](item);
  52096. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  52097. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  52098. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  52099. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  52100. return p;
  52101. });
  52102. return {values: values, xyMinMax: xyMinMax};
  52103. }
  52104. };
  52105. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  52106. if (__DEV__) {
  52107. assert$1(
  52108. coordSys.type === 'cartesian2d',
  52109. 'lineX/lineY brush is available only in cartesian2d.'
  52110. );
  52111. }
  52112. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  52113. var values = formatMinMax(map([0, 1], function (i) {
  52114. return to
  52115. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  52116. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  52117. }));
  52118. var xyMinMax = [];
  52119. xyMinMax[axisNameIndex] = values;
  52120. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  52121. return {values: values, xyMinMax: xyMinMax};
  52122. }
  52123. var diffProcessor = {
  52124. lineX: curry$6(axisDiffProcessor, 0),
  52125. lineY: curry$6(axisDiffProcessor, 1),
  52126. rect: function (values, refer, scales) {
  52127. return [
  52128. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  52129. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  52130. ];
  52131. },
  52132. polygon: function (values, refer, scales) {
  52133. return map(values, function (item, idx) {
  52134. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  52135. });
  52136. }
  52137. };
  52138. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  52139. return [
  52140. values[0] - scales[axisNameIndex] * refer[0],
  52141. values[1] - scales[axisNameIndex] * refer[1]
  52142. ];
  52143. }
  52144. // We have to process scale caused by dataZoom manually,
  52145. // although it might be not accurate.
  52146. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  52147. var sizeCurr = getSize(xyMinMaxCurr);
  52148. var sizeOrigin = getSize(xyMinMaxOrigin);
  52149. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  52150. isNaN(scales[0]) && (scales[0] = 1);
  52151. isNaN(scales[1]) && (scales[1] = 1);
  52152. return scales;
  52153. }
  52154. function getSize(xyMinMax) {
  52155. return xyMinMax
  52156. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  52157. : [NaN, NaN];
  52158. }
  52159. /*
  52160. * Licensed to the Apache Software Foundation (ASF) under one
  52161. * or more contributor license agreements. See the NOTICE file
  52162. * distributed with this work for additional information
  52163. * regarding copyright ownership. The ASF licenses this file
  52164. * to you under the Apache License, Version 2.0 (the
  52165. * "License"); you may not use this file except in compliance
  52166. * with the License. You may obtain a copy of the License at
  52167. *
  52168. * http://www.apache.org/licenses/LICENSE-2.0
  52169. *
  52170. * Unless required by applicable law or agreed to in writing,
  52171. * software distributed under the License is distributed on an
  52172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52173. * KIND, either express or implied. See the License for the
  52174. * specific language governing permissions and limitations
  52175. * under the License.
  52176. */
  52177. var each$18 = each$1;
  52178. var ATTR$2 = '\0_ec_hist_store';
  52179. /**
  52180. * @param {module:echarts/model/Global} ecModel
  52181. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  52182. */
  52183. function push(ecModel, newSnapshot) {
  52184. var store = giveStore$1(ecModel);
  52185. // If previous dataZoom can not be found,
  52186. // complete an range with current range.
  52187. each$18(newSnapshot, function (batchItem, dataZoomId) {
  52188. var i = store.length - 1;
  52189. for (; i >= 0; i--) {
  52190. var snapshot = store[i];
  52191. if (snapshot[dataZoomId]) {
  52192. break;
  52193. }
  52194. }
  52195. if (i < 0) {
  52196. // No origin range set, create one by current range.
  52197. var dataZoomModel = ecModel.queryComponents(
  52198. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  52199. )[0];
  52200. if (dataZoomModel) {
  52201. var percentRange = dataZoomModel.getPercentRange();
  52202. store[0][dataZoomId] = {
  52203. dataZoomId: dataZoomId,
  52204. start: percentRange[0],
  52205. end: percentRange[1]
  52206. };
  52207. }
  52208. }
  52209. });
  52210. store.push(newSnapshot);
  52211. }
  52212. /**
  52213. * @param {module:echarts/model/Global} ecModel
  52214. * @return {Object} snapshot
  52215. */
  52216. function pop(ecModel) {
  52217. var store = giveStore$1(ecModel);
  52218. var head = store[store.length - 1];
  52219. store.length > 1 && store.pop();
  52220. // Find top for all dataZoom.
  52221. var snapshot = {};
  52222. each$18(head, function (batchItem, dataZoomId) {
  52223. for (var i = store.length - 1; i >= 0; i--) {
  52224. var batchItem = store[i][dataZoomId];
  52225. if (batchItem) {
  52226. snapshot[dataZoomId] = batchItem;
  52227. break;
  52228. }
  52229. }
  52230. });
  52231. return snapshot;
  52232. }
  52233. /**
  52234. * @param {module:echarts/model/Global} ecModel
  52235. */
  52236. function clear$1(ecModel) {
  52237. ecModel[ATTR$2] = null;
  52238. }
  52239. /**
  52240. * @param {module:echarts/model/Global} ecModel
  52241. * @return {number} records. always >= 1.
  52242. */
  52243. function count(ecModel) {
  52244. return giveStore$1(ecModel).length;
  52245. }
  52246. /**
  52247. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  52248. * History length of each dataZoom may be different.
  52249. * this._history[0] is used to store origin range.
  52250. * @type {Array.<Object>}
  52251. */
  52252. function giveStore$1(ecModel) {
  52253. var store = ecModel[ATTR$2];
  52254. if (!store) {
  52255. store = ecModel[ATTR$2] = [{}];
  52256. }
  52257. return store;
  52258. }
  52259. /*
  52260. * Licensed to the Apache Software Foundation (ASF) under one
  52261. * or more contributor license agreements. See the NOTICE file
  52262. * distributed with this work for additional information
  52263. * regarding copyright ownership. The ASF licenses this file
  52264. * to you under the Apache License, Version 2.0 (the
  52265. * "License"); you may not use this file except in compliance
  52266. * with the License. You may obtain a copy of the License at
  52267. *
  52268. * http://www.apache.org/licenses/LICENSE-2.0
  52269. *
  52270. * Unless required by applicable law or agreed to in writing,
  52271. * software distributed under the License is distributed on an
  52272. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52273. * KIND, either express or implied. See the License for the
  52274. * specific language governing permissions and limitations
  52275. * under the License.
  52276. */
  52277. DataZoomModel.extend({
  52278. type: 'dataZoom.select'
  52279. });
  52280. /*
  52281. * Licensed to the Apache Software Foundation (ASF) under one
  52282. * or more contributor license agreements. See the NOTICE file
  52283. * distributed with this work for additional information
  52284. * regarding copyright ownership. The ASF licenses this file
  52285. * to you under the Apache License, Version 2.0 (the
  52286. * "License"); you may not use this file except in compliance
  52287. * with the License. You may obtain a copy of the License at
  52288. *
  52289. * http://www.apache.org/licenses/LICENSE-2.0
  52290. *
  52291. * Unless required by applicable law or agreed to in writing,
  52292. * software distributed under the License is distributed on an
  52293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52294. * KIND, either express or implied. See the License for the
  52295. * specific language governing permissions and limitations
  52296. * under the License.
  52297. */
  52298. DataZoomView.extend({
  52299. type: 'dataZoom.select'
  52300. });
  52301. /*
  52302. * Licensed to the Apache Software Foundation (ASF) under one
  52303. * or more contributor license agreements. See the NOTICE file
  52304. * distributed with this work for additional information
  52305. * regarding copyright ownership. The ASF licenses this file
  52306. * to you under the Apache License, Version 2.0 (the
  52307. * "License"); you may not use this file except in compliance
  52308. * with the License. You may obtain a copy of the License at
  52309. *
  52310. * http://www.apache.org/licenses/LICENSE-2.0
  52311. *
  52312. * Unless required by applicable law or agreed to in writing,
  52313. * software distributed under the License is distributed on an
  52314. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52315. * KIND, either express or implied. See the License for the
  52316. * specific language governing permissions and limitations
  52317. * under the License.
  52318. */
  52319. /**
  52320. * Only work for toolbox dataZoom. User
  52321. * MUST NOT import this module directly.
  52322. */
  52323. /*
  52324. * Licensed to the Apache Software Foundation (ASF) under one
  52325. * or more contributor license agreements. See the NOTICE file
  52326. * distributed with this work for additional information
  52327. * regarding copyright ownership. The ASF licenses this file
  52328. * to you under the Apache License, Version 2.0 (the
  52329. * "License"); you may not use this file except in compliance
  52330. * with the License. You may obtain a copy of the License at
  52331. *
  52332. * http://www.apache.org/licenses/LICENSE-2.0
  52333. *
  52334. * Unless required by applicable law or agreed to in writing,
  52335. * software distributed under the License is distributed on an
  52336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52337. * KIND, either express or implied. See the License for the
  52338. * specific language governing permissions and limitations
  52339. * under the License.
  52340. */
  52341. // Use dataZoomSelect
  52342. var dataZoomLang = lang.toolbox.dataZoom;
  52343. var each$15 = each$1;
  52344. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  52345. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  52346. function DataZoom(model, ecModel, api) {
  52347. /**
  52348. * @private
  52349. * @type {module:echarts/component/helper/BrushController}
  52350. */
  52351. (this._brushController = new BrushController(api.getZr()))
  52352. .on('brush', bind(this._onBrush, this))
  52353. .mount();
  52354. /**
  52355. * @private
  52356. * @type {boolean}
  52357. */
  52358. this._isZoomActive;
  52359. }
  52360. DataZoom.defaultOption = {
  52361. show: true,
  52362. filterMode: 'filter',
  52363. // Icon group
  52364. icon: {
  52365. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  52366. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  52367. },
  52368. // `zoom`, `back`
  52369. title: clone(dataZoomLang.title)
  52370. };
  52371. var proto$4 = DataZoom.prototype;
  52372. proto$4.render = function (featureModel, ecModel, api, payload) {
  52373. this.model = featureModel;
  52374. this.ecModel = ecModel;
  52375. this.api = api;
  52376. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  52377. updateBackBtnStatus(featureModel, ecModel);
  52378. };
  52379. proto$4.onclick = function (ecModel, api, type) {
  52380. handlers[type].call(this);
  52381. };
  52382. proto$4.remove = function (ecModel, api) {
  52383. this._brushController.unmount();
  52384. };
  52385. proto$4.dispose = function (ecModel, api) {
  52386. this._brushController.dispose();
  52387. };
  52388. /**
  52389. * @private
  52390. */
  52391. var handlers = {
  52392. zoom: function () {
  52393. var nextActive = !this._isZoomActive;
  52394. this.api.dispatchAction({
  52395. type: 'takeGlobalCursor',
  52396. key: 'dataZoomSelect',
  52397. dataZoomSelectActive: nextActive
  52398. });
  52399. },
  52400. back: function () {
  52401. this._dispatchZoomAction(pop(this.ecModel));
  52402. }
  52403. };
  52404. /**
  52405. * @private
  52406. */
  52407. proto$4._onBrush = function (areas, opt) {
  52408. if (!opt.isEnd || !areas.length) {
  52409. return;
  52410. }
  52411. var snapshot = {};
  52412. var ecModel = this.ecModel;
  52413. this._brushController.updateCovers([]); // remove cover
  52414. var brushTargetManager = new BrushTargetManager(
  52415. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  52416. );
  52417. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52418. if (coordSys.type !== 'cartesian2d') {
  52419. return;
  52420. }
  52421. var brushType = area.brushType;
  52422. if (brushType === 'rect') {
  52423. setBatch('x', coordSys, coordRange[0]);
  52424. setBatch('y', coordSys, coordRange[1]);
  52425. }
  52426. else {
  52427. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  52428. }
  52429. });
  52430. push(ecModel, snapshot);
  52431. this._dispatchZoomAction(snapshot);
  52432. function setBatch(dimName, coordSys, minMax) {
  52433. var axis = coordSys.getAxis(dimName);
  52434. var axisModel = axis.model;
  52435. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  52436. // Restrict range.
  52437. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  52438. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  52439. minMax = sliderMove(
  52440. 0, minMax.slice(), axis.scale.getExtent(), 0,
  52441. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  52442. );
  52443. }
  52444. dataZoomModel && (snapshot[dataZoomModel.id] = {
  52445. dataZoomId: dataZoomModel.id,
  52446. startValue: minMax[0],
  52447. endValue: minMax[1]
  52448. });
  52449. }
  52450. function findDataZoom(dimName, axisModel, ecModel) {
  52451. var found;
  52452. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  52453. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  52454. has && (found = dzModel);
  52455. });
  52456. return found;
  52457. }
  52458. };
  52459. /**
  52460. * @private
  52461. */
  52462. proto$4._dispatchZoomAction = function (snapshot) {
  52463. var batch = [];
  52464. // Convert from hash map to array.
  52465. each$15(snapshot, function (batchItem, dataZoomId) {
  52466. batch.push(clone(batchItem));
  52467. });
  52468. batch.length && this.api.dispatchAction({
  52469. type: 'dataZoom',
  52470. from: this.uid,
  52471. batch: batch
  52472. });
  52473. };
  52474. function retrieveAxisSetting(option) {
  52475. var setting = {};
  52476. // Compatible with previous setting: null => all axis, false => no axis.
  52477. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  52478. setting[name] = option[name];
  52479. setting[name] == null && (setting[name] = 'all');
  52480. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  52481. });
  52482. return setting;
  52483. }
  52484. function updateBackBtnStatus(featureModel, ecModel) {
  52485. featureModel.setIconStatus(
  52486. 'back',
  52487. count(ecModel) > 1 ? 'emphasis' : 'normal'
  52488. );
  52489. }
  52490. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  52491. var zoomActive = view._isZoomActive;
  52492. if (payload && payload.type === 'takeGlobalCursor') {
  52493. zoomActive = payload.key === 'dataZoomSelect'
  52494. ? payload.dataZoomSelectActive : false;
  52495. }
  52496. view._isZoomActive = zoomActive;
  52497. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  52498. var brushTargetManager = new BrushTargetManager(
  52499. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  52500. );
  52501. view._brushController
  52502. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  52503. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  52504. ? 'lineX'
  52505. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  52506. ? 'lineY'
  52507. : 'rect';
  52508. }))
  52509. .enableBrush(
  52510. zoomActive
  52511. ? {
  52512. brushType: 'auto',
  52513. brushStyle: {
  52514. // FIXME user customized?
  52515. lineWidth: 0,
  52516. fill: 'rgba(0,0,0,0.2)'
  52517. }
  52518. }
  52519. : false
  52520. );
  52521. }
  52522. register$2('dataZoom', DataZoom);
  52523. // Create special dataZoom option for select
  52524. // FIXME consider the case of merge option, where axes options are not exists.
  52525. registerPreprocessor(function (option) {
  52526. if (!option) {
  52527. return;
  52528. }
  52529. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  52530. if (!isArray(dataZoomOpts)) {
  52531. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  52532. }
  52533. var toolboxOpt = option.toolbox;
  52534. if (toolboxOpt) {
  52535. // Assume there is only one toolbox
  52536. if (isArray(toolboxOpt)) {
  52537. toolboxOpt = toolboxOpt[0];
  52538. }
  52539. if (toolboxOpt && toolboxOpt.feature) {
  52540. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  52541. // FIXME: If add dataZoom when setOption in merge mode,
  52542. // no axis info to be added. See `test/dataZoom-extreme.html`
  52543. addForAxis('xAxis', dataZoomOpt);
  52544. addForAxis('yAxis', dataZoomOpt);
  52545. }
  52546. }
  52547. function addForAxis(axisName, dataZoomOpt) {
  52548. if (!dataZoomOpt) {
  52549. return;
  52550. }
  52551. // Try not to modify model, because it is not merged yet.
  52552. var axisIndicesName = axisName + 'Index';
  52553. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  52554. if (givenAxisIndices != null
  52555. && givenAxisIndices !== 'all'
  52556. && !isArray(givenAxisIndices)
  52557. ) {
  52558. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  52559. }
  52560. forEachComponent(axisName, function (axisOpt, axisIndex) {
  52561. if (givenAxisIndices != null
  52562. && givenAxisIndices !== 'all'
  52563. && indexOf(givenAxisIndices, axisIndex) === -1
  52564. ) {
  52565. return;
  52566. }
  52567. var newOpt = {
  52568. type: 'select',
  52569. $fromToolbox: true,
  52570. // Default to be filter
  52571. filterMode: dataZoomOpt.filterMode || 'filter',
  52572. // Id for merge mapping.
  52573. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  52574. };
  52575. // FIXME
  52576. // Only support one axis now.
  52577. newOpt[axisIndicesName] = axisIndex;
  52578. dataZoomOpts.push(newOpt);
  52579. });
  52580. }
  52581. function forEachComponent(mainType, cb) {
  52582. var opts = option[mainType];
  52583. if (!isArray(opts)) {
  52584. opts = opts ? [opts] : [];
  52585. }
  52586. each$15(opts, cb);
  52587. }
  52588. });
  52589. /*
  52590. * Licensed to the Apache Software Foundation (ASF) under one
  52591. * or more contributor license agreements. See the NOTICE file
  52592. * distributed with this work for additional information
  52593. * regarding copyright ownership. The ASF licenses this file
  52594. * to you under the Apache License, Version 2.0 (the
  52595. * "License"); you may not use this file except in compliance
  52596. * with the License. You may obtain a copy of the License at
  52597. *
  52598. * http://www.apache.org/licenses/LICENSE-2.0
  52599. *
  52600. * Unless required by applicable law or agreed to in writing,
  52601. * software distributed under the License is distributed on an
  52602. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52603. * KIND, either express or implied. See the License for the
  52604. * specific language governing permissions and limitations
  52605. * under the License.
  52606. */
  52607. var restoreLang = lang.toolbox.restore;
  52608. function Restore(model) {
  52609. this.model = model;
  52610. }
  52611. Restore.defaultOption = {
  52612. show: true,
  52613. /* eslint-disable */
  52614. 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',
  52615. /* eslint-enable */
  52616. title: restoreLang.title
  52617. };
  52618. var proto$6 = Restore.prototype;
  52619. proto$6.onclick = function (ecModel, api, type) {
  52620. clear$1(ecModel);
  52621. api.dispatchAction({
  52622. type: 'restore',
  52623. from: this.uid
  52624. });
  52625. };
  52626. register$2('restore', Restore);
  52627. registerAction(
  52628. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  52629. function (payload, ecModel) {
  52630. ecModel.resetOption('recreate');
  52631. }
  52632. );
  52633. /*
  52634. * Licensed to the Apache Software Foundation (ASF) under one
  52635. * or more contributor license agreements. See the NOTICE file
  52636. * distributed with this work for additional information
  52637. * regarding copyright ownership. The ASF licenses this file
  52638. * to you under the Apache License, Version 2.0 (the
  52639. * "License"); you may not use this file except in compliance
  52640. * with the License. You may obtain a copy of the License at
  52641. *
  52642. * http://www.apache.org/licenses/LICENSE-2.0
  52643. *
  52644. * Unless required by applicable law or agreed to in writing,
  52645. * software distributed under the License is distributed on an
  52646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52647. * KIND, either express or implied. See the License for the
  52648. * specific language governing permissions and limitations
  52649. * under the License.
  52650. */
  52651. var urn = 'urn:schemas-microsoft-com:vml';
  52652. var win = typeof window === 'undefined' ? null : window;
  52653. var vmlInited = false;
  52654. var doc = win && win.document;
  52655. function createNode(tagName) {
  52656. return doCreateNode(tagName);
  52657. }
  52658. // Avoid assign to an exported variable, for transforming to cjs.
  52659. var doCreateNode;
  52660. if (doc && !env$1.canvasSupported) {
  52661. try {
  52662. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  52663. doCreateNode = function (tagName) {
  52664. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  52665. };
  52666. }
  52667. catch (e) {
  52668. doCreateNode = function (tagName) {
  52669. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  52670. };
  52671. }
  52672. }
  52673. // From raphael
  52674. function initVML() {
  52675. if (vmlInited || !doc) {
  52676. return;
  52677. }
  52678. vmlInited = true;
  52679. var styleSheets = doc.styleSheets;
  52680. if (styleSheets.length < 31) {
  52681. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  52682. }
  52683. else {
  52684. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  52685. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  52686. }
  52687. }
  52688. // http://www.w3.org/TR/NOTE-VML
  52689. // TODO Use proxy like svg instead of overwrite brush methods
  52690. var CMD$3 = PathProxy.CMD;
  52691. var round$2 = Math.round;
  52692. var sqrt = Math.sqrt;
  52693. var abs$1 = Math.abs;
  52694. var cos = Math.cos;
  52695. var sin = Math.sin;
  52696. var mathMax$6 = Math.max;
  52697. if (!env$1.canvasSupported) {
  52698. var comma = ',';
  52699. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  52700. var Z = 21600;
  52701. var Z2 = Z / 2;
  52702. var ZLEVEL_BASE = 100000;
  52703. var Z_BASE = 1000;
  52704. var initRootElStyle = function (el) {
  52705. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  52706. el.coordsize = Z + ',' + Z;
  52707. el.coordorigin = '0,0';
  52708. };
  52709. var encodeHtmlAttribute = function (s) {
  52710. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  52711. };
  52712. var rgb2Str = function (r, g, b) {
  52713. return 'rgb(' + [r, g, b].join(',') + ')';
  52714. };
  52715. var append = function (parent, child) {
  52716. if (child && parent && child.parentNode !== parent) {
  52717. parent.appendChild(child);
  52718. }
  52719. };
  52720. var remove = function (parent, child) {
  52721. if (child && parent && child.parentNode === parent) {
  52722. parent.removeChild(child);
  52723. }
  52724. };
  52725. var getZIndex = function (zlevel, z, z2) {
  52726. // z 的取值范围为 [0, 1000]
  52727. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  52728. };
  52729. var parsePercent$3 = parsePercent;
  52730. /***************************************************
  52731. * PATH
  52732. **************************************************/
  52733. var setColorAndOpacity = function (el, color, opacity) {
  52734. var colorArr = parse(color);
  52735. opacity = +opacity;
  52736. if (isNaN(opacity)) {
  52737. opacity = 1;
  52738. }
  52739. if (colorArr) {
  52740. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  52741. el.opacity = opacity * colorArr[3];
  52742. }
  52743. };
  52744. var getColorAndAlpha = function (color) {
  52745. var colorArr = parse(color);
  52746. return [
  52747. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  52748. colorArr[3]
  52749. ];
  52750. };
  52751. var updateFillNode = function (el, style, zrEl) {
  52752. // TODO pattern
  52753. var fill = style.fill;
  52754. if (fill != null) {
  52755. // Modified from excanvas
  52756. if (fill instanceof Gradient) {
  52757. var gradientType;
  52758. var angle = 0;
  52759. var focus = [0, 0];
  52760. // additional offset
  52761. var shift = 0;
  52762. // scale factor for offset
  52763. var expansion = 1;
  52764. var rect = zrEl.getBoundingRect();
  52765. var rectWidth = rect.width;
  52766. var rectHeight = rect.height;
  52767. if (fill.type === 'linear') {
  52768. gradientType = 'gradient';
  52769. var transform = zrEl.transform;
  52770. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  52771. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  52772. if (transform) {
  52773. applyTransform(p0, p0, transform);
  52774. applyTransform(p1, p1, transform);
  52775. }
  52776. var dx = p1[0] - p0[0];
  52777. var dy = p1[1] - p0[1];
  52778. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  52779. // The angle should be a non-negative number.
  52780. if (angle < 0) {
  52781. angle += 360;
  52782. }
  52783. // Very small angles produce an unexpected result because they are
  52784. // converted to a scientific notation string.
  52785. if (angle < 1e-6) {
  52786. angle = 0;
  52787. }
  52788. }
  52789. else {
  52790. gradientType = 'gradientradial';
  52791. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  52792. var transform = zrEl.transform;
  52793. var scale$$1 = zrEl.scale;
  52794. var width = rectWidth;
  52795. var height = rectHeight;
  52796. focus = [
  52797. // Percent in bounding rect
  52798. (p0[0] - rect.x) / width,
  52799. (p0[1] - rect.y) / height
  52800. ];
  52801. if (transform) {
  52802. applyTransform(p0, p0, transform);
  52803. }
  52804. width /= scale$$1[0] * Z;
  52805. height /= scale$$1[1] * Z;
  52806. var dimension = mathMax$6(width, height);
  52807. shift = 2 * 0 / dimension;
  52808. expansion = 2 * fill.r / dimension - shift;
  52809. }
  52810. // We need to sort the color stops in ascending order by offset,
  52811. // otherwise IE won't interpret it correctly.
  52812. var stops = fill.colorStops.slice();
  52813. stops.sort(function (cs1, cs2) {
  52814. return cs1.offset - cs2.offset;
  52815. });
  52816. var length$$1 = stops.length;
  52817. // Color and alpha list of first and last stop
  52818. var colorAndAlphaList = [];
  52819. var colors = [];
  52820. for (var i = 0; i < length$$1; i++) {
  52821. var stop = stops[i];
  52822. var colorAndAlpha = getColorAndAlpha(stop.color);
  52823. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  52824. if (i === 0 || i === length$$1 - 1) {
  52825. colorAndAlphaList.push(colorAndAlpha);
  52826. }
  52827. }
  52828. if (length$$1 >= 2) {
  52829. var color1 = colorAndAlphaList[0][0];
  52830. var color2 = colorAndAlphaList[1][0];
  52831. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  52832. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  52833. el.type = gradientType;
  52834. el.method = 'none';
  52835. el.focus = '100%';
  52836. el.angle = angle;
  52837. el.color = color1;
  52838. el.color2 = color2;
  52839. el.colors = colors.join(',');
  52840. // When colors attribute is used, the meanings of opacity and o:opacity2
  52841. // are reversed.
  52842. el.opacity = opacity2;
  52843. // FIXME g_o_:opacity ?
  52844. el.opacity2 = opacity1;
  52845. }
  52846. if (gradientType === 'radial') {
  52847. el.focusposition = focus.join(',');
  52848. }
  52849. }
  52850. else {
  52851. // FIXME Change from Gradient fill to color fill
  52852. setColorAndOpacity(el, fill, style.opacity);
  52853. }
  52854. }
  52855. };
  52856. var updateStrokeNode = function (el, style) {
  52857. // if (style.lineJoin != null) {
  52858. // el.joinstyle = style.lineJoin;
  52859. // }
  52860. // if (style.miterLimit != null) {
  52861. // el.miterlimit = style.miterLimit * Z;
  52862. // }
  52863. // if (style.lineCap != null) {
  52864. // el.endcap = style.lineCap;
  52865. // }
  52866. if (style.lineDash) {
  52867. el.dashstyle = style.lineDash.join(' ');
  52868. }
  52869. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  52870. setColorAndOpacity(el, style.stroke, style.opacity);
  52871. }
  52872. };
  52873. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  52874. var isFill = type === 'fill';
  52875. var el = vmlEl.getElementsByTagName(type)[0];
  52876. // Stroke must have lineWidth
  52877. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  52878. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  52879. // FIXME Remove before updating, or set `colors` will throw error
  52880. if (style[type] instanceof Gradient) {
  52881. remove(vmlEl, el);
  52882. }
  52883. if (!el) {
  52884. el = createNode(type);
  52885. }
  52886. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  52887. append(vmlEl, el);
  52888. }
  52889. else {
  52890. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  52891. remove(vmlEl, el);
  52892. }
  52893. };
  52894. var points$1 = [[], [], []];
  52895. var pathDataToString = function (path, m) {
  52896. var M = CMD$3.M;
  52897. var C = CMD$3.C;
  52898. var L = CMD$3.L;
  52899. var A = CMD$3.A;
  52900. var Q = CMD$3.Q;
  52901. var str = [];
  52902. var nPoint;
  52903. var cmdStr;
  52904. var cmd;
  52905. var i;
  52906. var xi;
  52907. var yi;
  52908. var data = path.data;
  52909. var dataLength = path.len();
  52910. for (i = 0; i < dataLength;) {
  52911. cmd = data[i++];
  52912. cmdStr = '';
  52913. nPoint = 0;
  52914. switch (cmd) {
  52915. case M:
  52916. cmdStr = ' m ';
  52917. nPoint = 1;
  52918. xi = data[i++];
  52919. yi = data[i++];
  52920. points$1[0][0] = xi;
  52921. points$1[0][1] = yi;
  52922. break;
  52923. case L:
  52924. cmdStr = ' l ';
  52925. nPoint = 1;
  52926. xi = data[i++];
  52927. yi = data[i++];
  52928. points$1[0][0] = xi;
  52929. points$1[0][1] = yi;
  52930. break;
  52931. case Q:
  52932. case C:
  52933. cmdStr = ' c ';
  52934. nPoint = 3;
  52935. var x1 = data[i++];
  52936. var y1 = data[i++];
  52937. var x2 = data[i++];
  52938. var y2 = data[i++];
  52939. var x3;
  52940. var y3;
  52941. if (cmd === Q) {
  52942. // Convert quadratic to cubic using degree elevation
  52943. x3 = x2;
  52944. y3 = y2;
  52945. x2 = (x2 + 2 * x1) / 3;
  52946. y2 = (y2 + 2 * y1) / 3;
  52947. x1 = (xi + 2 * x1) / 3;
  52948. y1 = (yi + 2 * y1) / 3;
  52949. }
  52950. else {
  52951. x3 = data[i++];
  52952. y3 = data[i++];
  52953. }
  52954. points$1[0][0] = x1;
  52955. points$1[0][1] = y1;
  52956. points$1[1][0] = x2;
  52957. points$1[1][1] = y2;
  52958. points$1[2][0] = x3;
  52959. points$1[2][1] = y3;
  52960. xi = x3;
  52961. yi = y3;
  52962. break;
  52963. case A:
  52964. var x = 0;
  52965. var y = 0;
  52966. var sx = 1;
  52967. var sy = 1;
  52968. var angle = 0;
  52969. if (m) {
  52970. // Extract SRT from matrix
  52971. x = m[4];
  52972. y = m[5];
  52973. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  52974. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  52975. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  52976. }
  52977. var cx = data[i++];
  52978. var cy = data[i++];
  52979. var rx = data[i++];
  52980. var ry = data[i++];
  52981. var startAngle = data[i++] + angle;
  52982. var endAngle = data[i++] + startAngle + angle;
  52983. // FIXME
  52984. // var psi = data[i++];
  52985. i++;
  52986. var clockwise = data[i++];
  52987. var x0 = cx + cos(startAngle) * rx;
  52988. var y0 = cy + sin(startAngle) * ry;
  52989. var x1 = cx + cos(endAngle) * rx;
  52990. var y1 = cy + sin(endAngle) * ry;
  52991. var type = clockwise ? ' wa ' : ' at ';
  52992. if (Math.abs(x0 - x1) < 1e-4) {
  52993. // IE won't render arches drawn counter clockwise if x0 == x1.
  52994. if (Math.abs(endAngle - startAngle) > 1e-2) {
  52995. // Offset x0 by 1/80 of a pixel. Use something
  52996. // that can be represented in binary
  52997. if (clockwise) {
  52998. x0 += 270 / Z;
  52999. }
  53000. }
  53001. else {
  53002. // Avoid case draw full circle
  53003. if (Math.abs(y0 - cy) < 1e-4) {
  53004. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  53005. y1 -= 270 / Z;
  53006. }
  53007. else {
  53008. y1 += 270 / Z;
  53009. }
  53010. }
  53011. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  53012. x1 += 270 / Z;
  53013. }
  53014. else {
  53015. x1 -= 270 / Z;
  53016. }
  53017. }
  53018. }
  53019. str.push(
  53020. type,
  53021. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  53022. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  53023. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  53024. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  53025. round$2((x0 * sx + x) * Z - Z2), comma,
  53026. round$2((y0 * sy + y) * Z - Z2), comma,
  53027. round$2((x1 * sx + x) * Z - Z2), comma,
  53028. round$2((y1 * sy + y) * Z - Z2)
  53029. );
  53030. xi = x1;
  53031. yi = y1;
  53032. break;
  53033. case CMD$3.R:
  53034. var p0 = points$1[0];
  53035. var p1 = points$1[1];
  53036. // x0, y0
  53037. p0[0] = data[i++];
  53038. p0[1] = data[i++];
  53039. // x1, y1
  53040. p1[0] = p0[0] + data[i++];
  53041. p1[1] = p0[1] + data[i++];
  53042. if (m) {
  53043. applyTransform(p0, p0, m);
  53044. applyTransform(p1, p1, m);
  53045. }
  53046. p0[0] = round$2(p0[0] * Z - Z2);
  53047. p1[0] = round$2(p1[0] * Z - Z2);
  53048. p0[1] = round$2(p0[1] * Z - Z2);
  53049. p1[1] = round$2(p1[1] * Z - Z2);
  53050. str.push(
  53051. // x0, y0
  53052. ' m ', p0[0], comma, p0[1],
  53053. // x1, y0
  53054. ' l ', p1[0], comma, p0[1],
  53055. // x1, y1
  53056. ' l ', p1[0], comma, p1[1],
  53057. // x0, y1
  53058. ' l ', p0[0], comma, p1[1]
  53059. );
  53060. break;
  53061. case CMD$3.Z:
  53062. // FIXME Update xi, yi
  53063. str.push(' x ');
  53064. }
  53065. if (nPoint > 0) {
  53066. str.push(cmdStr);
  53067. for (var k = 0; k < nPoint; k++) {
  53068. var p = points$1[k];
  53069. m && applyTransform(p, p, m);
  53070. // 不 round 会非常慢
  53071. str.push(
  53072. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  53073. k < nPoint - 1 ? comma : ''
  53074. );
  53075. }
  53076. }
  53077. }
  53078. return str.join('');
  53079. };
  53080. // Rewrite the original path method
  53081. Path.prototype.brushVML = function (vmlRoot) {
  53082. var style = this.style;
  53083. var vmlEl = this._vmlEl;
  53084. if (!vmlEl) {
  53085. vmlEl = createNode('shape');
  53086. initRootElStyle(vmlEl);
  53087. this._vmlEl = vmlEl;
  53088. }
  53089. updateFillAndStroke(vmlEl, 'fill', style, this);
  53090. updateFillAndStroke(vmlEl, 'stroke', style, this);
  53091. var m = this.transform;
  53092. var needTransform = m != null;
  53093. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  53094. if (strokeEl) {
  53095. var lineWidth = style.lineWidth;
  53096. // Get the line scale.
  53097. // Determinant of this.m_ means how much the area is enlarged by the
  53098. // transformation. So its square root can be used as a scale factor
  53099. // for width.
  53100. if (needTransform && !style.strokeNoScale) {
  53101. var det = m[0] * m[3] - m[1] * m[2];
  53102. lineWidth *= sqrt(abs$1(det));
  53103. }
  53104. strokeEl.weight = lineWidth + 'px';
  53105. }
  53106. var path = this.path || (this.path = new PathProxy());
  53107. if (this.__dirtyPath) {
  53108. path.beginPath();
  53109. path.subPixelOptimize = false;
  53110. this.buildPath(path, this.shape);
  53111. path.toStatic();
  53112. this.__dirtyPath = false;
  53113. }
  53114. vmlEl.path = pathDataToString(path, this.transform);
  53115. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53116. // Append to root
  53117. append(vmlRoot, vmlEl);
  53118. // Text
  53119. if (style.text != null) {
  53120. this.drawRectText(vmlRoot, this.getBoundingRect());
  53121. }
  53122. else {
  53123. this.removeRectText(vmlRoot);
  53124. }
  53125. };
  53126. Path.prototype.onRemove = function (vmlRoot) {
  53127. remove(vmlRoot, this._vmlEl);
  53128. this.removeRectText(vmlRoot);
  53129. };
  53130. Path.prototype.onAdd = function (vmlRoot) {
  53131. append(vmlRoot, this._vmlEl);
  53132. this.appendRectText(vmlRoot);
  53133. };
  53134. /***************************************************
  53135. * IMAGE
  53136. **************************************************/
  53137. var isImage = function (img) {
  53138. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  53139. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  53140. // return img instanceof Image;
  53141. };
  53142. // Rewrite the original path method
  53143. ZImage.prototype.brushVML = function (vmlRoot) {
  53144. var style = this.style;
  53145. var image = style.image;
  53146. // Image original width, height
  53147. var ow;
  53148. var oh;
  53149. if (isImage(image)) {
  53150. var src = image.src;
  53151. if (src === this._imageSrc) {
  53152. ow = this._imageWidth;
  53153. oh = this._imageHeight;
  53154. }
  53155. else {
  53156. var imageRuntimeStyle = image.runtimeStyle;
  53157. var oldRuntimeWidth = imageRuntimeStyle.width;
  53158. var oldRuntimeHeight = imageRuntimeStyle.height;
  53159. imageRuntimeStyle.width = 'auto';
  53160. imageRuntimeStyle.height = 'auto';
  53161. // get the original size
  53162. ow = image.width;
  53163. oh = image.height;
  53164. // and remove overides
  53165. imageRuntimeStyle.width = oldRuntimeWidth;
  53166. imageRuntimeStyle.height = oldRuntimeHeight;
  53167. // Caching image original width, height and src
  53168. this._imageSrc = src;
  53169. this._imageWidth = ow;
  53170. this._imageHeight = oh;
  53171. }
  53172. image = src;
  53173. }
  53174. else {
  53175. if (image === this._imageSrc) {
  53176. ow = this._imageWidth;
  53177. oh = this._imageHeight;
  53178. }
  53179. }
  53180. if (!image) {
  53181. return;
  53182. }
  53183. var x = style.x || 0;
  53184. var y = style.y || 0;
  53185. var dw = style.width;
  53186. var dh = style.height;
  53187. var sw = style.sWidth;
  53188. var sh = style.sHeight;
  53189. var sx = style.sx || 0;
  53190. var sy = style.sy || 0;
  53191. var hasCrop = sw && sh;
  53192. var vmlEl = this._vmlEl;
  53193. if (!vmlEl) {
  53194. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  53195. // vmlEl = vmlCore.createNode('group');
  53196. vmlEl = doc.createElement('div');
  53197. initRootElStyle(vmlEl);
  53198. this._vmlEl = vmlEl;
  53199. }
  53200. var vmlElStyle = vmlEl.style;
  53201. var hasRotation = false;
  53202. var m;
  53203. var scaleX = 1;
  53204. var scaleY = 1;
  53205. if (this.transform) {
  53206. m = this.transform;
  53207. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  53208. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  53209. hasRotation = m[1] || m[2];
  53210. }
  53211. if (hasRotation) {
  53212. // If filters are necessary (rotation exists), create them
  53213. // filters are bog-slow, so only create them if abbsolutely necessary
  53214. // The following check doesn't account for skews (which don't exist
  53215. // in the canvas spec (yet) anyway.
  53216. // From excanvas
  53217. var p0 = [x, y];
  53218. var p1 = [x + dw, y];
  53219. var p2 = [x, y + dh];
  53220. var p3 = [x + dw, y + dh];
  53221. applyTransform(p0, p0, m);
  53222. applyTransform(p1, p1, m);
  53223. applyTransform(p2, p2, m);
  53224. applyTransform(p3, p3, m);
  53225. var maxX = mathMax$6(p0[0], p1[0], p2[0], p3[0]);
  53226. var maxY = mathMax$6(p0[1], p1[1], p2[1], p3[1]);
  53227. var transformFilter = [];
  53228. transformFilter.push('M11=', m[0] / scaleX, comma,
  53229. 'M12=', m[2] / scaleY, comma,
  53230. 'M21=', m[1] / scaleX, comma,
  53231. 'M22=', m[3] / scaleY, comma,
  53232. 'Dx=', round$2(x * scaleX + m[4]), comma,
  53233. 'Dy=', round$2(y * scaleY + m[5]));
  53234. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  53235. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  53236. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  53237. + transformFilter.join('') + ', SizingMethod=clip)';
  53238. }
  53239. else {
  53240. if (m) {
  53241. x = x * scaleX + m[4];
  53242. y = y * scaleY + m[5];
  53243. }
  53244. vmlElStyle.filter = '';
  53245. vmlElStyle.left = round$2(x) + 'px';
  53246. vmlElStyle.top = round$2(y) + 'px';
  53247. }
  53248. var imageEl = this._imageEl;
  53249. var cropEl = this._cropEl;
  53250. if (!imageEl) {
  53251. imageEl = doc.createElement('div');
  53252. this._imageEl = imageEl;
  53253. }
  53254. var imageELStyle = imageEl.style;
  53255. if (hasCrop) {
  53256. // Needs know image original width and height
  53257. if (!(ow && oh)) {
  53258. var tmpImage = new Image();
  53259. var self = this;
  53260. tmpImage.onload = function () {
  53261. tmpImage.onload = null;
  53262. ow = tmpImage.width;
  53263. oh = tmpImage.height;
  53264. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  53265. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53266. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53267. // Caching image original width, height and src
  53268. self._imageWidth = ow;
  53269. self._imageHeight = oh;
  53270. self._imageSrc = image;
  53271. };
  53272. tmpImage.src = image;
  53273. }
  53274. else {
  53275. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53276. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53277. }
  53278. if (!cropEl) {
  53279. cropEl = doc.createElement('div');
  53280. cropEl.style.overflow = 'hidden';
  53281. this._cropEl = cropEl;
  53282. }
  53283. var cropElStyle = cropEl.style;
  53284. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  53285. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  53286. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  53287. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  53288. if (!cropEl.parentNode) {
  53289. vmlEl.appendChild(cropEl);
  53290. }
  53291. if (imageEl.parentNode !== cropEl) {
  53292. cropEl.appendChild(imageEl);
  53293. }
  53294. }
  53295. else {
  53296. imageELStyle.width = round$2(scaleX * dw) + 'px';
  53297. imageELStyle.height = round$2(scaleY * dh) + 'px';
  53298. vmlEl.appendChild(imageEl);
  53299. if (cropEl && cropEl.parentNode) {
  53300. vmlEl.removeChild(cropEl);
  53301. this._cropEl = null;
  53302. }
  53303. }
  53304. var filterStr = '';
  53305. var alpha = style.opacity;
  53306. if (alpha < 1) {
  53307. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  53308. }
  53309. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  53310. imageELStyle.filter = filterStr;
  53311. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53312. // Append to root
  53313. append(vmlRoot, vmlEl);
  53314. // Text
  53315. if (style.text != null) {
  53316. this.drawRectText(vmlRoot, this.getBoundingRect());
  53317. }
  53318. };
  53319. ZImage.prototype.onRemove = function (vmlRoot) {
  53320. remove(vmlRoot, this._vmlEl);
  53321. this._vmlEl = null;
  53322. this._cropEl = null;
  53323. this._imageEl = null;
  53324. this.removeRectText(vmlRoot);
  53325. };
  53326. ZImage.prototype.onAdd = function (vmlRoot) {
  53327. append(vmlRoot, this._vmlEl);
  53328. this.appendRectText(vmlRoot);
  53329. };
  53330. /***************************************************
  53331. * TEXT
  53332. **************************************************/
  53333. var DEFAULT_STYLE_NORMAL = 'normal';
  53334. var fontStyleCache = {};
  53335. var fontStyleCacheCount = 0;
  53336. var MAX_FONT_CACHE_SIZE = 100;
  53337. var fontEl = document.createElement('div');
  53338. var getFontStyle = function (fontString) {
  53339. var fontStyle = fontStyleCache[fontString];
  53340. if (!fontStyle) {
  53341. // Clear cache
  53342. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  53343. fontStyleCacheCount = 0;
  53344. fontStyleCache = {};
  53345. }
  53346. var style = fontEl.style;
  53347. var fontFamily;
  53348. try {
  53349. style.font = fontString;
  53350. fontFamily = style.fontFamily.split(',')[0];
  53351. }
  53352. catch (e) {
  53353. }
  53354. fontStyle = {
  53355. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  53356. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  53357. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  53358. size: parseFloat(style.fontSize || 12) | 0,
  53359. family: fontFamily || 'Microsoft YaHei'
  53360. };
  53361. fontStyleCache[fontString] = fontStyle;
  53362. fontStyleCacheCount++;
  53363. }
  53364. return fontStyle;
  53365. };
  53366. var textMeasureEl;
  53367. // Overwrite measure text method
  53368. $override$1('measureText', function (text, textFont) {
  53369. var doc$$1 = doc;
  53370. if (!textMeasureEl) {
  53371. textMeasureEl = doc$$1.createElement('div');
  53372. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  53373. + 'padding:0;margin:0;border:none;white-space:pre;';
  53374. doc.body.appendChild(textMeasureEl);
  53375. }
  53376. try {
  53377. textMeasureEl.style.font = textFont;
  53378. }
  53379. catch (ex) {
  53380. // Ignore failures to set to invalid font.
  53381. }
  53382. textMeasureEl.innerHTML = '';
  53383. // Don't use innerHTML or innerText because they allow markup/whitespace.
  53384. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  53385. return {
  53386. width: textMeasureEl.offsetWidth
  53387. };
  53388. });
  53389. var tmpRect$2 = new BoundingRect();
  53390. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  53391. var style = this.style;
  53392. // Optimize, avoid normalize every time.
  53393. this.__dirty && normalizeTextStyle(style, true);
  53394. var text = style.text;
  53395. // Convert to string
  53396. text != null && (text += '');
  53397. if (!text) {
  53398. return;
  53399. }
  53400. // Convert rich text to plain text. Rich text is not supported in
  53401. // IE8-, but tags in rich text template will be removed.
  53402. if (style.rich) {
  53403. var contentBlock = parseRichText(text, style);
  53404. text = [];
  53405. for (var i = 0; i < contentBlock.lines.length; i++) {
  53406. var tokens = contentBlock.lines[i].tokens;
  53407. var textLine = [];
  53408. for (var j = 0; j < tokens.length; j++) {
  53409. textLine.push(tokens[j].text);
  53410. }
  53411. text.push(textLine.join(''));
  53412. }
  53413. text = text.join('\n');
  53414. }
  53415. var x;
  53416. var y;
  53417. var align = style.textAlign;
  53418. var verticalAlign = style.textVerticalAlign;
  53419. var fontStyle = getFontStyle(style.font);
  53420. // FIXME encodeHtmlAttribute ?
  53421. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  53422. + fontStyle.size + 'px "' + fontStyle.family + '"';
  53423. textRect = textRect || getBoundingRect(
  53424. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  53425. );
  53426. // Transform rect to view space
  53427. var m = this.transform;
  53428. // Ignore transform for text in other element
  53429. if (m && !fromTextEl) {
  53430. tmpRect$2.copy(rect);
  53431. tmpRect$2.applyTransform(m);
  53432. rect = tmpRect$2;
  53433. }
  53434. if (!fromTextEl) {
  53435. var textPosition = style.textPosition;
  53436. // Text position represented by coord
  53437. if (textPosition instanceof Array) {
  53438. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  53439. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  53440. align = align || 'left';
  53441. }
  53442. else {
  53443. var res = this.calculateTextPosition
  53444. ? this.calculateTextPosition({}, style, rect)
  53445. : calculateTextPosition({}, style, rect);
  53446. x = res.x;
  53447. y = res.y;
  53448. // Default align and baseline when has textPosition
  53449. align = align || res.textAlign;
  53450. verticalAlign = verticalAlign || res.textVerticalAlign;
  53451. }
  53452. }
  53453. else {
  53454. x = rect.x;
  53455. y = rect.y;
  53456. }
  53457. x = adjustTextX(x, textRect.width, align);
  53458. y = adjustTextY(y, textRect.height, verticalAlign);
  53459. // Force baseline 'middle'
  53460. y += textRect.height / 2;
  53461. // var fontSize = fontStyle.size;
  53462. // 1.75 is an arbitrary number, as there is no info about the text baseline
  53463. // switch (baseline) {
  53464. // case 'hanging':
  53465. // case 'top':
  53466. // y += fontSize / 1.75;
  53467. // break;
  53468. // case 'middle':
  53469. // break;
  53470. // default:
  53471. // // case null:
  53472. // // case 'alphabetic':
  53473. // // case 'ideographic':
  53474. // // case 'bottom':
  53475. // y -= fontSize / 2.25;
  53476. // break;
  53477. // }
  53478. // switch (align) {
  53479. // case 'left':
  53480. // break;
  53481. // case 'center':
  53482. // x -= textRect.width / 2;
  53483. // break;
  53484. // case 'right':
  53485. // x -= textRect.width;
  53486. // break;
  53487. // case 'end':
  53488. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  53489. // break;
  53490. // case 'start':
  53491. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  53492. // break;
  53493. // default:
  53494. // align = 'left';
  53495. // }
  53496. var createNode$$1 = createNode;
  53497. var textVmlEl = this._textVmlEl;
  53498. var pathEl;
  53499. var textPathEl;
  53500. var skewEl;
  53501. if (!textVmlEl) {
  53502. textVmlEl = createNode$$1('line');
  53503. pathEl = createNode$$1('path');
  53504. textPathEl = createNode$$1('textpath');
  53505. skewEl = createNode$$1('skew');
  53506. // FIXME Why here is not cammel case
  53507. // Align 'center' seems wrong
  53508. textPathEl.style['v-text-align'] = 'left';
  53509. initRootElStyle(textVmlEl);
  53510. pathEl.textpathok = true;
  53511. textPathEl.on = true;
  53512. textVmlEl.from = '0 0';
  53513. textVmlEl.to = '1000 0.05';
  53514. append(textVmlEl, skewEl);
  53515. append(textVmlEl, pathEl);
  53516. append(textVmlEl, textPathEl);
  53517. this._textVmlEl = textVmlEl;
  53518. }
  53519. else {
  53520. // 这里是在前面 appendChild 保证顺序的前提下
  53521. skewEl = textVmlEl.firstChild;
  53522. pathEl = skewEl.nextSibling;
  53523. textPathEl = pathEl.nextSibling;
  53524. }
  53525. var coords = [x, y];
  53526. var textVmlElStyle = textVmlEl.style;
  53527. // Ignore transform for text in other element
  53528. if (m && fromTextEl) {
  53529. applyTransform(coords, coords, m);
  53530. skewEl.on = true;
  53531. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  53532. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  53533. // Text position
  53534. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  53535. // Left top point as origin
  53536. skewEl.origin = '0 0';
  53537. textVmlElStyle.left = '0px';
  53538. textVmlElStyle.top = '0px';
  53539. }
  53540. else {
  53541. skewEl.on = false;
  53542. textVmlElStyle.left = round$2(x) + 'px';
  53543. textVmlElStyle.top = round$2(y) + 'px';
  53544. }
  53545. textPathEl.string = encodeHtmlAttribute(text);
  53546. // TODO
  53547. try {
  53548. textPathEl.style.font = font;
  53549. }
  53550. // Error font format
  53551. catch (e) {}
  53552. updateFillAndStroke(textVmlEl, 'fill', {
  53553. fill: style.textFill,
  53554. opacity: style.opacity
  53555. }, this);
  53556. updateFillAndStroke(textVmlEl, 'stroke', {
  53557. stroke: style.textStroke,
  53558. opacity: style.opacity,
  53559. lineDash: style.lineDash || null // style.lineDash can be `false`.
  53560. }, this);
  53561. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53562. // Attached to root
  53563. append(vmlRoot, textVmlEl);
  53564. };
  53565. var removeRectText = function (vmlRoot) {
  53566. remove(vmlRoot, this._textVmlEl);
  53567. this._textVmlEl = null;
  53568. };
  53569. var appendRectText = function (vmlRoot) {
  53570. append(vmlRoot, this._textVmlEl);
  53571. };
  53572. var list = [RectText, Displayable, ZImage, Path, Text];
  53573. // In case Displayable has been mixed in RectText
  53574. for (var i$1 = 0; i$1 < list.length; i$1++) {
  53575. var proto$7 = list[i$1].prototype;
  53576. proto$7.drawRectText = drawRectText;
  53577. proto$7.removeRectText = removeRectText;
  53578. proto$7.appendRectText = appendRectText;
  53579. }
  53580. Text.prototype.brushVML = function (vmlRoot) {
  53581. var style = this.style;
  53582. if (style.text != null) {
  53583. this.drawRectText(vmlRoot, {
  53584. x: style.x || 0, y: style.y || 0,
  53585. width: 0, height: 0
  53586. }, this.getBoundingRect(), true);
  53587. }
  53588. else {
  53589. this.removeRectText(vmlRoot);
  53590. }
  53591. };
  53592. Text.prototype.onRemove = function (vmlRoot) {
  53593. this.removeRectText(vmlRoot);
  53594. };
  53595. Text.prototype.onAdd = function (vmlRoot) {
  53596. this.appendRectText(vmlRoot);
  53597. };
  53598. }
  53599. /**
  53600. * VML Painter.
  53601. *
  53602. * @module zrender/vml/Painter
  53603. */
  53604. function parseInt10$1(val) {
  53605. return parseInt(val, 10);
  53606. }
  53607. /**
  53608. * @alias module:zrender/vml/Painter
  53609. */
  53610. function VMLPainter(root, storage) {
  53611. initVML();
  53612. this.root = root;
  53613. this.storage = storage;
  53614. var vmlViewport = document.createElement('div');
  53615. var vmlRoot = document.createElement('div');
  53616. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  53617. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  53618. root.appendChild(vmlViewport);
  53619. this._vmlRoot = vmlRoot;
  53620. this._vmlViewport = vmlViewport;
  53621. this.resize();
  53622. // Modify storage
  53623. var oldDelFromStorage = storage.delFromStorage;
  53624. var oldAddToStorage = storage.addToStorage;
  53625. storage.delFromStorage = function (el) {
  53626. oldDelFromStorage.call(storage, el);
  53627. if (el) {
  53628. el.onRemove && el.onRemove(vmlRoot);
  53629. }
  53630. };
  53631. storage.addToStorage = function (el) {
  53632. // Displayable already has a vml node
  53633. el.onAdd && el.onAdd(vmlRoot);
  53634. oldAddToStorage.call(storage, el);
  53635. };
  53636. this._firstPaint = true;
  53637. }
  53638. VMLPainter.prototype = {
  53639. constructor: VMLPainter,
  53640. getType: function () {
  53641. return 'vml';
  53642. },
  53643. /**
  53644. * @return {HTMLDivElement}
  53645. */
  53646. getViewportRoot: function () {
  53647. return this._vmlViewport;
  53648. },
  53649. getViewportRootOffset: function () {
  53650. var viewportRoot = this.getViewportRoot();
  53651. if (viewportRoot) {
  53652. return {
  53653. offsetLeft: viewportRoot.offsetLeft || 0,
  53654. offsetTop: viewportRoot.offsetTop || 0
  53655. };
  53656. }
  53657. },
  53658. /**
  53659. * 刷新
  53660. */
  53661. refresh: function () {
  53662. var list = this.storage.getDisplayList(true, true);
  53663. this._paintList(list);
  53664. },
  53665. _paintList: function (list) {
  53666. var vmlRoot = this._vmlRoot;
  53667. for (var i = 0; i < list.length; i++) {
  53668. var el = list[i];
  53669. if (el.invisible || el.ignore) {
  53670. if (!el.__alreadyNotVisible) {
  53671. el.onRemove(vmlRoot);
  53672. }
  53673. // Set as already invisible
  53674. el.__alreadyNotVisible = true;
  53675. }
  53676. else {
  53677. if (el.__alreadyNotVisible) {
  53678. el.onAdd(vmlRoot);
  53679. }
  53680. el.__alreadyNotVisible = false;
  53681. if (el.__dirty) {
  53682. el.beforeBrush && el.beforeBrush();
  53683. (el.brushVML || el.brush).call(el, vmlRoot);
  53684. el.afterBrush && el.afterBrush();
  53685. }
  53686. }
  53687. el.__dirty = false;
  53688. }
  53689. if (this._firstPaint) {
  53690. // Detached from document at first time
  53691. // to avoid page refreshing too many times
  53692. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  53693. this._vmlViewport.appendChild(vmlRoot);
  53694. this._firstPaint = false;
  53695. }
  53696. },
  53697. resize: function (width, height) {
  53698. var width = width == null ? this._getWidth() : width;
  53699. var height = height == null ? this._getHeight() : height;
  53700. if (this._width !== width || this._height !== height) {
  53701. this._width = width;
  53702. this._height = height;
  53703. var vmlViewportStyle = this._vmlViewport.style;
  53704. vmlViewportStyle.width = width + 'px';
  53705. vmlViewportStyle.height = height + 'px';
  53706. }
  53707. },
  53708. dispose: function () {
  53709. this.root.innerHTML = '';
  53710. this._vmlRoot =
  53711. this._vmlViewport =
  53712. this.storage = null;
  53713. },
  53714. getWidth: function () {
  53715. return this._width;
  53716. },
  53717. getHeight: function () {
  53718. return this._height;
  53719. },
  53720. clear: function () {
  53721. if (this._vmlViewport) {
  53722. this.root.removeChild(this._vmlViewport);
  53723. }
  53724. },
  53725. _getWidth: function () {
  53726. var root = this.root;
  53727. var stl = root.currentStyle;
  53728. return ((root.clientWidth || parseInt10$1(stl.width))
  53729. - parseInt10$1(stl.paddingLeft)
  53730. - parseInt10$1(stl.paddingRight)) | 0;
  53731. },
  53732. _getHeight: function () {
  53733. var root = this.root;
  53734. var stl = root.currentStyle;
  53735. return ((root.clientHeight || parseInt10$1(stl.height))
  53736. - parseInt10$1(stl.paddingTop)
  53737. - parseInt10$1(stl.paddingBottom)) | 0;
  53738. }
  53739. };
  53740. // Not supported methods
  53741. function createMethodNotSupport(method) {
  53742. return function () {
  53743. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  53744. };
  53745. }
  53746. // Unsupported methods
  53747. each$1([
  53748. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  53749. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  53750. ], function (name) {
  53751. VMLPainter.prototype[name] = createMethodNotSupport(name);
  53752. });
  53753. registerPainter('vml', VMLPainter);
  53754. var svgURI = 'http://www.w3.org/2000/svg';
  53755. function createElement(name) {
  53756. return document.createElementNS(svgURI, name);
  53757. }
  53758. // TODO
  53759. // 1. shadow
  53760. // 2. Image: sx, sy, sw, sh
  53761. var CMD$4 = PathProxy.CMD;
  53762. var arrayJoin = Array.prototype.join;
  53763. var NONE = 'none';
  53764. var mathRound = Math.round;
  53765. var mathSin$3 = Math.sin;
  53766. var mathCos$3 = Math.cos;
  53767. var PI$3 = Math.PI;
  53768. var PI2$5 = Math.PI * 2;
  53769. var degree = 180 / PI$3;
  53770. var EPSILON$4 = 1e-4;
  53771. function round4(val) {
  53772. return mathRound(val * 1e4) / 1e4;
  53773. }
  53774. function isAroundZero$1(val) {
  53775. return val < EPSILON$4 && val > -EPSILON$4;
  53776. }
  53777. function pathHasFill(style, isText) {
  53778. var fill = isText ? style.textFill : style.fill;
  53779. return fill != null && fill !== NONE;
  53780. }
  53781. function pathHasStroke(style, isText) {
  53782. var stroke = isText ? style.textStroke : style.stroke;
  53783. return stroke != null && stroke !== NONE;
  53784. }
  53785. function setTransform(svgEl, m) {
  53786. if (m) {
  53787. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  53788. }
  53789. }
  53790. function attr(el, key, val) {
  53791. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  53792. // Don't set attribute for gradient, since it need new dom nodes
  53793. el.setAttribute(key, val);
  53794. }
  53795. }
  53796. function attrXLink(el, key, val) {
  53797. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  53798. }
  53799. function bindStyle(svgEl, style, isText, el) {
  53800. if (pathHasFill(style, isText)) {
  53801. var fill = isText ? style.textFill : style.fill;
  53802. fill = fill === 'transparent' ? NONE : fill;
  53803. attr(svgEl, 'fill', fill);
  53804. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  53805. }
  53806. else {
  53807. attr(svgEl, 'fill', NONE);
  53808. }
  53809. if (pathHasStroke(style, isText)) {
  53810. var stroke = isText ? style.textStroke : style.stroke;
  53811. stroke = stroke === 'transparent' ? NONE : stroke;
  53812. attr(svgEl, 'stroke', stroke);
  53813. var strokeWidth = isText
  53814. ? style.textStrokeWidth
  53815. : style.lineWidth;
  53816. var strokeScale = !isText && style.strokeNoScale
  53817. ? el.getLineScale()
  53818. : 1;
  53819. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  53820. // stroke then fill for text; fill then stroke for others
  53821. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  53822. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  53823. var lineDash = style.lineDash;
  53824. if (lineDash) {
  53825. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  53826. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  53827. }
  53828. else {
  53829. attr(svgEl, 'stroke-dasharray', '');
  53830. }
  53831. // PENDING
  53832. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  53833. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  53834. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  53835. }
  53836. else {
  53837. attr(svgEl, 'stroke', NONE);
  53838. }
  53839. }
  53840. /***************************************************
  53841. * PATH
  53842. **************************************************/
  53843. function pathDataToString$1(path) {
  53844. var str = [];
  53845. var data = path.data;
  53846. var dataLength = path.len();
  53847. for (var i = 0; i < dataLength;) {
  53848. var cmd = data[i++];
  53849. var cmdStr = '';
  53850. var nData = 0;
  53851. switch (cmd) {
  53852. case CMD$4.M:
  53853. cmdStr = 'M';
  53854. nData = 2;
  53855. break;
  53856. case CMD$4.L:
  53857. cmdStr = 'L';
  53858. nData = 2;
  53859. break;
  53860. case CMD$4.Q:
  53861. cmdStr = 'Q';
  53862. nData = 4;
  53863. break;
  53864. case CMD$4.C:
  53865. cmdStr = 'C';
  53866. nData = 6;
  53867. break;
  53868. case CMD$4.A:
  53869. var cx = data[i++];
  53870. var cy = data[i++];
  53871. var rx = data[i++];
  53872. var ry = data[i++];
  53873. var theta = data[i++];
  53874. var dTheta = data[i++];
  53875. var psi = data[i++];
  53876. var clockwise = data[i++];
  53877. var dThetaPositive = Math.abs(dTheta);
  53878. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  53879. || (clockwise ? dTheta >= PI2$5 : -dTheta >= PI2$5);
  53880. // Mapping to 0~2PI
  53881. var unifiedTheta = dTheta > 0 ? dTheta % PI2$5 : (dTheta % PI2$5 + PI2$5);
  53882. var large = false;
  53883. if (isCircle) {
  53884. large = true;
  53885. }
  53886. else if (isAroundZero$1(dThetaPositive)) {
  53887. large = false;
  53888. }
  53889. else {
  53890. large = (unifiedTheta >= PI$3) === !!clockwise;
  53891. }
  53892. var x0 = round4(cx + rx * mathCos$3(theta));
  53893. var y0 = round4(cy + ry * mathSin$3(theta));
  53894. // It will not draw if start point and end point are exactly the same
  53895. // We need to shift the end point with a small value
  53896. // FIXME A better way to draw circle ?
  53897. if (isCircle) {
  53898. if (clockwise) {
  53899. dTheta = PI2$5 - 1e-4;
  53900. }
  53901. else {
  53902. dTheta = -PI2$5 + 1e-4;
  53903. }
  53904. large = true;
  53905. if (i === 9) {
  53906. // Move to (x0, y0) only when CMD.A comes at the
  53907. // first position of a shape.
  53908. // For instance, when drawing a ring, CMD.A comes
  53909. // after CMD.M, so it's unnecessary to move to
  53910. // (x0, y0).
  53911. str.push('M', x0, y0);
  53912. }
  53913. }
  53914. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  53915. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  53916. // FIXME Ellipse
  53917. str.push('A', round4(rx), round4(ry),
  53918. mathRound(psi * degree), +large, +clockwise, x, y);
  53919. break;
  53920. case CMD$4.Z:
  53921. cmdStr = 'Z';
  53922. break;
  53923. case CMD$4.R:
  53924. var x = round4(data[i++]);
  53925. var y = round4(data[i++]);
  53926. var w = round4(data[i++]);
  53927. var h = round4(data[i++]);
  53928. str.push(
  53929. 'M', x, y,
  53930. 'L', x + w, y,
  53931. 'L', x + w, y + h,
  53932. 'L', x, y + h,
  53933. 'L', x, y
  53934. );
  53935. break;
  53936. }
  53937. cmdStr && str.push(cmdStr);
  53938. for (var j = 0; j < nData; j++) {
  53939. // PENDING With scale
  53940. str.push(round4(data[i++]));
  53941. }
  53942. }
  53943. return str.join(' ');
  53944. }
  53945. var svgPath = {};
  53946. svgPath.brush = function (el) {
  53947. var style = el.style;
  53948. var svgEl = el.__svgEl;
  53949. if (!svgEl) {
  53950. svgEl = createElement('path');
  53951. el.__svgEl = svgEl;
  53952. }
  53953. if (!el.path) {
  53954. el.createPathProxy();
  53955. }
  53956. var path = el.path;
  53957. if (el.__dirtyPath) {
  53958. path.beginPath();
  53959. path.subPixelOptimize = false;
  53960. el.buildPath(path, el.shape);
  53961. el.__dirtyPath = false;
  53962. var pathStr = pathDataToString$1(path);
  53963. if (pathStr.indexOf('NaN') < 0) {
  53964. // Ignore illegal path, which may happen such in out-of-range
  53965. // data in Calendar series.
  53966. attr(svgEl, 'd', pathStr);
  53967. }
  53968. }
  53969. bindStyle(svgEl, style, false, el);
  53970. setTransform(svgEl, el.transform);
  53971. if (style.text != null) {
  53972. svgTextDrawRectText(el, el.getBoundingRect());
  53973. }
  53974. else {
  53975. removeOldTextNode(el);
  53976. }
  53977. };
  53978. /***************************************************
  53979. * IMAGE
  53980. **************************************************/
  53981. var svgImage = {};
  53982. svgImage.brush = function (el) {
  53983. var style = el.style;
  53984. var image = style.image;
  53985. if (image instanceof HTMLImageElement) {
  53986. var src = image.src;
  53987. image = src;
  53988. }
  53989. if (!image) {
  53990. return;
  53991. }
  53992. var x = style.x || 0;
  53993. var y = style.y || 0;
  53994. var dw = style.width;
  53995. var dh = style.height;
  53996. var svgEl = el.__svgEl;
  53997. if (!svgEl) {
  53998. svgEl = createElement('image');
  53999. el.__svgEl = svgEl;
  54000. }
  54001. if (image !== el.__imageSrc) {
  54002. attrXLink(svgEl, 'href', image);
  54003. // Caching image src
  54004. el.__imageSrc = image;
  54005. }
  54006. attr(svgEl, 'width', dw);
  54007. attr(svgEl, 'height', dh);
  54008. attr(svgEl, 'x', x);
  54009. attr(svgEl, 'y', y);
  54010. setTransform(svgEl, el.transform);
  54011. if (style.text != null) {
  54012. svgTextDrawRectText(el, el.getBoundingRect());
  54013. }
  54014. else {
  54015. removeOldTextNode(el);
  54016. }
  54017. };
  54018. /***************************************************
  54019. * TEXT
  54020. **************************************************/
  54021. var svgText = {};
  54022. var _tmpTextHostRect = new BoundingRect();
  54023. var _tmpTextBoxPos = {};
  54024. var _tmpTextTransform = [];
  54025. var TEXT_ALIGN_TO_ANCHRO = {
  54026. left: 'start',
  54027. right: 'end',
  54028. center: 'middle',
  54029. middle: 'middle'
  54030. };
  54031. /**
  54032. * @param {module:zrender/Element} el
  54033. * @param {Object|boolean} [hostRect] {x, y, width, height}
  54034. * If set false, rect text is not used.
  54035. */
  54036. var svgTextDrawRectText = function (el, hostRect) {
  54037. var style = el.style;
  54038. var elTransform = el.transform;
  54039. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  54040. el.__dirty && normalizeTextStyle(style, true);
  54041. var text = style.text;
  54042. // Convert to string
  54043. text != null && (text += '');
  54044. if (!needDrawText(text, style)) {
  54045. return;
  54046. }
  54047. // render empty text for svg if no text but need draw text.
  54048. text == null && (text = '');
  54049. // Follow the setting in the canvas renderer, if not transform the
  54050. // text, transform the hostRect, by which the text is located.
  54051. if (!needTransformTextByHostEl && elTransform) {
  54052. _tmpTextHostRect.copy(hostRect);
  54053. _tmpTextHostRect.applyTransform(elTransform);
  54054. hostRect = _tmpTextHostRect;
  54055. }
  54056. var textSvgEl = el.__textSvgEl;
  54057. if (!textSvgEl) {
  54058. textSvgEl = createElement('text');
  54059. el.__textSvgEl = textSvgEl;
  54060. }
  54061. // style.font has been normalized by `normalizeTextStyle`.
  54062. var textSvgElStyle = textSvgEl.style;
  54063. var font = style.font || DEFAULT_FONT$1;
  54064. var computedFont = textSvgEl.__computedFont;
  54065. if (font !== textSvgEl.__styleFont) {
  54066. textSvgElStyle.font = textSvgEl.__styleFont = font;
  54067. // The computedFont might not be the orginal font if it is illegal font.
  54068. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  54069. }
  54070. var textPadding = style.textPadding;
  54071. var textLineHeight = style.textLineHeight;
  54072. var contentBlock = el.__textCotentBlock;
  54073. if (!contentBlock || el.__dirtyText) {
  54074. contentBlock = el.__textCotentBlock = parsePlainText(
  54075. text, computedFont, textPadding, textLineHeight, style.truncate
  54076. );
  54077. }
  54078. var outerHeight = contentBlock.outerHeight;
  54079. var lineHeight = contentBlock.lineHeight;
  54080. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  54081. var baseX = _tmpTextBoxPos.baseX;
  54082. var baseY = _tmpTextBoxPos.baseY;
  54083. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  54084. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  54085. setTextTransform(
  54086. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  54087. );
  54088. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  54089. var textX = baseX;
  54090. var textY = boxY;
  54091. // TODO needDrawBg
  54092. if (textPadding) {
  54093. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  54094. textY += textPadding[0];
  54095. }
  54096. // `textBaseline` is set as 'middle'.
  54097. textY += lineHeight / 2;
  54098. bindStyle(textSvgEl, style, true, el);
  54099. // FIXME
  54100. // Add a <style> to reset all of the text font as inherit?
  54101. // otherwise the outer <style> may set the unexpected style.
  54102. // Font may affect position of each tspan elements
  54103. var canCacheByTextString = contentBlock.canCacheByTextString;
  54104. var tspanList = el.__tspanList || (el.__tspanList = []);
  54105. var tspanOriginLen = tspanList.length;
  54106. // Optimize for most cases, just compare text string to determine change.
  54107. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  54108. if (el.__dirtyText && tspanOriginLen) {
  54109. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  54110. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  54111. }
  54112. }
  54113. }
  54114. else {
  54115. el.__text = text;
  54116. el.__canCacheByTextString = canCacheByTextString;
  54117. var textLines = contentBlock.lines;
  54118. var nTextLines = textLines.length;
  54119. var idx = 0;
  54120. for (; idx < nTextLines; idx++) {
  54121. // Using cached tspan elements
  54122. var tspan = tspanList[idx];
  54123. var singleLineText = textLines[idx];
  54124. if (!tspan) {
  54125. tspan = tspanList[idx] = createElement('tspan');
  54126. textSvgEl.appendChild(tspan);
  54127. tspan.appendChild(document.createTextNode(singleLineText));
  54128. }
  54129. else if (tspan.__zrText !== singleLineText) {
  54130. tspan.innerHTML = '';
  54131. tspan.appendChild(document.createTextNode(singleLineText));
  54132. }
  54133. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  54134. }
  54135. // Remove unused tspan elements
  54136. if (tspanOriginLen > nTextLines) {
  54137. for (; idx < tspanOriginLen; idx++) {
  54138. textSvgEl.removeChild(tspanList[idx]);
  54139. }
  54140. tspanList.length = nTextLines;
  54141. }
  54142. }
  54143. };
  54144. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  54145. identity(_tmpTextTransform);
  54146. if (needTransformTextByHostEl && elTransform) {
  54147. copy$1(_tmpTextTransform, elTransform);
  54148. }
  54149. // textRotation only apply in RectText.
  54150. var textRotation = style.textRotation;
  54151. if (hostRect && textRotation) {
  54152. var origin = style.textOrigin;
  54153. if (origin === 'center') {
  54154. baseX = hostRect.width / 2 + hostRect.x;
  54155. baseY = hostRect.height / 2 + hostRect.y;
  54156. }
  54157. else if (origin) {
  54158. baseX = origin[0] + hostRect.x;
  54159. baseY = origin[1] + hostRect.y;
  54160. }
  54161. _tmpTextTransform[4] -= baseX;
  54162. _tmpTextTransform[5] -= baseY;
  54163. // Positive: anticlockwise
  54164. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  54165. _tmpTextTransform[4] += baseX;
  54166. _tmpTextTransform[5] += baseY;
  54167. }
  54168. // See the definition in `Style.js#textOrigin`, the default
  54169. // origin is from the result of `getBoxPosition`.
  54170. setTransform(textSvgEl, _tmpTextTransform);
  54171. }
  54172. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  54173. function getTextXForPadding$1(x, textAlign, textPadding) {
  54174. return textAlign === 'right'
  54175. ? (x - textPadding[1])
  54176. : textAlign === 'center'
  54177. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  54178. : (x + textPadding[3]);
  54179. }
  54180. function updateTextLocation(tspan, textAlign, x, y) {
  54181. // Consider different font display differently in vertial align, we always
  54182. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  54183. attr(tspan, 'dominant-baseline', 'middle');
  54184. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  54185. attr(tspan, 'x', x);
  54186. attr(tspan, 'y', y);
  54187. }
  54188. function removeOldTextNode(el) {
  54189. if (el && el.__textSvgEl) {
  54190. // textSvgEl may has no parentNode if el has been removed temporary.
  54191. if (el.__textSvgEl.parentNode) {
  54192. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  54193. }
  54194. el.__textSvgEl = null;
  54195. el.__tspanList = [];
  54196. el.__text = null;
  54197. }
  54198. }
  54199. svgText.drawRectText = svgTextDrawRectText;
  54200. svgText.brush = function (el) {
  54201. var style = el.style;
  54202. if (style.text != null) {
  54203. svgTextDrawRectText(el, false);
  54204. }
  54205. else {
  54206. removeOldTextNode(el);
  54207. }
  54208. };
  54209. // Myers' Diff Algorithm
  54210. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  54211. function Diff() {}
  54212. Diff.prototype = {
  54213. diff: function (oldArr, newArr, equals) {
  54214. if (!equals) {
  54215. equals = function (a, b) {
  54216. return a === b;
  54217. };
  54218. }
  54219. this.equals = equals;
  54220. var self = this;
  54221. oldArr = oldArr.slice();
  54222. newArr = newArr.slice();
  54223. // Allow subclasses to massage the input prior to running
  54224. var newLen = newArr.length;
  54225. var oldLen = oldArr.length;
  54226. var editLength = 1;
  54227. var maxEditLength = newLen + oldLen;
  54228. var bestPath = [{ newPos: -1, components: [] }];
  54229. // Seed editLength = 0, i.e. the content starts with the same values
  54230. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  54231. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54232. var indices = [];
  54233. for (var i = 0; i < newArr.length; i++) {
  54234. indices.push(i);
  54235. }
  54236. // Identity per the equality and tokenizer
  54237. return [{
  54238. indices: indices, count: newArr.length
  54239. }];
  54240. }
  54241. // Main worker method. checks all permutations of a given edit length for acceptance.
  54242. function execEditLength() {
  54243. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  54244. var basePath;
  54245. var addPath = bestPath[diagonalPath - 1];
  54246. var removePath = bestPath[diagonalPath + 1];
  54247. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  54248. if (addPath) {
  54249. // No one else is going to attempt to use this value, clear it
  54250. bestPath[diagonalPath - 1] = undefined;
  54251. }
  54252. var canAdd = addPath && addPath.newPos + 1 < newLen;
  54253. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  54254. if (!canAdd && !canRemove) {
  54255. // If this path is a terminal then prune
  54256. bestPath[diagonalPath] = undefined;
  54257. continue;
  54258. }
  54259. // Select the diagonal that we want to branch from. We select the prior
  54260. // path whose position in the new string is the farthest from the origin
  54261. // and does not pass the bounds of the diff graph
  54262. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  54263. basePath = clonePath(removePath);
  54264. self.pushComponent(basePath.components, undefined, true);
  54265. }
  54266. else {
  54267. basePath = addPath; // No need to clone, we've pulled it from the list
  54268. basePath.newPos++;
  54269. self.pushComponent(basePath.components, true, undefined);
  54270. }
  54271. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  54272. // If we have hit the end of both strings, then we are done
  54273. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54274. return buildValues(self, basePath.components, newArr, oldArr);
  54275. }
  54276. else {
  54277. // Otherwise track this path as a potential candidate and continue.
  54278. bestPath[diagonalPath] = basePath;
  54279. }
  54280. }
  54281. editLength++;
  54282. }
  54283. while (editLength <= maxEditLength) {
  54284. var ret = execEditLength();
  54285. if (ret) {
  54286. return ret;
  54287. }
  54288. }
  54289. },
  54290. pushComponent: function (components, added, removed) {
  54291. var last = components[components.length - 1];
  54292. if (last && last.added === added && last.removed === removed) {
  54293. // We need to clone here as the component clone operation is just
  54294. // as shallow array clone
  54295. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  54296. }
  54297. else {
  54298. components.push({count: 1, added: added, removed: removed });
  54299. }
  54300. },
  54301. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  54302. var newLen = newArr.length;
  54303. var oldLen = oldArr.length;
  54304. var newPos = basePath.newPos;
  54305. var oldPos = newPos - diagonalPath;
  54306. var commonCount = 0;
  54307. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  54308. newPos++;
  54309. oldPos++;
  54310. commonCount++;
  54311. }
  54312. if (commonCount) {
  54313. basePath.components.push({count: commonCount});
  54314. }
  54315. basePath.newPos = newPos;
  54316. return oldPos;
  54317. },
  54318. tokenize: function (value) {
  54319. return value.slice();
  54320. },
  54321. join: function (value) {
  54322. return value.slice();
  54323. }
  54324. };
  54325. function buildValues(diff, components, newArr, oldArr) {
  54326. var componentPos = 0;
  54327. var componentLen = components.length;
  54328. var newPos = 0;
  54329. var oldPos = 0;
  54330. for (; componentPos < componentLen; componentPos++) {
  54331. var component = components[componentPos];
  54332. if (!component.removed) {
  54333. var indices = [];
  54334. for (var i = newPos; i < newPos + component.count; i++) {
  54335. indices.push(i);
  54336. }
  54337. component.indices = indices;
  54338. newPos += component.count;
  54339. // Common case
  54340. if (!component.added) {
  54341. oldPos += component.count;
  54342. }
  54343. }
  54344. else {
  54345. var indices = [];
  54346. for (var i = oldPos; i < oldPos + component.count; i++) {
  54347. indices.push(i);
  54348. }
  54349. component.indices = indices;
  54350. oldPos += component.count;
  54351. }
  54352. }
  54353. return components;
  54354. }
  54355. function clonePath(path) {
  54356. return { newPos: path.newPos, components: path.components.slice(0) };
  54357. }
  54358. var arrayDiff = new Diff();
  54359. var arrayDiff$1 = function (oldArr, newArr, callback) {
  54360. return arrayDiff.diff(oldArr, newArr, callback);
  54361. };
  54362. /**
  54363. * @file Manages elements that can be defined in <defs> in SVG,
  54364. * e.g., gradients, clip path, etc.
  54365. * @author Zhang Wenli
  54366. */
  54367. var MARK_UNUSED = '0';
  54368. var MARK_USED = '1';
  54369. /**
  54370. * Manages elements that can be defined in <defs> in SVG,
  54371. * e.g., gradients, clip path, etc.
  54372. *
  54373. * @class
  54374. * @param {number} zrId zrender instance id
  54375. * @param {SVGElement} svgRoot root of SVG document
  54376. * @param {string|string[]} tagNames possible tag names
  54377. * @param {string} markLabel label name to make if the element
  54378. * is used
  54379. */
  54380. function Definable(
  54381. zrId,
  54382. svgRoot,
  54383. tagNames,
  54384. markLabel,
  54385. domName
  54386. ) {
  54387. this._zrId = zrId;
  54388. this._svgRoot = svgRoot;
  54389. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  54390. this._markLabel = markLabel;
  54391. this._domName = domName || '_dom';
  54392. this.nextId = 0;
  54393. }
  54394. Definable.prototype.createElement = createElement;
  54395. /**
  54396. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  54397. *
  54398. * @param {boolean} isForceCreating if need to create when not exists
  54399. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  54400. * exist and isForceCreating is false
  54401. */
  54402. Definable.prototype.getDefs = function (isForceCreating) {
  54403. var svgRoot = this._svgRoot;
  54404. var defs = this._svgRoot.getElementsByTagName('defs');
  54405. if (defs.length === 0) {
  54406. // Not exist
  54407. if (isForceCreating) {
  54408. defs = svgRoot.insertBefore(
  54409. this.createElement('defs'), // Create new tag
  54410. svgRoot.firstChild // Insert in the front of svg
  54411. );
  54412. if (!defs.contains) {
  54413. // IE doesn't support contains method
  54414. defs.contains = function (el) {
  54415. var children = defs.children;
  54416. if (!children) {
  54417. return false;
  54418. }
  54419. for (var i = children.length - 1; i >= 0; --i) {
  54420. if (children[i] === el) {
  54421. return true;
  54422. }
  54423. }
  54424. return false;
  54425. };
  54426. }
  54427. return defs;
  54428. }
  54429. else {
  54430. return null;
  54431. }
  54432. }
  54433. else {
  54434. return defs[0];
  54435. }
  54436. };
  54437. /**
  54438. * Update DOM element if necessary.
  54439. *
  54440. * @param {Object|string} element style element. e.g., for gradient,
  54441. * it may be '#ccc' or {type: 'linear', ...}
  54442. * @param {Function|undefined} onUpdate update callback
  54443. */
  54444. Definable.prototype.update = function (element, onUpdate) {
  54445. if (!element) {
  54446. return;
  54447. }
  54448. var defs = this.getDefs(false);
  54449. if (element[this._domName] && defs.contains(element[this._domName])) {
  54450. // Update DOM
  54451. if (typeof onUpdate === 'function') {
  54452. onUpdate(element);
  54453. }
  54454. }
  54455. else {
  54456. // No previous dom, create new
  54457. var dom = this.add(element);
  54458. if (dom) {
  54459. element[this._domName] = dom;
  54460. }
  54461. }
  54462. };
  54463. /**
  54464. * Add gradient dom to defs
  54465. *
  54466. * @param {SVGElement} dom DOM to be added to <defs>
  54467. */
  54468. Definable.prototype.addDom = function (dom) {
  54469. var defs = this.getDefs(true);
  54470. defs.appendChild(dom);
  54471. };
  54472. /**
  54473. * Remove DOM of a given element.
  54474. *
  54475. * @param {SVGElement} element element to remove dom
  54476. */
  54477. Definable.prototype.removeDom = function (element) {
  54478. var defs = this.getDefs(false);
  54479. if (defs && element[this._domName]) {
  54480. defs.removeChild(element[this._domName]);
  54481. element[this._domName] = null;
  54482. }
  54483. };
  54484. /**
  54485. * Get DOMs of this element.
  54486. *
  54487. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  54488. */
  54489. Definable.prototype.getDoms = function () {
  54490. var defs = this.getDefs(false);
  54491. if (!defs) {
  54492. // No dom when defs is not defined
  54493. return [];
  54494. }
  54495. var doms = [];
  54496. each$1(this._tagNames, function (tagName) {
  54497. var tags = defs.getElementsByTagName(tagName);
  54498. // Note that tags is HTMLCollection, which is array-like
  54499. // rather than real array.
  54500. // So `doms.concat(tags)` add tags as one object.
  54501. doms = doms.concat([].slice.call(tags));
  54502. });
  54503. return doms;
  54504. };
  54505. /**
  54506. * Mark DOMs to be unused before painting, and clear unused ones at the end
  54507. * of the painting.
  54508. */
  54509. Definable.prototype.markAllUnused = function () {
  54510. var doms = this.getDoms();
  54511. var that = this;
  54512. each$1(doms, function (dom) {
  54513. dom[that._markLabel] = MARK_UNUSED;
  54514. });
  54515. };
  54516. /**
  54517. * Mark a single DOM to be used.
  54518. *
  54519. * @param {SVGElement} dom DOM to mark
  54520. */
  54521. Definable.prototype.markUsed = function (dom) {
  54522. if (dom) {
  54523. dom[this._markLabel] = MARK_USED;
  54524. }
  54525. };
  54526. /**
  54527. * Remove unused DOMs defined in <defs>
  54528. */
  54529. Definable.prototype.removeUnused = function () {
  54530. var defs = this.getDefs(false);
  54531. if (!defs) {
  54532. // Nothing to remove
  54533. return;
  54534. }
  54535. var doms = this.getDoms();
  54536. var that = this;
  54537. each$1(doms, function (dom) {
  54538. if (dom[that._markLabel] !== MARK_USED) {
  54539. // Remove gradient
  54540. defs.removeChild(dom);
  54541. }
  54542. });
  54543. };
  54544. /**
  54545. * Get SVG proxy.
  54546. *
  54547. * @param {Displayable} displayable displayable element
  54548. * @return {Path|Image|Text} svg proxy of given element
  54549. */
  54550. Definable.prototype.getSvgProxy = function (displayable) {
  54551. if (displayable instanceof Path) {
  54552. return svgPath;
  54553. }
  54554. else if (displayable instanceof ZImage) {
  54555. return svgImage;
  54556. }
  54557. else if (displayable instanceof Text) {
  54558. return svgText;
  54559. }
  54560. else {
  54561. return svgPath;
  54562. }
  54563. };
  54564. /**
  54565. * Get text SVG element.
  54566. *
  54567. * @param {Displayable} displayable displayable element
  54568. * @return {SVGElement} SVG element of text
  54569. */
  54570. Definable.prototype.getTextSvgElement = function (displayable) {
  54571. return displayable.__textSvgEl;
  54572. };
  54573. /**
  54574. * Get SVG element.
  54575. *
  54576. * @param {Displayable} displayable displayable element
  54577. * @return {SVGElement} SVG element
  54578. */
  54579. Definable.prototype.getSvgElement = function (displayable) {
  54580. return displayable.__svgEl;
  54581. };
  54582. /**
  54583. * @file Manages SVG gradient elements.
  54584. * @author Zhang Wenli
  54585. */
  54586. /**
  54587. * Manages SVG gradient elements.
  54588. *
  54589. * @class
  54590. * @extends Definable
  54591. * @param {number} zrId zrender instance id
  54592. * @param {SVGElement} svgRoot root of SVG document
  54593. */
  54594. function GradientManager(zrId, svgRoot) {
  54595. Definable.call(
  54596. this,
  54597. zrId,
  54598. svgRoot,
  54599. ['linearGradient', 'radialGradient'],
  54600. '__gradient_in_use__'
  54601. );
  54602. }
  54603. inherits(GradientManager, Definable);
  54604. /**
  54605. * Create new gradient DOM for fill or stroke if not exist,
  54606. * but will not update gradient if exists.
  54607. *
  54608. * @param {SvgElement} svgElement SVG element to paint
  54609. * @param {Displayable} displayable zrender displayable element
  54610. */
  54611. GradientManager.prototype.addWithoutUpdate = function (
  54612. svgElement,
  54613. displayable
  54614. ) {
  54615. if (displayable && displayable.style) {
  54616. var that = this;
  54617. each$1(['fill', 'stroke'], function (fillOrStroke) {
  54618. if (displayable.style[fillOrStroke]
  54619. && (displayable.style[fillOrStroke].type === 'linear'
  54620. || displayable.style[fillOrStroke].type === 'radial')
  54621. ) {
  54622. var gradient = displayable.style[fillOrStroke];
  54623. var defs = that.getDefs(true);
  54624. // Create dom in <defs> if not exists
  54625. var dom;
  54626. if (gradient._dom) {
  54627. // Gradient exists
  54628. dom = gradient._dom;
  54629. if (!defs.contains(gradient._dom)) {
  54630. // _dom is no longer in defs, recreate
  54631. that.addDom(dom);
  54632. }
  54633. }
  54634. else {
  54635. // New dom
  54636. dom = that.add(gradient);
  54637. }
  54638. that.markUsed(displayable);
  54639. var id = dom.getAttribute('id');
  54640. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  54641. }
  54642. });
  54643. }
  54644. };
  54645. /**
  54646. * Add a new gradient tag in <defs>
  54647. *
  54648. * @param {Gradient} gradient zr gradient instance
  54649. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  54650. * created DOM
  54651. */
  54652. GradientManager.prototype.add = function (gradient) {
  54653. var dom;
  54654. if (gradient.type === 'linear') {
  54655. dom = this.createElement('linearGradient');
  54656. }
  54657. else if (gradient.type === 'radial') {
  54658. dom = this.createElement('radialGradient');
  54659. }
  54660. else {
  54661. logError$1('Illegal gradient type.');
  54662. return null;
  54663. }
  54664. // Set dom id with gradient id, since each gradient instance
  54665. // will have no more than one dom element.
  54666. // id may exists before for those dirty elements, in which case
  54667. // id should remain the same, and other attributes should be
  54668. // updated.
  54669. gradient.id = gradient.id || this.nextId++;
  54670. dom.setAttribute('id', 'zr' + this._zrId
  54671. + '-gradient-' + gradient.id);
  54672. this.updateDom(gradient, dom);
  54673. this.addDom(dom);
  54674. return dom;
  54675. };
  54676. /**
  54677. * Update gradient.
  54678. *
  54679. * @param {Gradient} gradient zr gradient instance
  54680. */
  54681. GradientManager.prototype.update = function (gradient) {
  54682. var that = this;
  54683. Definable.prototype.update.call(this, gradient, function () {
  54684. var type = gradient.type;
  54685. var tagName = gradient._dom.tagName;
  54686. if (type === 'linear' && tagName === 'linearGradient'
  54687. || type === 'radial' && tagName === 'radialGradient'
  54688. ) {
  54689. // Gradient type is not changed, update gradient
  54690. that.updateDom(gradient, gradient._dom);
  54691. }
  54692. else {
  54693. // Remove and re-create if type is changed
  54694. that.removeDom(gradient);
  54695. that.add(gradient);
  54696. }
  54697. });
  54698. };
  54699. /**
  54700. * Update gradient dom
  54701. *
  54702. * @param {Gradient} gradient zr gradient instance
  54703. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  54704. * DOM to update
  54705. */
  54706. GradientManager.prototype.updateDom = function (gradient, dom) {
  54707. if (gradient.type === 'linear') {
  54708. dom.setAttribute('x1', gradient.x);
  54709. dom.setAttribute('y1', gradient.y);
  54710. dom.setAttribute('x2', gradient.x2);
  54711. dom.setAttribute('y2', gradient.y2);
  54712. }
  54713. else if (gradient.type === 'radial') {
  54714. dom.setAttribute('cx', gradient.x);
  54715. dom.setAttribute('cy', gradient.y);
  54716. dom.setAttribute('r', gradient.r);
  54717. }
  54718. else {
  54719. logError$1('Illegal gradient type.');
  54720. return;
  54721. }
  54722. if (gradient.global) {
  54723. // x1, x2, y1, y2 in range of 0 to canvas width or height
  54724. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  54725. }
  54726. else {
  54727. // x1, x2, y1, y2 in range of 0 to 1
  54728. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  54729. }
  54730. // Remove color stops if exists
  54731. dom.innerHTML = '';
  54732. // Add color stops
  54733. var colors = gradient.colorStops;
  54734. for (var i = 0, len = colors.length; i < len; ++i) {
  54735. var stop = this.createElement('stop');
  54736. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  54737. var color = colors[i].color;
  54738. if (color.indexOf('rgba' > -1)) {
  54739. // Fix Safari bug that stop-color not recognizing alpha #9014
  54740. var opacity = parse(color)[3];
  54741. var hex = toHex(color);
  54742. // stop-color cannot be color, since:
  54743. // The opacity value used for the gradient calculation is the
  54744. // *product* of the value of stop-opacity and the opacity of the
  54745. // value of stop-color.
  54746. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  54747. stop.setAttribute('stop-color', '#' + hex);
  54748. stop.setAttribute('stop-opacity', opacity);
  54749. }
  54750. else {
  54751. stop.setAttribute('stop-color', colors[i].color);
  54752. }
  54753. dom.appendChild(stop);
  54754. }
  54755. // Store dom element in gradient, to avoid creating multiple
  54756. // dom instances for the same gradient element
  54757. gradient._dom = dom;
  54758. };
  54759. /**
  54760. * Mark a single gradient to be used
  54761. *
  54762. * @param {Displayable} displayable displayable element
  54763. */
  54764. GradientManager.prototype.markUsed = function (displayable) {
  54765. if (displayable.style) {
  54766. var gradient = displayable.style.fill;
  54767. if (gradient && gradient._dom) {
  54768. Definable.prototype.markUsed.call(this, gradient._dom);
  54769. }
  54770. gradient = displayable.style.stroke;
  54771. if (gradient && gradient._dom) {
  54772. Definable.prototype.markUsed.call(this, gradient._dom);
  54773. }
  54774. }
  54775. };
  54776. /**
  54777. * @file Manages SVG clipPath elements.
  54778. * @author Zhang Wenli
  54779. */
  54780. /**
  54781. * Manages SVG clipPath elements.
  54782. *
  54783. * @class
  54784. * @extends Definable
  54785. * @param {number} zrId zrender instance id
  54786. * @param {SVGElement} svgRoot root of SVG document
  54787. */
  54788. function ClippathManager(zrId, svgRoot) {
  54789. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  54790. }
  54791. inherits(ClippathManager, Definable);
  54792. /**
  54793. * Update clipPath.
  54794. *
  54795. * @param {Displayable} displayable displayable element
  54796. */
  54797. ClippathManager.prototype.update = function (displayable) {
  54798. var svgEl = this.getSvgElement(displayable);
  54799. if (svgEl) {
  54800. this.updateDom(svgEl, displayable.__clipPaths, false);
  54801. }
  54802. var textEl = this.getTextSvgElement(displayable);
  54803. if (textEl) {
  54804. // Make another clipPath for text, since it's transform
  54805. // matrix is not the same with svgElement
  54806. this.updateDom(textEl, displayable.__clipPaths, true);
  54807. }
  54808. this.markUsed(displayable);
  54809. };
  54810. /**
  54811. * Create an SVGElement of displayable and create a <clipPath> of its
  54812. * clipPath
  54813. *
  54814. * @param {Displayable} parentEl parent element
  54815. * @param {ClipPath[]} clipPaths clipPaths of parent element
  54816. * @param {boolean} isText if parent element is Text
  54817. */
  54818. ClippathManager.prototype.updateDom = function (
  54819. parentEl,
  54820. clipPaths,
  54821. isText
  54822. ) {
  54823. if (clipPaths && clipPaths.length > 0) {
  54824. // Has clipPath, create <clipPath> with the first clipPath
  54825. var defs = this.getDefs(true);
  54826. var clipPath = clipPaths[0];
  54827. var clipPathEl;
  54828. var id;
  54829. var dom = isText ? '_textDom' : '_dom';
  54830. if (clipPath[dom]) {
  54831. // Use a dom that is already in <defs>
  54832. id = clipPath[dom].getAttribute('id');
  54833. clipPathEl = clipPath[dom];
  54834. // Use a dom that is already in <defs>
  54835. if (!defs.contains(clipPathEl)) {
  54836. // This happens when set old clipPath that has
  54837. // been previously removed
  54838. defs.appendChild(clipPathEl);
  54839. }
  54840. }
  54841. else {
  54842. // New <clipPath>
  54843. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  54844. ++this.nextId;
  54845. clipPathEl = this.createElement('clipPath');
  54846. clipPathEl.setAttribute('id', id);
  54847. defs.appendChild(clipPathEl);
  54848. clipPath[dom] = clipPathEl;
  54849. }
  54850. // Build path and add to <clipPath>
  54851. var svgProxy = this.getSvgProxy(clipPath);
  54852. if (clipPath.transform
  54853. && clipPath.parent.invTransform
  54854. && !isText
  54855. ) {
  54856. /**
  54857. * If a clipPath has a parent with transform, the transform
  54858. * of parent should not be considered when setting transform
  54859. * of clipPath. So we need to transform back from parent's
  54860. * transform, which is done by multiplying parent's inverse
  54861. * transform.
  54862. */
  54863. // Store old transform
  54864. var transform = Array.prototype.slice.call(
  54865. clipPath.transform
  54866. );
  54867. // Transform back from parent, and brush path
  54868. mul$1(
  54869. clipPath.transform,
  54870. clipPath.parent.invTransform,
  54871. clipPath.transform
  54872. );
  54873. svgProxy.brush(clipPath);
  54874. // Set back transform of clipPath
  54875. clipPath.transform = transform;
  54876. }
  54877. else {
  54878. svgProxy.brush(clipPath);
  54879. }
  54880. var pathEl = this.getSvgElement(clipPath);
  54881. clipPathEl.innerHTML = '';
  54882. /**
  54883. * Use `cloneNode()` here to appendChild to multiple parents,
  54884. * which may happend when Text and other shapes are using the same
  54885. * clipPath. Since Text will create an extra clipPath DOM due to
  54886. * different transform rules.
  54887. */
  54888. clipPathEl.appendChild(pathEl.cloneNode());
  54889. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  54890. if (clipPaths.length > 1) {
  54891. // Make the other clipPaths recursively
  54892. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  54893. }
  54894. }
  54895. else {
  54896. // No clipPath
  54897. if (parentEl) {
  54898. parentEl.setAttribute('clip-path', 'none');
  54899. }
  54900. }
  54901. };
  54902. /**
  54903. * Mark a single clipPath to be used
  54904. *
  54905. * @param {Displayable} displayable displayable element
  54906. */
  54907. ClippathManager.prototype.markUsed = function (displayable) {
  54908. var that = this;
  54909. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  54910. if (displayable.__clipPaths) {
  54911. each$1(displayable.__clipPaths, function (clipPath) {
  54912. if (clipPath._dom) {
  54913. Definable.prototype.markUsed.call(that, clipPath._dom);
  54914. }
  54915. if (clipPath._textDom) {
  54916. Definable.prototype.markUsed.call(that, clipPath._textDom);
  54917. }
  54918. });
  54919. }
  54920. };
  54921. /**
  54922. * @file Manages SVG shadow elements.
  54923. * @author Zhang Wenli
  54924. */
  54925. /**
  54926. * Manages SVG shadow elements.
  54927. *
  54928. * @class
  54929. * @extends Definable
  54930. * @param {number} zrId zrender instance id
  54931. * @param {SVGElement} svgRoot root of SVG document
  54932. */
  54933. function ShadowManager(zrId, svgRoot) {
  54934. Definable.call(
  54935. this,
  54936. zrId,
  54937. svgRoot,
  54938. ['filter'],
  54939. '__filter_in_use__',
  54940. '_shadowDom'
  54941. );
  54942. }
  54943. inherits(ShadowManager, Definable);
  54944. /**
  54945. * Create new shadow DOM for fill or stroke if not exist,
  54946. * but will not update shadow if exists.
  54947. *
  54948. * @param {SvgElement} svgElement SVG element to paint
  54949. * @param {Displayable} displayable zrender displayable element
  54950. */
  54951. ShadowManager.prototype.addWithoutUpdate = function (
  54952. svgElement,
  54953. displayable
  54954. ) {
  54955. if (displayable && hasShadow(displayable.style)) {
  54956. // Create dom in <defs> if not exists
  54957. var dom;
  54958. if (displayable._shadowDom) {
  54959. // Gradient exists
  54960. dom = displayable._shadowDom;
  54961. var defs = this.getDefs(true);
  54962. if (!defs.contains(displayable._shadowDom)) {
  54963. // _shadowDom is no longer in defs, recreate
  54964. this.addDom(dom);
  54965. }
  54966. }
  54967. else {
  54968. // New dom
  54969. dom = this.add(displayable);
  54970. }
  54971. this.markUsed(displayable);
  54972. var id = dom.getAttribute('id');
  54973. svgElement.style.filter = 'url(#' + id + ')';
  54974. }
  54975. };
  54976. /**
  54977. * Add a new shadow tag in <defs>
  54978. *
  54979. * @param {Displayable} displayable zrender displayable element
  54980. * @return {SVGFilterElement} created DOM
  54981. */
  54982. ShadowManager.prototype.add = function (displayable) {
  54983. var dom = this.createElement('filter');
  54984. // Set dom id with shadow id, since each shadow instance
  54985. // will have no more than one dom element.
  54986. // id may exists before for those dirty elements, in which case
  54987. // id should remain the same, and other attributes should be
  54988. // updated.
  54989. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  54990. dom.setAttribute('id', 'zr' + this._zrId
  54991. + '-shadow-' + displayable._shadowDomId);
  54992. this.updateDom(displayable, dom);
  54993. this.addDom(dom);
  54994. return dom;
  54995. };
  54996. /**
  54997. * Update shadow.
  54998. *
  54999. * @param {Displayable} displayable zrender displayable element
  55000. */
  55001. ShadowManager.prototype.update = function (svgElement, displayable) {
  55002. var style = displayable.style;
  55003. if (hasShadow(style)) {
  55004. var that = this;
  55005. Definable.prototype.update.call(this, displayable, function () {
  55006. that.updateDom(displayable, displayable._shadowDom);
  55007. });
  55008. }
  55009. else {
  55010. // Remove shadow
  55011. this.remove(svgElement, displayable);
  55012. }
  55013. };
  55014. /**
  55015. * Remove DOM and clear parent filter
  55016. */
  55017. ShadowManager.prototype.remove = function (svgElement, displayable) {
  55018. if (displayable._shadowDomId != null) {
  55019. this.removeDom(svgElement);
  55020. svgElement.style.filter = '';
  55021. }
  55022. };
  55023. /**
  55024. * Update shadow dom
  55025. *
  55026. * @param {Displayable} displayable zrender displayable element
  55027. * @param {SVGFilterElement} dom DOM to update
  55028. */
  55029. ShadowManager.prototype.updateDom = function (displayable, dom) {
  55030. var domChild = dom.getElementsByTagName('feDropShadow');
  55031. if (domChild.length === 0) {
  55032. domChild = this.createElement('feDropShadow');
  55033. }
  55034. else {
  55035. domChild = domChild[0];
  55036. }
  55037. var style = displayable.style;
  55038. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  55039. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  55040. // TODO: textBoxShadowBlur is not supported yet
  55041. var offsetX;
  55042. var offsetY;
  55043. var blur;
  55044. var color;
  55045. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  55046. offsetX = style.shadowOffsetX || 0;
  55047. offsetY = style.shadowOffsetY || 0;
  55048. blur = style.shadowBlur;
  55049. color = style.shadowColor;
  55050. }
  55051. else if (style.textShadowBlur) {
  55052. offsetX = style.textShadowOffsetX || 0;
  55053. offsetY = style.textShadowOffsetY || 0;
  55054. blur = style.textShadowBlur;
  55055. color = style.textShadowColor;
  55056. }
  55057. else {
  55058. // Remove shadow
  55059. this.removeDom(dom, style);
  55060. return;
  55061. }
  55062. domChild.setAttribute('dx', offsetX / scaleX);
  55063. domChild.setAttribute('dy', offsetY / scaleY);
  55064. domChild.setAttribute('flood-color', color);
  55065. // Divide by two here so that it looks the same as in canvas
  55066. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  55067. var stdDx = blur / 2 / scaleX;
  55068. var stdDy = blur / 2 / scaleY;
  55069. var stdDeviation = stdDx + ' ' + stdDy;
  55070. domChild.setAttribute('stdDeviation', stdDeviation);
  55071. // Fix filter clipping problem
  55072. dom.setAttribute('x', '-100%');
  55073. dom.setAttribute('y', '-100%');
  55074. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  55075. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  55076. dom.appendChild(domChild);
  55077. // Store dom element in shadow, to avoid creating multiple
  55078. // dom instances for the same shadow element
  55079. displayable._shadowDom = dom;
  55080. };
  55081. /**
  55082. * Mark a single shadow to be used
  55083. *
  55084. * @param {Displayable} displayable displayable element
  55085. */
  55086. ShadowManager.prototype.markUsed = function (displayable) {
  55087. if (displayable._shadowDom) {
  55088. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  55089. }
  55090. };
  55091. function hasShadow(style) {
  55092. // TODO: textBoxShadowBlur is not supported yet
  55093. return style
  55094. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  55095. || style.textShadowBlur || style.textShadowOffsetX
  55096. || style.textShadowOffsetY);
  55097. }
  55098. /**
  55099. * SVG Painter
  55100. * @module zrender/svg/Painter
  55101. */
  55102. function parseInt10$2(val) {
  55103. return parseInt(val, 10);
  55104. }
  55105. function getSvgProxy(el) {
  55106. if (el instanceof Path) {
  55107. return svgPath;
  55108. }
  55109. else if (el instanceof ZImage) {
  55110. return svgImage;
  55111. }
  55112. else if (el instanceof Text) {
  55113. return svgText;
  55114. }
  55115. else {
  55116. return svgPath;
  55117. }
  55118. }
  55119. function checkParentAvailable(parent, child) {
  55120. return child && parent && child.parentNode !== parent;
  55121. }
  55122. function insertAfter(parent, child, prevSibling) {
  55123. if (checkParentAvailable(parent, child) && prevSibling) {
  55124. var nextSibling = prevSibling.nextSibling;
  55125. nextSibling ? parent.insertBefore(child, nextSibling)
  55126. : parent.appendChild(child);
  55127. }
  55128. }
  55129. function prepend(parent, child) {
  55130. if (checkParentAvailable(parent, child)) {
  55131. var firstChild = parent.firstChild;
  55132. firstChild ? parent.insertBefore(child, firstChild)
  55133. : parent.appendChild(child);
  55134. }
  55135. }
  55136. // function append(parent, child) {
  55137. // if (checkParentAvailable(parent, child)) {
  55138. // parent.appendChild(child);
  55139. // }
  55140. // }
  55141. function remove$1(parent, child) {
  55142. if (child && parent && child.parentNode === parent) {
  55143. parent.removeChild(child);
  55144. }
  55145. }
  55146. function getTextSvgElement(displayable) {
  55147. return displayable.__textSvgEl;
  55148. }
  55149. function getSvgElement(displayable) {
  55150. return displayable.__svgEl;
  55151. }
  55152. /**
  55153. * @alias module:zrender/svg/Painter
  55154. * @constructor
  55155. * @param {HTMLElement} root 绘图容器
  55156. * @param {module:zrender/Storage} storage
  55157. * @param {Object} opts
  55158. */
  55159. var SVGPainter = function (root, storage, opts, zrId) {
  55160. this.root = root;
  55161. this.storage = storage;
  55162. this._opts = opts = extend({}, opts || {});
  55163. var svgRoot = createElement('svg');
  55164. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  55165. svgRoot.setAttribute('version', '1.1');
  55166. svgRoot.setAttribute('baseProfile', 'full');
  55167. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  55168. this.gradientManager = new GradientManager(zrId, svgRoot);
  55169. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  55170. this.shadowManager = new ShadowManager(zrId, svgRoot);
  55171. var viewport = document.createElement('div');
  55172. viewport.style.cssText = 'overflow:hidden;position:relative';
  55173. this._svgRoot = svgRoot;
  55174. this._viewport = viewport;
  55175. root.appendChild(viewport);
  55176. viewport.appendChild(svgRoot);
  55177. this.resize(opts.width, opts.height);
  55178. this._visibleList = [];
  55179. };
  55180. SVGPainter.prototype = {
  55181. constructor: SVGPainter,
  55182. getType: function () {
  55183. return 'svg';
  55184. },
  55185. getViewportRoot: function () {
  55186. return this._viewport;
  55187. },
  55188. getViewportRootOffset: function () {
  55189. var viewportRoot = this.getViewportRoot();
  55190. if (viewportRoot) {
  55191. return {
  55192. offsetLeft: viewportRoot.offsetLeft || 0,
  55193. offsetTop: viewportRoot.offsetTop || 0
  55194. };
  55195. }
  55196. },
  55197. refresh: function () {
  55198. var list = this.storage.getDisplayList(true);
  55199. this._paintList(list);
  55200. },
  55201. setBackgroundColor: function (backgroundColor) {
  55202. // TODO gradient
  55203. this._viewport.style.background = backgroundColor;
  55204. },
  55205. _paintList: function (list) {
  55206. this.gradientManager.markAllUnused();
  55207. this.clipPathManager.markAllUnused();
  55208. this.shadowManager.markAllUnused();
  55209. var svgRoot = this._svgRoot;
  55210. var visibleList = this._visibleList;
  55211. var listLen = list.length;
  55212. var newVisibleList = [];
  55213. var i;
  55214. for (i = 0; i < listLen; i++) {
  55215. var displayable = list[i];
  55216. var svgProxy = getSvgProxy(displayable);
  55217. var svgElement = getSvgElement(displayable)
  55218. || getTextSvgElement(displayable);
  55219. if (!displayable.invisible) {
  55220. if (displayable.__dirty) {
  55221. svgProxy && svgProxy.brush(displayable);
  55222. // Update clipPath
  55223. this.clipPathManager.update(displayable);
  55224. // Update gradient and shadow
  55225. if (displayable.style) {
  55226. this.gradientManager
  55227. .update(displayable.style.fill);
  55228. this.gradientManager
  55229. .update(displayable.style.stroke);
  55230. this.shadowManager
  55231. .update(svgElement, displayable);
  55232. }
  55233. displayable.__dirty = false;
  55234. }
  55235. newVisibleList.push(displayable);
  55236. }
  55237. }
  55238. var diff = arrayDiff$1(visibleList, newVisibleList);
  55239. var prevSvgElement;
  55240. // First do remove, in case element moved to the head and do remove
  55241. // after add
  55242. for (i = 0; i < diff.length; i++) {
  55243. var item = diff[i];
  55244. if (item.removed) {
  55245. for (var k = 0; k < item.count; k++) {
  55246. var displayable = visibleList[item.indices[k]];
  55247. var svgElement = getSvgElement(displayable);
  55248. var textSvgElement = getTextSvgElement(displayable);
  55249. remove$1(svgRoot, svgElement);
  55250. remove$1(svgRoot, textSvgElement);
  55251. }
  55252. }
  55253. }
  55254. for (i = 0; i < diff.length; i++) {
  55255. var item = diff[i];
  55256. if (item.added) {
  55257. for (var k = 0; k < item.count; k++) {
  55258. var displayable = newVisibleList[item.indices[k]];
  55259. var svgElement = getSvgElement(displayable);
  55260. var textSvgElement = getTextSvgElement(displayable);
  55261. prevSvgElement
  55262. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  55263. : prepend(svgRoot, svgElement);
  55264. if (svgElement) {
  55265. insertAfter(svgRoot, textSvgElement, svgElement);
  55266. }
  55267. else if (prevSvgElement) {
  55268. insertAfter(
  55269. svgRoot, textSvgElement, prevSvgElement
  55270. );
  55271. }
  55272. else {
  55273. prepend(svgRoot, textSvgElement);
  55274. }
  55275. // Insert text
  55276. insertAfter(svgRoot, textSvgElement, svgElement);
  55277. prevSvgElement = textSvgElement || svgElement
  55278. || prevSvgElement;
  55279. // zrender.Text only create textSvgElement.
  55280. this.gradientManager
  55281. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55282. this.shadowManager
  55283. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55284. this.clipPathManager.markUsed(displayable);
  55285. }
  55286. }
  55287. else if (!item.removed) {
  55288. for (var k = 0; k < item.count; k++) {
  55289. var displayable = newVisibleList[item.indices[k]];
  55290. var svgElement = getSvgElement(displayable);
  55291. var textSvgElement = getTextSvgElement(displayable);
  55292. var svgElement = getSvgElement(displayable);
  55293. var textSvgElement = getTextSvgElement(displayable);
  55294. this.gradientManager.markUsed(displayable);
  55295. this.gradientManager
  55296. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55297. this.shadowManager.markUsed(displayable);
  55298. this.shadowManager
  55299. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55300. this.clipPathManager.markUsed(displayable);
  55301. if (textSvgElement) { // Insert text.
  55302. insertAfter(svgRoot, textSvgElement, svgElement);
  55303. }
  55304. prevSvgElement = svgElement
  55305. || textSvgElement || prevSvgElement;
  55306. }
  55307. }
  55308. }
  55309. this.gradientManager.removeUnused();
  55310. this.clipPathManager.removeUnused();
  55311. this.shadowManager.removeUnused();
  55312. this._visibleList = newVisibleList;
  55313. },
  55314. _getDefs: function (isForceCreating) {
  55315. var svgRoot = this._svgRoot;
  55316. var defs = this._svgRoot.getElementsByTagName('defs');
  55317. if (defs.length === 0) {
  55318. // Not exist
  55319. if (isForceCreating) {
  55320. var defs = svgRoot.insertBefore(
  55321. createElement('defs'), // Create new tag
  55322. svgRoot.firstChild // Insert in the front of svg
  55323. );
  55324. if (!defs.contains) {
  55325. // IE doesn't support contains method
  55326. defs.contains = function (el) {
  55327. var children = defs.children;
  55328. if (!children) {
  55329. return false;
  55330. }
  55331. for (var i = children.length - 1; i >= 0; --i) {
  55332. if (children[i] === el) {
  55333. return true;
  55334. }
  55335. }
  55336. return false;
  55337. };
  55338. }
  55339. return defs;
  55340. }
  55341. else {
  55342. return null;
  55343. }
  55344. }
  55345. else {
  55346. return defs[0];
  55347. }
  55348. },
  55349. resize: function (width, height) {
  55350. var viewport = this._viewport;
  55351. // FIXME Why ?
  55352. viewport.style.display = 'none';
  55353. // Save input w/h
  55354. var opts = this._opts;
  55355. width != null && (opts.width = width);
  55356. height != null && (opts.height = height);
  55357. width = this._getSize(0);
  55358. height = this._getSize(1);
  55359. viewport.style.display = '';
  55360. if (this._width !== width || this._height !== height) {
  55361. this._width = width;
  55362. this._height = height;
  55363. var viewportStyle = viewport.style;
  55364. viewportStyle.width = width + 'px';
  55365. viewportStyle.height = height + 'px';
  55366. var svgRoot = this._svgRoot;
  55367. // Set width by 'svgRoot.width = width' is invalid
  55368. svgRoot.setAttribute('width', width);
  55369. svgRoot.setAttribute('height', height);
  55370. }
  55371. },
  55372. /**
  55373. * 获取绘图区域宽度
  55374. */
  55375. getWidth: function () {
  55376. return this._width;
  55377. },
  55378. /**
  55379. * 获取绘图区域高度
  55380. */
  55381. getHeight: function () {
  55382. return this._height;
  55383. },
  55384. _getSize: function (whIdx) {
  55385. var opts = this._opts;
  55386. var wh = ['width', 'height'][whIdx];
  55387. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  55388. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  55389. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  55390. if (opts[wh] != null && opts[wh] !== 'auto') {
  55391. return parseFloat(opts[wh]);
  55392. }
  55393. var root = this.root;
  55394. // IE8 does not support getComputedStyle, but it use VML.
  55395. var stl = document.defaultView.getComputedStyle(root);
  55396. return (
  55397. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  55398. - (parseInt10$2(stl[plt]) || 0)
  55399. - (parseInt10$2(stl[prb]) || 0)
  55400. ) | 0;
  55401. },
  55402. dispose: function () {
  55403. this.root.innerHTML = '';
  55404. this._svgRoot =
  55405. this._viewport =
  55406. this.storage =
  55407. null;
  55408. },
  55409. clear: function () {
  55410. if (this._viewport) {
  55411. this.root.removeChild(this._viewport);
  55412. }
  55413. },
  55414. pathToDataUrl: function () {
  55415. this.refresh();
  55416. var html = this._svgRoot.outerHTML;
  55417. return 'data:image/svg+xml;charset=UTF-8,' + html;
  55418. }
  55419. };
  55420. // Not supported methods
  55421. function createMethodNotSupport$1(method) {
  55422. return function () {
  55423. logError$1('In SVG mode painter not support method "' + method + '"');
  55424. };
  55425. }
  55426. // Unsuppoted methods
  55427. each$1([
  55428. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  55429. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  55430. 'toDataURL', 'pathToImage'
  55431. ], function (name) {
  55432. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  55433. });
  55434. registerPainter('svg', SVGPainter);
  55435. /*
  55436. * Licensed to the Apache Software Foundation (ASF) under one
  55437. * or more contributor license agreements. See the NOTICE file
  55438. * distributed with this work for additional information
  55439. * regarding copyright ownership. The ASF licenses this file
  55440. * to you under the Apache License, Version 2.0 (the
  55441. * "License"); you may not use this file except in compliance
  55442. * with the License. You may obtain a copy of the License at
  55443. *
  55444. * http://www.apache.org/licenses/LICENSE-2.0
  55445. *
  55446. * Unless required by applicable law or agreed to in writing,
  55447. * software distributed under the License is distributed on an
  55448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55449. * KIND, either express or implied. See the License for the
  55450. * specific language governing permissions and limitations
  55451. * under the License.
  55452. */
  55453. exports.version = version;
  55454. exports.dependencies = dependencies;
  55455. exports.PRIORITY = PRIORITY;
  55456. exports.init = init;
  55457. exports.connect = connect;
  55458. exports.disConnect = disConnect;
  55459. exports.disconnect = disconnect;
  55460. exports.dispose = dispose;
  55461. exports.getInstanceByDom = getInstanceByDom;
  55462. exports.getInstanceById = getInstanceById;
  55463. exports.registerTheme = registerTheme;
  55464. exports.registerPreprocessor = registerPreprocessor;
  55465. exports.registerProcessor = registerProcessor;
  55466. exports.registerPostUpdate = registerPostUpdate;
  55467. exports.registerAction = registerAction;
  55468. exports.registerCoordinateSystem = registerCoordinateSystem;
  55469. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  55470. exports.registerLayout = registerLayout;
  55471. exports.registerVisual = registerVisual;
  55472. exports.registerLoading = registerLoading;
  55473. exports.extendComponentModel = extendComponentModel;
  55474. exports.extendComponentView = extendComponentView;
  55475. exports.extendSeriesModel = extendSeriesModel;
  55476. exports.extendChartView = extendChartView;
  55477. exports.setCanvasCreator = setCanvasCreator;
  55478. exports.registerMap = registerMap;
  55479. exports.getMap = getMap;
  55480. exports.dataTool = dataTool;
  55481. exports.zrender = zrender;
  55482. exports.number = number;
  55483. exports.format = format;
  55484. exports.throttle = throttle;
  55485. exports.helper = helper;
  55486. exports.matrix = matrix;
  55487. exports.vector = vector;
  55488. exports.color = color;
  55489. exports.parseGeoJSON = parseGeoJSON;
  55490. exports.parseGeoJson = parseGeoJson;
  55491. exports.util = ecUtil;
  55492. exports.graphic = graphic$1;
  55493. exports.List = List;
  55494. exports.Model = Model;
  55495. exports.Axis = Axis;
  55496. exports.env = env$1;
  55497. })));