echarts.common.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. if (typeof b !== "function" && b !== null)
  45. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  46. extendStatics(d, b);
  47. function __() { this.constructor = d; }
  48. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  49. }
  50. var Browser = (function () {
  51. function Browser() {
  52. this.firefox = false;
  53. this.ie = false;
  54. this.edge = false;
  55. this.newEdge = false;
  56. this.weChat = false;
  57. }
  58. return Browser;
  59. }());
  60. var Env = (function () {
  61. function Env() {
  62. this.browser = new Browser();
  63. this.node = false;
  64. this.wxa = false;
  65. this.worker = false;
  66. this.svgSupported = false;
  67. this.touchEventsSupported = false;
  68. this.pointerEventsSupported = false;
  69. this.domSupported = false;
  70. this.transformSupported = false;
  71. this.transform3dSupported = false;
  72. this.hasGlobalWindow = typeof window !== 'undefined';
  73. }
  74. return Env;
  75. }());
  76. var env = new Env();
  77. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  78. env.wxa = true;
  79. env.touchEventsSupported = true;
  80. }
  81. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  82. env.worker = true;
  83. }
  84. else if (!env.hasGlobalWindow || 'Deno' in window) {
  85. env.node = true;
  86. env.svgSupported = true;
  87. }
  88. else {
  89. detect(navigator.userAgent, env);
  90. }
  91. function detect(ua, env) {
  92. var browser = env.browser;
  93. var firefox = ua.match(/Firefox\/([\d.]+)/);
  94. var ie = ua.match(/MSIE\s([\d.]+)/)
  95. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  96. var edge = ua.match(/Edge?\/([\d.]+)/);
  97. var weChat = (/micromessenger/i).test(ua);
  98. if (firefox) {
  99. browser.firefox = true;
  100. browser.version = firefox[1];
  101. }
  102. if (ie) {
  103. browser.ie = true;
  104. browser.version = ie[1];
  105. }
  106. if (edge) {
  107. browser.edge = true;
  108. browser.version = edge[1];
  109. browser.newEdge = +edge[1].split('.')[0] > 18;
  110. }
  111. if (weChat) {
  112. browser.weChat = true;
  113. }
  114. env.svgSupported = typeof SVGRect !== 'undefined';
  115. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  116. env.pointerEventsSupported = 'onpointerdown' in window
  117. && (browser.edge || (browser.ie && +browser.version >= 11));
  118. env.domSupported = typeof document !== 'undefined';
  119. var style = document.documentElement.style;
  120. env.transform3dSupported = ((browser.ie && 'transition' in style)
  121. || browser.edge
  122. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  123. || 'MozPerspective' in style)
  124. && !('OTransition' in style);
  125. env.transformSupported = env.transform3dSupported
  126. || (browser.ie && +browser.version >= 9);
  127. }
  128. var DEFAULT_FONT_SIZE = 12;
  129. var DEFAULT_FONT_FAMILY = 'sans-serif';
  130. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  131. var OFFSET = 20;
  132. var SCALE = 100;
  133. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  134. function getTextWidthMap(mapStr) {
  135. var map = {};
  136. if (typeof JSON === 'undefined') {
  137. return map;
  138. }
  139. for (var i = 0; i < mapStr.length; i++) {
  140. var char = String.fromCharCode(i + 32);
  141. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  142. map[char] = size;
  143. }
  144. return map;
  145. }
  146. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  147. var platformApi = {
  148. createCanvas: function () {
  149. return typeof document !== 'undefined'
  150. && document.createElement('canvas');
  151. },
  152. measureText: (function () {
  153. var _ctx;
  154. var _cachedFont;
  155. return function (text, font) {
  156. if (!_ctx) {
  157. var canvas = platformApi.createCanvas();
  158. _ctx = canvas && canvas.getContext('2d');
  159. }
  160. if (_ctx) {
  161. if (_cachedFont !== font) {
  162. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  163. }
  164. return _ctx.measureText(text);
  165. }
  166. else {
  167. text = text || '';
  168. font = font || DEFAULT_FONT;
  169. var res = /((?:\d+)?\.?\d*)px/.exec(font);
  170. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  171. var width = 0;
  172. if (font.indexOf('mono') >= 0) {
  173. width = fontSize * text.length;
  174. }
  175. else {
  176. for (var i = 0; i < text.length; i++) {
  177. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  178. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  179. }
  180. }
  181. return { width: width };
  182. }
  183. };
  184. })(),
  185. loadImage: function (src, onload, onerror) {
  186. var image = new Image();
  187. image.onload = onload;
  188. image.onerror = onerror;
  189. image.src = src;
  190. return image;
  191. }
  192. };
  193. function setPlatformAPI(newPlatformApis) {
  194. for (var key in platformApi) {
  195. if (newPlatformApis[key]) {
  196. platformApi[key] = newPlatformApis[key];
  197. }
  198. }
  199. }
  200. var BUILTIN_OBJECT = reduce([
  201. 'Function',
  202. 'RegExp',
  203. 'Date',
  204. 'Error',
  205. 'CanvasGradient',
  206. 'CanvasPattern',
  207. 'Image',
  208. 'Canvas'
  209. ], function (obj, val) {
  210. obj['[object ' + val + ']'] = true;
  211. return obj;
  212. }, {});
  213. var TYPED_ARRAY = reduce([
  214. 'Int8',
  215. 'Uint8',
  216. 'Uint8Clamped',
  217. 'Int16',
  218. 'Uint16',
  219. 'Int32',
  220. 'Uint32',
  221. 'Float32',
  222. 'Float64'
  223. ], function (obj, val) {
  224. obj['[object ' + val + 'Array]'] = true;
  225. return obj;
  226. }, {});
  227. var objToString = Object.prototype.toString;
  228. var arrayProto = Array.prototype;
  229. var nativeForEach = arrayProto.forEach;
  230. var nativeFilter = arrayProto.filter;
  231. var nativeSlice = arrayProto.slice;
  232. var nativeMap = arrayProto.map;
  233. var ctorFunction = function () { }.constructor;
  234. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  235. var protoKey = '__proto__';
  236. var idStart = 0x0907;
  237. function guid() {
  238. return idStart++;
  239. }
  240. function logError() {
  241. var args = [];
  242. for (var _i = 0; _i < arguments.length; _i++) {
  243. args[_i] = arguments[_i];
  244. }
  245. if (typeof console !== 'undefined') {
  246. console.error.apply(console, args);
  247. }
  248. }
  249. function clone(source) {
  250. if (source == null || typeof source !== 'object') {
  251. return source;
  252. }
  253. var result = source;
  254. var typeStr = objToString.call(source);
  255. if (typeStr === '[object Array]') {
  256. if (!isPrimitive(source)) {
  257. result = [];
  258. for (var i = 0, len = source.length; i < len; i++) {
  259. result[i] = clone(source[i]);
  260. }
  261. }
  262. }
  263. else if (TYPED_ARRAY[typeStr]) {
  264. if (!isPrimitive(source)) {
  265. var Ctor = source.constructor;
  266. if (Ctor.from) {
  267. result = Ctor.from(source);
  268. }
  269. else {
  270. result = new Ctor(source.length);
  271. for (var i = 0, len = source.length; i < len; i++) {
  272. result[i] = source[i];
  273. }
  274. }
  275. }
  276. }
  277. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  278. result = {};
  279. for (var key in source) {
  280. if (source.hasOwnProperty(key) && key !== protoKey) {
  281. result[key] = clone(source[key]);
  282. }
  283. }
  284. }
  285. return result;
  286. }
  287. function merge(target, source, overwrite) {
  288. if (!isObject(source) || !isObject(target)) {
  289. return overwrite ? clone(source) : target;
  290. }
  291. for (var key in source) {
  292. if (source.hasOwnProperty(key) && key !== protoKey) {
  293. var targetProp = target[key];
  294. var sourceProp = source[key];
  295. if (isObject(sourceProp)
  296. && isObject(targetProp)
  297. && !isArray(sourceProp)
  298. && !isArray(targetProp)
  299. && !isDom(sourceProp)
  300. && !isDom(targetProp)
  301. && !isBuiltInObject(sourceProp)
  302. && !isBuiltInObject(targetProp)
  303. && !isPrimitive(sourceProp)
  304. && !isPrimitive(targetProp)) {
  305. merge(targetProp, sourceProp, overwrite);
  306. }
  307. else if (overwrite || !(key in target)) {
  308. target[key] = clone(source[key]);
  309. }
  310. }
  311. }
  312. return target;
  313. }
  314. function mergeAll(targetAndSources, overwrite) {
  315. var result = targetAndSources[0];
  316. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  317. result = merge(result, targetAndSources[i], overwrite);
  318. }
  319. return result;
  320. }
  321. function extend(target, source) {
  322. if (Object.assign) {
  323. Object.assign(target, source);
  324. }
  325. else {
  326. for (var key in source) {
  327. if (source.hasOwnProperty(key) && key !== protoKey) {
  328. target[key] = source[key];
  329. }
  330. }
  331. }
  332. return target;
  333. }
  334. function defaults(target, source, overlay) {
  335. var keysArr = keys(source);
  336. for (var i = 0, len = keysArr.length; i < len; i++) {
  337. var key = keysArr[i];
  338. if ((overlay ? source[key] != null : target[key] == null)) {
  339. target[key] = source[key];
  340. }
  341. }
  342. return target;
  343. }
  344. var createCanvas = platformApi.createCanvas;
  345. function indexOf(array, value) {
  346. if (array) {
  347. if (array.indexOf) {
  348. return array.indexOf(value);
  349. }
  350. for (var i = 0, len = array.length; i < len; i++) {
  351. if (array[i] === value) {
  352. return i;
  353. }
  354. }
  355. }
  356. return -1;
  357. }
  358. function inherits(clazz, baseClazz) {
  359. var clazzPrototype = clazz.prototype;
  360. function F() { }
  361. F.prototype = baseClazz.prototype;
  362. clazz.prototype = new F();
  363. for (var prop in clazzPrototype) {
  364. if (clazzPrototype.hasOwnProperty(prop)) {
  365. clazz.prototype[prop] = clazzPrototype[prop];
  366. }
  367. }
  368. clazz.prototype.constructor = clazz;
  369. clazz.superClass = baseClazz;
  370. }
  371. function mixin(target, source, override) {
  372. target = 'prototype' in target ? target.prototype : target;
  373. source = 'prototype' in source ? source.prototype : source;
  374. if (Object.getOwnPropertyNames) {
  375. var keyList = Object.getOwnPropertyNames(source);
  376. for (var i = 0; i < keyList.length; i++) {
  377. var key = keyList[i];
  378. if (key !== 'constructor') {
  379. if ((override ? source[key] != null : target[key] == null)) {
  380. target[key] = source[key];
  381. }
  382. }
  383. }
  384. }
  385. else {
  386. defaults(target, source, override);
  387. }
  388. }
  389. function isArrayLike(data) {
  390. if (!data) {
  391. return false;
  392. }
  393. if (typeof data === 'string') {
  394. return false;
  395. }
  396. return typeof data.length === 'number';
  397. }
  398. function each(arr, cb, context) {
  399. if (!(arr && cb)) {
  400. return;
  401. }
  402. if (arr.forEach && arr.forEach === nativeForEach) {
  403. arr.forEach(cb, context);
  404. }
  405. else if (arr.length === +arr.length) {
  406. for (var i = 0, len = arr.length; i < len; i++) {
  407. cb.call(context, arr[i], i, arr);
  408. }
  409. }
  410. else {
  411. for (var key in arr) {
  412. if (arr.hasOwnProperty(key)) {
  413. cb.call(context, arr[key], key, arr);
  414. }
  415. }
  416. }
  417. }
  418. function map(arr, cb, context) {
  419. if (!arr) {
  420. return [];
  421. }
  422. if (!cb) {
  423. return slice(arr);
  424. }
  425. if (arr.map && arr.map === nativeMap) {
  426. return arr.map(cb, context);
  427. }
  428. else {
  429. var result = [];
  430. for (var i = 0, len = arr.length; i < len; i++) {
  431. result.push(cb.call(context, arr[i], i, arr));
  432. }
  433. return result;
  434. }
  435. }
  436. function reduce(arr, cb, memo, context) {
  437. if (!(arr && cb)) {
  438. return;
  439. }
  440. for (var i = 0, len = arr.length; i < len; i++) {
  441. memo = cb.call(context, memo, arr[i], i, arr);
  442. }
  443. return memo;
  444. }
  445. function filter(arr, cb, context) {
  446. if (!arr) {
  447. return [];
  448. }
  449. if (!cb) {
  450. return slice(arr);
  451. }
  452. if (arr.filter && arr.filter === nativeFilter) {
  453. return arr.filter(cb, context);
  454. }
  455. else {
  456. var result = [];
  457. for (var i = 0, len = arr.length; i < len; i++) {
  458. if (cb.call(context, arr[i], i, arr)) {
  459. result.push(arr[i]);
  460. }
  461. }
  462. return result;
  463. }
  464. }
  465. function find(arr, cb, context) {
  466. if (!(arr && cb)) {
  467. return;
  468. }
  469. for (var i = 0, len = arr.length; i < len; i++) {
  470. if (cb.call(context, arr[i], i, arr)) {
  471. return arr[i];
  472. }
  473. }
  474. }
  475. function keys(obj) {
  476. if (!obj) {
  477. return [];
  478. }
  479. if (Object.keys) {
  480. return Object.keys(obj);
  481. }
  482. var keyList = [];
  483. for (var key in obj) {
  484. if (obj.hasOwnProperty(key)) {
  485. keyList.push(key);
  486. }
  487. }
  488. return keyList;
  489. }
  490. function bindPolyfill(func, context) {
  491. var args = [];
  492. for (var _i = 2; _i < arguments.length; _i++) {
  493. args[_i - 2] = arguments[_i];
  494. }
  495. return function () {
  496. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  497. };
  498. }
  499. var bind = (protoFunction && isFunction(protoFunction.bind))
  500. ? protoFunction.call.bind(protoFunction.bind)
  501. : bindPolyfill;
  502. function curry(func) {
  503. var args = [];
  504. for (var _i = 1; _i < arguments.length; _i++) {
  505. args[_i - 1] = arguments[_i];
  506. }
  507. return function () {
  508. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  509. };
  510. }
  511. function isArray(value) {
  512. if (Array.isArray) {
  513. return Array.isArray(value);
  514. }
  515. return objToString.call(value) === '[object Array]';
  516. }
  517. function isFunction(value) {
  518. return typeof value === 'function';
  519. }
  520. function isString(value) {
  521. return typeof value === 'string';
  522. }
  523. function isStringSafe(value) {
  524. return objToString.call(value) === '[object String]';
  525. }
  526. function isNumber(value) {
  527. return typeof value === 'number';
  528. }
  529. function isObject(value) {
  530. var type = typeof value;
  531. return type === 'function' || (!!value && type === 'object');
  532. }
  533. function isBuiltInObject(value) {
  534. return !!BUILTIN_OBJECT[objToString.call(value)];
  535. }
  536. function isTypedArray(value) {
  537. return !!TYPED_ARRAY[objToString.call(value)];
  538. }
  539. function isDom(value) {
  540. return typeof value === 'object'
  541. && typeof value.nodeType === 'number'
  542. && typeof value.ownerDocument === 'object';
  543. }
  544. function isGradientObject(value) {
  545. return value.colorStops != null;
  546. }
  547. function isImagePatternObject(value) {
  548. return value.image != null;
  549. }
  550. function isRegExp(value) {
  551. return objToString.call(value) === '[object RegExp]';
  552. }
  553. function eqNaN(value) {
  554. return value !== value;
  555. }
  556. function retrieve() {
  557. var args = [];
  558. for (var _i = 0; _i < arguments.length; _i++) {
  559. args[_i] = arguments[_i];
  560. }
  561. for (var i = 0, len = args.length; i < len; i++) {
  562. if (args[i] != null) {
  563. return args[i];
  564. }
  565. }
  566. }
  567. function retrieve2(value0, value1) {
  568. return value0 != null
  569. ? value0
  570. : value1;
  571. }
  572. function retrieve3(value0, value1, value2) {
  573. return value0 != null
  574. ? value0
  575. : value1 != null
  576. ? value1
  577. : value2;
  578. }
  579. function slice(arr) {
  580. var args = [];
  581. for (var _i = 1; _i < arguments.length; _i++) {
  582. args[_i - 1] = arguments[_i];
  583. }
  584. return nativeSlice.apply(arr, args);
  585. }
  586. function normalizeCssArray(val) {
  587. if (typeof (val) === 'number') {
  588. return [val, val, val, val];
  589. }
  590. var len = val.length;
  591. if (len === 2) {
  592. return [val[0], val[1], val[0], val[1]];
  593. }
  594. else if (len === 3) {
  595. return [val[0], val[1], val[2], val[1]];
  596. }
  597. return val;
  598. }
  599. function assert(condition, message) {
  600. if (!condition) {
  601. throw new Error(message);
  602. }
  603. }
  604. function trim(str) {
  605. if (str == null) {
  606. return null;
  607. }
  608. else if (typeof str.trim === 'function') {
  609. return str.trim();
  610. }
  611. else {
  612. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  613. }
  614. }
  615. var primitiveKey = '__ec_primitive__';
  616. function setAsPrimitive(obj) {
  617. obj[primitiveKey] = true;
  618. }
  619. function isPrimitive(obj) {
  620. return obj[primitiveKey];
  621. }
  622. var MapPolyfill = (function () {
  623. function MapPolyfill() {
  624. this.data = {};
  625. }
  626. MapPolyfill.prototype["delete"] = function (key) {
  627. var existed = this.has(key);
  628. if (existed) {
  629. delete this.data[key];
  630. }
  631. return existed;
  632. };
  633. MapPolyfill.prototype.has = function (key) {
  634. return this.data.hasOwnProperty(key);
  635. };
  636. MapPolyfill.prototype.get = function (key) {
  637. return this.data[key];
  638. };
  639. MapPolyfill.prototype.set = function (key, value) {
  640. this.data[key] = value;
  641. return this;
  642. };
  643. MapPolyfill.prototype.keys = function () {
  644. return keys(this.data);
  645. };
  646. MapPolyfill.prototype.forEach = function (callback) {
  647. var data = this.data;
  648. for (var key in data) {
  649. if (data.hasOwnProperty(key)) {
  650. callback(data[key], key);
  651. }
  652. }
  653. };
  654. return MapPolyfill;
  655. }());
  656. var isNativeMapSupported = typeof Map === 'function';
  657. function maybeNativeMap() {
  658. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  659. }
  660. var HashMap = (function () {
  661. function HashMap(obj) {
  662. var isArr = isArray(obj);
  663. this.data = maybeNativeMap();
  664. var thisMap = this;
  665. (obj instanceof HashMap)
  666. ? obj.each(visit)
  667. : (obj && each(obj, visit));
  668. function visit(value, key) {
  669. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  670. }
  671. }
  672. HashMap.prototype.hasKey = function (key) {
  673. return this.data.has(key);
  674. };
  675. HashMap.prototype.get = function (key) {
  676. return this.data.get(key);
  677. };
  678. HashMap.prototype.set = function (key, value) {
  679. this.data.set(key, value);
  680. return value;
  681. };
  682. HashMap.prototype.each = function (cb, context) {
  683. this.data.forEach(function (value, key) {
  684. cb.call(context, value, key);
  685. });
  686. };
  687. HashMap.prototype.keys = function () {
  688. var keys = this.data.keys();
  689. return isNativeMapSupported
  690. ? Array.from(keys)
  691. : keys;
  692. };
  693. HashMap.prototype.removeKey = function (key) {
  694. this.data["delete"](key);
  695. };
  696. return HashMap;
  697. }());
  698. function createHashMap(obj) {
  699. return new HashMap(obj);
  700. }
  701. function concatArray(a, b) {
  702. var newArray = new a.constructor(a.length + b.length);
  703. for (var i = 0; i < a.length; i++) {
  704. newArray[i] = a[i];
  705. }
  706. var offset = a.length;
  707. for (var i = 0; i < b.length; i++) {
  708. newArray[i + offset] = b[i];
  709. }
  710. return newArray;
  711. }
  712. function createObject(proto, properties) {
  713. var obj;
  714. if (Object.create) {
  715. obj = Object.create(proto);
  716. }
  717. else {
  718. var StyleCtor = function () { };
  719. StyleCtor.prototype = proto;
  720. obj = new StyleCtor();
  721. }
  722. if (properties) {
  723. extend(obj, properties);
  724. }
  725. return obj;
  726. }
  727. function disableUserSelect(dom) {
  728. var domStyle = dom.style;
  729. domStyle.webkitUserSelect = 'none';
  730. domStyle.userSelect = 'none';
  731. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  732. domStyle['-webkit-touch-callout'] = 'none';
  733. }
  734. function hasOwn(own, prop) {
  735. return own.hasOwnProperty(prop);
  736. }
  737. function noop() { }
  738. var RADIAN_TO_DEGREE = 180 / Math.PI;
  739. var util = /*#__PURE__*/Object.freeze({
  740. __proto__: null,
  741. guid: guid,
  742. logError: logError,
  743. clone: clone,
  744. merge: merge,
  745. mergeAll: mergeAll,
  746. extend: extend,
  747. defaults: defaults,
  748. createCanvas: createCanvas,
  749. indexOf: indexOf,
  750. inherits: inherits,
  751. mixin: mixin,
  752. isArrayLike: isArrayLike,
  753. each: each,
  754. map: map,
  755. reduce: reduce,
  756. filter: filter,
  757. find: find,
  758. keys: keys,
  759. bind: bind,
  760. curry: curry,
  761. isArray: isArray,
  762. isFunction: isFunction,
  763. isString: isString,
  764. isStringSafe: isStringSafe,
  765. isNumber: isNumber,
  766. isObject: isObject,
  767. isBuiltInObject: isBuiltInObject,
  768. isTypedArray: isTypedArray,
  769. isDom: isDom,
  770. isGradientObject: isGradientObject,
  771. isImagePatternObject: isImagePatternObject,
  772. isRegExp: isRegExp,
  773. eqNaN: eqNaN,
  774. retrieve: retrieve,
  775. retrieve2: retrieve2,
  776. retrieve3: retrieve3,
  777. slice: slice,
  778. normalizeCssArray: normalizeCssArray,
  779. assert: assert,
  780. trim: trim,
  781. setAsPrimitive: setAsPrimitive,
  782. isPrimitive: isPrimitive,
  783. HashMap: HashMap,
  784. createHashMap: createHashMap,
  785. concatArray: concatArray,
  786. createObject: createObject,
  787. disableUserSelect: disableUserSelect,
  788. hasOwn: hasOwn,
  789. noop: noop,
  790. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  791. });
  792. function create(x, y) {
  793. if (x == null) {
  794. x = 0;
  795. }
  796. if (y == null) {
  797. y = 0;
  798. }
  799. return [x, y];
  800. }
  801. function copy(out, v) {
  802. out[0] = v[0];
  803. out[1] = v[1];
  804. return out;
  805. }
  806. function clone$1(v) {
  807. return [v[0], v[1]];
  808. }
  809. function set(out, a, b) {
  810. out[0] = a;
  811. out[1] = b;
  812. return out;
  813. }
  814. function add(out, v1, v2) {
  815. out[0] = v1[0] + v2[0];
  816. out[1] = v1[1] + v2[1];
  817. return out;
  818. }
  819. function scaleAndAdd(out, v1, v2, a) {
  820. out[0] = v1[0] + v2[0] * a;
  821. out[1] = v1[1] + v2[1] * a;
  822. return out;
  823. }
  824. function sub(out, v1, v2) {
  825. out[0] = v1[0] - v2[0];
  826. out[1] = v1[1] - v2[1];
  827. return out;
  828. }
  829. function len(v) {
  830. return Math.sqrt(lenSquare(v));
  831. }
  832. var length = len;
  833. function lenSquare(v) {
  834. return v[0] * v[0] + v[1] * v[1];
  835. }
  836. var lengthSquare = lenSquare;
  837. function mul(out, v1, v2) {
  838. out[0] = v1[0] * v2[0];
  839. out[1] = v1[1] * v2[1];
  840. return out;
  841. }
  842. function div(out, v1, v2) {
  843. out[0] = v1[0] / v2[0];
  844. out[1] = v1[1] / v2[1];
  845. return out;
  846. }
  847. function dot(v1, v2) {
  848. return v1[0] * v2[0] + v1[1] * v2[1];
  849. }
  850. function scale(out, v, s) {
  851. out[0] = v[0] * s;
  852. out[1] = v[1] * s;
  853. return out;
  854. }
  855. function normalize(out, v) {
  856. var d = len(v);
  857. if (d === 0) {
  858. out[0] = 0;
  859. out[1] = 0;
  860. }
  861. else {
  862. out[0] = v[0] / d;
  863. out[1] = v[1] / d;
  864. }
  865. return out;
  866. }
  867. function distance(v1, v2) {
  868. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  869. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  870. }
  871. var dist = distance;
  872. function distanceSquare(v1, v2) {
  873. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  874. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  875. }
  876. var distSquare = distanceSquare;
  877. function negate(out, v) {
  878. out[0] = -v[0];
  879. out[1] = -v[1];
  880. return out;
  881. }
  882. function lerp(out, v1, v2, t) {
  883. out[0] = v1[0] + t * (v2[0] - v1[0]);
  884. out[1] = v1[1] + t * (v2[1] - v1[1]);
  885. return out;
  886. }
  887. function applyTransform(out, v, m) {
  888. var x = v[0];
  889. var y = v[1];
  890. out[0] = m[0] * x + m[2] * y + m[4];
  891. out[1] = m[1] * x + m[3] * y + m[5];
  892. return out;
  893. }
  894. function min(out, v1, v2) {
  895. out[0] = Math.min(v1[0], v2[0]);
  896. out[1] = Math.min(v1[1], v2[1]);
  897. return out;
  898. }
  899. function max(out, v1, v2) {
  900. out[0] = Math.max(v1[0], v2[0]);
  901. out[1] = Math.max(v1[1], v2[1]);
  902. return out;
  903. }
  904. var vector = /*#__PURE__*/Object.freeze({
  905. __proto__: null,
  906. create: create,
  907. copy: copy,
  908. clone: clone$1,
  909. set: set,
  910. add: add,
  911. scaleAndAdd: scaleAndAdd,
  912. sub: sub,
  913. len: len,
  914. length: length,
  915. lenSquare: lenSquare,
  916. lengthSquare: lengthSquare,
  917. mul: mul,
  918. div: div,
  919. dot: dot,
  920. scale: scale,
  921. normalize: normalize,
  922. distance: distance,
  923. dist: dist,
  924. distanceSquare: distanceSquare,
  925. distSquare: distSquare,
  926. negate: negate,
  927. lerp: lerp,
  928. applyTransform: applyTransform,
  929. min: min,
  930. max: max
  931. });
  932. var Param = (function () {
  933. function Param(target, e) {
  934. this.target = target;
  935. this.topTarget = e && e.topTarget;
  936. }
  937. return Param;
  938. }());
  939. var Draggable = (function () {
  940. function Draggable(handler) {
  941. this.handler = handler;
  942. handler.on('mousedown', this._dragStart, this);
  943. handler.on('mousemove', this._drag, this);
  944. handler.on('mouseup', this._dragEnd, this);
  945. }
  946. Draggable.prototype._dragStart = function (e) {
  947. var draggingTarget = e.target;
  948. while (draggingTarget && !draggingTarget.draggable) {
  949. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  950. }
  951. if (draggingTarget) {
  952. this._draggingTarget = draggingTarget;
  953. draggingTarget.dragging = true;
  954. this._x = e.offsetX;
  955. this._y = e.offsetY;
  956. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  957. }
  958. };
  959. Draggable.prototype._drag = function (e) {
  960. var draggingTarget = this._draggingTarget;
  961. if (draggingTarget) {
  962. var x = e.offsetX;
  963. var y = e.offsetY;
  964. var dx = x - this._x;
  965. var dy = y - this._y;
  966. this._x = x;
  967. this._y = y;
  968. draggingTarget.drift(dx, dy, e);
  969. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  970. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  971. var lastDropTarget = this._dropTarget;
  972. this._dropTarget = dropTarget;
  973. if (draggingTarget !== dropTarget) {
  974. if (lastDropTarget && dropTarget !== lastDropTarget) {
  975. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  976. }
  977. if (dropTarget && dropTarget !== lastDropTarget) {
  978. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  979. }
  980. }
  981. }
  982. };
  983. Draggable.prototype._dragEnd = function (e) {
  984. var draggingTarget = this._draggingTarget;
  985. if (draggingTarget) {
  986. draggingTarget.dragging = false;
  987. }
  988. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  989. if (this._dropTarget) {
  990. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  991. }
  992. this._draggingTarget = null;
  993. this._dropTarget = null;
  994. };
  995. return Draggable;
  996. }());
  997. var Eventful = (function () {
  998. function Eventful(eventProcessors) {
  999. if (eventProcessors) {
  1000. this._$eventProcessor = eventProcessors;
  1001. }
  1002. }
  1003. Eventful.prototype.on = function (event, query, handler, context) {
  1004. if (!this._$handlers) {
  1005. this._$handlers = {};
  1006. }
  1007. var _h = this._$handlers;
  1008. if (typeof query === 'function') {
  1009. context = handler;
  1010. handler = query;
  1011. query = null;
  1012. }
  1013. if (!handler || !event) {
  1014. return this;
  1015. }
  1016. var eventProcessor = this._$eventProcessor;
  1017. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1018. query = eventProcessor.normalizeQuery(query);
  1019. }
  1020. if (!_h[event]) {
  1021. _h[event] = [];
  1022. }
  1023. for (var i = 0; i < _h[event].length; i++) {
  1024. if (_h[event][i].h === handler) {
  1025. return this;
  1026. }
  1027. }
  1028. var wrap = {
  1029. h: handler,
  1030. query: query,
  1031. ctx: (context || this),
  1032. callAtLast: handler.zrEventfulCallAtLast
  1033. };
  1034. var lastIndex = _h[event].length - 1;
  1035. var lastWrap = _h[event][lastIndex];
  1036. (lastWrap && lastWrap.callAtLast)
  1037. ? _h[event].splice(lastIndex, 0, wrap)
  1038. : _h[event].push(wrap);
  1039. return this;
  1040. };
  1041. Eventful.prototype.isSilent = function (eventName) {
  1042. var _h = this._$handlers;
  1043. return !_h || !_h[eventName] || !_h[eventName].length;
  1044. };
  1045. Eventful.prototype.off = function (eventType, handler) {
  1046. var _h = this._$handlers;
  1047. if (!_h) {
  1048. return this;
  1049. }
  1050. if (!eventType) {
  1051. this._$handlers = {};
  1052. return this;
  1053. }
  1054. if (handler) {
  1055. if (_h[eventType]) {
  1056. var newList = [];
  1057. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1058. if (_h[eventType][i].h !== handler) {
  1059. newList.push(_h[eventType][i]);
  1060. }
  1061. }
  1062. _h[eventType] = newList;
  1063. }
  1064. if (_h[eventType] && _h[eventType].length === 0) {
  1065. delete _h[eventType];
  1066. }
  1067. }
  1068. else {
  1069. delete _h[eventType];
  1070. }
  1071. return this;
  1072. };
  1073. Eventful.prototype.trigger = function (eventType) {
  1074. var args = [];
  1075. for (var _i = 1; _i < arguments.length; _i++) {
  1076. args[_i - 1] = arguments[_i];
  1077. }
  1078. if (!this._$handlers) {
  1079. return this;
  1080. }
  1081. var _h = this._$handlers[eventType];
  1082. var eventProcessor = this._$eventProcessor;
  1083. if (_h) {
  1084. var argLen = args.length;
  1085. var len = _h.length;
  1086. for (var i = 0; i < len; i++) {
  1087. var hItem = _h[i];
  1088. if (eventProcessor
  1089. && eventProcessor.filter
  1090. && hItem.query != null
  1091. && !eventProcessor.filter(eventType, hItem.query)) {
  1092. continue;
  1093. }
  1094. switch (argLen) {
  1095. case 0:
  1096. hItem.h.call(hItem.ctx);
  1097. break;
  1098. case 1:
  1099. hItem.h.call(hItem.ctx, args[0]);
  1100. break;
  1101. case 2:
  1102. hItem.h.call(hItem.ctx, args[0], args[1]);
  1103. break;
  1104. default:
  1105. hItem.h.apply(hItem.ctx, args);
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. eventProcessor && eventProcessor.afterTrigger
  1111. && eventProcessor.afterTrigger(eventType);
  1112. return this;
  1113. };
  1114. Eventful.prototype.triggerWithContext = function (type) {
  1115. var args = [];
  1116. for (var _i = 1; _i < arguments.length; _i++) {
  1117. args[_i - 1] = arguments[_i];
  1118. }
  1119. if (!this._$handlers) {
  1120. return this;
  1121. }
  1122. var _h = this._$handlers[type];
  1123. var eventProcessor = this._$eventProcessor;
  1124. if (_h) {
  1125. var argLen = args.length;
  1126. var ctx = args[argLen - 1];
  1127. var len = _h.length;
  1128. for (var i = 0; i < len; i++) {
  1129. var hItem = _h[i];
  1130. if (eventProcessor
  1131. && eventProcessor.filter
  1132. && hItem.query != null
  1133. && !eventProcessor.filter(type, hItem.query)) {
  1134. continue;
  1135. }
  1136. switch (argLen) {
  1137. case 0:
  1138. hItem.h.call(ctx);
  1139. break;
  1140. case 1:
  1141. hItem.h.call(ctx, args[0]);
  1142. break;
  1143. case 2:
  1144. hItem.h.call(ctx, args[0], args[1]);
  1145. break;
  1146. default:
  1147. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1148. break;
  1149. }
  1150. }
  1151. }
  1152. eventProcessor && eventProcessor.afterTrigger
  1153. && eventProcessor.afterTrigger(type);
  1154. return this;
  1155. };
  1156. return Eventful;
  1157. }());
  1158. var LN2 = Math.log(2);
  1159. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1160. var cacheKey = rowMask + '-' + colMask;
  1161. var fullRank = rows.length;
  1162. if (detCache.hasOwnProperty(cacheKey)) {
  1163. return detCache[cacheKey];
  1164. }
  1165. if (rank === 1) {
  1166. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1167. return rows[rowStart][colStart];
  1168. }
  1169. var subRowMask = rowMask | (1 << rowStart);
  1170. var subRowStart = rowStart + 1;
  1171. while (rowMask & (1 << subRowStart)) {
  1172. subRowStart++;
  1173. }
  1174. var sum = 0;
  1175. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1176. var colTag = 1 << j;
  1177. if (!(colTag & colMask)) {
  1178. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1179. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1180. colLocalIdx++;
  1181. }
  1182. }
  1183. detCache[cacheKey] = sum;
  1184. return sum;
  1185. }
  1186. function buildTransformer(src, dest) {
  1187. var mA = [
  1188. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1189. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1190. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1191. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1192. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1193. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1194. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1195. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1196. ];
  1197. var detCache = {};
  1198. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1199. if (det === 0) {
  1200. return;
  1201. }
  1202. var vh = [];
  1203. for (var i = 0; i < 8; i++) {
  1204. for (var j = 0; j < 8; j++) {
  1205. vh[j] == null && (vh[j] = 0);
  1206. vh[j] += ((i + j) % 2 ? -1 : 1)
  1207. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1208. / det * dest[i];
  1209. }
  1210. }
  1211. return function (out, srcPointX, srcPointY) {
  1212. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1213. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1214. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1215. };
  1216. }
  1217. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1218. var _calcOut = [];
  1219. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1220. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1221. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1222. }
  1223. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1224. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1225. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1226. var markers = prepareCoordMarkers(el, saved);
  1227. var transformer = preparePointerTransformer(markers, saved, inverse);
  1228. if (transformer) {
  1229. transformer(out, inX, inY);
  1230. return true;
  1231. }
  1232. }
  1233. return false;
  1234. }
  1235. function prepareCoordMarkers(el, saved) {
  1236. var markers = saved.markers;
  1237. if (markers) {
  1238. return markers;
  1239. }
  1240. markers = saved.markers = [];
  1241. var propLR = ['left', 'right'];
  1242. var propTB = ['top', 'bottom'];
  1243. for (var i = 0; i < 4; i++) {
  1244. var marker = document.createElement('div');
  1245. var stl = marker.style;
  1246. var idxLR = i % 2;
  1247. var idxTB = (i >> 1) % 2;
  1248. stl.cssText = [
  1249. 'position: absolute',
  1250. 'visibility: hidden',
  1251. 'padding: 0',
  1252. 'margin: 0',
  1253. 'border-width: 0',
  1254. 'user-select: none',
  1255. 'width:0',
  1256. 'height:0',
  1257. propLR[idxLR] + ':0',
  1258. propTB[idxTB] + ':0',
  1259. propLR[1 - idxLR] + ':auto',
  1260. propTB[1 - idxTB] + ':auto',
  1261. ''
  1262. ].join('!important;');
  1263. el.appendChild(marker);
  1264. markers.push(marker);
  1265. }
  1266. return markers;
  1267. }
  1268. function preparePointerTransformer(markers, saved, inverse) {
  1269. var transformerName = inverse ? 'invTrans' : 'trans';
  1270. var transformer = saved[transformerName];
  1271. var oldSrcCoords = saved.srcCoords;
  1272. var srcCoords = [];
  1273. var destCoords = [];
  1274. var oldCoordTheSame = true;
  1275. for (var i = 0; i < 4; i++) {
  1276. var rect = markers[i].getBoundingClientRect();
  1277. var ii = 2 * i;
  1278. var x = rect.left;
  1279. var y = rect.top;
  1280. srcCoords.push(x, y);
  1281. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1282. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1283. }
  1284. return (oldCoordTheSame && transformer)
  1285. ? transformer
  1286. : (saved.srcCoords = srcCoords,
  1287. saved[transformerName] = inverse
  1288. ? buildTransformer(destCoords, srcCoords)
  1289. : buildTransformer(srcCoords, destCoords));
  1290. }
  1291. function isCanvasEl(el) {
  1292. return el.nodeName.toUpperCase() === 'CANVAS';
  1293. }
  1294. var replaceReg = /([&<>"'])/g;
  1295. var replaceMap = {
  1296. '&': '&amp;',
  1297. '<': '&lt;',
  1298. '>': '&gt;',
  1299. '"': '&quot;',
  1300. '\'': '&#39;'
  1301. };
  1302. function encodeHTML(source) {
  1303. return source == null
  1304. ? ''
  1305. : (source + '').replace(replaceReg, function (str, c) {
  1306. return replaceMap[c];
  1307. });
  1308. }
  1309. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1310. var _calcOut$1 = [];
  1311. var firefoxNotSupportOffsetXY = env.browser.firefox
  1312. && +env.browser.version.split('.')[0] < 39;
  1313. function clientToLocal(el, e, out, calculate) {
  1314. out = out || {};
  1315. if (calculate) {
  1316. calculateZrXY(el, e, out);
  1317. }
  1318. else if (firefoxNotSupportOffsetXY
  1319. && e.layerX != null
  1320. && e.layerX !== e.offsetX) {
  1321. out.zrX = e.layerX;
  1322. out.zrY = e.layerY;
  1323. }
  1324. else if (e.offsetX != null) {
  1325. out.zrX = e.offsetX;
  1326. out.zrY = e.offsetY;
  1327. }
  1328. else {
  1329. calculateZrXY(el, e, out);
  1330. }
  1331. return out;
  1332. }
  1333. function calculateZrXY(el, e, out) {
  1334. if (env.domSupported && el.getBoundingClientRect) {
  1335. var ex = e.clientX;
  1336. var ey = e.clientY;
  1337. if (isCanvasEl(el)) {
  1338. var box = el.getBoundingClientRect();
  1339. out.zrX = ex - box.left;
  1340. out.zrY = ey - box.top;
  1341. return;
  1342. }
  1343. else {
  1344. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1345. out.zrX = _calcOut$1[0];
  1346. out.zrY = _calcOut$1[1];
  1347. return;
  1348. }
  1349. }
  1350. }
  1351. out.zrX = out.zrY = 0;
  1352. }
  1353. function getNativeEvent(e) {
  1354. return e
  1355. || window.event;
  1356. }
  1357. function normalizeEvent(el, e, calculate) {
  1358. e = getNativeEvent(e);
  1359. if (e.zrX != null) {
  1360. return e;
  1361. }
  1362. var eventType = e.type;
  1363. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1364. if (!isTouch) {
  1365. clientToLocal(el, e, e, calculate);
  1366. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1367. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1368. }
  1369. else {
  1370. var touch = eventType !== 'touchend'
  1371. ? e.targetTouches[0]
  1372. : e.changedTouches[0];
  1373. touch && clientToLocal(el, touch, e, calculate);
  1374. }
  1375. var button = e.button;
  1376. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1377. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1378. }
  1379. return e;
  1380. }
  1381. function getWheelDeltaMayPolyfill(e) {
  1382. var rawWheelDelta = e.wheelDelta;
  1383. if (rawWheelDelta) {
  1384. return rawWheelDelta;
  1385. }
  1386. var deltaX = e.deltaX;
  1387. var deltaY = e.deltaY;
  1388. if (deltaX == null || deltaY == null) {
  1389. return rawWheelDelta;
  1390. }
  1391. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1392. var sign = deltaY > 0 ? -1
  1393. : deltaY < 0 ? 1
  1394. : deltaX > 0 ? -1
  1395. : 1;
  1396. return 3 * delta * sign;
  1397. }
  1398. function addEventListener(el, name, handler, opt) {
  1399. el.addEventListener(name, handler, opt);
  1400. }
  1401. function removeEventListener(el, name, handler, opt) {
  1402. el.removeEventListener(name, handler, opt);
  1403. }
  1404. var stop = function (e) {
  1405. e.preventDefault();
  1406. e.stopPropagation();
  1407. e.cancelBubble = true;
  1408. };
  1409. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1410. return e.which === 2 || e.which === 3;
  1411. }
  1412. var GestureMgr = (function () {
  1413. function GestureMgr() {
  1414. this._track = [];
  1415. }
  1416. GestureMgr.prototype.recognize = function (event, target, root) {
  1417. this._doTrack(event, target, root);
  1418. return this._recognize(event);
  1419. };
  1420. GestureMgr.prototype.clear = function () {
  1421. this._track.length = 0;
  1422. return this;
  1423. };
  1424. GestureMgr.prototype._doTrack = function (event, target, root) {
  1425. var touches = event.touches;
  1426. if (!touches) {
  1427. return;
  1428. }
  1429. var trackItem = {
  1430. points: [],
  1431. touches: [],
  1432. target: target,
  1433. event: event
  1434. };
  1435. for (var i = 0, len = touches.length; i < len; i++) {
  1436. var touch = touches[i];
  1437. var pos = clientToLocal(root, touch, {});
  1438. trackItem.points.push([pos.zrX, pos.zrY]);
  1439. trackItem.touches.push(touch);
  1440. }
  1441. this._track.push(trackItem);
  1442. };
  1443. GestureMgr.prototype._recognize = function (event) {
  1444. for (var eventName in recognizers) {
  1445. if (recognizers.hasOwnProperty(eventName)) {
  1446. var gestureInfo = recognizers[eventName](this._track, event);
  1447. if (gestureInfo) {
  1448. return gestureInfo;
  1449. }
  1450. }
  1451. }
  1452. };
  1453. return GestureMgr;
  1454. }());
  1455. function dist$1(pointPair) {
  1456. var dx = pointPair[1][0] - pointPair[0][0];
  1457. var dy = pointPair[1][1] - pointPair[0][1];
  1458. return Math.sqrt(dx * dx + dy * dy);
  1459. }
  1460. function center(pointPair) {
  1461. return [
  1462. (pointPair[0][0] + pointPair[1][0]) / 2,
  1463. (pointPair[0][1] + pointPair[1][1]) / 2
  1464. ];
  1465. }
  1466. var recognizers = {
  1467. pinch: function (tracks, event) {
  1468. var trackLen = tracks.length;
  1469. if (!trackLen) {
  1470. return;
  1471. }
  1472. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1473. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1474. if (pinchPre
  1475. && pinchPre.length > 1
  1476. && pinchEnd
  1477. && pinchEnd.length > 1) {
  1478. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1479. !isFinite(pinchScale) && (pinchScale = 1);
  1480. event.pinchScale = pinchScale;
  1481. var pinchCenter = center(pinchEnd);
  1482. event.pinchX = pinchCenter[0];
  1483. event.pinchY = pinchCenter[1];
  1484. return {
  1485. type: 'pinch',
  1486. target: tracks[0].target,
  1487. event: event
  1488. };
  1489. }
  1490. }
  1491. };
  1492. function create$1() {
  1493. return [1, 0, 0, 1, 0, 0];
  1494. }
  1495. function identity(out) {
  1496. out[0] = 1;
  1497. out[1] = 0;
  1498. out[2] = 0;
  1499. out[3] = 1;
  1500. out[4] = 0;
  1501. out[5] = 0;
  1502. return out;
  1503. }
  1504. function copy$1(out, m) {
  1505. out[0] = m[0];
  1506. out[1] = m[1];
  1507. out[2] = m[2];
  1508. out[3] = m[3];
  1509. out[4] = m[4];
  1510. out[5] = m[5];
  1511. return out;
  1512. }
  1513. function mul$1(out, m1, m2) {
  1514. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1515. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1516. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1517. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1518. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1519. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1520. out[0] = out0;
  1521. out[1] = out1;
  1522. out[2] = out2;
  1523. out[3] = out3;
  1524. out[4] = out4;
  1525. out[5] = out5;
  1526. return out;
  1527. }
  1528. function translate(out, a, v) {
  1529. out[0] = a[0];
  1530. out[1] = a[1];
  1531. out[2] = a[2];
  1532. out[3] = a[3];
  1533. out[4] = a[4] + v[0];
  1534. out[5] = a[5] + v[1];
  1535. return out;
  1536. }
  1537. function rotate(out, a, rad, pivot) {
  1538. if (pivot === void 0) { pivot = [0, 0]; }
  1539. var aa = a[0];
  1540. var ac = a[2];
  1541. var atx = a[4];
  1542. var ab = a[1];
  1543. var ad = a[3];
  1544. var aty = a[5];
  1545. var st = Math.sin(rad);
  1546. var ct = Math.cos(rad);
  1547. out[0] = aa * ct + ab * st;
  1548. out[1] = -aa * st + ab * ct;
  1549. out[2] = ac * ct + ad * st;
  1550. out[3] = -ac * st + ct * ad;
  1551. out[4] = ct * (atx - pivot[0]) + st * (aty - pivot[1]) + pivot[0];
  1552. out[5] = ct * (aty - pivot[1]) - st * (atx - pivot[0]) + pivot[1];
  1553. return out;
  1554. }
  1555. function scale$1(out, a, v) {
  1556. var vx = v[0];
  1557. var vy = v[1];
  1558. out[0] = a[0] * vx;
  1559. out[1] = a[1] * vy;
  1560. out[2] = a[2] * vx;
  1561. out[3] = a[3] * vy;
  1562. out[4] = a[4] * vx;
  1563. out[5] = a[5] * vy;
  1564. return out;
  1565. }
  1566. function invert(out, a) {
  1567. var aa = a[0];
  1568. var ac = a[2];
  1569. var atx = a[4];
  1570. var ab = a[1];
  1571. var ad = a[3];
  1572. var aty = a[5];
  1573. var det = aa * ad - ab * ac;
  1574. if (!det) {
  1575. return null;
  1576. }
  1577. det = 1.0 / det;
  1578. out[0] = ad * det;
  1579. out[1] = -ab * det;
  1580. out[2] = -ac * det;
  1581. out[3] = aa * det;
  1582. out[4] = (ac * aty - ad * atx) * det;
  1583. out[5] = (ab * atx - aa * aty) * det;
  1584. return out;
  1585. }
  1586. function clone$2(a) {
  1587. var b = create$1();
  1588. copy$1(b, a);
  1589. return b;
  1590. }
  1591. var matrix = /*#__PURE__*/Object.freeze({
  1592. __proto__: null,
  1593. create: create$1,
  1594. identity: identity,
  1595. copy: copy$1,
  1596. mul: mul$1,
  1597. translate: translate,
  1598. rotate: rotate,
  1599. scale: scale$1,
  1600. invert: invert,
  1601. clone: clone$2
  1602. });
  1603. var Point = (function () {
  1604. function Point(x, y) {
  1605. this.x = x || 0;
  1606. this.y = y || 0;
  1607. }
  1608. Point.prototype.copy = function (other) {
  1609. this.x = other.x;
  1610. this.y = other.y;
  1611. return this;
  1612. };
  1613. Point.prototype.clone = function () {
  1614. return new Point(this.x, this.y);
  1615. };
  1616. Point.prototype.set = function (x, y) {
  1617. this.x = x;
  1618. this.y = y;
  1619. return this;
  1620. };
  1621. Point.prototype.equal = function (other) {
  1622. return other.x === this.x && other.y === this.y;
  1623. };
  1624. Point.prototype.add = function (other) {
  1625. this.x += other.x;
  1626. this.y += other.y;
  1627. return this;
  1628. };
  1629. Point.prototype.scale = function (scalar) {
  1630. this.x *= scalar;
  1631. this.y *= scalar;
  1632. };
  1633. Point.prototype.scaleAndAdd = function (other, scalar) {
  1634. this.x += other.x * scalar;
  1635. this.y += other.y * scalar;
  1636. };
  1637. Point.prototype.sub = function (other) {
  1638. this.x -= other.x;
  1639. this.y -= other.y;
  1640. return this;
  1641. };
  1642. Point.prototype.dot = function (other) {
  1643. return this.x * other.x + this.y * other.y;
  1644. };
  1645. Point.prototype.len = function () {
  1646. return Math.sqrt(this.x * this.x + this.y * this.y);
  1647. };
  1648. Point.prototype.lenSquare = function () {
  1649. return this.x * this.x + this.y * this.y;
  1650. };
  1651. Point.prototype.normalize = function () {
  1652. var len = this.len();
  1653. this.x /= len;
  1654. this.y /= len;
  1655. return this;
  1656. };
  1657. Point.prototype.distance = function (other) {
  1658. var dx = this.x - other.x;
  1659. var dy = this.y - other.y;
  1660. return Math.sqrt(dx * dx + dy * dy);
  1661. };
  1662. Point.prototype.distanceSquare = function (other) {
  1663. var dx = this.x - other.x;
  1664. var dy = this.y - other.y;
  1665. return dx * dx + dy * dy;
  1666. };
  1667. Point.prototype.negate = function () {
  1668. this.x = -this.x;
  1669. this.y = -this.y;
  1670. return this;
  1671. };
  1672. Point.prototype.transform = function (m) {
  1673. if (!m) {
  1674. return;
  1675. }
  1676. var x = this.x;
  1677. var y = this.y;
  1678. this.x = m[0] * x + m[2] * y + m[4];
  1679. this.y = m[1] * x + m[3] * y + m[5];
  1680. return this;
  1681. };
  1682. Point.prototype.toArray = function (out) {
  1683. out[0] = this.x;
  1684. out[1] = this.y;
  1685. return out;
  1686. };
  1687. Point.prototype.fromArray = function (input) {
  1688. this.x = input[0];
  1689. this.y = input[1];
  1690. };
  1691. Point.set = function (p, x, y) {
  1692. p.x = x;
  1693. p.y = y;
  1694. };
  1695. Point.copy = function (p, p2) {
  1696. p.x = p2.x;
  1697. p.y = p2.y;
  1698. };
  1699. Point.len = function (p) {
  1700. return Math.sqrt(p.x * p.x + p.y * p.y);
  1701. };
  1702. Point.lenSquare = function (p) {
  1703. return p.x * p.x + p.y * p.y;
  1704. };
  1705. Point.dot = function (p0, p1) {
  1706. return p0.x * p1.x + p0.y * p1.y;
  1707. };
  1708. Point.add = function (out, p0, p1) {
  1709. out.x = p0.x + p1.x;
  1710. out.y = p0.y + p1.y;
  1711. };
  1712. Point.sub = function (out, p0, p1) {
  1713. out.x = p0.x - p1.x;
  1714. out.y = p0.y - p1.y;
  1715. };
  1716. Point.scale = function (out, p0, scalar) {
  1717. out.x = p0.x * scalar;
  1718. out.y = p0.y * scalar;
  1719. };
  1720. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1721. out.x = p0.x + p1.x * scalar;
  1722. out.y = p0.y + p1.y * scalar;
  1723. };
  1724. Point.lerp = function (out, p0, p1, t) {
  1725. var onet = 1 - t;
  1726. out.x = onet * p0.x + t * p1.x;
  1727. out.y = onet * p0.y + t * p1.y;
  1728. };
  1729. return Point;
  1730. }());
  1731. var mathMin = Math.min;
  1732. var mathMax = Math.max;
  1733. var lt = new Point();
  1734. var rb = new Point();
  1735. var lb = new Point();
  1736. var rt = new Point();
  1737. var minTv = new Point();
  1738. var maxTv = new Point();
  1739. var BoundingRect = (function () {
  1740. function BoundingRect(x, y, width, height) {
  1741. if (width < 0) {
  1742. x = x + width;
  1743. width = -width;
  1744. }
  1745. if (height < 0) {
  1746. y = y + height;
  1747. height = -height;
  1748. }
  1749. this.x = x;
  1750. this.y = y;
  1751. this.width = width;
  1752. this.height = height;
  1753. }
  1754. BoundingRect.prototype.union = function (other) {
  1755. var x = mathMin(other.x, this.x);
  1756. var y = mathMin(other.y, this.y);
  1757. if (isFinite(this.x) && isFinite(this.width)) {
  1758. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1759. }
  1760. else {
  1761. this.width = other.width;
  1762. }
  1763. if (isFinite(this.y) && isFinite(this.height)) {
  1764. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1765. }
  1766. else {
  1767. this.height = other.height;
  1768. }
  1769. this.x = x;
  1770. this.y = y;
  1771. };
  1772. BoundingRect.prototype.applyTransform = function (m) {
  1773. BoundingRect.applyTransform(this, this, m);
  1774. };
  1775. BoundingRect.prototype.calculateTransform = function (b) {
  1776. var a = this;
  1777. var sx = b.width / a.width;
  1778. var sy = b.height / a.height;
  1779. var m = create$1();
  1780. translate(m, m, [-a.x, -a.y]);
  1781. scale$1(m, m, [sx, sy]);
  1782. translate(m, m, [b.x, b.y]);
  1783. return m;
  1784. };
  1785. BoundingRect.prototype.intersect = function (b, mtv) {
  1786. if (!b) {
  1787. return false;
  1788. }
  1789. if (!(b instanceof BoundingRect)) {
  1790. b = BoundingRect.create(b);
  1791. }
  1792. var a = this;
  1793. var ax0 = a.x;
  1794. var ax1 = a.x + a.width;
  1795. var ay0 = a.y;
  1796. var ay1 = a.y + a.height;
  1797. var bx0 = b.x;
  1798. var bx1 = b.x + b.width;
  1799. var by0 = b.y;
  1800. var by1 = b.y + b.height;
  1801. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1802. if (mtv) {
  1803. var dMin = Infinity;
  1804. var dMax = 0;
  1805. var d0 = Math.abs(ax1 - bx0);
  1806. var d1 = Math.abs(bx1 - ax0);
  1807. var d2 = Math.abs(ay1 - by0);
  1808. var d3 = Math.abs(by1 - ay0);
  1809. var dx = Math.min(d0, d1);
  1810. var dy = Math.min(d2, d3);
  1811. if (ax1 < bx0 || bx1 < ax0) {
  1812. if (dx > dMax) {
  1813. dMax = dx;
  1814. if (d0 < d1) {
  1815. Point.set(maxTv, -d0, 0);
  1816. }
  1817. else {
  1818. Point.set(maxTv, d1, 0);
  1819. }
  1820. }
  1821. }
  1822. else {
  1823. if (dx < dMin) {
  1824. dMin = dx;
  1825. if (d0 < d1) {
  1826. Point.set(minTv, d0, 0);
  1827. }
  1828. else {
  1829. Point.set(minTv, -d1, 0);
  1830. }
  1831. }
  1832. }
  1833. if (ay1 < by0 || by1 < ay0) {
  1834. if (dy > dMax) {
  1835. dMax = dy;
  1836. if (d2 < d3) {
  1837. Point.set(maxTv, 0, -d2);
  1838. }
  1839. else {
  1840. Point.set(maxTv, 0, d3);
  1841. }
  1842. }
  1843. }
  1844. else {
  1845. if (dx < dMin) {
  1846. dMin = dx;
  1847. if (d2 < d3) {
  1848. Point.set(minTv, 0, d2);
  1849. }
  1850. else {
  1851. Point.set(minTv, 0, -d3);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. if (mtv) {
  1857. Point.copy(mtv, overlap ? minTv : maxTv);
  1858. }
  1859. return overlap;
  1860. };
  1861. BoundingRect.prototype.contain = function (x, y) {
  1862. var rect = this;
  1863. return x >= rect.x
  1864. && x <= (rect.x + rect.width)
  1865. && y >= rect.y
  1866. && y <= (rect.y + rect.height);
  1867. };
  1868. BoundingRect.prototype.clone = function () {
  1869. return new BoundingRect(this.x, this.y, this.width, this.height);
  1870. };
  1871. BoundingRect.prototype.copy = function (other) {
  1872. BoundingRect.copy(this, other);
  1873. };
  1874. BoundingRect.prototype.plain = function () {
  1875. return {
  1876. x: this.x,
  1877. y: this.y,
  1878. width: this.width,
  1879. height: this.height
  1880. };
  1881. };
  1882. BoundingRect.prototype.isFinite = function () {
  1883. return isFinite(this.x)
  1884. && isFinite(this.y)
  1885. && isFinite(this.width)
  1886. && isFinite(this.height);
  1887. };
  1888. BoundingRect.prototype.isZero = function () {
  1889. return this.width === 0 || this.height === 0;
  1890. };
  1891. BoundingRect.create = function (rect) {
  1892. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1893. };
  1894. BoundingRect.copy = function (target, source) {
  1895. target.x = source.x;
  1896. target.y = source.y;
  1897. target.width = source.width;
  1898. target.height = source.height;
  1899. };
  1900. BoundingRect.applyTransform = function (target, source, m) {
  1901. if (!m) {
  1902. if (target !== source) {
  1903. BoundingRect.copy(target, source);
  1904. }
  1905. return;
  1906. }
  1907. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1908. var sx = m[0];
  1909. var sy = m[3];
  1910. var tx = m[4];
  1911. var ty = m[5];
  1912. target.x = source.x * sx + tx;
  1913. target.y = source.y * sy + ty;
  1914. target.width = source.width * sx;
  1915. target.height = source.height * sy;
  1916. if (target.width < 0) {
  1917. target.x += target.width;
  1918. target.width = -target.width;
  1919. }
  1920. if (target.height < 0) {
  1921. target.y += target.height;
  1922. target.height = -target.height;
  1923. }
  1924. return;
  1925. }
  1926. lt.x = lb.x = source.x;
  1927. lt.y = rt.y = source.y;
  1928. rb.x = rt.x = source.x + source.width;
  1929. rb.y = lb.y = source.y + source.height;
  1930. lt.transform(m);
  1931. rt.transform(m);
  1932. rb.transform(m);
  1933. lb.transform(m);
  1934. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1935. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1936. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1937. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1938. target.width = maxX - target.x;
  1939. target.height = maxY - target.y;
  1940. };
  1941. return BoundingRect;
  1942. }());
  1943. var SILENT = 'silent';
  1944. function makeEventPacket(eveType, targetInfo, event) {
  1945. return {
  1946. type: eveType,
  1947. event: event,
  1948. target: targetInfo.target,
  1949. topTarget: targetInfo.topTarget,
  1950. cancelBubble: false,
  1951. offsetX: event.zrX,
  1952. offsetY: event.zrY,
  1953. gestureEvent: event.gestureEvent,
  1954. pinchX: event.pinchX,
  1955. pinchY: event.pinchY,
  1956. pinchScale: event.pinchScale,
  1957. wheelDelta: event.zrDelta,
  1958. zrByTouch: event.zrByTouch,
  1959. which: event.which,
  1960. stop: stopEvent
  1961. };
  1962. }
  1963. function stopEvent() {
  1964. stop(this.event);
  1965. }
  1966. var EmptyProxy = (function (_super) {
  1967. __extends(EmptyProxy, _super);
  1968. function EmptyProxy() {
  1969. var _this = _super !== null && _super.apply(this, arguments) || this;
  1970. _this.handler = null;
  1971. return _this;
  1972. }
  1973. EmptyProxy.prototype.dispose = function () { };
  1974. EmptyProxy.prototype.setCursor = function () { };
  1975. return EmptyProxy;
  1976. }(Eventful));
  1977. var HoveredResult = (function () {
  1978. function HoveredResult(x, y) {
  1979. this.x = x;
  1980. this.y = y;
  1981. }
  1982. return HoveredResult;
  1983. }());
  1984. var handlerNames = [
  1985. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1986. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1987. ];
  1988. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1989. var Handler = (function (_super) {
  1990. __extends(Handler, _super);
  1991. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1992. var _this = _super.call(this) || this;
  1993. _this._hovered = new HoveredResult(0, 0);
  1994. _this.storage = storage;
  1995. _this.painter = painter;
  1996. _this.painterRoot = painterRoot;
  1997. _this._pointerSize = pointerSize;
  1998. proxy = proxy || new EmptyProxy();
  1999. _this.proxy = null;
  2000. _this.setHandlerProxy(proxy);
  2001. _this._draggingMgr = new Draggable(_this);
  2002. return _this;
  2003. }
  2004. Handler.prototype.setHandlerProxy = function (proxy) {
  2005. if (this.proxy) {
  2006. this.proxy.dispose();
  2007. }
  2008. if (proxy) {
  2009. each(handlerNames, function (name) {
  2010. proxy.on && proxy.on(name, this[name], this);
  2011. }, this);
  2012. proxy.handler = this;
  2013. }
  2014. this.proxy = proxy;
  2015. };
  2016. Handler.prototype.mousemove = function (event) {
  2017. var x = event.zrX;
  2018. var y = event.zrY;
  2019. var isOutside = isOutsideBoundary(this, x, y);
  2020. var lastHovered = this._hovered;
  2021. var lastHoveredTarget = lastHovered.target;
  2022. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2023. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2024. lastHoveredTarget = lastHovered.target;
  2025. }
  2026. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2027. var hoveredTarget = hovered.target;
  2028. var proxy = this.proxy;
  2029. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2030. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2031. this.dispatchToElement(lastHovered, 'mouseout', event);
  2032. }
  2033. this.dispatchToElement(hovered, 'mousemove', event);
  2034. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2035. this.dispatchToElement(hovered, 'mouseover', event);
  2036. }
  2037. };
  2038. Handler.prototype.mouseout = function (event) {
  2039. var eventControl = event.zrEventControl;
  2040. if (eventControl !== 'only_globalout') {
  2041. this.dispatchToElement(this._hovered, 'mouseout', event);
  2042. }
  2043. if (eventControl !== 'no_globalout') {
  2044. this.trigger('globalout', { type: 'globalout', event: event });
  2045. }
  2046. };
  2047. Handler.prototype.resize = function () {
  2048. this._hovered = new HoveredResult(0, 0);
  2049. };
  2050. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2051. var handler = this[eventName];
  2052. handler && handler.call(this, eventArgs);
  2053. };
  2054. Handler.prototype.dispose = function () {
  2055. this.proxy.dispose();
  2056. this.storage = null;
  2057. this.proxy = null;
  2058. this.painter = null;
  2059. };
  2060. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2061. var proxy = this.proxy;
  2062. proxy.setCursor && proxy.setCursor(cursorStyle);
  2063. };
  2064. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2065. targetInfo = targetInfo || {};
  2066. var el = targetInfo.target;
  2067. if (el && el.silent) {
  2068. return;
  2069. }
  2070. var eventKey = ('on' + eventName);
  2071. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2072. while (el) {
  2073. el[eventKey]
  2074. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2075. el.trigger(eventName, eventPacket);
  2076. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2077. if (eventPacket.cancelBubble) {
  2078. break;
  2079. }
  2080. }
  2081. if (!eventPacket.cancelBubble) {
  2082. this.trigger(eventName, eventPacket);
  2083. if (this.painter && this.painter.eachOtherLayer) {
  2084. this.painter.eachOtherLayer(function (layer) {
  2085. if (typeof (layer[eventKey]) === 'function') {
  2086. layer[eventKey].call(layer, eventPacket);
  2087. }
  2088. if (layer.trigger) {
  2089. layer.trigger(eventName, eventPacket);
  2090. }
  2091. });
  2092. }
  2093. }
  2094. };
  2095. Handler.prototype.findHover = function (x, y, exclude) {
  2096. var list = this.storage.getDisplayList();
  2097. var out = new HoveredResult(x, y);
  2098. setHoverTarget(list, out, x, y, exclude);
  2099. if (this._pointerSize && !out.target) {
  2100. var candidates = [];
  2101. var pointerSize = this._pointerSize;
  2102. var targetSizeHalf = pointerSize / 2;
  2103. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2104. for (var i = list.length - 1; i >= 0; i--) {
  2105. var el = list[i];
  2106. if (el !== exclude
  2107. && !el.ignore
  2108. && !el.ignoreCoarsePointer
  2109. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2110. tmpRect.copy(el.getBoundingRect());
  2111. if (el.transform) {
  2112. tmpRect.applyTransform(el.transform);
  2113. }
  2114. if (tmpRect.intersect(pointerRect)) {
  2115. candidates.push(el);
  2116. }
  2117. }
  2118. }
  2119. if (candidates.length) {
  2120. var rStep = 4;
  2121. var thetaStep = Math.PI / 12;
  2122. var PI2 = Math.PI * 2;
  2123. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2124. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2125. var x1 = x + r * Math.cos(theta);
  2126. var y1 = y + r * Math.sin(theta);
  2127. setHoverTarget(candidates, out, x1, y1, exclude);
  2128. if (out.target) {
  2129. return out;
  2130. }
  2131. }
  2132. }
  2133. }
  2134. }
  2135. return out;
  2136. };
  2137. Handler.prototype.processGesture = function (event, stage) {
  2138. if (!this._gestureMgr) {
  2139. this._gestureMgr = new GestureMgr();
  2140. }
  2141. var gestureMgr = this._gestureMgr;
  2142. stage === 'start' && gestureMgr.clear();
  2143. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2144. stage === 'end' && gestureMgr.clear();
  2145. if (gestureInfo) {
  2146. var type = gestureInfo.type;
  2147. event.gestureEvent = type;
  2148. var res = new HoveredResult();
  2149. res.target = gestureInfo.target;
  2150. this.dispatchToElement(res, type, gestureInfo.event);
  2151. }
  2152. };
  2153. return Handler;
  2154. }(Eventful));
  2155. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2156. Handler.prototype[name] = function (event) {
  2157. var x = event.zrX;
  2158. var y = event.zrY;
  2159. var isOutside = isOutsideBoundary(this, x, y);
  2160. var hovered;
  2161. var hoveredTarget;
  2162. if (name !== 'mouseup' || !isOutside) {
  2163. hovered = this.findHover(x, y);
  2164. hoveredTarget = hovered.target;
  2165. }
  2166. if (name === 'mousedown') {
  2167. this._downEl = hoveredTarget;
  2168. this._downPoint = [event.zrX, event.zrY];
  2169. this._upEl = hoveredTarget;
  2170. }
  2171. else if (name === 'mouseup') {
  2172. this._upEl = hoveredTarget;
  2173. }
  2174. else if (name === 'click') {
  2175. if (this._downEl !== this._upEl
  2176. || !this._downPoint
  2177. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2178. return;
  2179. }
  2180. this._downPoint = null;
  2181. }
  2182. this.dispatchToElement(hovered, name, event);
  2183. };
  2184. });
  2185. function isHover(displayable, x, y) {
  2186. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2187. var el = displayable;
  2188. var isSilent = void 0;
  2189. var ignoreClip = false;
  2190. while (el) {
  2191. if (el.ignoreClip) {
  2192. ignoreClip = true;
  2193. }
  2194. if (!ignoreClip) {
  2195. var clipPath = el.getClipPath();
  2196. if (clipPath && !clipPath.contain(x, y)) {
  2197. return false;
  2198. }
  2199. }
  2200. if (el.silent) {
  2201. isSilent = true;
  2202. }
  2203. var hostEl = el.__hostTarget;
  2204. el = hostEl ? hostEl : el.parent;
  2205. }
  2206. return isSilent ? SILENT : true;
  2207. }
  2208. return false;
  2209. }
  2210. function setHoverTarget(list, out, x, y, exclude) {
  2211. for (var i = list.length - 1; i >= 0; i--) {
  2212. var el = list[i];
  2213. var hoverCheckResult = void 0;
  2214. if (el !== exclude
  2215. && !el.ignore
  2216. && (hoverCheckResult = isHover(el, x, y))) {
  2217. !out.topTarget && (out.topTarget = el);
  2218. if (hoverCheckResult !== SILENT) {
  2219. out.target = el;
  2220. break;
  2221. }
  2222. }
  2223. }
  2224. }
  2225. function isOutsideBoundary(handlerInstance, x, y) {
  2226. var painter = handlerInstance.painter;
  2227. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2228. }
  2229. var DEFAULT_MIN_MERGE = 32;
  2230. var DEFAULT_MIN_GALLOPING = 7;
  2231. function minRunLength(n) {
  2232. var r = 0;
  2233. while (n >= DEFAULT_MIN_MERGE) {
  2234. r |= n & 1;
  2235. n >>= 1;
  2236. }
  2237. return n + r;
  2238. }
  2239. function makeAscendingRun(array, lo, hi, compare) {
  2240. var runHi = lo + 1;
  2241. if (runHi === hi) {
  2242. return 1;
  2243. }
  2244. if (compare(array[runHi++], array[lo]) < 0) {
  2245. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2246. runHi++;
  2247. }
  2248. reverseRun(array, lo, runHi);
  2249. }
  2250. else {
  2251. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2252. runHi++;
  2253. }
  2254. }
  2255. return runHi - lo;
  2256. }
  2257. function reverseRun(array, lo, hi) {
  2258. hi--;
  2259. while (lo < hi) {
  2260. var t = array[lo];
  2261. array[lo++] = array[hi];
  2262. array[hi--] = t;
  2263. }
  2264. }
  2265. function binaryInsertionSort(array, lo, hi, start, compare) {
  2266. if (start === lo) {
  2267. start++;
  2268. }
  2269. for (; start < hi; start++) {
  2270. var pivot = array[start];
  2271. var left = lo;
  2272. var right = start;
  2273. var mid;
  2274. while (left < right) {
  2275. mid = left + right >>> 1;
  2276. if (compare(pivot, array[mid]) < 0) {
  2277. right = mid;
  2278. }
  2279. else {
  2280. left = mid + 1;
  2281. }
  2282. }
  2283. var n = start - left;
  2284. switch (n) {
  2285. case 3:
  2286. array[left + 3] = array[left + 2];
  2287. case 2:
  2288. array[left + 2] = array[left + 1];
  2289. case 1:
  2290. array[left + 1] = array[left];
  2291. break;
  2292. default:
  2293. while (n > 0) {
  2294. array[left + n] = array[left + n - 1];
  2295. n--;
  2296. }
  2297. }
  2298. array[left] = pivot;
  2299. }
  2300. }
  2301. function gallopLeft(value, array, start, length, hint, compare) {
  2302. var lastOffset = 0;
  2303. var maxOffset = 0;
  2304. var offset = 1;
  2305. if (compare(value, array[start + hint]) > 0) {
  2306. maxOffset = length - hint;
  2307. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2308. lastOffset = offset;
  2309. offset = (offset << 1) + 1;
  2310. if (offset <= 0) {
  2311. offset = maxOffset;
  2312. }
  2313. }
  2314. if (offset > maxOffset) {
  2315. offset = maxOffset;
  2316. }
  2317. lastOffset += hint;
  2318. offset += hint;
  2319. }
  2320. else {
  2321. maxOffset = hint + 1;
  2322. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2323. lastOffset = offset;
  2324. offset = (offset << 1) + 1;
  2325. if (offset <= 0) {
  2326. offset = maxOffset;
  2327. }
  2328. }
  2329. if (offset > maxOffset) {
  2330. offset = maxOffset;
  2331. }
  2332. var tmp = lastOffset;
  2333. lastOffset = hint - offset;
  2334. offset = hint - tmp;
  2335. }
  2336. lastOffset++;
  2337. while (lastOffset < offset) {
  2338. var m = lastOffset + (offset - lastOffset >>> 1);
  2339. if (compare(value, array[start + m]) > 0) {
  2340. lastOffset = m + 1;
  2341. }
  2342. else {
  2343. offset = m;
  2344. }
  2345. }
  2346. return offset;
  2347. }
  2348. function gallopRight(value, array, start, length, hint, compare) {
  2349. var lastOffset = 0;
  2350. var maxOffset = 0;
  2351. var offset = 1;
  2352. if (compare(value, array[start + hint]) < 0) {
  2353. maxOffset = hint + 1;
  2354. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2355. lastOffset = offset;
  2356. offset = (offset << 1) + 1;
  2357. if (offset <= 0) {
  2358. offset = maxOffset;
  2359. }
  2360. }
  2361. if (offset > maxOffset) {
  2362. offset = maxOffset;
  2363. }
  2364. var tmp = lastOffset;
  2365. lastOffset = hint - offset;
  2366. offset = hint - tmp;
  2367. }
  2368. else {
  2369. maxOffset = length - hint;
  2370. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2371. lastOffset = offset;
  2372. offset = (offset << 1) + 1;
  2373. if (offset <= 0) {
  2374. offset = maxOffset;
  2375. }
  2376. }
  2377. if (offset > maxOffset) {
  2378. offset = maxOffset;
  2379. }
  2380. lastOffset += hint;
  2381. offset += hint;
  2382. }
  2383. lastOffset++;
  2384. while (lastOffset < offset) {
  2385. var m = lastOffset + (offset - lastOffset >>> 1);
  2386. if (compare(value, array[start + m]) < 0) {
  2387. offset = m;
  2388. }
  2389. else {
  2390. lastOffset = m + 1;
  2391. }
  2392. }
  2393. return offset;
  2394. }
  2395. function TimSort(array, compare) {
  2396. var minGallop = DEFAULT_MIN_GALLOPING;
  2397. var runStart;
  2398. var runLength;
  2399. var stackSize = 0;
  2400. var tmp = [];
  2401. runStart = [];
  2402. runLength = [];
  2403. function pushRun(_runStart, _runLength) {
  2404. runStart[stackSize] = _runStart;
  2405. runLength[stackSize] = _runLength;
  2406. stackSize += 1;
  2407. }
  2408. function mergeRuns() {
  2409. while (stackSize > 1) {
  2410. var n = stackSize - 2;
  2411. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2412. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2413. if (runLength[n - 1] < runLength[n + 1]) {
  2414. n--;
  2415. }
  2416. }
  2417. else if (runLength[n] > runLength[n + 1]) {
  2418. break;
  2419. }
  2420. mergeAt(n);
  2421. }
  2422. }
  2423. function forceMergeRuns() {
  2424. while (stackSize > 1) {
  2425. var n = stackSize - 2;
  2426. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2427. n--;
  2428. }
  2429. mergeAt(n);
  2430. }
  2431. }
  2432. function mergeAt(i) {
  2433. var start1 = runStart[i];
  2434. var length1 = runLength[i];
  2435. var start2 = runStart[i + 1];
  2436. var length2 = runLength[i + 1];
  2437. runLength[i] = length1 + length2;
  2438. if (i === stackSize - 3) {
  2439. runStart[i + 1] = runStart[i + 2];
  2440. runLength[i + 1] = runLength[i + 2];
  2441. }
  2442. stackSize--;
  2443. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2444. start1 += k;
  2445. length1 -= k;
  2446. if (length1 === 0) {
  2447. return;
  2448. }
  2449. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2450. if (length2 === 0) {
  2451. return;
  2452. }
  2453. if (length1 <= length2) {
  2454. mergeLow(start1, length1, start2, length2);
  2455. }
  2456. else {
  2457. mergeHigh(start1, length1, start2, length2);
  2458. }
  2459. }
  2460. function mergeLow(start1, length1, start2, length2) {
  2461. var i = 0;
  2462. for (i = 0; i < length1; i++) {
  2463. tmp[i] = array[start1 + i];
  2464. }
  2465. var cursor1 = 0;
  2466. var cursor2 = start2;
  2467. var dest = start1;
  2468. array[dest++] = array[cursor2++];
  2469. if (--length2 === 0) {
  2470. for (i = 0; i < length1; i++) {
  2471. array[dest + i] = tmp[cursor1 + i];
  2472. }
  2473. return;
  2474. }
  2475. if (length1 === 1) {
  2476. for (i = 0; i < length2; i++) {
  2477. array[dest + i] = array[cursor2 + i];
  2478. }
  2479. array[dest + length2] = tmp[cursor1];
  2480. return;
  2481. }
  2482. var _minGallop = minGallop;
  2483. var count1;
  2484. var count2;
  2485. var exit;
  2486. while (1) {
  2487. count1 = 0;
  2488. count2 = 0;
  2489. exit = false;
  2490. do {
  2491. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2492. array[dest++] = array[cursor2++];
  2493. count2++;
  2494. count1 = 0;
  2495. if (--length2 === 0) {
  2496. exit = true;
  2497. break;
  2498. }
  2499. }
  2500. else {
  2501. array[dest++] = tmp[cursor1++];
  2502. count1++;
  2503. count2 = 0;
  2504. if (--length1 === 1) {
  2505. exit = true;
  2506. break;
  2507. }
  2508. }
  2509. } while ((count1 | count2) < _minGallop);
  2510. if (exit) {
  2511. break;
  2512. }
  2513. do {
  2514. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2515. if (count1 !== 0) {
  2516. for (i = 0; i < count1; i++) {
  2517. array[dest + i] = tmp[cursor1 + i];
  2518. }
  2519. dest += count1;
  2520. cursor1 += count1;
  2521. length1 -= count1;
  2522. if (length1 <= 1) {
  2523. exit = true;
  2524. break;
  2525. }
  2526. }
  2527. array[dest++] = array[cursor2++];
  2528. if (--length2 === 0) {
  2529. exit = true;
  2530. break;
  2531. }
  2532. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2533. if (count2 !== 0) {
  2534. for (i = 0; i < count2; i++) {
  2535. array[dest + i] = array[cursor2 + i];
  2536. }
  2537. dest += count2;
  2538. cursor2 += count2;
  2539. length2 -= count2;
  2540. if (length2 === 0) {
  2541. exit = true;
  2542. break;
  2543. }
  2544. }
  2545. array[dest++] = tmp[cursor1++];
  2546. if (--length1 === 1) {
  2547. exit = true;
  2548. break;
  2549. }
  2550. _minGallop--;
  2551. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2552. if (exit) {
  2553. break;
  2554. }
  2555. if (_minGallop < 0) {
  2556. _minGallop = 0;
  2557. }
  2558. _minGallop += 2;
  2559. }
  2560. minGallop = _minGallop;
  2561. minGallop < 1 && (minGallop = 1);
  2562. if (length1 === 1) {
  2563. for (i = 0; i < length2; i++) {
  2564. array[dest + i] = array[cursor2 + i];
  2565. }
  2566. array[dest + length2] = tmp[cursor1];
  2567. }
  2568. else if (length1 === 0) {
  2569. throw new Error();
  2570. }
  2571. else {
  2572. for (i = 0; i < length1; i++) {
  2573. array[dest + i] = tmp[cursor1 + i];
  2574. }
  2575. }
  2576. }
  2577. function mergeHigh(start1, length1, start2, length2) {
  2578. var i = 0;
  2579. for (i = 0; i < length2; i++) {
  2580. tmp[i] = array[start2 + i];
  2581. }
  2582. var cursor1 = start1 + length1 - 1;
  2583. var cursor2 = length2 - 1;
  2584. var dest = start2 + length2 - 1;
  2585. var customCursor = 0;
  2586. var customDest = 0;
  2587. array[dest--] = array[cursor1--];
  2588. if (--length1 === 0) {
  2589. customCursor = dest - (length2 - 1);
  2590. for (i = 0; i < length2; i++) {
  2591. array[customCursor + i] = tmp[i];
  2592. }
  2593. return;
  2594. }
  2595. if (length2 === 1) {
  2596. dest -= length1;
  2597. cursor1 -= length1;
  2598. customDest = dest + 1;
  2599. customCursor = cursor1 + 1;
  2600. for (i = length1 - 1; i >= 0; i--) {
  2601. array[customDest + i] = array[customCursor + i];
  2602. }
  2603. array[dest] = tmp[cursor2];
  2604. return;
  2605. }
  2606. var _minGallop = minGallop;
  2607. while (true) {
  2608. var count1 = 0;
  2609. var count2 = 0;
  2610. var exit = false;
  2611. do {
  2612. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2613. array[dest--] = array[cursor1--];
  2614. count1++;
  2615. count2 = 0;
  2616. if (--length1 === 0) {
  2617. exit = true;
  2618. break;
  2619. }
  2620. }
  2621. else {
  2622. array[dest--] = tmp[cursor2--];
  2623. count2++;
  2624. count1 = 0;
  2625. if (--length2 === 1) {
  2626. exit = true;
  2627. break;
  2628. }
  2629. }
  2630. } while ((count1 | count2) < _minGallop);
  2631. if (exit) {
  2632. break;
  2633. }
  2634. do {
  2635. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2636. if (count1 !== 0) {
  2637. dest -= count1;
  2638. cursor1 -= count1;
  2639. length1 -= count1;
  2640. customDest = dest + 1;
  2641. customCursor = cursor1 + 1;
  2642. for (i = count1 - 1; i >= 0; i--) {
  2643. array[customDest + i] = array[customCursor + i];
  2644. }
  2645. if (length1 === 0) {
  2646. exit = true;
  2647. break;
  2648. }
  2649. }
  2650. array[dest--] = tmp[cursor2--];
  2651. if (--length2 === 1) {
  2652. exit = true;
  2653. break;
  2654. }
  2655. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2656. if (count2 !== 0) {
  2657. dest -= count2;
  2658. cursor2 -= count2;
  2659. length2 -= count2;
  2660. customDest = dest + 1;
  2661. customCursor = cursor2 + 1;
  2662. for (i = 0; i < count2; i++) {
  2663. array[customDest + i] = tmp[customCursor + i];
  2664. }
  2665. if (length2 <= 1) {
  2666. exit = true;
  2667. break;
  2668. }
  2669. }
  2670. array[dest--] = array[cursor1--];
  2671. if (--length1 === 0) {
  2672. exit = true;
  2673. break;
  2674. }
  2675. _minGallop--;
  2676. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2677. if (exit) {
  2678. break;
  2679. }
  2680. if (_minGallop < 0) {
  2681. _minGallop = 0;
  2682. }
  2683. _minGallop += 2;
  2684. }
  2685. minGallop = _minGallop;
  2686. if (minGallop < 1) {
  2687. minGallop = 1;
  2688. }
  2689. if (length2 === 1) {
  2690. dest -= length1;
  2691. cursor1 -= length1;
  2692. customDest = dest + 1;
  2693. customCursor = cursor1 + 1;
  2694. for (i = length1 - 1; i >= 0; i--) {
  2695. array[customDest + i] = array[customCursor + i];
  2696. }
  2697. array[dest] = tmp[cursor2];
  2698. }
  2699. else if (length2 === 0) {
  2700. throw new Error();
  2701. }
  2702. else {
  2703. customCursor = dest - (length2 - 1);
  2704. for (i = 0; i < length2; i++) {
  2705. array[customCursor + i] = tmp[i];
  2706. }
  2707. }
  2708. }
  2709. return {
  2710. mergeRuns: mergeRuns,
  2711. forceMergeRuns: forceMergeRuns,
  2712. pushRun: pushRun
  2713. };
  2714. }
  2715. function sort(array, compare, lo, hi) {
  2716. if (!lo) {
  2717. lo = 0;
  2718. }
  2719. if (!hi) {
  2720. hi = array.length;
  2721. }
  2722. var remaining = hi - lo;
  2723. if (remaining < 2) {
  2724. return;
  2725. }
  2726. var runLength = 0;
  2727. if (remaining < DEFAULT_MIN_MERGE) {
  2728. runLength = makeAscendingRun(array, lo, hi, compare);
  2729. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2730. return;
  2731. }
  2732. var ts = TimSort(array, compare);
  2733. var minRun = minRunLength(remaining);
  2734. do {
  2735. runLength = makeAscendingRun(array, lo, hi, compare);
  2736. if (runLength < minRun) {
  2737. var force = remaining;
  2738. if (force > minRun) {
  2739. force = minRun;
  2740. }
  2741. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2742. runLength = force;
  2743. }
  2744. ts.pushRun(lo, runLength);
  2745. ts.mergeRuns();
  2746. remaining -= runLength;
  2747. lo += runLength;
  2748. } while (remaining !== 0);
  2749. ts.forceMergeRuns();
  2750. }
  2751. var REDRAW_BIT = 1;
  2752. var STYLE_CHANGED_BIT = 2;
  2753. var SHAPE_CHANGED_BIT = 4;
  2754. var invalidZErrorLogged = false;
  2755. function logInvalidZError() {
  2756. if (invalidZErrorLogged) {
  2757. return;
  2758. }
  2759. invalidZErrorLogged = true;
  2760. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2761. }
  2762. function shapeCompareFunc(a, b) {
  2763. if (a.zlevel === b.zlevel) {
  2764. if (a.z === b.z) {
  2765. return a.z2 - b.z2;
  2766. }
  2767. return a.z - b.z;
  2768. }
  2769. return a.zlevel - b.zlevel;
  2770. }
  2771. var Storage = (function () {
  2772. function Storage() {
  2773. this._roots = [];
  2774. this._displayList = [];
  2775. this._displayListLen = 0;
  2776. this.displayableSortFunc = shapeCompareFunc;
  2777. }
  2778. Storage.prototype.traverse = function (cb, context) {
  2779. for (var i = 0; i < this._roots.length; i++) {
  2780. this._roots[i].traverse(cb, context);
  2781. }
  2782. };
  2783. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2784. includeIgnore = includeIgnore || false;
  2785. var displayList = this._displayList;
  2786. if (update || !displayList.length) {
  2787. this.updateDisplayList(includeIgnore);
  2788. }
  2789. return displayList;
  2790. };
  2791. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2792. this._displayListLen = 0;
  2793. var roots = this._roots;
  2794. var displayList = this._displayList;
  2795. for (var i = 0, len = roots.length; i < len; i++) {
  2796. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2797. }
  2798. displayList.length = this._displayListLen;
  2799. sort(displayList, shapeCompareFunc);
  2800. };
  2801. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2802. if (el.ignore && !includeIgnore) {
  2803. return;
  2804. }
  2805. el.beforeUpdate();
  2806. el.update();
  2807. el.afterUpdate();
  2808. var userSetClipPath = el.getClipPath();
  2809. if (el.ignoreClip) {
  2810. clipPaths = null;
  2811. }
  2812. else if (userSetClipPath) {
  2813. if (clipPaths) {
  2814. clipPaths = clipPaths.slice();
  2815. }
  2816. else {
  2817. clipPaths = [];
  2818. }
  2819. var currentClipPath = userSetClipPath;
  2820. var parentClipPath = el;
  2821. while (currentClipPath) {
  2822. currentClipPath.parent = parentClipPath;
  2823. currentClipPath.updateTransform();
  2824. clipPaths.push(currentClipPath);
  2825. parentClipPath = currentClipPath;
  2826. currentClipPath = currentClipPath.getClipPath();
  2827. }
  2828. }
  2829. if (el.childrenRef) {
  2830. var children = el.childrenRef();
  2831. for (var i = 0; i < children.length; i++) {
  2832. var child = children[i];
  2833. if (el.__dirty) {
  2834. child.__dirty |= REDRAW_BIT;
  2835. }
  2836. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2837. }
  2838. el.__dirty = 0;
  2839. }
  2840. else {
  2841. var disp = el;
  2842. if (clipPaths && clipPaths.length) {
  2843. disp.__clipPaths = clipPaths;
  2844. }
  2845. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2846. disp.__clipPaths = [];
  2847. }
  2848. if (isNaN(disp.z)) {
  2849. logInvalidZError();
  2850. disp.z = 0;
  2851. }
  2852. if (isNaN(disp.z2)) {
  2853. logInvalidZError();
  2854. disp.z2 = 0;
  2855. }
  2856. if (isNaN(disp.zlevel)) {
  2857. logInvalidZError();
  2858. disp.zlevel = 0;
  2859. }
  2860. this._displayList[this._displayListLen++] = disp;
  2861. }
  2862. var decalEl = el.getDecalElement && el.getDecalElement();
  2863. if (decalEl) {
  2864. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2865. }
  2866. var textGuide = el.getTextGuideLine();
  2867. if (textGuide) {
  2868. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2869. }
  2870. var textEl = el.getTextContent();
  2871. if (textEl) {
  2872. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2873. }
  2874. };
  2875. Storage.prototype.addRoot = function (el) {
  2876. if (el.__zr && el.__zr.storage === this) {
  2877. return;
  2878. }
  2879. this._roots.push(el);
  2880. };
  2881. Storage.prototype.delRoot = function (el) {
  2882. if (el instanceof Array) {
  2883. for (var i = 0, l = el.length; i < l; i++) {
  2884. this.delRoot(el[i]);
  2885. }
  2886. return;
  2887. }
  2888. var idx = indexOf(this._roots, el);
  2889. if (idx >= 0) {
  2890. this._roots.splice(idx, 1);
  2891. }
  2892. };
  2893. Storage.prototype.delAllRoots = function () {
  2894. this._roots = [];
  2895. this._displayList = [];
  2896. this._displayListLen = 0;
  2897. return;
  2898. };
  2899. Storage.prototype.getRoots = function () {
  2900. return this._roots;
  2901. };
  2902. Storage.prototype.dispose = function () {
  2903. this._displayList = null;
  2904. this._roots = null;
  2905. };
  2906. return Storage;
  2907. }());
  2908. var requestAnimationFrame;
  2909. requestAnimationFrame = (env.hasGlobalWindow
  2910. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2911. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2912. || window.mozRequestAnimationFrame
  2913. || window.webkitRequestAnimationFrame)) || function (func) {
  2914. return setTimeout(func, 16);
  2915. };
  2916. var requestAnimationFrame$1 = requestAnimationFrame;
  2917. var easingFuncs = {
  2918. linear: function (k) {
  2919. return k;
  2920. },
  2921. quadraticIn: function (k) {
  2922. return k * k;
  2923. },
  2924. quadraticOut: function (k) {
  2925. return k * (2 - k);
  2926. },
  2927. quadraticInOut: function (k) {
  2928. if ((k *= 2) < 1) {
  2929. return 0.5 * k * k;
  2930. }
  2931. return -0.5 * (--k * (k - 2) - 1);
  2932. },
  2933. cubicIn: function (k) {
  2934. return k * k * k;
  2935. },
  2936. cubicOut: function (k) {
  2937. return --k * k * k + 1;
  2938. },
  2939. cubicInOut: function (k) {
  2940. if ((k *= 2) < 1) {
  2941. return 0.5 * k * k * k;
  2942. }
  2943. return 0.5 * ((k -= 2) * k * k + 2);
  2944. },
  2945. quarticIn: function (k) {
  2946. return k * k * k * k;
  2947. },
  2948. quarticOut: function (k) {
  2949. return 1 - (--k * k * k * k);
  2950. },
  2951. quarticInOut: function (k) {
  2952. if ((k *= 2) < 1) {
  2953. return 0.5 * k * k * k * k;
  2954. }
  2955. return -0.5 * ((k -= 2) * k * k * k - 2);
  2956. },
  2957. quinticIn: function (k) {
  2958. return k * k * k * k * k;
  2959. },
  2960. quinticOut: function (k) {
  2961. return --k * k * k * k * k + 1;
  2962. },
  2963. quinticInOut: function (k) {
  2964. if ((k *= 2) < 1) {
  2965. return 0.5 * k * k * k * k * k;
  2966. }
  2967. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2968. },
  2969. sinusoidalIn: function (k) {
  2970. return 1 - Math.cos(k * Math.PI / 2);
  2971. },
  2972. sinusoidalOut: function (k) {
  2973. return Math.sin(k * Math.PI / 2);
  2974. },
  2975. sinusoidalInOut: function (k) {
  2976. return 0.5 * (1 - Math.cos(Math.PI * k));
  2977. },
  2978. exponentialIn: function (k) {
  2979. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2980. },
  2981. exponentialOut: function (k) {
  2982. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2983. },
  2984. exponentialInOut: function (k) {
  2985. if (k === 0) {
  2986. return 0;
  2987. }
  2988. if (k === 1) {
  2989. return 1;
  2990. }
  2991. if ((k *= 2) < 1) {
  2992. return 0.5 * Math.pow(1024, k - 1);
  2993. }
  2994. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2995. },
  2996. circularIn: function (k) {
  2997. return 1 - Math.sqrt(1 - k * k);
  2998. },
  2999. circularOut: function (k) {
  3000. return Math.sqrt(1 - (--k * k));
  3001. },
  3002. circularInOut: function (k) {
  3003. if ((k *= 2) < 1) {
  3004. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3005. }
  3006. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3007. },
  3008. elasticIn: function (k) {
  3009. var s;
  3010. var a = 0.1;
  3011. var p = 0.4;
  3012. if (k === 0) {
  3013. return 0;
  3014. }
  3015. if (k === 1) {
  3016. return 1;
  3017. }
  3018. if (!a || a < 1) {
  3019. a = 1;
  3020. s = p / 4;
  3021. }
  3022. else {
  3023. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3024. }
  3025. return -(a * Math.pow(2, 10 * (k -= 1))
  3026. * Math.sin((k - s) * (2 * Math.PI) / p));
  3027. },
  3028. elasticOut: function (k) {
  3029. var s;
  3030. var a = 0.1;
  3031. var p = 0.4;
  3032. if (k === 0) {
  3033. return 0;
  3034. }
  3035. if (k === 1) {
  3036. return 1;
  3037. }
  3038. if (!a || a < 1) {
  3039. a = 1;
  3040. s = p / 4;
  3041. }
  3042. else {
  3043. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3044. }
  3045. return (a * Math.pow(2, -10 * k)
  3046. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3047. },
  3048. elasticInOut: function (k) {
  3049. var s;
  3050. var a = 0.1;
  3051. var p = 0.4;
  3052. if (k === 0) {
  3053. return 0;
  3054. }
  3055. if (k === 1) {
  3056. return 1;
  3057. }
  3058. if (!a || a < 1) {
  3059. a = 1;
  3060. s = p / 4;
  3061. }
  3062. else {
  3063. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3064. }
  3065. if ((k *= 2) < 1) {
  3066. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3067. * Math.sin((k - s) * (2 * Math.PI) / p));
  3068. }
  3069. return a * Math.pow(2, -10 * (k -= 1))
  3070. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3071. },
  3072. backIn: function (k) {
  3073. var s = 1.70158;
  3074. return k * k * ((s + 1) * k - s);
  3075. },
  3076. backOut: function (k) {
  3077. var s = 1.70158;
  3078. return --k * k * ((s + 1) * k + s) + 1;
  3079. },
  3080. backInOut: function (k) {
  3081. var s = 1.70158 * 1.525;
  3082. if ((k *= 2) < 1) {
  3083. return 0.5 * (k * k * ((s + 1) * k - s));
  3084. }
  3085. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3086. },
  3087. bounceIn: function (k) {
  3088. return 1 - easingFuncs.bounceOut(1 - k);
  3089. },
  3090. bounceOut: function (k) {
  3091. if (k < (1 / 2.75)) {
  3092. return 7.5625 * k * k;
  3093. }
  3094. else if (k < (2 / 2.75)) {
  3095. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3096. }
  3097. else if (k < (2.5 / 2.75)) {
  3098. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3099. }
  3100. else {
  3101. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3102. }
  3103. },
  3104. bounceInOut: function (k) {
  3105. if (k < 0.5) {
  3106. return easingFuncs.bounceIn(k * 2) * 0.5;
  3107. }
  3108. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3109. }
  3110. };
  3111. var mathPow = Math.pow;
  3112. var mathSqrt = Math.sqrt;
  3113. var EPSILON = 1e-8;
  3114. var EPSILON_NUMERIC = 1e-4;
  3115. var THREE_SQRT = mathSqrt(3);
  3116. var ONE_THIRD = 1 / 3;
  3117. var _v0 = create();
  3118. var _v1 = create();
  3119. var _v2 = create();
  3120. function isAroundZero(val) {
  3121. return val > -EPSILON && val < EPSILON;
  3122. }
  3123. function isNotAroundZero(val) {
  3124. return val > EPSILON || val < -EPSILON;
  3125. }
  3126. function cubicAt(p0, p1, p2, p3, t) {
  3127. var onet = 1 - t;
  3128. return onet * onet * (onet * p0 + 3 * t * p1)
  3129. + t * t * (t * p3 + 3 * onet * p2);
  3130. }
  3131. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3132. var onet = 1 - t;
  3133. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3134. + (p3 - p2) * t * t);
  3135. }
  3136. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3137. var a = p3 + 3 * (p1 - p2) - p0;
  3138. var b = 3 * (p2 - p1 * 2 + p0);
  3139. var c = 3 * (p1 - p0);
  3140. var d = p0 - val;
  3141. var A = b * b - 3 * a * c;
  3142. var B = b * c - 9 * a * d;
  3143. var C = c * c - 3 * b * d;
  3144. var n = 0;
  3145. if (isAroundZero(A) && isAroundZero(B)) {
  3146. if (isAroundZero(b)) {
  3147. roots[0] = 0;
  3148. }
  3149. else {
  3150. var t1 = -c / b;
  3151. if (t1 >= 0 && t1 <= 1) {
  3152. roots[n++] = t1;
  3153. }
  3154. }
  3155. }
  3156. else {
  3157. var disc = B * B - 4 * A * C;
  3158. if (isAroundZero(disc)) {
  3159. var K = B / A;
  3160. var t1 = -b / a + K;
  3161. var t2 = -K / 2;
  3162. if (t1 >= 0 && t1 <= 1) {
  3163. roots[n++] = t1;
  3164. }
  3165. if (t2 >= 0 && t2 <= 1) {
  3166. roots[n++] = t2;
  3167. }
  3168. }
  3169. else if (disc > 0) {
  3170. var discSqrt = mathSqrt(disc);
  3171. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3172. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3173. if (Y1 < 0) {
  3174. Y1 = -mathPow(-Y1, ONE_THIRD);
  3175. }
  3176. else {
  3177. Y1 = mathPow(Y1, ONE_THIRD);
  3178. }
  3179. if (Y2 < 0) {
  3180. Y2 = -mathPow(-Y2, ONE_THIRD);
  3181. }
  3182. else {
  3183. Y2 = mathPow(Y2, ONE_THIRD);
  3184. }
  3185. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3186. if (t1 >= 0 && t1 <= 1) {
  3187. roots[n++] = t1;
  3188. }
  3189. }
  3190. else {
  3191. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3192. var theta = Math.acos(T) / 3;
  3193. var ASqrt = mathSqrt(A);
  3194. var tmp = Math.cos(theta);
  3195. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3196. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3197. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3198. if (t1 >= 0 && t1 <= 1) {
  3199. roots[n++] = t1;
  3200. }
  3201. if (t2 >= 0 && t2 <= 1) {
  3202. roots[n++] = t2;
  3203. }
  3204. if (t3 >= 0 && t3 <= 1) {
  3205. roots[n++] = t3;
  3206. }
  3207. }
  3208. }
  3209. return n;
  3210. }
  3211. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3212. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3213. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3214. var c = 3 * p1 - 3 * p0;
  3215. var n = 0;
  3216. if (isAroundZero(a)) {
  3217. if (isNotAroundZero(b)) {
  3218. var t1 = -c / b;
  3219. if (t1 >= 0 && t1 <= 1) {
  3220. extrema[n++] = t1;
  3221. }
  3222. }
  3223. }
  3224. else {
  3225. var disc = b * b - 4 * a * c;
  3226. if (isAroundZero(disc)) {
  3227. extrema[0] = -b / (2 * a);
  3228. }
  3229. else if (disc > 0) {
  3230. var discSqrt = mathSqrt(disc);
  3231. var t1 = (-b + discSqrt) / (2 * a);
  3232. var t2 = (-b - discSqrt) / (2 * a);
  3233. if (t1 >= 0 && t1 <= 1) {
  3234. extrema[n++] = t1;
  3235. }
  3236. if (t2 >= 0 && t2 <= 1) {
  3237. extrema[n++] = t2;
  3238. }
  3239. }
  3240. }
  3241. return n;
  3242. }
  3243. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3244. var p01 = (p1 - p0) * t + p0;
  3245. var p12 = (p2 - p1) * t + p1;
  3246. var p23 = (p3 - p2) * t + p2;
  3247. var p012 = (p12 - p01) * t + p01;
  3248. var p123 = (p23 - p12) * t + p12;
  3249. var p0123 = (p123 - p012) * t + p012;
  3250. out[0] = p0;
  3251. out[1] = p01;
  3252. out[2] = p012;
  3253. out[3] = p0123;
  3254. out[4] = p0123;
  3255. out[5] = p123;
  3256. out[6] = p23;
  3257. out[7] = p3;
  3258. }
  3259. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3260. var t;
  3261. var interval = 0.005;
  3262. var d = Infinity;
  3263. var prev;
  3264. var next;
  3265. var d1;
  3266. var d2;
  3267. _v0[0] = x;
  3268. _v0[1] = y;
  3269. for (var _t = 0; _t < 1; _t += 0.05) {
  3270. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3271. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3272. d1 = distSquare(_v0, _v1);
  3273. if (d1 < d) {
  3274. t = _t;
  3275. d = d1;
  3276. }
  3277. }
  3278. d = Infinity;
  3279. for (var i = 0; i < 32; i++) {
  3280. if (interval < EPSILON_NUMERIC) {
  3281. break;
  3282. }
  3283. prev = t - interval;
  3284. next = t + interval;
  3285. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3286. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3287. d1 = distSquare(_v1, _v0);
  3288. if (prev >= 0 && d1 < d) {
  3289. t = prev;
  3290. d = d1;
  3291. }
  3292. else {
  3293. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3294. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3295. d2 = distSquare(_v2, _v0);
  3296. if (next <= 1 && d2 < d) {
  3297. t = next;
  3298. d = d2;
  3299. }
  3300. else {
  3301. interval *= 0.5;
  3302. }
  3303. }
  3304. }
  3305. if (out) {
  3306. out[0] = cubicAt(x0, x1, x2, x3, t);
  3307. out[1] = cubicAt(y0, y1, y2, y3, t);
  3308. }
  3309. return mathSqrt(d);
  3310. }
  3311. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3312. var px = x0;
  3313. var py = y0;
  3314. var d = 0;
  3315. var step = 1 / iteration;
  3316. for (var i = 1; i <= iteration; i++) {
  3317. var t = i * step;
  3318. var x = cubicAt(x0, x1, x2, x3, t);
  3319. var y = cubicAt(y0, y1, y2, y3, t);
  3320. var dx = x - px;
  3321. var dy = y - py;
  3322. d += Math.sqrt(dx * dx + dy * dy);
  3323. px = x;
  3324. py = y;
  3325. }
  3326. return d;
  3327. }
  3328. function quadraticAt(p0, p1, p2, t) {
  3329. var onet = 1 - t;
  3330. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3331. }
  3332. function quadraticDerivativeAt(p0, p1, p2, t) {
  3333. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3334. }
  3335. function quadraticRootAt(p0, p1, p2, val, roots) {
  3336. var a = p0 - 2 * p1 + p2;
  3337. var b = 2 * (p1 - p0);
  3338. var c = p0 - val;
  3339. var n = 0;
  3340. if (isAroundZero(a)) {
  3341. if (isNotAroundZero(b)) {
  3342. var t1 = -c / b;
  3343. if (t1 >= 0 && t1 <= 1) {
  3344. roots[n++] = t1;
  3345. }
  3346. }
  3347. }
  3348. else {
  3349. var disc = b * b - 4 * a * c;
  3350. if (isAroundZero(disc)) {
  3351. var t1 = -b / (2 * a);
  3352. if (t1 >= 0 && t1 <= 1) {
  3353. roots[n++] = t1;
  3354. }
  3355. }
  3356. else if (disc > 0) {
  3357. var discSqrt = mathSqrt(disc);
  3358. var t1 = (-b + discSqrt) / (2 * a);
  3359. var t2 = (-b - discSqrt) / (2 * a);
  3360. if (t1 >= 0 && t1 <= 1) {
  3361. roots[n++] = t1;
  3362. }
  3363. if (t2 >= 0 && t2 <= 1) {
  3364. roots[n++] = t2;
  3365. }
  3366. }
  3367. }
  3368. return n;
  3369. }
  3370. function quadraticExtremum(p0, p1, p2) {
  3371. var divider = p0 + p2 - 2 * p1;
  3372. if (divider === 0) {
  3373. return 0.5;
  3374. }
  3375. else {
  3376. return (p0 - p1) / divider;
  3377. }
  3378. }
  3379. function quadraticSubdivide(p0, p1, p2, t, out) {
  3380. var p01 = (p1 - p0) * t + p0;
  3381. var p12 = (p2 - p1) * t + p1;
  3382. var p012 = (p12 - p01) * t + p01;
  3383. out[0] = p0;
  3384. out[1] = p01;
  3385. out[2] = p012;
  3386. out[3] = p012;
  3387. out[4] = p12;
  3388. out[5] = p2;
  3389. }
  3390. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3391. var t;
  3392. var interval = 0.005;
  3393. var d = Infinity;
  3394. _v0[0] = x;
  3395. _v0[1] = y;
  3396. for (var _t = 0; _t < 1; _t += 0.05) {
  3397. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3398. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3399. var d1 = distSquare(_v0, _v1);
  3400. if (d1 < d) {
  3401. t = _t;
  3402. d = d1;
  3403. }
  3404. }
  3405. d = Infinity;
  3406. for (var i = 0; i < 32; i++) {
  3407. if (interval < EPSILON_NUMERIC) {
  3408. break;
  3409. }
  3410. var prev = t - interval;
  3411. var next = t + interval;
  3412. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3413. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3414. var d1 = distSquare(_v1, _v0);
  3415. if (prev >= 0 && d1 < d) {
  3416. t = prev;
  3417. d = d1;
  3418. }
  3419. else {
  3420. _v2[0] = quadraticAt(x0, x1, x2, next);
  3421. _v2[1] = quadraticAt(y0, y1, y2, next);
  3422. var d2 = distSquare(_v2, _v0);
  3423. if (next <= 1 && d2 < d) {
  3424. t = next;
  3425. d = d2;
  3426. }
  3427. else {
  3428. interval *= 0.5;
  3429. }
  3430. }
  3431. }
  3432. if (out) {
  3433. out[0] = quadraticAt(x0, x1, x2, t);
  3434. out[1] = quadraticAt(y0, y1, y2, t);
  3435. }
  3436. return mathSqrt(d);
  3437. }
  3438. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3439. var px = x0;
  3440. var py = y0;
  3441. var d = 0;
  3442. var step = 1 / iteration;
  3443. for (var i = 1; i <= iteration; i++) {
  3444. var t = i * step;
  3445. var x = quadraticAt(x0, x1, x2, t);
  3446. var y = quadraticAt(y0, y1, y2, t);
  3447. var dx = x - px;
  3448. var dy = y - py;
  3449. d += Math.sqrt(dx * dx + dy * dy);
  3450. px = x;
  3451. py = y;
  3452. }
  3453. return d;
  3454. }
  3455. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3456. function createCubicEasingFunc(cubicEasingStr) {
  3457. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3458. if (cubic) {
  3459. var points = cubic[1].split(',');
  3460. var a_1 = +trim(points[0]);
  3461. var b_1 = +trim(points[1]);
  3462. var c_1 = +trim(points[2]);
  3463. var d_1 = +trim(points[3]);
  3464. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3465. return;
  3466. }
  3467. var roots_1 = [];
  3468. return function (p) {
  3469. return p <= 0
  3470. ? 0 : p >= 1
  3471. ? 1
  3472. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3473. };
  3474. }
  3475. }
  3476. var Clip = (function () {
  3477. function Clip(opts) {
  3478. this._inited = false;
  3479. this._startTime = 0;
  3480. this._pausedTime = 0;
  3481. this._paused = false;
  3482. this._life = opts.life || 1000;
  3483. this._delay = opts.delay || 0;
  3484. this.loop = opts.loop || false;
  3485. this.onframe = opts.onframe || noop;
  3486. this.ondestroy = opts.ondestroy || noop;
  3487. this.onrestart = opts.onrestart || noop;
  3488. opts.easing && this.setEasing(opts.easing);
  3489. }
  3490. Clip.prototype.step = function (globalTime, deltaTime) {
  3491. if (!this._inited) {
  3492. this._startTime = globalTime + this._delay;
  3493. this._inited = true;
  3494. }
  3495. if (this._paused) {
  3496. this._pausedTime += deltaTime;
  3497. return;
  3498. }
  3499. var life = this._life;
  3500. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3501. var percent = elapsedTime / life;
  3502. if (percent < 0) {
  3503. percent = 0;
  3504. }
  3505. percent = Math.min(percent, 1);
  3506. var easingFunc = this.easingFunc;
  3507. var schedule = easingFunc ? easingFunc(percent) : percent;
  3508. this.onframe(schedule);
  3509. if (percent === 1) {
  3510. if (this.loop) {
  3511. var remainder = elapsedTime % life;
  3512. this._startTime = globalTime - remainder;
  3513. this._pausedTime = 0;
  3514. this.onrestart();
  3515. }
  3516. else {
  3517. return true;
  3518. }
  3519. }
  3520. return false;
  3521. };
  3522. Clip.prototype.pause = function () {
  3523. this._paused = true;
  3524. };
  3525. Clip.prototype.resume = function () {
  3526. this._paused = false;
  3527. };
  3528. Clip.prototype.setEasing = function (easing) {
  3529. this.easing = easing;
  3530. this.easingFunc = isFunction(easing)
  3531. ? easing
  3532. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3533. };
  3534. return Clip;
  3535. }());
  3536. var Entry = (function () {
  3537. function Entry(val) {
  3538. this.value = val;
  3539. }
  3540. return Entry;
  3541. }());
  3542. var LinkedList = (function () {
  3543. function LinkedList() {
  3544. this._len = 0;
  3545. }
  3546. LinkedList.prototype.insert = function (val) {
  3547. var entry = new Entry(val);
  3548. this.insertEntry(entry);
  3549. return entry;
  3550. };
  3551. LinkedList.prototype.insertEntry = function (entry) {
  3552. if (!this.head) {
  3553. this.head = this.tail = entry;
  3554. }
  3555. else {
  3556. this.tail.next = entry;
  3557. entry.prev = this.tail;
  3558. entry.next = null;
  3559. this.tail = entry;
  3560. }
  3561. this._len++;
  3562. };
  3563. LinkedList.prototype.remove = function (entry) {
  3564. var prev = entry.prev;
  3565. var next = entry.next;
  3566. if (prev) {
  3567. prev.next = next;
  3568. }
  3569. else {
  3570. this.head = next;
  3571. }
  3572. if (next) {
  3573. next.prev = prev;
  3574. }
  3575. else {
  3576. this.tail = prev;
  3577. }
  3578. entry.next = entry.prev = null;
  3579. this._len--;
  3580. };
  3581. LinkedList.prototype.len = function () {
  3582. return this._len;
  3583. };
  3584. LinkedList.prototype.clear = function () {
  3585. this.head = this.tail = null;
  3586. this._len = 0;
  3587. };
  3588. return LinkedList;
  3589. }());
  3590. var LRU = (function () {
  3591. function LRU(maxSize) {
  3592. this._list = new LinkedList();
  3593. this._maxSize = 10;
  3594. this._map = {};
  3595. this._maxSize = maxSize;
  3596. }
  3597. LRU.prototype.put = function (key, value) {
  3598. var list = this._list;
  3599. var map = this._map;
  3600. var removed = null;
  3601. if (map[key] == null) {
  3602. var len = list.len();
  3603. var entry = this._lastRemovedEntry;
  3604. if (len >= this._maxSize && len > 0) {
  3605. var leastUsedEntry = list.head;
  3606. list.remove(leastUsedEntry);
  3607. delete map[leastUsedEntry.key];
  3608. removed = leastUsedEntry.value;
  3609. this._lastRemovedEntry = leastUsedEntry;
  3610. }
  3611. if (entry) {
  3612. entry.value = value;
  3613. }
  3614. else {
  3615. entry = new Entry(value);
  3616. }
  3617. entry.key = key;
  3618. list.insertEntry(entry);
  3619. map[key] = entry;
  3620. }
  3621. return removed;
  3622. };
  3623. LRU.prototype.get = function (key) {
  3624. var entry = this._map[key];
  3625. var list = this._list;
  3626. if (entry != null) {
  3627. if (entry !== list.tail) {
  3628. list.remove(entry);
  3629. list.insertEntry(entry);
  3630. }
  3631. return entry.value;
  3632. }
  3633. };
  3634. LRU.prototype.clear = function () {
  3635. this._list.clear();
  3636. this._map = {};
  3637. };
  3638. LRU.prototype.len = function () {
  3639. return this._list.len();
  3640. };
  3641. return LRU;
  3642. }());
  3643. var kCSSColorTable = {
  3644. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3645. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3646. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3647. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3648. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3649. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3650. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3651. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3652. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3653. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3654. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3655. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3656. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3657. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3658. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3659. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3660. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3661. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3662. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3663. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3664. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3665. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3666. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3667. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3668. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3669. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3670. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3671. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3672. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3673. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3674. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3675. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3676. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3677. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3678. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3679. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3680. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3681. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3682. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3683. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3684. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3685. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3686. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3687. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3688. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3689. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3690. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3691. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3692. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3693. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3694. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3695. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3696. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3697. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3698. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3699. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3700. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3701. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3702. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3703. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3704. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3705. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3706. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3707. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3708. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3709. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3710. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3711. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3712. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3713. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3714. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3715. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3716. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3717. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3718. };
  3719. function clampCssByte(i) {
  3720. i = Math.round(i);
  3721. return i < 0 ? 0 : i > 255 ? 255 : i;
  3722. }
  3723. function clampCssAngle(i) {
  3724. i = Math.round(i);
  3725. return i < 0 ? 0 : i > 360 ? 360 : i;
  3726. }
  3727. function clampCssFloat(f) {
  3728. return f < 0 ? 0 : f > 1 ? 1 : f;
  3729. }
  3730. function parseCssInt(val) {
  3731. var str = val;
  3732. if (str.length && str.charAt(str.length - 1) === '%') {
  3733. return clampCssByte(parseFloat(str) / 100 * 255);
  3734. }
  3735. return clampCssByte(parseInt(str, 10));
  3736. }
  3737. function parseCssFloat(val) {
  3738. var str = val;
  3739. if (str.length && str.charAt(str.length - 1) === '%') {
  3740. return clampCssFloat(parseFloat(str) / 100);
  3741. }
  3742. return clampCssFloat(parseFloat(str));
  3743. }
  3744. function cssHueToRgb(m1, m2, h) {
  3745. if (h < 0) {
  3746. h += 1;
  3747. }
  3748. else if (h > 1) {
  3749. h -= 1;
  3750. }
  3751. if (h * 6 < 1) {
  3752. return m1 + (m2 - m1) * h * 6;
  3753. }
  3754. if (h * 2 < 1) {
  3755. return m2;
  3756. }
  3757. if (h * 3 < 2) {
  3758. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3759. }
  3760. return m1;
  3761. }
  3762. function lerpNumber(a, b, p) {
  3763. return a + (b - a) * p;
  3764. }
  3765. function setRgba(out, r, g, b, a) {
  3766. out[0] = r;
  3767. out[1] = g;
  3768. out[2] = b;
  3769. out[3] = a;
  3770. return out;
  3771. }
  3772. function copyRgba(out, a) {
  3773. out[0] = a[0];
  3774. out[1] = a[1];
  3775. out[2] = a[2];
  3776. out[3] = a[3];
  3777. return out;
  3778. }
  3779. var colorCache = new LRU(20);
  3780. var lastRemovedArr = null;
  3781. function putToCache(colorStr, rgbaArr) {
  3782. if (lastRemovedArr) {
  3783. copyRgba(lastRemovedArr, rgbaArr);
  3784. }
  3785. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3786. }
  3787. function parse(colorStr, rgbaArr) {
  3788. if (!colorStr) {
  3789. return;
  3790. }
  3791. rgbaArr = rgbaArr || [];
  3792. var cached = colorCache.get(colorStr);
  3793. if (cached) {
  3794. return copyRgba(rgbaArr, cached);
  3795. }
  3796. colorStr = colorStr + '';
  3797. var str = colorStr.replace(/ /g, '').toLowerCase();
  3798. if (str in kCSSColorTable) {
  3799. copyRgba(rgbaArr, kCSSColorTable[str]);
  3800. putToCache(colorStr, rgbaArr);
  3801. return rgbaArr;
  3802. }
  3803. var strLen = str.length;
  3804. if (str.charAt(0) === '#') {
  3805. if (strLen === 4 || strLen === 5) {
  3806. var iv = parseInt(str.slice(1, 4), 16);
  3807. if (!(iv >= 0 && iv <= 0xfff)) {
  3808. setRgba(rgbaArr, 0, 0, 0, 1);
  3809. return;
  3810. }
  3811. setRgba(rgbaArr, ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), strLen === 5 ? parseInt(str.slice(4), 16) / 0xf : 1);
  3812. putToCache(colorStr, rgbaArr);
  3813. return rgbaArr;
  3814. }
  3815. else if (strLen === 7 || strLen === 9) {
  3816. var iv = parseInt(str.slice(1, 7), 16);
  3817. if (!(iv >= 0 && iv <= 0xffffff)) {
  3818. setRgba(rgbaArr, 0, 0, 0, 1);
  3819. return;
  3820. }
  3821. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3822. putToCache(colorStr, rgbaArr);
  3823. return rgbaArr;
  3824. }
  3825. return;
  3826. }
  3827. var op = str.indexOf('(');
  3828. var ep = str.indexOf(')');
  3829. if (op !== -1 && ep + 1 === strLen) {
  3830. var fname = str.substr(0, op);
  3831. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3832. var alpha = 1;
  3833. switch (fname) {
  3834. case 'rgba':
  3835. if (params.length !== 4) {
  3836. return params.length === 3
  3837. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3838. : setRgba(rgbaArr, 0, 0, 0, 1);
  3839. }
  3840. alpha = parseCssFloat(params.pop());
  3841. case 'rgb':
  3842. if (params.length >= 3) {
  3843. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3844. putToCache(colorStr, rgbaArr);
  3845. return rgbaArr;
  3846. }
  3847. else {
  3848. setRgba(rgbaArr, 0, 0, 0, 1);
  3849. return;
  3850. }
  3851. case 'hsla':
  3852. if (params.length !== 4) {
  3853. setRgba(rgbaArr, 0, 0, 0, 1);
  3854. return;
  3855. }
  3856. params[3] = parseCssFloat(params[3]);
  3857. hsla2rgba(params, rgbaArr);
  3858. putToCache(colorStr, rgbaArr);
  3859. return rgbaArr;
  3860. case 'hsl':
  3861. if (params.length !== 3) {
  3862. setRgba(rgbaArr, 0, 0, 0, 1);
  3863. return;
  3864. }
  3865. hsla2rgba(params, rgbaArr);
  3866. putToCache(colorStr, rgbaArr);
  3867. return rgbaArr;
  3868. default:
  3869. return;
  3870. }
  3871. }
  3872. setRgba(rgbaArr, 0, 0, 0, 1);
  3873. return;
  3874. }
  3875. function hsla2rgba(hsla, rgba) {
  3876. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3877. var s = parseCssFloat(hsla[1]);
  3878. var l = parseCssFloat(hsla[2]);
  3879. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3880. var m1 = l * 2 - m2;
  3881. rgba = rgba || [];
  3882. setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1);
  3883. if (hsla.length === 4) {
  3884. rgba[3] = hsla[3];
  3885. }
  3886. return rgba;
  3887. }
  3888. function rgba2hsla(rgba) {
  3889. if (!rgba) {
  3890. return;
  3891. }
  3892. var R = rgba[0] / 255;
  3893. var G = rgba[1] / 255;
  3894. var B = rgba[2] / 255;
  3895. var vMin = Math.min(R, G, B);
  3896. var vMax = Math.max(R, G, B);
  3897. var delta = vMax - vMin;
  3898. var L = (vMax + vMin) / 2;
  3899. var H;
  3900. var S;
  3901. if (delta === 0) {
  3902. H = 0;
  3903. S = 0;
  3904. }
  3905. else {
  3906. if (L < 0.5) {
  3907. S = delta / (vMax + vMin);
  3908. }
  3909. else {
  3910. S = delta / (2 - vMax - vMin);
  3911. }
  3912. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3913. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3914. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3915. if (R === vMax) {
  3916. H = deltaB - deltaG;
  3917. }
  3918. else if (G === vMax) {
  3919. H = (1 / 3) + deltaR - deltaB;
  3920. }
  3921. else if (B === vMax) {
  3922. H = (2 / 3) + deltaG - deltaR;
  3923. }
  3924. if (H < 0) {
  3925. H += 1;
  3926. }
  3927. if (H > 1) {
  3928. H -= 1;
  3929. }
  3930. }
  3931. var hsla = [H * 360, S, L];
  3932. if (rgba[3] != null) {
  3933. hsla.push(rgba[3]);
  3934. }
  3935. return hsla;
  3936. }
  3937. function lift(color, level) {
  3938. var colorArr = parse(color);
  3939. if (colorArr) {
  3940. for (var i = 0; i < 3; i++) {
  3941. if (level < 0) {
  3942. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3943. }
  3944. else {
  3945. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3946. }
  3947. if (colorArr[i] > 255) {
  3948. colorArr[i] = 255;
  3949. }
  3950. else if (colorArr[i] < 0) {
  3951. colorArr[i] = 0;
  3952. }
  3953. }
  3954. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3955. }
  3956. }
  3957. function toHex(color) {
  3958. var colorArr = parse(color);
  3959. if (colorArr) {
  3960. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3961. }
  3962. }
  3963. function fastLerp(normalizedValue, colors, out) {
  3964. if (!(colors && colors.length)
  3965. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3966. return;
  3967. }
  3968. out = out || [];
  3969. var value = normalizedValue * (colors.length - 1);
  3970. var leftIndex = Math.floor(value);
  3971. var rightIndex = Math.ceil(value);
  3972. var leftColor = colors[leftIndex];
  3973. var rightColor = colors[rightIndex];
  3974. var dv = value - leftIndex;
  3975. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3976. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3977. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3978. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3979. return out;
  3980. }
  3981. var fastMapToColor = fastLerp;
  3982. function lerp$1(normalizedValue, colors, fullOutput) {
  3983. if (!(colors && colors.length)
  3984. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3985. return;
  3986. }
  3987. var value = normalizedValue * (colors.length - 1);
  3988. var leftIndex = Math.floor(value);
  3989. var rightIndex = Math.ceil(value);
  3990. var leftColor = parse(colors[leftIndex]);
  3991. var rightColor = parse(colors[rightIndex]);
  3992. var dv = value - leftIndex;
  3993. var color = stringify([
  3994. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3995. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3996. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3997. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3998. ], 'rgba');
  3999. return fullOutput
  4000. ? {
  4001. color: color,
  4002. leftIndex: leftIndex,
  4003. rightIndex: rightIndex,
  4004. value: value
  4005. }
  4006. : color;
  4007. }
  4008. var mapToColor = lerp$1;
  4009. function modifyHSL(color, h, s, l) {
  4010. var colorArr = parse(color);
  4011. if (color) {
  4012. colorArr = rgba2hsla(colorArr);
  4013. h != null && (colorArr[0] = clampCssAngle(h));
  4014. s != null && (colorArr[1] = parseCssFloat(s));
  4015. l != null && (colorArr[2] = parseCssFloat(l));
  4016. return stringify(hsla2rgba(colorArr), 'rgba');
  4017. }
  4018. }
  4019. function modifyAlpha(color, alpha) {
  4020. var colorArr = parse(color);
  4021. if (colorArr && alpha != null) {
  4022. colorArr[3] = clampCssFloat(alpha);
  4023. return stringify(colorArr, 'rgba');
  4024. }
  4025. }
  4026. function stringify(arrColor, type) {
  4027. if (!arrColor || !arrColor.length) {
  4028. return;
  4029. }
  4030. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4031. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4032. colorStr += ',' + arrColor[3];
  4033. }
  4034. return type + '(' + colorStr + ')';
  4035. }
  4036. function lum(color, backgroundLum) {
  4037. var arr = parse(color);
  4038. return arr
  4039. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4040. + (1 - arr[3]) * backgroundLum
  4041. : 0;
  4042. }
  4043. function random() {
  4044. return stringify([
  4045. Math.round(Math.random() * 255),
  4046. Math.round(Math.random() * 255),
  4047. Math.round(Math.random() * 255)
  4048. ], 'rgb');
  4049. }
  4050. var liftedColorCache = new LRU(100);
  4051. function liftColor(color) {
  4052. if (isString(color)) {
  4053. var liftedColor = liftedColorCache.get(color);
  4054. if (!liftedColor) {
  4055. liftedColor = lift(color, -0.1);
  4056. liftedColorCache.put(color, liftedColor);
  4057. }
  4058. return liftedColor;
  4059. }
  4060. else if (isGradientObject(color)) {
  4061. var ret = extend({}, color);
  4062. ret.colorStops = map(color.colorStops, function (stop) { return ({
  4063. offset: stop.offset,
  4064. color: lift(stop.color, -0.1)
  4065. }); });
  4066. return ret;
  4067. }
  4068. return color;
  4069. }
  4070. var color = /*#__PURE__*/Object.freeze({
  4071. __proto__: null,
  4072. parse: parse,
  4073. lift: lift,
  4074. toHex: toHex,
  4075. fastLerp: fastLerp,
  4076. fastMapToColor: fastMapToColor,
  4077. lerp: lerp$1,
  4078. mapToColor: mapToColor,
  4079. modifyHSL: modifyHSL,
  4080. modifyAlpha: modifyAlpha,
  4081. stringify: stringify,
  4082. lum: lum,
  4083. random: random,
  4084. liftColor: liftColor
  4085. });
  4086. var mathRound = Math.round;
  4087. function normalizeColor(color) {
  4088. var opacity;
  4089. if (!color || color === 'transparent') {
  4090. color = 'none';
  4091. }
  4092. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4093. var arr = parse(color);
  4094. if (arr) {
  4095. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4096. opacity = arr[3];
  4097. }
  4098. }
  4099. return {
  4100. color: color,
  4101. opacity: opacity == null ? 1 : opacity
  4102. };
  4103. }
  4104. var EPSILON$1 = 1e-4;
  4105. function isAroundZero$1(transform) {
  4106. return transform < EPSILON$1 && transform > -EPSILON$1;
  4107. }
  4108. function round3(transform) {
  4109. return mathRound(transform * 1e3) / 1e3;
  4110. }
  4111. function round4(transform) {
  4112. return mathRound(transform * 1e4) / 1e4;
  4113. }
  4114. function getMatrixStr(m) {
  4115. return 'matrix('
  4116. + round3(m[0]) + ','
  4117. + round3(m[1]) + ','
  4118. + round3(m[2]) + ','
  4119. + round3(m[3]) + ','
  4120. + round4(m[4]) + ','
  4121. + round4(m[5])
  4122. + ')';
  4123. }
  4124. var TEXT_ALIGN_TO_ANCHOR = {
  4125. left: 'start',
  4126. right: 'end',
  4127. center: 'middle',
  4128. middle: 'middle'
  4129. };
  4130. function adjustTextY(y, lineHeight, textBaseline) {
  4131. if (textBaseline === 'top') {
  4132. y += lineHeight / 2;
  4133. }
  4134. else if (textBaseline === 'bottom') {
  4135. y -= lineHeight / 2;
  4136. }
  4137. return y;
  4138. }
  4139. function hasShadow(style) {
  4140. return style
  4141. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4142. }
  4143. function getShadowKey(displayable) {
  4144. var style = displayable.style;
  4145. var globalScale = displayable.getGlobalScale();
  4146. return [
  4147. style.shadowColor,
  4148. (style.shadowBlur || 0).toFixed(2),
  4149. (style.shadowOffsetX || 0).toFixed(2),
  4150. (style.shadowOffsetY || 0).toFixed(2),
  4151. globalScale[0],
  4152. globalScale[1]
  4153. ].join(',');
  4154. }
  4155. function isImagePattern(val) {
  4156. return val && (!!val.image);
  4157. }
  4158. function isSVGPattern(val) {
  4159. return val && (!!val.svgElement);
  4160. }
  4161. function isPattern(val) {
  4162. return isImagePattern(val) || isSVGPattern(val);
  4163. }
  4164. function isLinearGradient(val) {
  4165. return val.type === 'linear';
  4166. }
  4167. function isRadialGradient(val) {
  4168. return val.type === 'radial';
  4169. }
  4170. function isGradient(val) {
  4171. return val && (val.type === 'linear'
  4172. || val.type === 'radial');
  4173. }
  4174. function getIdURL(id) {
  4175. return "url(#" + id + ")";
  4176. }
  4177. function getPathPrecision(el) {
  4178. var scale = el.getGlobalScale();
  4179. var size = Math.max(scale[0], scale[1]);
  4180. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4181. }
  4182. function getSRTTransformString(transform) {
  4183. var x = transform.x || 0;
  4184. var y = transform.y || 0;
  4185. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4186. var scaleX = retrieve2(transform.scaleX, 1);
  4187. var scaleY = retrieve2(transform.scaleY, 1);
  4188. var skewX = transform.skewX || 0;
  4189. var skewY = transform.skewY || 0;
  4190. var res = [];
  4191. if (x || y) {
  4192. res.push("translate(" + x + "px," + y + "px)");
  4193. }
  4194. if (rotation) {
  4195. res.push("rotate(" + rotation + ")");
  4196. }
  4197. if (scaleX !== 1 || scaleY !== 1) {
  4198. res.push("scale(" + scaleX + "," + scaleY + ")");
  4199. }
  4200. if (skewX || skewY) {
  4201. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4202. }
  4203. return res.join(' ');
  4204. }
  4205. var encodeBase64 = (function () {
  4206. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4207. return function (str) {
  4208. return window.btoa(unescape(encodeURIComponent(str)));
  4209. };
  4210. }
  4211. if (typeof Buffer !== 'undefined') {
  4212. return function (str) {
  4213. return Buffer.from(str).toString('base64');
  4214. };
  4215. }
  4216. return function (str) {
  4217. if ("development" !== 'production') {
  4218. logError('Base64 isn\'t natively supported in the current environment.');
  4219. }
  4220. return null;
  4221. };
  4222. })();
  4223. var arraySlice = Array.prototype.slice;
  4224. function interpolateNumber(p0, p1, percent) {
  4225. return (p1 - p0) * percent + p0;
  4226. }
  4227. function interpolate1DArray(out, p0, p1, percent) {
  4228. var len = p0.length;
  4229. for (var i = 0; i < len; i++) {
  4230. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4231. }
  4232. return out;
  4233. }
  4234. function interpolate2DArray(out, p0, p1, percent) {
  4235. var len = p0.length;
  4236. var len2 = len && p0[0].length;
  4237. for (var i = 0; i < len; i++) {
  4238. if (!out[i]) {
  4239. out[i] = [];
  4240. }
  4241. for (var j = 0; j < len2; j++) {
  4242. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4243. }
  4244. }
  4245. return out;
  4246. }
  4247. function add1DArray(out, p0, p1, sign) {
  4248. var len = p0.length;
  4249. for (var i = 0; i < len; i++) {
  4250. out[i] = p0[i] + p1[i] * sign;
  4251. }
  4252. return out;
  4253. }
  4254. function add2DArray(out, p0, p1, sign) {
  4255. var len = p0.length;
  4256. var len2 = len && p0[0].length;
  4257. for (var i = 0; i < len; i++) {
  4258. if (!out[i]) {
  4259. out[i] = [];
  4260. }
  4261. for (var j = 0; j < len2; j++) {
  4262. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4263. }
  4264. }
  4265. return out;
  4266. }
  4267. function fillColorStops(val0, val1) {
  4268. var len0 = val0.length;
  4269. var len1 = val1.length;
  4270. var shorterArr = len0 > len1 ? val1 : val0;
  4271. var shorterLen = Math.min(len0, len1);
  4272. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4273. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4274. shorterArr.push({
  4275. offset: last.offset,
  4276. color: last.color.slice()
  4277. });
  4278. }
  4279. }
  4280. function fillArray(val0, val1, arrDim) {
  4281. var arr0 = val0;
  4282. var arr1 = val1;
  4283. if (!arr0.push || !arr1.push) {
  4284. return;
  4285. }
  4286. var arr0Len = arr0.length;
  4287. var arr1Len = arr1.length;
  4288. if (arr0Len !== arr1Len) {
  4289. var isPreviousLarger = arr0Len > arr1Len;
  4290. if (isPreviousLarger) {
  4291. arr0.length = arr1Len;
  4292. }
  4293. else {
  4294. for (var i = arr0Len; i < arr1Len; i++) {
  4295. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4296. }
  4297. }
  4298. }
  4299. var len2 = arr0[0] && arr0[0].length;
  4300. for (var i = 0; i < arr0.length; i++) {
  4301. if (arrDim === 1) {
  4302. if (isNaN(arr0[i])) {
  4303. arr0[i] = arr1[i];
  4304. }
  4305. }
  4306. else {
  4307. for (var j = 0; j < len2; j++) {
  4308. if (isNaN(arr0[i][j])) {
  4309. arr0[i][j] = arr1[i][j];
  4310. }
  4311. }
  4312. }
  4313. }
  4314. }
  4315. function cloneValue(value) {
  4316. if (isArrayLike(value)) {
  4317. var len = value.length;
  4318. if (isArrayLike(value[0])) {
  4319. var ret = [];
  4320. for (var i = 0; i < len; i++) {
  4321. ret.push(arraySlice.call(value[i]));
  4322. }
  4323. return ret;
  4324. }
  4325. return arraySlice.call(value);
  4326. }
  4327. return value;
  4328. }
  4329. function rgba2String(rgba) {
  4330. rgba[0] = Math.floor(rgba[0]) || 0;
  4331. rgba[1] = Math.floor(rgba[1]) || 0;
  4332. rgba[2] = Math.floor(rgba[2]) || 0;
  4333. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4334. return 'rgba(' + rgba.join(',') + ')';
  4335. }
  4336. function guessArrayDim(value) {
  4337. return isArrayLike(value && value[0]) ? 2 : 1;
  4338. }
  4339. var VALUE_TYPE_NUMBER = 0;
  4340. var VALUE_TYPE_1D_ARRAY = 1;
  4341. var VALUE_TYPE_2D_ARRAY = 2;
  4342. var VALUE_TYPE_COLOR = 3;
  4343. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4344. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4345. var VALUE_TYPE_UNKOWN = 6;
  4346. function isGradientValueType(valType) {
  4347. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4348. }
  4349. function isArrayValueType(valType) {
  4350. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4351. }
  4352. var tmpRgba = [0, 0, 0, 0];
  4353. var Track = (function () {
  4354. function Track(propName) {
  4355. this.keyframes = [];
  4356. this.discrete = false;
  4357. this._invalid = false;
  4358. this._needsSort = false;
  4359. this._lastFr = 0;
  4360. this._lastFrP = 0;
  4361. this.propName = propName;
  4362. }
  4363. Track.prototype.isFinished = function () {
  4364. return this._finished;
  4365. };
  4366. Track.prototype.setFinished = function () {
  4367. this._finished = true;
  4368. if (this._additiveTrack) {
  4369. this._additiveTrack.setFinished();
  4370. }
  4371. };
  4372. Track.prototype.needsAnimate = function () {
  4373. return this.keyframes.length >= 1;
  4374. };
  4375. Track.prototype.getAdditiveTrack = function () {
  4376. return this._additiveTrack;
  4377. };
  4378. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4379. this._needsSort = true;
  4380. var keyframes = this.keyframes;
  4381. var len = keyframes.length;
  4382. var discrete = false;
  4383. var valType = VALUE_TYPE_UNKOWN;
  4384. var value = rawValue;
  4385. if (isArrayLike(rawValue)) {
  4386. var arrayDim = guessArrayDim(rawValue);
  4387. valType = arrayDim;
  4388. if (arrayDim === 1 && !isNumber(rawValue[0])
  4389. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4390. discrete = true;
  4391. }
  4392. }
  4393. else {
  4394. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4395. valType = VALUE_TYPE_NUMBER;
  4396. }
  4397. else if (isString(rawValue)) {
  4398. if (!isNaN(+rawValue)) {
  4399. valType = VALUE_TYPE_NUMBER;
  4400. }
  4401. else {
  4402. var colorArray = parse(rawValue);
  4403. if (colorArray) {
  4404. value = colorArray;
  4405. valType = VALUE_TYPE_COLOR;
  4406. }
  4407. }
  4408. }
  4409. else if (isGradientObject(rawValue)) {
  4410. var parsedGradient = extend({}, value);
  4411. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4412. offset: colorStop.offset,
  4413. color: parse(colorStop.color)
  4414. }); });
  4415. if (isLinearGradient(rawValue)) {
  4416. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4417. }
  4418. else if (isRadialGradient(rawValue)) {
  4419. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4420. }
  4421. value = parsedGradient;
  4422. }
  4423. }
  4424. if (len === 0) {
  4425. this.valType = valType;
  4426. }
  4427. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4428. discrete = true;
  4429. }
  4430. this.discrete = this.discrete || discrete;
  4431. var kf = {
  4432. time: time,
  4433. value: value,
  4434. rawValue: rawValue,
  4435. percent: 0
  4436. };
  4437. if (easing) {
  4438. kf.easing = easing;
  4439. kf.easingFunc = isFunction(easing)
  4440. ? easing
  4441. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4442. }
  4443. keyframes.push(kf);
  4444. return kf;
  4445. };
  4446. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4447. var kfs = this.keyframes;
  4448. if (this._needsSort) {
  4449. kfs.sort(function (a, b) {
  4450. return a.time - b.time;
  4451. });
  4452. }
  4453. var valType = this.valType;
  4454. var kfsLen = kfs.length;
  4455. var lastKf = kfs[kfsLen - 1];
  4456. var isDiscrete = this.discrete;
  4457. var isArr = isArrayValueType(valType);
  4458. var isGradient = isGradientValueType(valType);
  4459. for (var i = 0; i < kfsLen; i++) {
  4460. var kf = kfs[i];
  4461. var value = kf.value;
  4462. var lastValue = lastKf.value;
  4463. kf.percent = kf.time / maxTime;
  4464. if (!isDiscrete) {
  4465. if (isArr && i !== kfsLen - 1) {
  4466. fillArray(value, lastValue, valType);
  4467. }
  4468. else if (isGradient) {
  4469. fillColorStops(value.colorStops, lastValue.colorStops);
  4470. }
  4471. }
  4472. }
  4473. if (!isDiscrete
  4474. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4475. && additiveTrack
  4476. && this.needsAnimate()
  4477. && additiveTrack.needsAnimate()
  4478. && valType === additiveTrack.valType
  4479. && !additiveTrack._finished) {
  4480. this._additiveTrack = additiveTrack;
  4481. var startValue = kfs[0].value;
  4482. for (var i = 0; i < kfsLen; i++) {
  4483. if (valType === VALUE_TYPE_NUMBER) {
  4484. kfs[i].additiveValue = kfs[i].value - startValue;
  4485. }
  4486. else if (valType === VALUE_TYPE_COLOR) {
  4487. kfs[i].additiveValue =
  4488. add1DArray([], kfs[i].value, startValue, -1);
  4489. }
  4490. else if (isArrayValueType(valType)) {
  4491. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4492. ? add1DArray([], kfs[i].value, startValue, -1)
  4493. : add2DArray([], kfs[i].value, startValue, -1);
  4494. }
  4495. }
  4496. }
  4497. };
  4498. Track.prototype.step = function (target, percent) {
  4499. if (this._finished) {
  4500. return;
  4501. }
  4502. if (this._additiveTrack && this._additiveTrack._finished) {
  4503. this._additiveTrack = null;
  4504. }
  4505. var isAdditive = this._additiveTrack != null;
  4506. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4507. var valType = this.valType;
  4508. var keyframes = this.keyframes;
  4509. var kfsNum = keyframes.length;
  4510. var propName = this.propName;
  4511. var isValueColor = valType === VALUE_TYPE_COLOR;
  4512. var frameIdx;
  4513. var lastFrame = this._lastFr;
  4514. var mathMin = Math.min;
  4515. var frame;
  4516. var nextFrame;
  4517. if (kfsNum === 1) {
  4518. frame = nextFrame = keyframes[0];
  4519. }
  4520. else {
  4521. if (percent < 0) {
  4522. frameIdx = 0;
  4523. }
  4524. else if (percent < this._lastFrP) {
  4525. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4526. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4527. if (keyframes[frameIdx].percent <= percent) {
  4528. break;
  4529. }
  4530. }
  4531. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4532. }
  4533. else {
  4534. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4535. if (keyframes[frameIdx].percent > percent) {
  4536. break;
  4537. }
  4538. }
  4539. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4540. }
  4541. nextFrame = keyframes[frameIdx + 1];
  4542. frame = keyframes[frameIdx];
  4543. }
  4544. if (!(frame && nextFrame)) {
  4545. return;
  4546. }
  4547. this._lastFr = frameIdx;
  4548. this._lastFrP = percent;
  4549. var interval = (nextFrame.percent - frame.percent);
  4550. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4551. if (nextFrame.easingFunc) {
  4552. w = nextFrame.easingFunc(w);
  4553. }
  4554. var targetArr = isAdditive ? this._additiveValue
  4555. : (isValueColor ? tmpRgba : target[propName]);
  4556. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4557. targetArr = this._additiveValue = [];
  4558. }
  4559. if (this.discrete) {
  4560. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4561. }
  4562. else if (isArrayValueType(valType)) {
  4563. valType === VALUE_TYPE_1D_ARRAY
  4564. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4565. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4566. }
  4567. else if (isGradientValueType(valType)) {
  4568. var val = frame[valueKey];
  4569. var nextVal_1 = nextFrame[valueKey];
  4570. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4571. target[propName] = {
  4572. type: isLinearGradient_1 ? 'linear' : 'radial',
  4573. x: interpolateNumber(val.x, nextVal_1.x, w),
  4574. y: interpolateNumber(val.y, nextVal_1.y, w),
  4575. colorStops: map(val.colorStops, function (colorStop, idx) {
  4576. var nextColorStop = nextVal_1.colorStops[idx];
  4577. return {
  4578. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4579. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4580. };
  4581. }),
  4582. global: nextVal_1.global
  4583. };
  4584. if (isLinearGradient_1) {
  4585. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4586. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4587. }
  4588. else {
  4589. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4590. }
  4591. }
  4592. else if (isValueColor) {
  4593. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4594. if (!isAdditive) {
  4595. target[propName] = rgba2String(targetArr);
  4596. }
  4597. }
  4598. else {
  4599. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4600. if (isAdditive) {
  4601. this._additiveValue = value;
  4602. }
  4603. else {
  4604. target[propName] = value;
  4605. }
  4606. }
  4607. if (isAdditive) {
  4608. this._addToTarget(target);
  4609. }
  4610. };
  4611. Track.prototype._addToTarget = function (target) {
  4612. var valType = this.valType;
  4613. var propName = this.propName;
  4614. var additiveValue = this._additiveValue;
  4615. if (valType === VALUE_TYPE_NUMBER) {
  4616. target[propName] = target[propName] + additiveValue;
  4617. }
  4618. else if (valType === VALUE_TYPE_COLOR) {
  4619. parse(target[propName], tmpRgba);
  4620. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4621. target[propName] = rgba2String(tmpRgba);
  4622. }
  4623. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4624. add1DArray(target[propName], target[propName], additiveValue, 1);
  4625. }
  4626. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4627. add2DArray(target[propName], target[propName], additiveValue, 1);
  4628. }
  4629. };
  4630. return Track;
  4631. }());
  4632. var Animator = (function () {
  4633. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4634. this._tracks = {};
  4635. this._trackKeys = [];
  4636. this._maxTime = 0;
  4637. this._started = 0;
  4638. this._clip = null;
  4639. this._target = target;
  4640. this._loop = loop;
  4641. if (loop && additiveTo) {
  4642. logError('Can\' use additive animation on looped animation.');
  4643. return;
  4644. }
  4645. this._additiveAnimators = additiveTo;
  4646. this._allowDiscrete = allowDiscreteAnimation;
  4647. }
  4648. Animator.prototype.getMaxTime = function () {
  4649. return this._maxTime;
  4650. };
  4651. Animator.prototype.getDelay = function () {
  4652. return this._delay;
  4653. };
  4654. Animator.prototype.getLoop = function () {
  4655. return this._loop;
  4656. };
  4657. Animator.prototype.getTarget = function () {
  4658. return this._target;
  4659. };
  4660. Animator.prototype.changeTarget = function (target) {
  4661. this._target = target;
  4662. };
  4663. Animator.prototype.when = function (time, props, easing) {
  4664. return this.whenWithKeys(time, props, keys(props), easing);
  4665. };
  4666. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4667. var tracks = this._tracks;
  4668. for (var i = 0; i < propNames.length; i++) {
  4669. var propName = propNames[i];
  4670. var track = tracks[propName];
  4671. if (!track) {
  4672. track = tracks[propName] = new Track(propName);
  4673. var initialValue = void 0;
  4674. var additiveTrack = this._getAdditiveTrack(propName);
  4675. if (additiveTrack) {
  4676. var addtiveTrackKfs = additiveTrack.keyframes;
  4677. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4678. initialValue = lastFinalKf && lastFinalKf.value;
  4679. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4680. initialValue = rgba2String(initialValue);
  4681. }
  4682. }
  4683. else {
  4684. initialValue = this._target[propName];
  4685. }
  4686. if (initialValue == null) {
  4687. continue;
  4688. }
  4689. if (time > 0) {
  4690. track.addKeyframe(0, cloneValue(initialValue), easing);
  4691. }
  4692. this._trackKeys.push(propName);
  4693. }
  4694. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4695. }
  4696. this._maxTime = Math.max(this._maxTime, time);
  4697. return this;
  4698. };
  4699. Animator.prototype.pause = function () {
  4700. this._clip.pause();
  4701. this._paused = true;
  4702. };
  4703. Animator.prototype.resume = function () {
  4704. this._clip.resume();
  4705. this._paused = false;
  4706. };
  4707. Animator.prototype.isPaused = function () {
  4708. return !!this._paused;
  4709. };
  4710. Animator.prototype.duration = function (duration) {
  4711. this._maxTime = duration;
  4712. this._force = true;
  4713. return this;
  4714. };
  4715. Animator.prototype._doneCallback = function () {
  4716. this._setTracksFinished();
  4717. this._clip = null;
  4718. var doneList = this._doneCbs;
  4719. if (doneList) {
  4720. var len = doneList.length;
  4721. for (var i = 0; i < len; i++) {
  4722. doneList[i].call(this);
  4723. }
  4724. }
  4725. };
  4726. Animator.prototype._abortedCallback = function () {
  4727. this._setTracksFinished();
  4728. var animation = this.animation;
  4729. var abortedList = this._abortedCbs;
  4730. if (animation) {
  4731. animation.removeClip(this._clip);
  4732. }
  4733. this._clip = null;
  4734. if (abortedList) {
  4735. for (var i = 0; i < abortedList.length; i++) {
  4736. abortedList[i].call(this);
  4737. }
  4738. }
  4739. };
  4740. Animator.prototype._setTracksFinished = function () {
  4741. var tracks = this._tracks;
  4742. var tracksKeys = this._trackKeys;
  4743. for (var i = 0; i < tracksKeys.length; i++) {
  4744. tracks[tracksKeys[i]].setFinished();
  4745. }
  4746. };
  4747. Animator.prototype._getAdditiveTrack = function (trackName) {
  4748. var additiveTrack;
  4749. var additiveAnimators = this._additiveAnimators;
  4750. if (additiveAnimators) {
  4751. for (var i = 0; i < additiveAnimators.length; i++) {
  4752. var track = additiveAnimators[i].getTrack(trackName);
  4753. if (track) {
  4754. additiveTrack = track;
  4755. }
  4756. }
  4757. }
  4758. return additiveTrack;
  4759. };
  4760. Animator.prototype.start = function (easing) {
  4761. if (this._started > 0) {
  4762. return;
  4763. }
  4764. this._started = 1;
  4765. var self = this;
  4766. var tracks = [];
  4767. var maxTime = this._maxTime || 0;
  4768. for (var i = 0; i < this._trackKeys.length; i++) {
  4769. var propName = this._trackKeys[i];
  4770. var track = this._tracks[propName];
  4771. var additiveTrack = this._getAdditiveTrack(propName);
  4772. var kfs = track.keyframes;
  4773. var kfsNum = kfs.length;
  4774. track.prepare(maxTime, additiveTrack);
  4775. if (track.needsAnimate()) {
  4776. if (!this._allowDiscrete && track.discrete) {
  4777. var lastKf = kfs[kfsNum - 1];
  4778. if (lastKf) {
  4779. self._target[track.propName] = lastKf.rawValue;
  4780. }
  4781. track.setFinished();
  4782. }
  4783. else {
  4784. tracks.push(track);
  4785. }
  4786. }
  4787. }
  4788. if (tracks.length || this._force) {
  4789. var clip = new Clip({
  4790. life: maxTime,
  4791. loop: this._loop,
  4792. delay: this._delay || 0,
  4793. onframe: function (percent) {
  4794. self._started = 2;
  4795. var additiveAnimators = self._additiveAnimators;
  4796. if (additiveAnimators) {
  4797. var stillHasAdditiveAnimator = false;
  4798. for (var i = 0; i < additiveAnimators.length; i++) {
  4799. if (additiveAnimators[i]._clip) {
  4800. stillHasAdditiveAnimator = true;
  4801. break;
  4802. }
  4803. }
  4804. if (!stillHasAdditiveAnimator) {
  4805. self._additiveAnimators = null;
  4806. }
  4807. }
  4808. for (var i = 0; i < tracks.length; i++) {
  4809. tracks[i].step(self._target, percent);
  4810. }
  4811. var onframeList = self._onframeCbs;
  4812. if (onframeList) {
  4813. for (var i = 0; i < onframeList.length; i++) {
  4814. onframeList[i](self._target, percent);
  4815. }
  4816. }
  4817. },
  4818. ondestroy: function () {
  4819. self._doneCallback();
  4820. }
  4821. });
  4822. this._clip = clip;
  4823. if (this.animation) {
  4824. this.animation.addClip(clip);
  4825. }
  4826. if (easing) {
  4827. clip.setEasing(easing);
  4828. }
  4829. }
  4830. else {
  4831. this._doneCallback();
  4832. }
  4833. return this;
  4834. };
  4835. Animator.prototype.stop = function (forwardToLast) {
  4836. if (!this._clip) {
  4837. return;
  4838. }
  4839. var clip = this._clip;
  4840. if (forwardToLast) {
  4841. clip.onframe(1);
  4842. }
  4843. this._abortedCallback();
  4844. };
  4845. Animator.prototype.delay = function (time) {
  4846. this._delay = time;
  4847. return this;
  4848. };
  4849. Animator.prototype.during = function (cb) {
  4850. if (cb) {
  4851. if (!this._onframeCbs) {
  4852. this._onframeCbs = [];
  4853. }
  4854. this._onframeCbs.push(cb);
  4855. }
  4856. return this;
  4857. };
  4858. Animator.prototype.done = function (cb) {
  4859. if (cb) {
  4860. if (!this._doneCbs) {
  4861. this._doneCbs = [];
  4862. }
  4863. this._doneCbs.push(cb);
  4864. }
  4865. return this;
  4866. };
  4867. Animator.prototype.aborted = function (cb) {
  4868. if (cb) {
  4869. if (!this._abortedCbs) {
  4870. this._abortedCbs = [];
  4871. }
  4872. this._abortedCbs.push(cb);
  4873. }
  4874. return this;
  4875. };
  4876. Animator.prototype.getClip = function () {
  4877. return this._clip;
  4878. };
  4879. Animator.prototype.getTrack = function (propName) {
  4880. return this._tracks[propName];
  4881. };
  4882. Animator.prototype.getTracks = function () {
  4883. var _this = this;
  4884. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4885. };
  4886. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4887. if (!propNames.length || !this._clip) {
  4888. return true;
  4889. }
  4890. var tracks = this._tracks;
  4891. var tracksKeys = this._trackKeys;
  4892. for (var i = 0; i < propNames.length; i++) {
  4893. var track = tracks[propNames[i]];
  4894. if (track && !track.isFinished()) {
  4895. if (forwardToLast) {
  4896. track.step(this._target, 1);
  4897. }
  4898. else if (this._started === 1) {
  4899. track.step(this._target, 0);
  4900. }
  4901. track.setFinished();
  4902. }
  4903. }
  4904. var allAborted = true;
  4905. for (var i = 0; i < tracksKeys.length; i++) {
  4906. if (!tracks[tracksKeys[i]].isFinished()) {
  4907. allAborted = false;
  4908. break;
  4909. }
  4910. }
  4911. if (allAborted) {
  4912. this._abortedCallback();
  4913. }
  4914. return allAborted;
  4915. };
  4916. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4917. if (!target) {
  4918. return;
  4919. }
  4920. trackKeys = trackKeys || this._trackKeys;
  4921. for (var i = 0; i < trackKeys.length; i++) {
  4922. var propName = trackKeys[i];
  4923. var track = this._tracks[propName];
  4924. if (!track || track.isFinished()) {
  4925. continue;
  4926. }
  4927. var kfs = track.keyframes;
  4928. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4929. if (kf) {
  4930. target[propName] = cloneValue(kf.rawValue);
  4931. }
  4932. }
  4933. };
  4934. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4935. trackKeys = trackKeys || keys(finalProps);
  4936. for (var i = 0; i < trackKeys.length; i++) {
  4937. var propName = trackKeys[i];
  4938. var track = this._tracks[propName];
  4939. if (!track) {
  4940. continue;
  4941. }
  4942. var kfs = track.keyframes;
  4943. if (kfs.length > 1) {
  4944. var lastKf = kfs.pop();
  4945. track.addKeyframe(lastKf.time, finalProps[propName]);
  4946. track.prepare(this._maxTime, track.getAdditiveTrack());
  4947. }
  4948. }
  4949. };
  4950. return Animator;
  4951. }());
  4952. function getTime() {
  4953. return new Date().getTime();
  4954. }
  4955. var Animation = (function (_super) {
  4956. __extends(Animation, _super);
  4957. function Animation(opts) {
  4958. var _this = _super.call(this) || this;
  4959. _this._running = false;
  4960. _this._time = 0;
  4961. _this._pausedTime = 0;
  4962. _this._pauseStart = 0;
  4963. _this._paused = false;
  4964. opts = opts || {};
  4965. _this.stage = opts.stage || {};
  4966. return _this;
  4967. }
  4968. Animation.prototype.addClip = function (clip) {
  4969. if (clip.animation) {
  4970. this.removeClip(clip);
  4971. }
  4972. if (!this._head) {
  4973. this._head = this._tail = clip;
  4974. }
  4975. else {
  4976. this._tail.next = clip;
  4977. clip.prev = this._tail;
  4978. clip.next = null;
  4979. this._tail = clip;
  4980. }
  4981. clip.animation = this;
  4982. };
  4983. Animation.prototype.addAnimator = function (animator) {
  4984. animator.animation = this;
  4985. var clip = animator.getClip();
  4986. if (clip) {
  4987. this.addClip(clip);
  4988. }
  4989. };
  4990. Animation.prototype.removeClip = function (clip) {
  4991. if (!clip.animation) {
  4992. return;
  4993. }
  4994. var prev = clip.prev;
  4995. var next = clip.next;
  4996. if (prev) {
  4997. prev.next = next;
  4998. }
  4999. else {
  5000. this._head = next;
  5001. }
  5002. if (next) {
  5003. next.prev = prev;
  5004. }
  5005. else {
  5006. this._tail = prev;
  5007. }
  5008. clip.next = clip.prev = clip.animation = null;
  5009. };
  5010. Animation.prototype.removeAnimator = function (animator) {
  5011. var clip = animator.getClip();
  5012. if (clip) {
  5013. this.removeClip(clip);
  5014. }
  5015. animator.animation = null;
  5016. };
  5017. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5018. var time = getTime() - this._pausedTime;
  5019. var delta = time - this._time;
  5020. var clip = this._head;
  5021. while (clip) {
  5022. var nextClip = clip.next;
  5023. var finished = clip.step(time, delta);
  5024. if (finished) {
  5025. clip.ondestroy();
  5026. this.removeClip(clip);
  5027. clip = nextClip;
  5028. }
  5029. else {
  5030. clip = nextClip;
  5031. }
  5032. }
  5033. this._time = time;
  5034. if (!notTriggerFrameAndStageUpdate) {
  5035. this.trigger('frame', delta);
  5036. this.stage.update && this.stage.update();
  5037. }
  5038. };
  5039. Animation.prototype._startLoop = function () {
  5040. var self = this;
  5041. this._running = true;
  5042. function step() {
  5043. if (self._running) {
  5044. requestAnimationFrame$1(step);
  5045. !self._paused && self.update();
  5046. }
  5047. }
  5048. requestAnimationFrame$1(step);
  5049. };
  5050. Animation.prototype.start = function () {
  5051. if (this._running) {
  5052. return;
  5053. }
  5054. this._time = getTime();
  5055. this._pausedTime = 0;
  5056. this._startLoop();
  5057. };
  5058. Animation.prototype.stop = function () {
  5059. this._running = false;
  5060. };
  5061. Animation.prototype.pause = function () {
  5062. if (!this._paused) {
  5063. this._pauseStart = getTime();
  5064. this._paused = true;
  5065. }
  5066. };
  5067. Animation.prototype.resume = function () {
  5068. if (this._paused) {
  5069. this._pausedTime += getTime() - this._pauseStart;
  5070. this._paused = false;
  5071. }
  5072. };
  5073. Animation.prototype.clear = function () {
  5074. var clip = this._head;
  5075. while (clip) {
  5076. var nextClip = clip.next;
  5077. clip.prev = clip.next = clip.animation = null;
  5078. clip = nextClip;
  5079. }
  5080. this._head = this._tail = null;
  5081. };
  5082. Animation.prototype.isFinished = function () {
  5083. return this._head == null;
  5084. };
  5085. Animation.prototype.animate = function (target, options) {
  5086. options = options || {};
  5087. this.start();
  5088. var animator = new Animator(target, options.loop);
  5089. this.addAnimator(animator);
  5090. return animator;
  5091. };
  5092. return Animation;
  5093. }(Eventful));
  5094. var TOUCH_CLICK_DELAY = 300;
  5095. var globalEventSupported = env.domSupported;
  5096. var localNativeListenerNames = (function () {
  5097. var mouseHandlerNames = [
  5098. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5099. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5100. ];
  5101. var touchHandlerNames = [
  5102. 'touchstart', 'touchend', 'touchmove'
  5103. ];
  5104. var pointerEventNameMap = {
  5105. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5106. };
  5107. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5108. var nm = name.replace('mouse', 'pointer');
  5109. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5110. });
  5111. return {
  5112. mouse: mouseHandlerNames,
  5113. touch: touchHandlerNames,
  5114. pointer: pointerHandlerNames
  5115. };
  5116. })();
  5117. var globalNativeListenerNames = {
  5118. mouse: ['mousemove', 'mouseup'],
  5119. pointer: ['pointermove', 'pointerup']
  5120. };
  5121. var wheelEventSupported = false;
  5122. function isPointerFromTouch(event) {
  5123. var pointerType = event.pointerType;
  5124. return pointerType === 'pen' || pointerType === 'touch';
  5125. }
  5126. function setTouchTimer(scope) {
  5127. scope.touching = true;
  5128. if (scope.touchTimer != null) {
  5129. clearTimeout(scope.touchTimer);
  5130. scope.touchTimer = null;
  5131. }
  5132. scope.touchTimer = setTimeout(function () {
  5133. scope.touching = false;
  5134. scope.touchTimer = null;
  5135. }, 700);
  5136. }
  5137. function markTouch(event) {
  5138. event && (event.zrByTouch = true);
  5139. }
  5140. function normalizeGlobalEvent(instance, event) {
  5141. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5142. }
  5143. function isLocalEl(instance, el) {
  5144. var elTmp = el;
  5145. var isLocal = false;
  5146. while (elTmp && elTmp.nodeType !== 9
  5147. && !(isLocal = elTmp.domBelongToZr
  5148. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5149. elTmp = elTmp.parentNode;
  5150. }
  5151. return isLocal;
  5152. }
  5153. var FakeGlobalEvent = (function () {
  5154. function FakeGlobalEvent(instance, event) {
  5155. this.stopPropagation = noop;
  5156. this.stopImmediatePropagation = noop;
  5157. this.preventDefault = noop;
  5158. this.type = event.type;
  5159. this.target = this.currentTarget = instance.dom;
  5160. this.pointerType = event.pointerType;
  5161. this.clientX = event.clientX;
  5162. this.clientY = event.clientY;
  5163. }
  5164. return FakeGlobalEvent;
  5165. }());
  5166. var localDOMHandlers = {
  5167. mousedown: function (event) {
  5168. event = normalizeEvent(this.dom, event);
  5169. this.__mayPointerCapture = [event.zrX, event.zrY];
  5170. this.trigger('mousedown', event);
  5171. },
  5172. mousemove: function (event) {
  5173. event = normalizeEvent(this.dom, event);
  5174. var downPoint = this.__mayPointerCapture;
  5175. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5176. this.__togglePointerCapture(true);
  5177. }
  5178. this.trigger('mousemove', event);
  5179. },
  5180. mouseup: function (event) {
  5181. event = normalizeEvent(this.dom, event);
  5182. this.__togglePointerCapture(false);
  5183. this.trigger('mouseup', event);
  5184. },
  5185. mouseout: function (event) {
  5186. event = normalizeEvent(this.dom, event);
  5187. var element = event.toElement || event.relatedTarget;
  5188. if (!isLocalEl(this, element)) {
  5189. if (this.__pointerCapturing) {
  5190. event.zrEventControl = 'no_globalout';
  5191. }
  5192. this.trigger('mouseout', event);
  5193. }
  5194. },
  5195. wheel: function (event) {
  5196. wheelEventSupported = true;
  5197. event = normalizeEvent(this.dom, event);
  5198. this.trigger('mousewheel', event);
  5199. },
  5200. mousewheel: function (event) {
  5201. if (wheelEventSupported) {
  5202. return;
  5203. }
  5204. event = normalizeEvent(this.dom, event);
  5205. this.trigger('mousewheel', event);
  5206. },
  5207. touchstart: function (event) {
  5208. event = normalizeEvent(this.dom, event);
  5209. markTouch(event);
  5210. this.__lastTouchMoment = new Date();
  5211. this.handler.processGesture(event, 'start');
  5212. localDOMHandlers.mousemove.call(this, event);
  5213. localDOMHandlers.mousedown.call(this, event);
  5214. },
  5215. touchmove: function (event) {
  5216. event = normalizeEvent(this.dom, event);
  5217. markTouch(event);
  5218. this.handler.processGesture(event, 'change');
  5219. localDOMHandlers.mousemove.call(this, event);
  5220. },
  5221. touchend: function (event) {
  5222. event = normalizeEvent(this.dom, event);
  5223. markTouch(event);
  5224. this.handler.processGesture(event, 'end');
  5225. localDOMHandlers.mouseup.call(this, event);
  5226. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5227. localDOMHandlers.click.call(this, event);
  5228. }
  5229. },
  5230. pointerdown: function (event) {
  5231. localDOMHandlers.mousedown.call(this, event);
  5232. },
  5233. pointermove: function (event) {
  5234. if (!isPointerFromTouch(event)) {
  5235. localDOMHandlers.mousemove.call(this, event);
  5236. }
  5237. },
  5238. pointerup: function (event) {
  5239. localDOMHandlers.mouseup.call(this, event);
  5240. },
  5241. pointerout: function (event) {
  5242. if (!isPointerFromTouch(event)) {
  5243. localDOMHandlers.mouseout.call(this, event);
  5244. }
  5245. }
  5246. };
  5247. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5248. localDOMHandlers[name] = function (event) {
  5249. event = normalizeEvent(this.dom, event);
  5250. this.trigger(name, event);
  5251. };
  5252. });
  5253. var globalDOMHandlers = {
  5254. pointermove: function (event) {
  5255. if (!isPointerFromTouch(event)) {
  5256. globalDOMHandlers.mousemove.call(this, event);
  5257. }
  5258. },
  5259. pointerup: function (event) {
  5260. globalDOMHandlers.mouseup.call(this, event);
  5261. },
  5262. mousemove: function (event) {
  5263. this.trigger('mousemove', event);
  5264. },
  5265. mouseup: function (event) {
  5266. var pointerCaptureReleasing = this.__pointerCapturing;
  5267. this.__togglePointerCapture(false);
  5268. this.trigger('mouseup', event);
  5269. if (pointerCaptureReleasing) {
  5270. event.zrEventControl = 'only_globalout';
  5271. this.trigger('mouseout', event);
  5272. }
  5273. }
  5274. };
  5275. function mountLocalDOMEventListeners(instance, scope) {
  5276. var domHandlers = scope.domHandlers;
  5277. if (env.pointerEventsSupported) {
  5278. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5279. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5280. domHandlers[nativeEventName].call(instance, event);
  5281. });
  5282. });
  5283. }
  5284. else {
  5285. if (env.touchEventsSupported) {
  5286. each(localNativeListenerNames.touch, function (nativeEventName) {
  5287. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5288. domHandlers[nativeEventName].call(instance, event);
  5289. setTouchTimer(scope);
  5290. });
  5291. });
  5292. }
  5293. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5294. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5295. event = getNativeEvent(event);
  5296. if (!scope.touching) {
  5297. domHandlers[nativeEventName].call(instance, event);
  5298. }
  5299. });
  5300. });
  5301. }
  5302. }
  5303. function mountGlobalDOMEventListeners(instance, scope) {
  5304. if (env.pointerEventsSupported) {
  5305. each(globalNativeListenerNames.pointer, mount);
  5306. }
  5307. else if (!env.touchEventsSupported) {
  5308. each(globalNativeListenerNames.mouse, mount);
  5309. }
  5310. function mount(nativeEventName) {
  5311. function nativeEventListener(event) {
  5312. event = getNativeEvent(event);
  5313. if (!isLocalEl(instance, event.target)) {
  5314. event = normalizeGlobalEvent(instance, event);
  5315. scope.domHandlers[nativeEventName].call(instance, event);
  5316. }
  5317. }
  5318. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5319. }
  5320. }
  5321. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5322. scope.mounted[nativeEventName] = listener;
  5323. scope.listenerOpts[nativeEventName] = opt;
  5324. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5325. }
  5326. function unmountDOMEventListeners(scope) {
  5327. var mounted = scope.mounted;
  5328. for (var nativeEventName in mounted) {
  5329. if (mounted.hasOwnProperty(nativeEventName)) {
  5330. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5331. }
  5332. }
  5333. scope.mounted = {};
  5334. }
  5335. var DOMHandlerScope = (function () {
  5336. function DOMHandlerScope(domTarget, domHandlers) {
  5337. this.mounted = {};
  5338. this.listenerOpts = {};
  5339. this.touching = false;
  5340. this.domTarget = domTarget;
  5341. this.domHandlers = domHandlers;
  5342. }
  5343. return DOMHandlerScope;
  5344. }());
  5345. var HandlerDomProxy = (function (_super) {
  5346. __extends(HandlerDomProxy, _super);
  5347. function HandlerDomProxy(dom, painterRoot) {
  5348. var _this = _super.call(this) || this;
  5349. _this.__pointerCapturing = false;
  5350. _this.dom = dom;
  5351. _this.painterRoot = painterRoot;
  5352. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5353. if (globalEventSupported) {
  5354. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5355. }
  5356. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5357. return _this;
  5358. }
  5359. HandlerDomProxy.prototype.dispose = function () {
  5360. unmountDOMEventListeners(this._localHandlerScope);
  5361. if (globalEventSupported) {
  5362. unmountDOMEventListeners(this._globalHandlerScope);
  5363. }
  5364. };
  5365. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5366. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5367. };
  5368. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5369. this.__mayPointerCapture = null;
  5370. if (globalEventSupported
  5371. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5372. this.__pointerCapturing = isPointerCapturing;
  5373. var globalHandlerScope = this._globalHandlerScope;
  5374. isPointerCapturing
  5375. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5376. : unmountDOMEventListeners(globalHandlerScope);
  5377. }
  5378. };
  5379. return HandlerDomProxy;
  5380. }(Eventful));
  5381. var dpr = 1;
  5382. if (env.hasGlobalWindow) {
  5383. dpr = Math.max(window.devicePixelRatio
  5384. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5385. || 1, 1);
  5386. }
  5387. var devicePixelRatio = dpr;
  5388. var DARK_MODE_THRESHOLD = 0.4;
  5389. var DARK_LABEL_COLOR = '#333';
  5390. var LIGHT_LABEL_COLOR = '#ccc';
  5391. var LIGHTER_LABEL_COLOR = '#eee';
  5392. var mIdentity = identity;
  5393. var EPSILON$2 = 5e-5;
  5394. function isNotAroundZero$1(val) {
  5395. return val > EPSILON$2 || val < -EPSILON$2;
  5396. }
  5397. var scaleTmp = [];
  5398. var tmpTransform = [];
  5399. var originTransform = create$1();
  5400. var abs = Math.abs;
  5401. var Transformable = (function () {
  5402. function Transformable() {
  5403. }
  5404. Transformable.prototype.getLocalTransform = function (m) {
  5405. return Transformable.getLocalTransform(this, m);
  5406. };
  5407. Transformable.prototype.setPosition = function (arr) {
  5408. this.x = arr[0];
  5409. this.y = arr[1];
  5410. };
  5411. Transformable.prototype.setScale = function (arr) {
  5412. this.scaleX = arr[0];
  5413. this.scaleY = arr[1];
  5414. };
  5415. Transformable.prototype.setSkew = function (arr) {
  5416. this.skewX = arr[0];
  5417. this.skewY = arr[1];
  5418. };
  5419. Transformable.prototype.setOrigin = function (arr) {
  5420. this.originX = arr[0];
  5421. this.originY = arr[1];
  5422. };
  5423. Transformable.prototype.needLocalTransform = function () {
  5424. return isNotAroundZero$1(this.rotation)
  5425. || isNotAroundZero$1(this.x)
  5426. || isNotAroundZero$1(this.y)
  5427. || isNotAroundZero$1(this.scaleX - 1)
  5428. || isNotAroundZero$1(this.scaleY - 1)
  5429. || isNotAroundZero$1(this.skewX)
  5430. || isNotAroundZero$1(this.skewY);
  5431. };
  5432. Transformable.prototype.updateTransform = function () {
  5433. var parentTransform = this.parent && this.parent.transform;
  5434. var needLocalTransform = this.needLocalTransform();
  5435. var m = this.transform;
  5436. if (!(needLocalTransform || parentTransform)) {
  5437. if (m) {
  5438. mIdentity(m);
  5439. this.invTransform = null;
  5440. }
  5441. return;
  5442. }
  5443. m = m || create$1();
  5444. if (needLocalTransform) {
  5445. this.getLocalTransform(m);
  5446. }
  5447. else {
  5448. mIdentity(m);
  5449. }
  5450. if (parentTransform) {
  5451. if (needLocalTransform) {
  5452. mul$1(m, parentTransform, m);
  5453. }
  5454. else {
  5455. copy$1(m, parentTransform);
  5456. }
  5457. }
  5458. this.transform = m;
  5459. this._resolveGlobalScaleRatio(m);
  5460. };
  5461. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5462. var globalScaleRatio = this.globalScaleRatio;
  5463. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5464. this.getGlobalScale(scaleTmp);
  5465. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5466. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5467. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5468. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5469. m[0] *= sx;
  5470. m[1] *= sx;
  5471. m[2] *= sy;
  5472. m[3] *= sy;
  5473. }
  5474. this.invTransform = this.invTransform || create$1();
  5475. invert(this.invTransform, m);
  5476. };
  5477. Transformable.prototype.getComputedTransform = function () {
  5478. var transformNode = this;
  5479. var ancestors = [];
  5480. while (transformNode) {
  5481. ancestors.push(transformNode);
  5482. transformNode = transformNode.parent;
  5483. }
  5484. while (transformNode = ancestors.pop()) {
  5485. transformNode.updateTransform();
  5486. }
  5487. return this.transform;
  5488. };
  5489. Transformable.prototype.setLocalTransform = function (m) {
  5490. if (!m) {
  5491. return;
  5492. }
  5493. var sx = m[0] * m[0] + m[1] * m[1];
  5494. var sy = m[2] * m[2] + m[3] * m[3];
  5495. var rotation = Math.atan2(m[1], m[0]);
  5496. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5497. sy = Math.sqrt(sy) * Math.cos(shearX);
  5498. sx = Math.sqrt(sx);
  5499. this.skewX = shearX;
  5500. this.skewY = 0;
  5501. this.rotation = -rotation;
  5502. this.x = +m[4];
  5503. this.y = +m[5];
  5504. this.scaleX = sx;
  5505. this.scaleY = sy;
  5506. this.originX = 0;
  5507. this.originY = 0;
  5508. };
  5509. Transformable.prototype.decomposeTransform = function () {
  5510. if (!this.transform) {
  5511. return;
  5512. }
  5513. var parent = this.parent;
  5514. var m = this.transform;
  5515. if (parent && parent.transform) {
  5516. parent.invTransform = parent.invTransform || create$1();
  5517. mul$1(tmpTransform, parent.invTransform, m);
  5518. m = tmpTransform;
  5519. }
  5520. var ox = this.originX;
  5521. var oy = this.originY;
  5522. if (ox || oy) {
  5523. originTransform[4] = ox;
  5524. originTransform[5] = oy;
  5525. mul$1(tmpTransform, m, originTransform);
  5526. tmpTransform[4] -= ox;
  5527. tmpTransform[5] -= oy;
  5528. m = tmpTransform;
  5529. }
  5530. this.setLocalTransform(m);
  5531. };
  5532. Transformable.prototype.getGlobalScale = function (out) {
  5533. var m = this.transform;
  5534. out = out || [];
  5535. if (!m) {
  5536. out[0] = 1;
  5537. out[1] = 1;
  5538. return out;
  5539. }
  5540. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5541. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5542. if (m[0] < 0) {
  5543. out[0] = -out[0];
  5544. }
  5545. if (m[3] < 0) {
  5546. out[1] = -out[1];
  5547. }
  5548. return out;
  5549. };
  5550. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5551. var v2 = [x, y];
  5552. var invTransform = this.invTransform;
  5553. if (invTransform) {
  5554. applyTransform(v2, v2, invTransform);
  5555. }
  5556. return v2;
  5557. };
  5558. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5559. var v2 = [x, y];
  5560. var transform = this.transform;
  5561. if (transform) {
  5562. applyTransform(v2, v2, transform);
  5563. }
  5564. return v2;
  5565. };
  5566. Transformable.prototype.getLineScale = function () {
  5567. var m = this.transform;
  5568. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5569. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5570. : 1;
  5571. };
  5572. Transformable.prototype.copyTransform = function (source) {
  5573. copyTransform(this, source);
  5574. };
  5575. Transformable.getLocalTransform = function (target, m) {
  5576. m = m || [];
  5577. var ox = target.originX || 0;
  5578. var oy = target.originY || 0;
  5579. var sx = target.scaleX;
  5580. var sy = target.scaleY;
  5581. var ax = target.anchorX;
  5582. var ay = target.anchorY;
  5583. var rotation = target.rotation || 0;
  5584. var x = target.x;
  5585. var y = target.y;
  5586. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5587. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5588. if (ox || oy || ax || ay) {
  5589. var dx = ox + ax;
  5590. var dy = oy + ay;
  5591. m[4] = -dx * sx - skewX * dy * sy;
  5592. m[5] = -dy * sy - skewY * dx * sx;
  5593. }
  5594. else {
  5595. m[4] = m[5] = 0;
  5596. }
  5597. m[0] = sx;
  5598. m[3] = sy;
  5599. m[1] = skewY * sx;
  5600. m[2] = skewX * sy;
  5601. rotation && rotate(m, m, rotation);
  5602. m[4] += ox + x;
  5603. m[5] += oy + y;
  5604. return m;
  5605. };
  5606. Transformable.initDefaultProps = (function () {
  5607. var proto = Transformable.prototype;
  5608. proto.scaleX =
  5609. proto.scaleY =
  5610. proto.globalScaleRatio = 1;
  5611. proto.x =
  5612. proto.y =
  5613. proto.originX =
  5614. proto.originY =
  5615. proto.skewX =
  5616. proto.skewY =
  5617. proto.rotation =
  5618. proto.anchorX =
  5619. proto.anchorY = 0;
  5620. })();
  5621. return Transformable;
  5622. }());
  5623. var TRANSFORMABLE_PROPS = [
  5624. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5625. ];
  5626. function copyTransform(target, source) {
  5627. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5628. var propName = TRANSFORMABLE_PROPS[i];
  5629. target[propName] = source[propName];
  5630. }
  5631. }
  5632. var textWidthCache = {};
  5633. function getWidth(text, font) {
  5634. font = font || DEFAULT_FONT;
  5635. var cacheOfFont = textWidthCache[font];
  5636. if (!cacheOfFont) {
  5637. cacheOfFont = textWidthCache[font] = new LRU(500);
  5638. }
  5639. var width = cacheOfFont.get(text);
  5640. if (width == null) {
  5641. width = platformApi.measureText(text, font).width;
  5642. cacheOfFont.put(text, width);
  5643. }
  5644. return width;
  5645. }
  5646. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5647. var width = getWidth(text, font);
  5648. var height = getLineHeight(font);
  5649. var x = adjustTextX(0, width, textAlign);
  5650. var y = adjustTextY$1(0, height, textBaseline);
  5651. var rect = new BoundingRect(x, y, width, height);
  5652. return rect;
  5653. }
  5654. function getBoundingRect(text, font, textAlign, textBaseline) {
  5655. var textLines = ((text || '') + '').split('\n');
  5656. var len = textLines.length;
  5657. if (len === 1) {
  5658. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5659. }
  5660. else {
  5661. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5662. for (var i = 0; i < textLines.length; i++) {
  5663. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5664. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5665. }
  5666. return uniondRect;
  5667. }
  5668. }
  5669. function adjustTextX(x, width, textAlign) {
  5670. if (textAlign === 'right') {
  5671. x -= width;
  5672. }
  5673. else if (textAlign === 'center') {
  5674. x -= width / 2;
  5675. }
  5676. return x;
  5677. }
  5678. function adjustTextY$1(y, height, verticalAlign) {
  5679. if (verticalAlign === 'middle') {
  5680. y -= height / 2;
  5681. }
  5682. else if (verticalAlign === 'bottom') {
  5683. y -= height;
  5684. }
  5685. return y;
  5686. }
  5687. function getLineHeight(font) {
  5688. return getWidth('国', font);
  5689. }
  5690. function parsePercent(value, maxValue) {
  5691. if (typeof value === 'string') {
  5692. if (value.lastIndexOf('%') >= 0) {
  5693. return parseFloat(value) / 100 * maxValue;
  5694. }
  5695. return parseFloat(value);
  5696. }
  5697. return value;
  5698. }
  5699. function calculateTextPosition(out, opts, rect) {
  5700. var textPosition = opts.position || 'inside';
  5701. var distance = opts.distance != null ? opts.distance : 5;
  5702. var height = rect.height;
  5703. var width = rect.width;
  5704. var halfHeight = height / 2;
  5705. var x = rect.x;
  5706. var y = rect.y;
  5707. var textAlign = 'left';
  5708. var textVerticalAlign = 'top';
  5709. if (textPosition instanceof Array) {
  5710. x += parsePercent(textPosition[0], rect.width);
  5711. y += parsePercent(textPosition[1], rect.height);
  5712. textAlign = null;
  5713. textVerticalAlign = null;
  5714. }
  5715. else {
  5716. switch (textPosition) {
  5717. case 'left':
  5718. x -= distance;
  5719. y += halfHeight;
  5720. textAlign = 'right';
  5721. textVerticalAlign = 'middle';
  5722. break;
  5723. case 'right':
  5724. x += distance + width;
  5725. y += halfHeight;
  5726. textVerticalAlign = 'middle';
  5727. break;
  5728. case 'top':
  5729. x += width / 2;
  5730. y -= distance;
  5731. textAlign = 'center';
  5732. textVerticalAlign = 'bottom';
  5733. break;
  5734. case 'bottom':
  5735. x += width / 2;
  5736. y += height + distance;
  5737. textAlign = 'center';
  5738. break;
  5739. case 'inside':
  5740. x += width / 2;
  5741. y += halfHeight;
  5742. textAlign = 'center';
  5743. textVerticalAlign = 'middle';
  5744. break;
  5745. case 'insideLeft':
  5746. x += distance;
  5747. y += halfHeight;
  5748. textVerticalAlign = 'middle';
  5749. break;
  5750. case 'insideRight':
  5751. x += width - distance;
  5752. y += halfHeight;
  5753. textAlign = 'right';
  5754. textVerticalAlign = 'middle';
  5755. break;
  5756. case 'insideTop':
  5757. x += width / 2;
  5758. y += distance;
  5759. textAlign = 'center';
  5760. break;
  5761. case 'insideBottom':
  5762. x += width / 2;
  5763. y += height - distance;
  5764. textAlign = 'center';
  5765. textVerticalAlign = 'bottom';
  5766. break;
  5767. case 'insideTopLeft':
  5768. x += distance;
  5769. y += distance;
  5770. break;
  5771. case 'insideTopRight':
  5772. x += width - distance;
  5773. y += distance;
  5774. textAlign = 'right';
  5775. break;
  5776. case 'insideBottomLeft':
  5777. x += distance;
  5778. y += height - distance;
  5779. textVerticalAlign = 'bottom';
  5780. break;
  5781. case 'insideBottomRight':
  5782. x += width - distance;
  5783. y += height - distance;
  5784. textAlign = 'right';
  5785. textVerticalAlign = 'bottom';
  5786. break;
  5787. }
  5788. }
  5789. out = out || {};
  5790. out.x = x;
  5791. out.y = y;
  5792. out.align = textAlign;
  5793. out.verticalAlign = textVerticalAlign;
  5794. return out;
  5795. }
  5796. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5797. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5798. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5799. obj[key] = true;
  5800. return obj;
  5801. }, { ignore: false });
  5802. var tmpTextPosCalcRes = {};
  5803. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5804. var Element = (function () {
  5805. function Element(props) {
  5806. this.id = guid();
  5807. this.animators = [];
  5808. this.currentStates = [];
  5809. this.states = {};
  5810. this._init(props);
  5811. }
  5812. Element.prototype._init = function (props) {
  5813. this.attr(props);
  5814. };
  5815. Element.prototype.drift = function (dx, dy, e) {
  5816. switch (this.draggable) {
  5817. case 'horizontal':
  5818. dy = 0;
  5819. break;
  5820. case 'vertical':
  5821. dx = 0;
  5822. break;
  5823. }
  5824. var m = this.transform;
  5825. if (!m) {
  5826. m = this.transform = [1, 0, 0, 1, 0, 0];
  5827. }
  5828. m[4] += dx;
  5829. m[5] += dy;
  5830. this.decomposeTransform();
  5831. this.markRedraw();
  5832. };
  5833. Element.prototype.beforeUpdate = function () { };
  5834. Element.prototype.afterUpdate = function () { };
  5835. Element.prototype.update = function () {
  5836. this.updateTransform();
  5837. if (this.__dirty) {
  5838. this.updateInnerText();
  5839. }
  5840. };
  5841. Element.prototype.updateInnerText = function (forceUpdate) {
  5842. var textEl = this._textContent;
  5843. if (textEl && (!textEl.ignore || forceUpdate)) {
  5844. if (!this.textConfig) {
  5845. this.textConfig = {};
  5846. }
  5847. var textConfig = this.textConfig;
  5848. var isLocal = textConfig.local;
  5849. var innerTransformable = textEl.innerTransformable;
  5850. var textAlign = void 0;
  5851. var textVerticalAlign = void 0;
  5852. var textStyleChanged = false;
  5853. innerTransformable.parent = isLocal ? this : null;
  5854. var innerOrigin = false;
  5855. innerTransformable.copyTransform(textEl);
  5856. if (textConfig.position != null) {
  5857. var layoutRect = tmpBoundingRect;
  5858. if (textConfig.layoutRect) {
  5859. layoutRect.copy(textConfig.layoutRect);
  5860. }
  5861. else {
  5862. layoutRect.copy(this.getBoundingRect());
  5863. }
  5864. if (!isLocal) {
  5865. layoutRect.applyTransform(this.transform);
  5866. }
  5867. if (this.calculateTextPosition) {
  5868. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5869. }
  5870. else {
  5871. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5872. }
  5873. innerTransformable.x = tmpTextPosCalcRes.x;
  5874. innerTransformable.y = tmpTextPosCalcRes.y;
  5875. textAlign = tmpTextPosCalcRes.align;
  5876. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5877. var textOrigin = textConfig.origin;
  5878. if (textOrigin && textConfig.rotation != null) {
  5879. var relOriginX = void 0;
  5880. var relOriginY = void 0;
  5881. if (textOrigin === 'center') {
  5882. relOriginX = layoutRect.width * 0.5;
  5883. relOriginY = layoutRect.height * 0.5;
  5884. }
  5885. else {
  5886. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5887. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5888. }
  5889. innerOrigin = true;
  5890. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5891. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5892. }
  5893. }
  5894. if (textConfig.rotation != null) {
  5895. innerTransformable.rotation = textConfig.rotation;
  5896. }
  5897. var textOffset = textConfig.offset;
  5898. if (textOffset) {
  5899. innerTransformable.x += textOffset[0];
  5900. innerTransformable.y += textOffset[1];
  5901. if (!innerOrigin) {
  5902. innerTransformable.originX = -textOffset[0];
  5903. innerTransformable.originY = -textOffset[1];
  5904. }
  5905. }
  5906. var isInside = textConfig.inside == null
  5907. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5908. : textConfig.inside;
  5909. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5910. var textFill = void 0;
  5911. var textStroke = void 0;
  5912. var autoStroke = void 0;
  5913. if (isInside && this.canBeInsideText()) {
  5914. textFill = textConfig.insideFill;
  5915. textStroke = textConfig.insideStroke;
  5916. if (textFill == null || textFill === 'auto') {
  5917. textFill = this.getInsideTextFill();
  5918. }
  5919. if (textStroke == null || textStroke === 'auto') {
  5920. textStroke = this.getInsideTextStroke(textFill);
  5921. autoStroke = true;
  5922. }
  5923. }
  5924. else {
  5925. textFill = textConfig.outsideFill;
  5926. textStroke = textConfig.outsideStroke;
  5927. if (textFill == null || textFill === 'auto') {
  5928. textFill = this.getOutsideFill();
  5929. }
  5930. if (textStroke == null || textStroke === 'auto') {
  5931. textStroke = this.getOutsideStroke(textFill);
  5932. autoStroke = true;
  5933. }
  5934. }
  5935. textFill = textFill || '#000';
  5936. if (textFill !== innerTextDefaultStyle.fill
  5937. || textStroke !== innerTextDefaultStyle.stroke
  5938. || autoStroke !== innerTextDefaultStyle.autoStroke
  5939. || textAlign !== innerTextDefaultStyle.align
  5940. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5941. textStyleChanged = true;
  5942. innerTextDefaultStyle.fill = textFill;
  5943. innerTextDefaultStyle.stroke = textStroke;
  5944. innerTextDefaultStyle.autoStroke = autoStroke;
  5945. innerTextDefaultStyle.align = textAlign;
  5946. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5947. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5948. }
  5949. textEl.__dirty |= REDRAW_BIT;
  5950. if (textStyleChanged) {
  5951. textEl.dirtyStyle(true);
  5952. }
  5953. }
  5954. };
  5955. Element.prototype.canBeInsideText = function () {
  5956. return true;
  5957. };
  5958. Element.prototype.getInsideTextFill = function () {
  5959. return '#fff';
  5960. };
  5961. Element.prototype.getInsideTextStroke = function (textFill) {
  5962. return '#000';
  5963. };
  5964. Element.prototype.getOutsideFill = function () {
  5965. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5966. };
  5967. Element.prototype.getOutsideStroke = function (textFill) {
  5968. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5969. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5970. if (!colorArr) {
  5971. colorArr = [255, 255, 255, 1];
  5972. }
  5973. var alpha = colorArr[3];
  5974. var isDark = this.__zr.isDarkMode();
  5975. for (var i = 0; i < 3; i++) {
  5976. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5977. }
  5978. colorArr[3] = 1;
  5979. return stringify(colorArr, 'rgba');
  5980. };
  5981. Element.prototype.traverse = function (cb, context) { };
  5982. Element.prototype.attrKV = function (key, value) {
  5983. if (key === 'textConfig') {
  5984. this.setTextConfig(value);
  5985. }
  5986. else if (key === 'textContent') {
  5987. this.setTextContent(value);
  5988. }
  5989. else if (key === 'clipPath') {
  5990. this.setClipPath(value);
  5991. }
  5992. else if (key === 'extra') {
  5993. this.extra = this.extra || {};
  5994. extend(this.extra, value);
  5995. }
  5996. else {
  5997. this[key] = value;
  5998. }
  5999. };
  6000. Element.prototype.hide = function () {
  6001. this.ignore = true;
  6002. this.markRedraw();
  6003. };
  6004. Element.prototype.show = function () {
  6005. this.ignore = false;
  6006. this.markRedraw();
  6007. };
  6008. Element.prototype.attr = function (keyOrObj, value) {
  6009. if (typeof keyOrObj === 'string') {
  6010. this.attrKV(keyOrObj, value);
  6011. }
  6012. else if (isObject(keyOrObj)) {
  6013. var obj = keyOrObj;
  6014. var keysArr = keys(obj);
  6015. for (var i = 0; i < keysArr.length; i++) {
  6016. var key = keysArr[i];
  6017. this.attrKV(key, keyOrObj[key]);
  6018. }
  6019. }
  6020. this.markRedraw();
  6021. return this;
  6022. };
  6023. Element.prototype.saveCurrentToNormalState = function (toState) {
  6024. this._innerSaveToNormal(toState);
  6025. var normalState = this._normalState;
  6026. for (var i = 0; i < this.animators.length; i++) {
  6027. var animator = this.animators[i];
  6028. var fromStateTransition = animator.__fromStateTransition;
  6029. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6030. continue;
  6031. }
  6032. var targetName = animator.targetName;
  6033. var target = targetName
  6034. ? normalState[targetName] : normalState;
  6035. animator.saveTo(target);
  6036. }
  6037. };
  6038. Element.prototype._innerSaveToNormal = function (toState) {
  6039. var normalState = this._normalState;
  6040. if (!normalState) {
  6041. normalState = this._normalState = {};
  6042. }
  6043. if (toState.textConfig && !normalState.textConfig) {
  6044. normalState.textConfig = this.textConfig;
  6045. }
  6046. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6047. };
  6048. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6049. for (var i = 0; i < primaryKeys.length; i++) {
  6050. var key = primaryKeys[i];
  6051. if (toState[key] != null && !(key in normalState)) {
  6052. normalState[key] = this[key];
  6053. }
  6054. }
  6055. };
  6056. Element.prototype.hasState = function () {
  6057. return this.currentStates.length > 0;
  6058. };
  6059. Element.prototype.getState = function (name) {
  6060. return this.states[name];
  6061. };
  6062. Element.prototype.ensureState = function (name) {
  6063. var states = this.states;
  6064. if (!states[name]) {
  6065. states[name] = {};
  6066. }
  6067. return states[name];
  6068. };
  6069. Element.prototype.clearStates = function (noAnimation) {
  6070. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6071. };
  6072. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6073. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6074. var hasStates = this.hasState();
  6075. if (!hasStates && toNormalState) {
  6076. return;
  6077. }
  6078. var currentStates = this.currentStates;
  6079. var animationCfg = this.stateTransition;
  6080. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6081. return;
  6082. }
  6083. var state;
  6084. if (this.stateProxy && !toNormalState) {
  6085. state = this.stateProxy(stateName);
  6086. }
  6087. if (!state) {
  6088. state = (this.states && this.states[stateName]);
  6089. }
  6090. if (!state && !toNormalState) {
  6091. logError("State " + stateName + " not exists.");
  6092. return;
  6093. }
  6094. if (!toNormalState) {
  6095. this.saveCurrentToNormalState(state);
  6096. }
  6097. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6098. if (useHoverLayer) {
  6099. this._toggleHoverLayerFlag(true);
  6100. }
  6101. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6102. var textContent = this._textContent;
  6103. var textGuide = this._textGuide;
  6104. if (textContent) {
  6105. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6106. }
  6107. if (textGuide) {
  6108. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6109. }
  6110. if (toNormalState) {
  6111. this.currentStates = [];
  6112. this._normalState = {};
  6113. }
  6114. else {
  6115. if (!keepCurrentStates) {
  6116. this.currentStates = [stateName];
  6117. }
  6118. else {
  6119. this.currentStates.push(stateName);
  6120. }
  6121. }
  6122. this._updateAnimationTargets();
  6123. this.markRedraw();
  6124. if (!useHoverLayer && this.__inHover) {
  6125. this._toggleHoverLayerFlag(false);
  6126. this.__dirty &= ~REDRAW_BIT;
  6127. }
  6128. return state;
  6129. };
  6130. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6131. if (!states.length) {
  6132. this.clearStates();
  6133. }
  6134. else {
  6135. var stateObjects = [];
  6136. var currentStates = this.currentStates;
  6137. var len = states.length;
  6138. var notChange = len === currentStates.length;
  6139. if (notChange) {
  6140. for (var i = 0; i < len; i++) {
  6141. if (states[i] !== currentStates[i]) {
  6142. notChange = false;
  6143. break;
  6144. }
  6145. }
  6146. }
  6147. if (notChange) {
  6148. return;
  6149. }
  6150. for (var i = 0; i < len; i++) {
  6151. var stateName = states[i];
  6152. var stateObj = void 0;
  6153. if (this.stateProxy) {
  6154. stateObj = this.stateProxy(stateName, states);
  6155. }
  6156. if (!stateObj) {
  6157. stateObj = this.states[stateName];
  6158. }
  6159. if (stateObj) {
  6160. stateObjects.push(stateObj);
  6161. }
  6162. }
  6163. var lastStateObj = stateObjects[len - 1];
  6164. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6165. if (useHoverLayer) {
  6166. this._toggleHoverLayerFlag(true);
  6167. }
  6168. var mergedState = this._mergeStates(stateObjects);
  6169. var animationCfg = this.stateTransition;
  6170. this.saveCurrentToNormalState(mergedState);
  6171. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6172. var textContent = this._textContent;
  6173. var textGuide = this._textGuide;
  6174. if (textContent) {
  6175. textContent.useStates(states, noAnimation, useHoverLayer);
  6176. }
  6177. if (textGuide) {
  6178. textGuide.useStates(states, noAnimation, useHoverLayer);
  6179. }
  6180. this._updateAnimationTargets();
  6181. this.currentStates = states.slice();
  6182. this.markRedraw();
  6183. if (!useHoverLayer && this.__inHover) {
  6184. this._toggleHoverLayerFlag(false);
  6185. this.__dirty &= ~REDRAW_BIT;
  6186. }
  6187. }
  6188. };
  6189. Element.prototype.isSilent = function () {
  6190. var isSilent = this.silent;
  6191. var ancestor = this.parent;
  6192. while (!isSilent && ancestor) {
  6193. if (ancestor.silent) {
  6194. isSilent = true;
  6195. break;
  6196. }
  6197. ancestor = ancestor.parent;
  6198. }
  6199. return isSilent;
  6200. };
  6201. Element.prototype._updateAnimationTargets = function () {
  6202. for (var i = 0; i < this.animators.length; i++) {
  6203. var animator = this.animators[i];
  6204. if (animator.targetName) {
  6205. animator.changeTarget(this[animator.targetName]);
  6206. }
  6207. }
  6208. };
  6209. Element.prototype.removeState = function (state) {
  6210. var idx = indexOf(this.currentStates, state);
  6211. if (idx >= 0) {
  6212. var currentStates = this.currentStates.slice();
  6213. currentStates.splice(idx, 1);
  6214. this.useStates(currentStates);
  6215. }
  6216. };
  6217. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6218. var currentStates = this.currentStates.slice();
  6219. var idx = indexOf(currentStates, oldState);
  6220. var newStateExists = indexOf(currentStates, newState) >= 0;
  6221. if (idx >= 0) {
  6222. if (!newStateExists) {
  6223. currentStates[idx] = newState;
  6224. }
  6225. else {
  6226. currentStates.splice(idx, 1);
  6227. }
  6228. }
  6229. else if (forceAdd && !newStateExists) {
  6230. currentStates.push(newState);
  6231. }
  6232. this.useStates(currentStates);
  6233. };
  6234. Element.prototype.toggleState = function (state, enable) {
  6235. if (enable) {
  6236. this.useState(state, true);
  6237. }
  6238. else {
  6239. this.removeState(state);
  6240. }
  6241. };
  6242. Element.prototype._mergeStates = function (states) {
  6243. var mergedState = {};
  6244. var mergedTextConfig;
  6245. for (var i = 0; i < states.length; i++) {
  6246. var state = states[i];
  6247. extend(mergedState, state);
  6248. if (state.textConfig) {
  6249. mergedTextConfig = mergedTextConfig || {};
  6250. extend(mergedTextConfig, state.textConfig);
  6251. }
  6252. }
  6253. if (mergedTextConfig) {
  6254. mergedState.textConfig = mergedTextConfig;
  6255. }
  6256. return mergedState;
  6257. };
  6258. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6259. var needsRestoreToNormal = !(state && keepCurrentStates);
  6260. if (state && state.textConfig) {
  6261. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6262. extend(this.textConfig, state.textConfig);
  6263. }
  6264. else if (needsRestoreToNormal) {
  6265. if (normalState.textConfig) {
  6266. this.textConfig = normalState.textConfig;
  6267. }
  6268. }
  6269. var transitionTarget = {};
  6270. var hasTransition = false;
  6271. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6272. var key = PRIMARY_STATES_KEYS[i];
  6273. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6274. if (state && state[key] != null) {
  6275. if (propNeedsTransition) {
  6276. hasTransition = true;
  6277. transitionTarget[key] = state[key];
  6278. }
  6279. else {
  6280. this[key] = state[key];
  6281. }
  6282. }
  6283. else if (needsRestoreToNormal) {
  6284. if (normalState[key] != null) {
  6285. if (propNeedsTransition) {
  6286. hasTransition = true;
  6287. transitionTarget[key] = normalState[key];
  6288. }
  6289. else {
  6290. this[key] = normalState[key];
  6291. }
  6292. }
  6293. }
  6294. }
  6295. if (!transition) {
  6296. for (var i = 0; i < this.animators.length; i++) {
  6297. var animator = this.animators[i];
  6298. var targetName = animator.targetName;
  6299. if (!animator.getLoop()) {
  6300. animator.__changeFinalValue(targetName
  6301. ? (state || normalState)[targetName]
  6302. : (state || normalState));
  6303. }
  6304. }
  6305. }
  6306. if (hasTransition) {
  6307. this._transitionState(stateName, transitionTarget, animationCfg);
  6308. }
  6309. };
  6310. Element.prototype._attachComponent = function (componentEl) {
  6311. if (componentEl.__zr && !componentEl.__hostTarget) {
  6312. if ("development" !== 'production') {
  6313. throw new Error('Text element has been added to zrender.');
  6314. }
  6315. return;
  6316. }
  6317. if (componentEl === this) {
  6318. if ("development" !== 'production') {
  6319. throw new Error('Recursive component attachment.');
  6320. }
  6321. return;
  6322. }
  6323. var zr = this.__zr;
  6324. if (zr) {
  6325. componentEl.addSelfToZr(zr);
  6326. }
  6327. componentEl.__zr = zr;
  6328. componentEl.__hostTarget = this;
  6329. };
  6330. Element.prototype._detachComponent = function (componentEl) {
  6331. if (componentEl.__zr) {
  6332. componentEl.removeSelfFromZr(componentEl.__zr);
  6333. }
  6334. componentEl.__zr = null;
  6335. componentEl.__hostTarget = null;
  6336. };
  6337. Element.prototype.getClipPath = function () {
  6338. return this._clipPath;
  6339. };
  6340. Element.prototype.setClipPath = function (clipPath) {
  6341. if (this._clipPath && this._clipPath !== clipPath) {
  6342. this.removeClipPath();
  6343. }
  6344. this._attachComponent(clipPath);
  6345. this._clipPath = clipPath;
  6346. this.markRedraw();
  6347. };
  6348. Element.prototype.removeClipPath = function () {
  6349. var clipPath = this._clipPath;
  6350. if (clipPath) {
  6351. this._detachComponent(clipPath);
  6352. this._clipPath = null;
  6353. this.markRedraw();
  6354. }
  6355. };
  6356. Element.prototype.getTextContent = function () {
  6357. return this._textContent;
  6358. };
  6359. Element.prototype.setTextContent = function (textEl) {
  6360. var previousTextContent = this._textContent;
  6361. if (previousTextContent === textEl) {
  6362. return;
  6363. }
  6364. if (previousTextContent && previousTextContent !== textEl) {
  6365. this.removeTextContent();
  6366. }
  6367. if ("development" !== 'production') {
  6368. if (textEl.__zr && !textEl.__hostTarget) {
  6369. throw new Error('Text element has been added to zrender.');
  6370. }
  6371. }
  6372. textEl.innerTransformable = new Transformable();
  6373. this._attachComponent(textEl);
  6374. this._textContent = textEl;
  6375. this.markRedraw();
  6376. };
  6377. Element.prototype.setTextConfig = function (cfg) {
  6378. if (!this.textConfig) {
  6379. this.textConfig = {};
  6380. }
  6381. extend(this.textConfig, cfg);
  6382. this.markRedraw();
  6383. };
  6384. Element.prototype.removeTextConfig = function () {
  6385. this.textConfig = null;
  6386. this.markRedraw();
  6387. };
  6388. Element.prototype.removeTextContent = function () {
  6389. var textEl = this._textContent;
  6390. if (textEl) {
  6391. textEl.innerTransformable = null;
  6392. this._detachComponent(textEl);
  6393. this._textContent = null;
  6394. this._innerTextDefaultStyle = null;
  6395. this.markRedraw();
  6396. }
  6397. };
  6398. Element.prototype.getTextGuideLine = function () {
  6399. return this._textGuide;
  6400. };
  6401. Element.prototype.setTextGuideLine = function (guideLine) {
  6402. if (this._textGuide && this._textGuide !== guideLine) {
  6403. this.removeTextGuideLine();
  6404. }
  6405. this._attachComponent(guideLine);
  6406. this._textGuide = guideLine;
  6407. this.markRedraw();
  6408. };
  6409. Element.prototype.removeTextGuideLine = function () {
  6410. var textGuide = this._textGuide;
  6411. if (textGuide) {
  6412. this._detachComponent(textGuide);
  6413. this._textGuide = null;
  6414. this.markRedraw();
  6415. }
  6416. };
  6417. Element.prototype.markRedraw = function () {
  6418. this.__dirty |= REDRAW_BIT;
  6419. var zr = this.__zr;
  6420. if (zr) {
  6421. if (this.__inHover) {
  6422. zr.refreshHover();
  6423. }
  6424. else {
  6425. zr.refresh();
  6426. }
  6427. }
  6428. if (this.__hostTarget) {
  6429. this.__hostTarget.markRedraw();
  6430. }
  6431. };
  6432. Element.prototype.dirty = function () {
  6433. this.markRedraw();
  6434. };
  6435. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6436. this.__inHover = inHover;
  6437. var textContent = this._textContent;
  6438. var textGuide = this._textGuide;
  6439. if (textContent) {
  6440. textContent.__inHover = inHover;
  6441. }
  6442. if (textGuide) {
  6443. textGuide.__inHover = inHover;
  6444. }
  6445. };
  6446. Element.prototype.addSelfToZr = function (zr) {
  6447. if (this.__zr === zr) {
  6448. return;
  6449. }
  6450. this.__zr = zr;
  6451. var animators = this.animators;
  6452. if (animators) {
  6453. for (var i = 0; i < animators.length; i++) {
  6454. zr.animation.addAnimator(animators[i]);
  6455. }
  6456. }
  6457. if (this._clipPath) {
  6458. this._clipPath.addSelfToZr(zr);
  6459. }
  6460. if (this._textContent) {
  6461. this._textContent.addSelfToZr(zr);
  6462. }
  6463. if (this._textGuide) {
  6464. this._textGuide.addSelfToZr(zr);
  6465. }
  6466. };
  6467. Element.prototype.removeSelfFromZr = function (zr) {
  6468. if (!this.__zr) {
  6469. return;
  6470. }
  6471. this.__zr = null;
  6472. var animators = this.animators;
  6473. if (animators) {
  6474. for (var i = 0; i < animators.length; i++) {
  6475. zr.animation.removeAnimator(animators[i]);
  6476. }
  6477. }
  6478. if (this._clipPath) {
  6479. this._clipPath.removeSelfFromZr(zr);
  6480. }
  6481. if (this._textContent) {
  6482. this._textContent.removeSelfFromZr(zr);
  6483. }
  6484. if (this._textGuide) {
  6485. this._textGuide.removeSelfFromZr(zr);
  6486. }
  6487. };
  6488. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6489. var target = key ? this[key] : this;
  6490. if ("development" !== 'production') {
  6491. if (!target) {
  6492. logError('Property "'
  6493. + key
  6494. + '" is not existed in element '
  6495. + this.id);
  6496. return;
  6497. }
  6498. }
  6499. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6500. key && (animator.targetName = key);
  6501. this.addAnimator(animator, key);
  6502. return animator;
  6503. };
  6504. Element.prototype.addAnimator = function (animator, key) {
  6505. var zr = this.__zr;
  6506. var el = this;
  6507. animator.during(function () {
  6508. el.updateDuringAnimation(key);
  6509. }).done(function () {
  6510. var animators = el.animators;
  6511. var idx = indexOf(animators, animator);
  6512. if (idx >= 0) {
  6513. animators.splice(idx, 1);
  6514. }
  6515. });
  6516. this.animators.push(animator);
  6517. if (zr) {
  6518. zr.animation.addAnimator(animator);
  6519. }
  6520. zr && zr.wakeUp();
  6521. };
  6522. Element.prototype.updateDuringAnimation = function (key) {
  6523. this.markRedraw();
  6524. };
  6525. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6526. var animators = this.animators;
  6527. var len = animators.length;
  6528. var leftAnimators = [];
  6529. for (var i = 0; i < len; i++) {
  6530. var animator = animators[i];
  6531. if (!scope || scope === animator.scope) {
  6532. animator.stop(forwardToLast);
  6533. }
  6534. else {
  6535. leftAnimators.push(animator);
  6536. }
  6537. }
  6538. this.animators = leftAnimators;
  6539. return this;
  6540. };
  6541. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6542. animateTo(this, target, cfg, animationProps);
  6543. };
  6544. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6545. animateTo(this, target, cfg, animationProps, true);
  6546. };
  6547. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6548. var animators = animateTo(this, target, cfg, animationProps);
  6549. for (var i = 0; i < animators.length; i++) {
  6550. animators[i].__fromStateTransition = stateName;
  6551. }
  6552. };
  6553. Element.prototype.getBoundingRect = function () {
  6554. return null;
  6555. };
  6556. Element.prototype.getPaintRect = function () {
  6557. return null;
  6558. };
  6559. Element.initDefaultProps = (function () {
  6560. var elProto = Element.prototype;
  6561. elProto.type = 'element';
  6562. elProto.name = '';
  6563. elProto.ignore =
  6564. elProto.silent =
  6565. elProto.isGroup =
  6566. elProto.draggable =
  6567. elProto.dragging =
  6568. elProto.ignoreClip =
  6569. elProto.__inHover = false;
  6570. elProto.__dirty = REDRAW_BIT;
  6571. var logs = {};
  6572. function logDeprecatedError(key, xKey, yKey) {
  6573. if (!logs[key + xKey + yKey]) {
  6574. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6575. logs[key + xKey + yKey] = true;
  6576. }
  6577. }
  6578. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6579. Object.defineProperty(elProto, key, {
  6580. get: function () {
  6581. if ("development" !== 'production') {
  6582. logDeprecatedError(key, xKey, yKey);
  6583. }
  6584. if (!this[privateKey]) {
  6585. var pos = this[privateKey] = [];
  6586. enhanceArray(this, pos);
  6587. }
  6588. return this[privateKey];
  6589. },
  6590. set: function (pos) {
  6591. if ("development" !== 'production') {
  6592. logDeprecatedError(key, xKey, yKey);
  6593. }
  6594. this[xKey] = pos[0];
  6595. this[yKey] = pos[1];
  6596. this[privateKey] = pos;
  6597. enhanceArray(this, pos);
  6598. }
  6599. });
  6600. function enhanceArray(self, pos) {
  6601. Object.defineProperty(pos, 0, {
  6602. get: function () {
  6603. return self[xKey];
  6604. },
  6605. set: function (val) {
  6606. self[xKey] = val;
  6607. }
  6608. });
  6609. Object.defineProperty(pos, 1, {
  6610. get: function () {
  6611. return self[yKey];
  6612. },
  6613. set: function (val) {
  6614. self[yKey] = val;
  6615. }
  6616. });
  6617. }
  6618. }
  6619. if (Object.defineProperty) {
  6620. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6621. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6622. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6623. }
  6624. })();
  6625. return Element;
  6626. }());
  6627. mixin(Element, Eventful);
  6628. mixin(Element, Transformable);
  6629. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6630. cfg = cfg || {};
  6631. var animators = [];
  6632. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6633. var finishCount = animators.length;
  6634. var doneHappened = false;
  6635. var cfgDone = cfg.done;
  6636. var cfgAborted = cfg.aborted;
  6637. var doneCb = function () {
  6638. doneHappened = true;
  6639. finishCount--;
  6640. if (finishCount <= 0) {
  6641. doneHappened
  6642. ? (cfgDone && cfgDone())
  6643. : (cfgAborted && cfgAborted());
  6644. }
  6645. };
  6646. var abortedCb = function () {
  6647. finishCount--;
  6648. if (finishCount <= 0) {
  6649. doneHappened
  6650. ? (cfgDone && cfgDone())
  6651. : (cfgAborted && cfgAborted());
  6652. }
  6653. };
  6654. if (!finishCount) {
  6655. cfgDone && cfgDone();
  6656. }
  6657. if (animators.length > 0 && cfg.during) {
  6658. animators[0].during(function (target, percent) {
  6659. cfg.during(percent);
  6660. });
  6661. }
  6662. for (var i = 0; i < animators.length; i++) {
  6663. var animator = animators[i];
  6664. if (doneCb) {
  6665. animator.done(doneCb);
  6666. }
  6667. if (abortedCb) {
  6668. animator.aborted(abortedCb);
  6669. }
  6670. if (cfg.force) {
  6671. animator.duration(cfg.duration);
  6672. }
  6673. animator.start(cfg.easing);
  6674. }
  6675. return animators;
  6676. }
  6677. function copyArrShallow(source, target, len) {
  6678. for (var i = 0; i < len; i++) {
  6679. source[i] = target[i];
  6680. }
  6681. }
  6682. function is2DArray(value) {
  6683. return isArrayLike(value[0]);
  6684. }
  6685. function copyValue(target, source, key) {
  6686. if (isArrayLike(source[key])) {
  6687. if (!isArrayLike(target[key])) {
  6688. target[key] = [];
  6689. }
  6690. if (isTypedArray(source[key])) {
  6691. var len = source[key].length;
  6692. if (target[key].length !== len) {
  6693. target[key] = new (source[key].constructor)(len);
  6694. copyArrShallow(target[key], source[key], len);
  6695. }
  6696. }
  6697. else {
  6698. var sourceArr = source[key];
  6699. var targetArr = target[key];
  6700. var len0 = sourceArr.length;
  6701. if (is2DArray(sourceArr)) {
  6702. var len1 = sourceArr[0].length;
  6703. for (var i = 0; i < len0; i++) {
  6704. if (!targetArr[i]) {
  6705. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6706. }
  6707. else {
  6708. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6709. }
  6710. }
  6711. }
  6712. else {
  6713. copyArrShallow(targetArr, sourceArr, len0);
  6714. }
  6715. targetArr.length = sourceArr.length;
  6716. }
  6717. }
  6718. else {
  6719. target[key] = source[key];
  6720. }
  6721. }
  6722. function isValueSame(val1, val2) {
  6723. return val1 === val2
  6724. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6725. }
  6726. function is1DArraySame(arr0, arr1) {
  6727. var len = arr0.length;
  6728. if (len !== arr1.length) {
  6729. return false;
  6730. }
  6731. for (var i = 0; i < len; i++) {
  6732. if (arr0[i] !== arr1[i]) {
  6733. return false;
  6734. }
  6735. }
  6736. return true;
  6737. }
  6738. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6739. var targetKeys = keys(target);
  6740. var duration = cfg.duration;
  6741. var delay = cfg.delay;
  6742. var additive = cfg.additive;
  6743. var setToFinal = cfg.setToFinal;
  6744. var animateAll = !isObject(animationProps);
  6745. var existsAnimators = animatable.animators;
  6746. var animationKeys = [];
  6747. for (var k = 0; k < targetKeys.length; k++) {
  6748. var innerKey = targetKeys[k];
  6749. var targetVal = target[innerKey];
  6750. if (targetVal != null && animateObj[innerKey] != null
  6751. && (animateAll || animationProps[innerKey])) {
  6752. if (isObject(targetVal)
  6753. && !isArrayLike(targetVal)
  6754. && !isGradientObject(targetVal)) {
  6755. if (topKey) {
  6756. if (!reverse) {
  6757. animateObj[innerKey] = targetVal;
  6758. animatable.updateDuringAnimation(topKey);
  6759. }
  6760. continue;
  6761. }
  6762. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6763. }
  6764. else {
  6765. animationKeys.push(innerKey);
  6766. }
  6767. }
  6768. else if (!reverse) {
  6769. animateObj[innerKey] = targetVal;
  6770. animatable.updateDuringAnimation(topKey);
  6771. animationKeys.push(innerKey);
  6772. }
  6773. }
  6774. var keyLen = animationKeys.length;
  6775. if (!additive && keyLen) {
  6776. for (var i = 0; i < existsAnimators.length; i++) {
  6777. var animator = existsAnimators[i];
  6778. if (animator.targetName === topKey) {
  6779. var allAborted = animator.stopTracks(animationKeys);
  6780. if (allAborted) {
  6781. var idx = indexOf(existsAnimators, animator);
  6782. existsAnimators.splice(idx, 1);
  6783. }
  6784. }
  6785. }
  6786. }
  6787. if (!cfg.force) {
  6788. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6789. keyLen = animationKeys.length;
  6790. }
  6791. if (keyLen > 0
  6792. || (cfg.force && !animators.length)) {
  6793. var revertedSource = void 0;
  6794. var reversedTarget = void 0;
  6795. var sourceClone = void 0;
  6796. if (reverse) {
  6797. reversedTarget = {};
  6798. if (setToFinal) {
  6799. revertedSource = {};
  6800. }
  6801. for (var i = 0; i < keyLen; i++) {
  6802. var innerKey = animationKeys[i];
  6803. reversedTarget[innerKey] = animateObj[innerKey];
  6804. if (setToFinal) {
  6805. revertedSource[innerKey] = target[innerKey];
  6806. }
  6807. else {
  6808. animateObj[innerKey] = target[innerKey];
  6809. }
  6810. }
  6811. }
  6812. else if (setToFinal) {
  6813. sourceClone = {};
  6814. for (var i = 0; i < keyLen; i++) {
  6815. var innerKey = animationKeys[i];
  6816. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6817. copyValue(animateObj, target, innerKey);
  6818. }
  6819. }
  6820. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6821. animator.targetName = topKey;
  6822. if (cfg.scope) {
  6823. animator.scope = cfg.scope;
  6824. }
  6825. if (setToFinal && revertedSource) {
  6826. animator.whenWithKeys(0, revertedSource, animationKeys);
  6827. }
  6828. if (sourceClone) {
  6829. animator.whenWithKeys(0, sourceClone, animationKeys);
  6830. }
  6831. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6832. animatable.addAnimator(animator, topKey);
  6833. animators.push(animator);
  6834. }
  6835. }
  6836. var Group = (function (_super) {
  6837. __extends(Group, _super);
  6838. function Group(opts) {
  6839. var _this = _super.call(this) || this;
  6840. _this.isGroup = true;
  6841. _this._children = [];
  6842. _this.attr(opts);
  6843. return _this;
  6844. }
  6845. Group.prototype.childrenRef = function () {
  6846. return this._children;
  6847. };
  6848. Group.prototype.children = function () {
  6849. return this._children.slice();
  6850. };
  6851. Group.prototype.childAt = function (idx) {
  6852. return this._children[idx];
  6853. };
  6854. Group.prototype.childOfName = function (name) {
  6855. var children = this._children;
  6856. for (var i = 0; i < children.length; i++) {
  6857. if (children[i].name === name) {
  6858. return children[i];
  6859. }
  6860. }
  6861. };
  6862. Group.prototype.childCount = function () {
  6863. return this._children.length;
  6864. };
  6865. Group.prototype.add = function (child) {
  6866. if (child) {
  6867. if (child !== this && child.parent !== this) {
  6868. this._children.push(child);
  6869. this._doAdd(child);
  6870. }
  6871. if ("development" !== 'production') {
  6872. if (child.__hostTarget) {
  6873. throw 'This elemenet has been used as an attachment';
  6874. }
  6875. }
  6876. }
  6877. return this;
  6878. };
  6879. Group.prototype.addBefore = function (child, nextSibling) {
  6880. if (child && child !== this && child.parent !== this
  6881. && nextSibling && nextSibling.parent === this) {
  6882. var children = this._children;
  6883. var idx = children.indexOf(nextSibling);
  6884. if (idx >= 0) {
  6885. children.splice(idx, 0, child);
  6886. this._doAdd(child);
  6887. }
  6888. }
  6889. return this;
  6890. };
  6891. Group.prototype.replace = function (oldChild, newChild) {
  6892. var idx = indexOf(this._children, oldChild);
  6893. if (idx >= 0) {
  6894. this.replaceAt(newChild, idx);
  6895. }
  6896. return this;
  6897. };
  6898. Group.prototype.replaceAt = function (child, index) {
  6899. var children = this._children;
  6900. var old = children[index];
  6901. if (child && child !== this && child.parent !== this && child !== old) {
  6902. children[index] = child;
  6903. old.parent = null;
  6904. var zr = this.__zr;
  6905. if (zr) {
  6906. old.removeSelfFromZr(zr);
  6907. }
  6908. this._doAdd(child);
  6909. }
  6910. return this;
  6911. };
  6912. Group.prototype._doAdd = function (child) {
  6913. if (child.parent) {
  6914. child.parent.remove(child);
  6915. }
  6916. child.parent = this;
  6917. var zr = this.__zr;
  6918. if (zr && zr !== child.__zr) {
  6919. child.addSelfToZr(zr);
  6920. }
  6921. zr && zr.refresh();
  6922. };
  6923. Group.prototype.remove = function (child) {
  6924. var zr = this.__zr;
  6925. var children = this._children;
  6926. var idx = indexOf(children, child);
  6927. if (idx < 0) {
  6928. return this;
  6929. }
  6930. children.splice(idx, 1);
  6931. child.parent = null;
  6932. if (zr) {
  6933. child.removeSelfFromZr(zr);
  6934. }
  6935. zr && zr.refresh();
  6936. return this;
  6937. };
  6938. Group.prototype.removeAll = function () {
  6939. var children = this._children;
  6940. var zr = this.__zr;
  6941. for (var i = 0; i < children.length; i++) {
  6942. var child = children[i];
  6943. if (zr) {
  6944. child.removeSelfFromZr(zr);
  6945. }
  6946. child.parent = null;
  6947. }
  6948. children.length = 0;
  6949. return this;
  6950. };
  6951. Group.prototype.eachChild = function (cb, context) {
  6952. var children = this._children;
  6953. for (var i = 0; i < children.length; i++) {
  6954. var child = children[i];
  6955. cb.call(context, child, i);
  6956. }
  6957. return this;
  6958. };
  6959. Group.prototype.traverse = function (cb, context) {
  6960. for (var i = 0; i < this._children.length; i++) {
  6961. var child = this._children[i];
  6962. var stopped = cb.call(context, child);
  6963. if (child.isGroup && !stopped) {
  6964. child.traverse(cb, context);
  6965. }
  6966. }
  6967. return this;
  6968. };
  6969. Group.prototype.addSelfToZr = function (zr) {
  6970. _super.prototype.addSelfToZr.call(this, zr);
  6971. for (var i = 0; i < this._children.length; i++) {
  6972. var child = this._children[i];
  6973. child.addSelfToZr(zr);
  6974. }
  6975. };
  6976. Group.prototype.removeSelfFromZr = function (zr) {
  6977. _super.prototype.removeSelfFromZr.call(this, zr);
  6978. for (var i = 0; i < this._children.length; i++) {
  6979. var child = this._children[i];
  6980. child.removeSelfFromZr(zr);
  6981. }
  6982. };
  6983. Group.prototype.getBoundingRect = function (includeChildren) {
  6984. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6985. var children = includeChildren || this._children;
  6986. var tmpMat = [];
  6987. var rect = null;
  6988. for (var i = 0; i < children.length; i++) {
  6989. var child = children[i];
  6990. if (child.ignore || child.invisible) {
  6991. continue;
  6992. }
  6993. var childRect = child.getBoundingRect();
  6994. var transform = child.getLocalTransform(tmpMat);
  6995. if (transform) {
  6996. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6997. rect = rect || tmpRect.clone();
  6998. rect.union(tmpRect);
  6999. }
  7000. else {
  7001. rect = rect || childRect.clone();
  7002. rect.union(childRect);
  7003. }
  7004. }
  7005. return rect || tmpRect;
  7006. };
  7007. return Group;
  7008. }(Element));
  7009. Group.prototype.type = 'group';
  7010. /*!
  7011. * ZRender, a high performance 2d drawing library.
  7012. *
  7013. * Copyright (c) 2013, Baidu Inc.
  7014. * All rights reserved.
  7015. *
  7016. * LICENSE
  7017. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  7018. */
  7019. var painterCtors = {};
  7020. var instances = {};
  7021. function delInstance(id) {
  7022. delete instances[id];
  7023. }
  7024. function isDarkMode(backgroundColor) {
  7025. if (!backgroundColor) {
  7026. return false;
  7027. }
  7028. if (typeof backgroundColor === 'string') {
  7029. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  7030. }
  7031. else if (backgroundColor.colorStops) {
  7032. var colorStops = backgroundColor.colorStops;
  7033. var totalLum = 0;
  7034. var len = colorStops.length;
  7035. for (var i = 0; i < len; i++) {
  7036. totalLum += lum(colorStops[i].color, 1);
  7037. }
  7038. totalLum /= len;
  7039. return totalLum < DARK_MODE_THRESHOLD;
  7040. }
  7041. return false;
  7042. }
  7043. var ZRender = (function () {
  7044. function ZRender(id, dom, opts) {
  7045. var _this = this;
  7046. this._sleepAfterStill = 10;
  7047. this._stillFrameAccum = 0;
  7048. this._needsRefresh = true;
  7049. this._needsRefreshHover = true;
  7050. this._darkMode = false;
  7051. opts = opts || {};
  7052. this.dom = dom;
  7053. this.id = id;
  7054. var storage = new Storage();
  7055. var rendererType = opts.renderer || 'canvas';
  7056. if (!painterCtors[rendererType]) {
  7057. rendererType = keys(painterCtors)[0];
  7058. }
  7059. if ("development" !== 'production') {
  7060. if (!painterCtors[rendererType]) {
  7061. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7062. }
  7063. }
  7064. opts.useDirtyRect = opts.useDirtyRect == null
  7065. ? false
  7066. : opts.useDirtyRect;
  7067. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7068. var ssrMode = opts.ssr || painter.ssrOnly;
  7069. this.storage = storage;
  7070. this.painter = painter;
  7071. var handlerProxy = (!env.node && !env.worker && !ssrMode)
  7072. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7073. : null;
  7074. var useCoarsePointer = opts.useCoarsePointer;
  7075. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7076. ? env.touchEventsSupported
  7077. : !!useCoarsePointer;
  7078. var defaultPointerSize = 44;
  7079. var pointerSize;
  7080. if (usePointerSize) {
  7081. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7082. }
  7083. this.handler = new Handler(storage, painter, handlerProxy, painter.root, pointerSize);
  7084. this.animation = new Animation({
  7085. stage: {
  7086. update: ssrMode ? null : function () { return _this._flush(true); }
  7087. }
  7088. });
  7089. if (!ssrMode) {
  7090. this.animation.start();
  7091. }
  7092. }
  7093. ZRender.prototype.add = function (el) {
  7094. if (this._disposed || !el) {
  7095. return;
  7096. }
  7097. this.storage.addRoot(el);
  7098. el.addSelfToZr(this);
  7099. this.refresh();
  7100. };
  7101. ZRender.prototype.remove = function (el) {
  7102. if (this._disposed || !el) {
  7103. return;
  7104. }
  7105. this.storage.delRoot(el);
  7106. el.removeSelfFromZr(this);
  7107. this.refresh();
  7108. };
  7109. ZRender.prototype.configLayer = function (zLevel, config) {
  7110. if (this._disposed) {
  7111. return;
  7112. }
  7113. if (this.painter.configLayer) {
  7114. this.painter.configLayer(zLevel, config);
  7115. }
  7116. this.refresh();
  7117. };
  7118. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7119. if (this._disposed) {
  7120. return;
  7121. }
  7122. if (this.painter.setBackgroundColor) {
  7123. this.painter.setBackgroundColor(backgroundColor);
  7124. }
  7125. this.refresh();
  7126. this._backgroundColor = backgroundColor;
  7127. this._darkMode = isDarkMode(backgroundColor);
  7128. };
  7129. ZRender.prototype.getBackgroundColor = function () {
  7130. return this._backgroundColor;
  7131. };
  7132. ZRender.prototype.setDarkMode = function (darkMode) {
  7133. this._darkMode = darkMode;
  7134. };
  7135. ZRender.prototype.isDarkMode = function () {
  7136. return this._darkMode;
  7137. };
  7138. ZRender.prototype.refreshImmediately = function (fromInside) {
  7139. if (this._disposed) {
  7140. return;
  7141. }
  7142. if (!fromInside) {
  7143. this.animation.update(true);
  7144. }
  7145. this._needsRefresh = false;
  7146. this.painter.refresh();
  7147. this._needsRefresh = false;
  7148. };
  7149. ZRender.prototype.refresh = function () {
  7150. if (this._disposed) {
  7151. return;
  7152. }
  7153. this._needsRefresh = true;
  7154. this.animation.start();
  7155. };
  7156. ZRender.prototype.flush = function () {
  7157. if (this._disposed) {
  7158. return;
  7159. }
  7160. this._flush(false);
  7161. };
  7162. ZRender.prototype._flush = function (fromInside) {
  7163. var triggerRendered;
  7164. var start = getTime();
  7165. if (this._needsRefresh) {
  7166. triggerRendered = true;
  7167. this.refreshImmediately(fromInside);
  7168. }
  7169. if (this._needsRefreshHover) {
  7170. triggerRendered = true;
  7171. this.refreshHoverImmediately();
  7172. }
  7173. var end = getTime();
  7174. if (triggerRendered) {
  7175. this._stillFrameAccum = 0;
  7176. this.trigger('rendered', {
  7177. elapsedTime: end - start
  7178. });
  7179. }
  7180. else if (this._sleepAfterStill > 0) {
  7181. this._stillFrameAccum++;
  7182. if (this._stillFrameAccum > this._sleepAfterStill) {
  7183. this.animation.stop();
  7184. }
  7185. }
  7186. };
  7187. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7188. this._sleepAfterStill = stillFramesCount;
  7189. };
  7190. ZRender.prototype.wakeUp = function () {
  7191. if (this._disposed) {
  7192. return;
  7193. }
  7194. this.animation.start();
  7195. this._stillFrameAccum = 0;
  7196. };
  7197. ZRender.prototype.refreshHover = function () {
  7198. this._needsRefreshHover = true;
  7199. };
  7200. ZRender.prototype.refreshHoverImmediately = function () {
  7201. if (this._disposed) {
  7202. return;
  7203. }
  7204. this._needsRefreshHover = false;
  7205. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7206. this.painter.refreshHover();
  7207. }
  7208. };
  7209. ZRender.prototype.resize = function (opts) {
  7210. if (this._disposed) {
  7211. return;
  7212. }
  7213. opts = opts || {};
  7214. this.painter.resize(opts.width, opts.height);
  7215. this.handler.resize();
  7216. };
  7217. ZRender.prototype.clearAnimation = function () {
  7218. if (this._disposed) {
  7219. return;
  7220. }
  7221. this.animation.clear();
  7222. };
  7223. ZRender.prototype.getWidth = function () {
  7224. if (this._disposed) {
  7225. return;
  7226. }
  7227. return this.painter.getWidth();
  7228. };
  7229. ZRender.prototype.getHeight = function () {
  7230. if (this._disposed) {
  7231. return;
  7232. }
  7233. return this.painter.getHeight();
  7234. };
  7235. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7236. if (this._disposed) {
  7237. return;
  7238. }
  7239. this.handler.setCursorStyle(cursorStyle);
  7240. };
  7241. ZRender.prototype.findHover = function (x, y) {
  7242. if (this._disposed) {
  7243. return;
  7244. }
  7245. return this.handler.findHover(x, y);
  7246. };
  7247. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7248. if (!this._disposed) {
  7249. this.handler.on(eventName, eventHandler, context);
  7250. }
  7251. return this;
  7252. };
  7253. ZRender.prototype.off = function (eventName, eventHandler) {
  7254. if (this._disposed) {
  7255. return;
  7256. }
  7257. this.handler.off(eventName, eventHandler);
  7258. };
  7259. ZRender.prototype.trigger = function (eventName, event) {
  7260. if (this._disposed) {
  7261. return;
  7262. }
  7263. this.handler.trigger(eventName, event);
  7264. };
  7265. ZRender.prototype.clear = function () {
  7266. if (this._disposed) {
  7267. return;
  7268. }
  7269. var roots = this.storage.getRoots();
  7270. for (var i = 0; i < roots.length; i++) {
  7271. if (roots[i] instanceof Group) {
  7272. roots[i].removeSelfFromZr(this);
  7273. }
  7274. }
  7275. this.storage.delAllRoots();
  7276. this.painter.clear();
  7277. };
  7278. ZRender.prototype.dispose = function () {
  7279. if (this._disposed) {
  7280. return;
  7281. }
  7282. this.animation.stop();
  7283. this.clear();
  7284. this.storage.dispose();
  7285. this.painter.dispose();
  7286. this.handler.dispose();
  7287. this.animation =
  7288. this.storage =
  7289. this.painter =
  7290. this.handler = null;
  7291. this._disposed = true;
  7292. delInstance(this.id);
  7293. };
  7294. return ZRender;
  7295. }());
  7296. function init(dom, opts) {
  7297. var zr = new ZRender(guid(), dom, opts);
  7298. instances[zr.id] = zr;
  7299. return zr;
  7300. }
  7301. function dispose(zr) {
  7302. zr.dispose();
  7303. }
  7304. function disposeAll() {
  7305. for (var key in instances) {
  7306. if (instances.hasOwnProperty(key)) {
  7307. instances[key].dispose();
  7308. }
  7309. }
  7310. instances = {};
  7311. }
  7312. function getInstance(id) {
  7313. return instances[id];
  7314. }
  7315. function registerPainter(name, Ctor) {
  7316. painterCtors[name] = Ctor;
  7317. }
  7318. var ssrDataGetter;
  7319. function getElementSSRData(el) {
  7320. if (typeof ssrDataGetter === 'function') {
  7321. return ssrDataGetter(el);
  7322. }
  7323. }
  7324. function registerSSRDataGetter(getter) {
  7325. ssrDataGetter = getter;
  7326. }
  7327. var version = '5.6.1';
  7328. var zrender = /*#__PURE__*/Object.freeze({
  7329. __proto__: null,
  7330. init: init,
  7331. dispose: dispose,
  7332. disposeAll: disposeAll,
  7333. getInstance: getInstance,
  7334. registerPainter: registerPainter,
  7335. getElementSSRData: getElementSSRData,
  7336. registerSSRDataGetter: registerSSRDataGetter,
  7337. version: version
  7338. });
  7339. var RADIAN_EPSILON = 1e-4;
  7340. // Although chrome already enlarge this number to 100 for `toFixed`, but
  7341. // we sill follow the spec for compatibility.
  7342. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7343. function _trim(str) {
  7344. return str.replace(/^\s+|\s+$/g, '');
  7345. }
  7346. /**
  7347. * Linear mapping a value from domain to range
  7348. * @param val
  7349. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7350. * @param range Range extent range[0] can be bigger than range[1]
  7351. * @param clamp Default to be false
  7352. */
  7353. function linearMap(val, domain, range, clamp) {
  7354. var d0 = domain[0];
  7355. var d1 = domain[1];
  7356. var r0 = range[0];
  7357. var r1 = range[1];
  7358. var subDomain = d1 - d0;
  7359. var subRange = r1 - r0;
  7360. if (subDomain === 0) {
  7361. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7362. }
  7363. // Avoid accuracy problem in edge, such as
  7364. // 146.39 - 62.83 === 83.55999999999999.
  7365. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7366. // It is a little verbose for efficiency considering this method
  7367. // is a hotspot.
  7368. if (clamp) {
  7369. if (subDomain > 0) {
  7370. if (val <= d0) {
  7371. return r0;
  7372. } else if (val >= d1) {
  7373. return r1;
  7374. }
  7375. } else {
  7376. if (val >= d0) {
  7377. return r0;
  7378. } else if (val <= d1) {
  7379. return r1;
  7380. }
  7381. }
  7382. } else {
  7383. if (val === d0) {
  7384. return r0;
  7385. }
  7386. if (val === d1) {
  7387. return r1;
  7388. }
  7389. }
  7390. return (val - d0) / subDomain * subRange + r0;
  7391. }
  7392. /**
  7393. * Convert a percent string to absolute number.
  7394. * Returns NaN if percent is not a valid string or number
  7395. */
  7396. function parsePercent$1(percent, all) {
  7397. switch (percent) {
  7398. case 'center':
  7399. case 'middle':
  7400. percent = '50%';
  7401. break;
  7402. case 'left':
  7403. case 'top':
  7404. percent = '0%';
  7405. break;
  7406. case 'right':
  7407. case 'bottom':
  7408. percent = '100%';
  7409. break;
  7410. }
  7411. if (isString(percent)) {
  7412. if (_trim(percent).match(/%$/)) {
  7413. return parseFloat(percent) / 100 * all;
  7414. }
  7415. return parseFloat(percent);
  7416. }
  7417. return percent == null ? NaN : +percent;
  7418. }
  7419. function round(x, precision, returnStr) {
  7420. if (precision == null) {
  7421. precision = 10;
  7422. }
  7423. // Avoid range error
  7424. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX);
  7425. // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7426. x = (+x).toFixed(precision);
  7427. return returnStr ? x : +x;
  7428. }
  7429. /**
  7430. * Inplacd asc sort arr.
  7431. * The input arr will be modified.
  7432. */
  7433. function asc(arr) {
  7434. arr.sort(function (a, b) {
  7435. return a - b;
  7436. });
  7437. return arr;
  7438. }
  7439. /**
  7440. * Get precision.
  7441. */
  7442. function getPrecision(val) {
  7443. val = +val;
  7444. if (isNaN(val)) {
  7445. return 0;
  7446. }
  7447. // It is much faster than methods converting number to string as follows
  7448. // let tmp = val.toString();
  7449. // return tmp.length - 1 - tmp.indexOf('.');
  7450. // especially when precision is low
  7451. // Notice:
  7452. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7453. // (see https://jsbench.me/2vkpcekkvw/1)
  7454. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7455. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7456. if (val > 1e-14) {
  7457. var e = 1;
  7458. for (var i = 0; i < 15; i++, e *= 10) {
  7459. if (Math.round(val * e) / e === val) {
  7460. return i;
  7461. }
  7462. }
  7463. }
  7464. return getPrecisionSafe(val);
  7465. }
  7466. /**
  7467. * Get precision with slow but safe method
  7468. */
  7469. function getPrecisionSafe(val) {
  7470. // toLowerCase for: '3.4E-12'
  7471. var str = val.toString().toLowerCase();
  7472. // Consider scientific notation: '3.4e-12' '3.4e+12'
  7473. var eIndex = str.indexOf('e');
  7474. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7475. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7476. var dotIndex = str.indexOf('.');
  7477. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7478. return Math.max(0, decimalPartLen - exp);
  7479. }
  7480. /**
  7481. * Minimal dicernible data precisioin according to a single pixel.
  7482. */
  7483. function getPixelPrecision(dataExtent, pixelExtent) {
  7484. var log = Math.log;
  7485. var LN10 = Math.LN10;
  7486. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7487. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  7488. // toFixed() digits argument must be between 0 and 20.
  7489. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7490. return !isFinite(precision) ? 20 : precision;
  7491. }
  7492. /**
  7493. * Get a data of given precision, assuring the sum of percentages
  7494. * in valueList is 1.
  7495. * The largest remainder method is used.
  7496. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7497. *
  7498. * @param valueList a list of all data
  7499. * @param idx index of the data to be processed in valueList
  7500. * @param precision integer number showing digits of precision
  7501. * @return percent ranging from 0 to 100
  7502. */
  7503. function getPercentWithPrecision(valueList, idx, precision) {
  7504. if (!valueList[idx]) {
  7505. return 0;
  7506. }
  7507. var seats = getPercentSeats(valueList, precision);
  7508. return seats[idx] || 0;
  7509. }
  7510. /**
  7511. * Get a data of given precision, assuring the sum of percentages
  7512. * in valueList is 1.
  7513. * The largest remainder method is used.
  7514. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7515. *
  7516. * @param valueList a list of all data
  7517. * @param precision integer number showing digits of precision
  7518. * @return {Array<number>}
  7519. */
  7520. function getPercentSeats(valueList, precision) {
  7521. var sum = reduce(valueList, function (acc, val) {
  7522. return acc + (isNaN(val) ? 0 : val);
  7523. }, 0);
  7524. if (sum === 0) {
  7525. return [];
  7526. }
  7527. var digits = Math.pow(10, precision);
  7528. var votesPerQuota = map(valueList, function (val) {
  7529. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7530. });
  7531. var targetSeats = digits * 100;
  7532. var seats = map(votesPerQuota, function (votes) {
  7533. // Assign automatic seats.
  7534. return Math.floor(votes);
  7535. });
  7536. var currentSum = reduce(seats, function (acc, val) {
  7537. return acc + val;
  7538. }, 0);
  7539. var remainder = map(votesPerQuota, function (votes, idx) {
  7540. return votes - seats[idx];
  7541. });
  7542. // Has remainding votes.
  7543. while (currentSum < targetSeats) {
  7544. // Find next largest remainder.
  7545. var max = Number.NEGATIVE_INFINITY;
  7546. var maxId = null;
  7547. for (var i = 0, len = remainder.length; i < len; ++i) {
  7548. if (remainder[i] > max) {
  7549. max = remainder[i];
  7550. maxId = i;
  7551. }
  7552. }
  7553. // Add a vote to max remainder.
  7554. ++seats[maxId];
  7555. remainder[maxId] = 0;
  7556. ++currentSum;
  7557. }
  7558. return map(seats, function (seat) {
  7559. return seat / digits;
  7560. });
  7561. }
  7562. /**
  7563. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7564. * See <http://0.30000000000000004.com/>
  7565. */
  7566. function addSafe(val0, val1) {
  7567. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1));
  7568. // const multiplier = Math.pow(10, maxPrecision);
  7569. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7570. var sum = val0 + val1;
  7571. // // PENDING: support more?
  7572. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7573. }
  7574. // Number.MAX_SAFE_INTEGER, ie do not support.
  7575. var MAX_SAFE_INTEGER = 9007199254740991;
  7576. /**
  7577. * To 0 - 2 * PI, considering negative radian.
  7578. */
  7579. function remRadian(radian) {
  7580. var pi2 = Math.PI * 2;
  7581. return (radian % pi2 + pi2) % pi2;
  7582. }
  7583. /**
  7584. * @param {type} radian
  7585. * @return {boolean}
  7586. */
  7587. function isRadianAroundZero(val) {
  7588. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7589. }
  7590. // eslint-disable-next-line
  7591. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  7592. /**
  7593. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7594. * These values can be accepted:
  7595. * + An instance of Date, represent a time in its own time zone.
  7596. * + Or string in a subset of ISO 8601, only including:
  7597. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7598. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7599. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7600. * all of which will be treated as local time if time zone is not specified
  7601. * (see <https://momentjs.com/>).
  7602. * + Or other string format, including (all of which will be treated as local time):
  7603. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7604. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7605. * + a timestamp, which represent a time in UTC.
  7606. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7607. */
  7608. function parseDate(value) {
  7609. if (value instanceof Date) {
  7610. return value;
  7611. } else if (isString(value)) {
  7612. // Different browsers parse date in different way, so we parse it manually.
  7613. // Some other issues:
  7614. // new Date('1970-01-01') is UTC,
  7615. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7616. // See issue #3623
  7617. var match = TIME_REG.exec(value);
  7618. if (!match) {
  7619. // return Invalid Date.
  7620. return new Date(NaN);
  7621. }
  7622. // Use local time when no timezone offset is specified.
  7623. if (!match[8]) {
  7624. // match[n] can only be string or undefined.
  7625. // But take care of '12' + 1 => '121'.
  7626. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0);
  7627. }
  7628. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7629. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7630. // For example, system timezone is set as "Time Zone: America/Toronto",
  7631. // then these code will get different result:
  7632. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7633. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7634. // So we should not use `new Date`, but use `Date.UTC`.
  7635. else {
  7636. var hour = +match[4] || 0;
  7637. if (match[8].toUpperCase() !== 'Z') {
  7638. hour -= +match[8].slice(0, 3);
  7639. }
  7640. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0));
  7641. }
  7642. } else if (value == null) {
  7643. return new Date(NaN);
  7644. }
  7645. return new Date(Math.round(value));
  7646. }
  7647. /**
  7648. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7649. *
  7650. * @param val
  7651. * @return
  7652. */
  7653. function quantity(val) {
  7654. return Math.pow(10, quantityExponent(val));
  7655. }
  7656. /**
  7657. * Exponent of the quantity of a number
  7658. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7659. *
  7660. * @param val non-negative value
  7661. * @return
  7662. */
  7663. function quantityExponent(val) {
  7664. if (val === 0) {
  7665. return 0;
  7666. }
  7667. var exp = Math.floor(Math.log(val) / Math.LN10);
  7668. /**
  7669. * exp is expected to be the rounded-down result of the base-10 log of val.
  7670. * But due to the precision loss with Math.log(val), we need to restore it
  7671. * using 10^exp to make sure we can get val back from exp. #11249
  7672. */
  7673. if (val / Math.pow(10, exp) >= 10) {
  7674. exp++;
  7675. }
  7676. return exp;
  7677. }
  7678. /**
  7679. * find a “nice” number approximately equal to x. Round the number if round = true,
  7680. * take ceiling if round = false. The primary observation is that the “nicest”
  7681. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7682. *
  7683. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7684. *
  7685. * @param val Non-negative value.
  7686. * @param round
  7687. * @return Niced number
  7688. */
  7689. function nice(val, round) {
  7690. var exponent = quantityExponent(val);
  7691. var exp10 = Math.pow(10, exponent);
  7692. var f = val / exp10; // 1 <= f < 10
  7693. var nf;
  7694. if (round) {
  7695. if (f < 1.5) {
  7696. nf = 1;
  7697. } else if (f < 2.5) {
  7698. nf = 2;
  7699. } else if (f < 4) {
  7700. nf = 3;
  7701. } else if (f < 7) {
  7702. nf = 5;
  7703. } else {
  7704. nf = 10;
  7705. }
  7706. } else {
  7707. if (f < 1) {
  7708. nf = 1;
  7709. } else if (f < 2) {
  7710. nf = 2;
  7711. } else if (f < 3) {
  7712. nf = 3;
  7713. } else if (f < 5) {
  7714. nf = 5;
  7715. } else {
  7716. nf = 10;
  7717. }
  7718. }
  7719. val = nf * exp10;
  7720. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7721. // 20 is the uppper bound of toFixed.
  7722. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7723. }
  7724. /**
  7725. * This code was copied from "d3.js"
  7726. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7727. * See the license statement at the head of this file.
  7728. * @param ascArr
  7729. */
  7730. function quantile(ascArr, p) {
  7731. var H = (ascArr.length - 1) * p + 1;
  7732. var h = Math.floor(H);
  7733. var v = +ascArr[h - 1];
  7734. var e = H - h;
  7735. return e ? v + e * (ascArr[h] - v) : v;
  7736. }
  7737. /**
  7738. * Order intervals asc, and split them when overlap.
  7739. * expect(numberUtil.reformIntervals([
  7740. * {interval: [18, 62], close: [1, 1]},
  7741. * {interval: [-Infinity, -70], close: [0, 0]},
  7742. * {interval: [-70, -26], close: [1, 1]},
  7743. * {interval: [-26, 18], close: [1, 1]},
  7744. * {interval: [62, 150], close: [1, 1]},
  7745. * {interval: [106, 150], close: [1, 1]},
  7746. * {interval: [150, Infinity], close: [0, 0]}
  7747. * ])).toEqual([
  7748. * {interval: [-Infinity, -70], close: [0, 0]},
  7749. * {interval: [-70, -26], close: [1, 1]},
  7750. * {interval: [-26, 18], close: [0, 1]},
  7751. * {interval: [18, 62], close: [0, 1]},
  7752. * {interval: [62, 150], close: [0, 1]},
  7753. * {interval: [150, Infinity], close: [0, 0]}
  7754. * ]);
  7755. * @param list, where `close` mean open or close
  7756. * of the interval, and Infinity can be used.
  7757. * @return The origin list, which has been reformed.
  7758. */
  7759. function reformIntervals(list) {
  7760. list.sort(function (a, b) {
  7761. return littleThan(a, b, 0) ? -1 : 1;
  7762. });
  7763. var curr = -Infinity;
  7764. var currClose = 1;
  7765. for (var i = 0; i < list.length;) {
  7766. var interval = list[i].interval;
  7767. var close_1 = list[i].close;
  7768. for (var lg = 0; lg < 2; lg++) {
  7769. if (interval[lg] <= curr) {
  7770. interval[lg] = curr;
  7771. close_1[lg] = !lg ? 1 - currClose : 1;
  7772. }
  7773. curr = interval[lg];
  7774. currClose = close_1[lg];
  7775. }
  7776. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7777. list.splice(i, 1);
  7778. } else {
  7779. i++;
  7780. }
  7781. }
  7782. return list;
  7783. function littleThan(a, b, lg) {
  7784. return a.interval[lg] < b.interval[lg] || a.interval[lg] === b.interval[lg] && (a.close[lg] - b.close[lg] === (!lg ? 1 : -1) || !lg && littleThan(a, b, 1));
  7785. }
  7786. }
  7787. /**
  7788. * [Numeric is defined as]:
  7789. * `parseFloat(val) == val`
  7790. * For example:
  7791. * numeric:
  7792. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7793. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7794. * not-numeric:
  7795. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7796. * empty string, string with only white-spaces or line-terminal (see es spec),
  7797. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7798. * non-string, ...
  7799. *
  7800. * @test See full test cases in `test/ut/spec/util/number.js`.
  7801. * @return Must be a typeof number. If not numeric, return NaN.
  7802. */
  7803. function numericToNumber(val) {
  7804. var valFloat = parseFloat(val);
  7805. return valFloat == val // eslint-disable-line eqeqeq
  7806. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7807. ? valFloat : NaN;
  7808. }
  7809. /**
  7810. * Definition of "numeric": see `numericToNumber`.
  7811. */
  7812. function isNumeric(val) {
  7813. return !isNaN(numericToNumber(val));
  7814. }
  7815. /**
  7816. * Use random base to prevent users hard code depending on
  7817. * this auto generated marker id.
  7818. * @return An positive integer.
  7819. */
  7820. function getRandomIdBase() {
  7821. return Math.round(Math.random() * 9);
  7822. }
  7823. /**
  7824. * Get the greatest common divisor.
  7825. *
  7826. * @param {number} a one number
  7827. * @param {number} b the other number
  7828. */
  7829. function getGreatestCommonDividor(a, b) {
  7830. if (b === 0) {
  7831. return a;
  7832. }
  7833. return getGreatestCommonDividor(b, a % b);
  7834. }
  7835. /**
  7836. * Get the least common multiple.
  7837. *
  7838. * @param {number} a one number
  7839. * @param {number} b the other number
  7840. */
  7841. function getLeastCommonMultiple(a, b) {
  7842. if (a == null) {
  7843. return b;
  7844. }
  7845. if (b == null) {
  7846. return a;
  7847. }
  7848. return a * b / getGreatestCommonDividor(a, b);
  7849. }
  7850. var ECHARTS_PREFIX = '[ECharts] ';
  7851. var storedLogs = {};
  7852. var hasConsole = typeof console !== 'undefined'
  7853. // eslint-disable-next-line
  7854. && console.warn && console.log;
  7855. function outputLog(type, str, onlyOnce) {
  7856. if (hasConsole) {
  7857. if (onlyOnce) {
  7858. if (storedLogs[str]) {
  7859. return;
  7860. }
  7861. storedLogs[str] = true;
  7862. }
  7863. // eslint-disable-next-line
  7864. console[type](ECHARTS_PREFIX + str);
  7865. }
  7866. }
  7867. function log(str, onlyOnce) {
  7868. outputLog('log', str, onlyOnce);
  7869. }
  7870. function warn(str, onlyOnce) {
  7871. outputLog('warn', str, onlyOnce);
  7872. }
  7873. function error(str, onlyOnce) {
  7874. outputLog('error', str, onlyOnce);
  7875. }
  7876. function deprecateLog(str) {
  7877. if ("development" !== 'production') {
  7878. // Not display duplicate message.
  7879. outputLog('warn', 'DEPRECATED: ' + str, true);
  7880. }
  7881. }
  7882. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7883. if ("development" !== 'production') {
  7884. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7885. }
  7886. }
  7887. /**
  7888. * If in __DEV__ environment, get console printable message for users hint.
  7889. * Parameters are separated by ' '.
  7890. * @usage
  7891. * makePrintable('This is an error on', someVar, someObj);
  7892. *
  7893. * @param hintInfo anything about the current execution context to hint users.
  7894. * @throws Error
  7895. */
  7896. function makePrintable() {
  7897. var hintInfo = [];
  7898. for (var _i = 0; _i < arguments.length; _i++) {
  7899. hintInfo[_i] = arguments[_i];
  7900. }
  7901. var msg = '';
  7902. if ("development" !== 'production') {
  7903. // Fuzzy stringify for print.
  7904. // This code only exist in dev environment.
  7905. var makePrintableStringIfPossible_1 = function (val) {
  7906. return val === void 0 ? 'undefined' : val === Infinity ? 'Infinity' : val === -Infinity ? '-Infinity' : eqNaN(val) ? 'NaN' : val instanceof Date ? 'Date(' + val.toISOString() + ')' : isFunction(val) ? 'function () { ... }' : isRegExp(val) ? val + '' : null;
  7907. };
  7908. msg = map(hintInfo, function (arg) {
  7909. if (isString(arg)) {
  7910. // Print without quotation mark for some statement.
  7911. return arg;
  7912. } else {
  7913. var printableStr = makePrintableStringIfPossible_1(arg);
  7914. if (printableStr != null) {
  7915. return printableStr;
  7916. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7917. try {
  7918. return JSON.stringify(arg, function (n, val) {
  7919. var printableStr = makePrintableStringIfPossible_1(val);
  7920. return printableStr == null ? val : printableStr;
  7921. });
  7922. // In most cases the info object is small, so do not line break.
  7923. } catch (err) {
  7924. return '?';
  7925. }
  7926. } else {
  7927. return '?';
  7928. }
  7929. }
  7930. }).join(' ');
  7931. }
  7932. return msg;
  7933. }
  7934. /**
  7935. * @throws Error
  7936. */
  7937. function throwError(msg) {
  7938. throw new Error(msg);
  7939. }
  7940. function interpolateNumber$1(p0, p1, percent) {
  7941. return (p1 - p0) * percent + p0;
  7942. }
  7943. /**
  7944. * Make the name displayable. But we should
  7945. * make sure it is not duplicated with user
  7946. * specified name, so use '\0';
  7947. */
  7948. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7949. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7950. /**
  7951. * If value is not array, then translate it to array.
  7952. * @param {*} value
  7953. * @return {Array} [value] or value
  7954. */
  7955. function normalizeToArray(value) {
  7956. return value instanceof Array ? value : value == null ? [] : [value];
  7957. }
  7958. /**
  7959. * Sync default option between normal and emphasis like `position` and `show`
  7960. * In case some one will write code like
  7961. * label: {
  7962. * show: false,
  7963. * position: 'outside',
  7964. * fontSize: 18
  7965. * },
  7966. * emphasis: {
  7967. * label: { show: true }
  7968. * }
  7969. */
  7970. function defaultEmphasis(opt, key, subOpts) {
  7971. // Caution: performance sensitive.
  7972. if (opt) {
  7973. opt[key] = opt[key] || {};
  7974. opt.emphasis = opt.emphasis || {};
  7975. opt.emphasis[key] = opt.emphasis[key] || {};
  7976. // Default emphasis option from normal
  7977. for (var i = 0, len = subOpts.length; i < len; i++) {
  7978. var subOptName = subOpts[i];
  7979. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7980. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7981. }
  7982. }
  7983. }
  7984. }
  7985. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'];
  7986. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7987. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7988. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7989. // // FIXME: deprecated, check and remove it.
  7990. // 'textStyle'
  7991. // ]);
  7992. /**
  7993. * The method does not ensure performance.
  7994. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7995. * This helper method retrieves value from data.
  7996. */
  7997. function getDataItemValue(dataItem) {
  7998. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7999. }
  8000. /**
  8001. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  8002. * This helper method determine if dataItem has extra option besides value
  8003. */
  8004. function isDataItemOption(dataItem) {
  8005. return isObject(dataItem) && !(dataItem instanceof Array);
  8006. // // markLine data can be array
  8007. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  8008. }
  8009. /**
  8010. * Mapping to existings for merge.
  8011. *
  8012. * Mode "normalMege":
  8013. * The mapping result (merge result) will keep the order of the existing
  8014. * component, rather than the order of new option. Because we should ensure
  8015. * some specified index reference (like xAxisIndex) keep work.
  8016. * And in most cases, "merge option" is used to update partial option but not
  8017. * be expected to change the order.
  8018. *
  8019. * Mode "replaceMege":
  8020. * (1) Only the id mapped components will be merged.
  8021. * (2) Other existing components (except internal components) will be removed.
  8022. * (3) Other new options will be used to create new component.
  8023. * (4) The index of the existing components will not be modified.
  8024. * That means their might be "hole" after the removal.
  8025. * The new components are created first at those available index.
  8026. *
  8027. * Mode "replaceAll":
  8028. * This mode try to support that reproduce an echarts instance from another
  8029. * echarts instance (via `getOption`) in some simple cases.
  8030. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  8031. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  8032. * the "hole" in `newCmptOptions` will also be kept.
  8033. * On the contrary, other modes try best to eliminate holes.
  8034. * PENDING: This is an experimental mode yet.
  8035. *
  8036. * @return See the comment of <MappingResult>.
  8037. */
  8038. function mappingToExists(existings, newCmptOptions, mode) {
  8039. var isNormalMergeMode = mode === 'normalMerge';
  8040. var isReplaceMergeMode = mode === 'replaceMerge';
  8041. var isReplaceAllMode = mode === 'replaceAll';
  8042. existings = existings || [];
  8043. newCmptOptions = (newCmptOptions || []).slice();
  8044. var existingIdIdxMap = createHashMap();
  8045. // Validate id and name on user input option.
  8046. each(newCmptOptions, function (cmptOption, index) {
  8047. if (!isObject(cmptOption)) {
  8048. newCmptOptions[index] = null;
  8049. return;
  8050. }
  8051. if ("development" !== 'production') {
  8052. // There is some legacy case that name is set as `false`.
  8053. // But should work normally rather than throw error.
  8054. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  8055. warnInvalidateIdOrName(cmptOption.id);
  8056. }
  8057. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  8058. warnInvalidateIdOrName(cmptOption.name);
  8059. }
  8060. }
  8061. });
  8062. var result = prepareResult(existings, existingIdIdxMap, mode);
  8063. if (isNormalMergeMode || isReplaceMergeMode) {
  8064. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  8065. }
  8066. if (isNormalMergeMode) {
  8067. mappingByName(result, newCmptOptions);
  8068. }
  8069. if (isNormalMergeMode || isReplaceMergeMode) {
  8070. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  8071. } else if (isReplaceAllMode) {
  8072. mappingInReplaceAllMode(result, newCmptOptions);
  8073. }
  8074. makeIdAndName(result);
  8075. // The array `result` MUST NOT contain elided items, otherwise the
  8076. // forEach will omit those items and result in incorrect result.
  8077. return result;
  8078. }
  8079. function prepareResult(existings, existingIdIdxMap, mode) {
  8080. var result = [];
  8081. if (mode === 'replaceAll') {
  8082. return result;
  8083. }
  8084. // Do not use native `map` to in case that the array `existings`
  8085. // contains elided items, which will be omitted.
  8086. for (var index = 0; index < existings.length; index++) {
  8087. var existing = existings[index];
  8088. // Because of replaceMerge, `existing` may be null/undefined.
  8089. if (existing && existing.id != null) {
  8090. existingIdIdxMap.set(existing.id, index);
  8091. }
  8092. // For non-internal-componnets:
  8093. // Mode "normalMerge": all existings kept.
  8094. // Mode "replaceMerge": all existing removed unless mapped by id.
  8095. // For internal-components:
  8096. // go with "replaceMerge" approach in both mode.
  8097. result.push({
  8098. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  8099. newOption: null,
  8100. keyInfo: null,
  8101. brandNew: null
  8102. });
  8103. }
  8104. return result;
  8105. }
  8106. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  8107. // Mapping by id if specified.
  8108. each(newCmptOptions, function (cmptOption, index) {
  8109. if (!cmptOption || cmptOption.id == null) {
  8110. return;
  8111. }
  8112. var optionId = makeComparableKey(cmptOption.id);
  8113. var existingIdx = existingIdIdxMap.get(optionId);
  8114. if (existingIdx != null) {
  8115. var resultItem = result[existingIdx];
  8116. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  8117. resultItem.newOption = cmptOption;
  8118. // In both mode, if id matched, new option will be merged to
  8119. // the existings rather than creating new component model.
  8120. resultItem.existing = existings[existingIdx];
  8121. newCmptOptions[index] = null;
  8122. }
  8123. });
  8124. }
  8125. function mappingByName(result, newCmptOptions) {
  8126. // Mapping by name if specified.
  8127. each(newCmptOptions, function (cmptOption, index) {
  8128. if (!cmptOption || cmptOption.name == null) {
  8129. return;
  8130. }
  8131. for (var i = 0; i < result.length; i++) {
  8132. var existing = result[i].existing;
  8133. if (!result[i].newOption // Consider name: two map to one.
  8134. // Can not match when both ids existing but different.
  8135. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8136. result[i].newOption = cmptOption;
  8137. newCmptOptions[index] = null;
  8138. return;
  8139. }
  8140. }
  8141. });
  8142. }
  8143. function mappingByIndex(result, newCmptOptions, brandNew) {
  8144. each(newCmptOptions, function (cmptOption) {
  8145. if (!cmptOption) {
  8146. return;
  8147. }
  8148. // Find the first place that not mapped by id and not internal component (consider the "hole").
  8149. var resultItem;
  8150. var nextIdx = 0;
  8151. while (
  8152. // Be `!resultItem` only when `nextIdx >= result.length`.
  8153. (resultItem = result[nextIdx]
  8154. // (1) Existing models that already have id should be able to mapped to. Because
  8155. // after mapping performed, model will always be assigned with an id if user not given.
  8156. // After that all models have id.
  8157. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8158. // not be merged to the existings with different id. Because id should not be overwritten.
  8159. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8160. ) && (resultItem.newOption || isComponentIdInternal(resultItem.existing) ||
  8161. // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8162. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8163. nextIdx++;
  8164. }
  8165. if (resultItem) {
  8166. resultItem.newOption = cmptOption;
  8167. resultItem.brandNew = brandNew;
  8168. } else {
  8169. result.push({
  8170. newOption: cmptOption,
  8171. brandNew: brandNew,
  8172. existing: null,
  8173. keyInfo: null
  8174. });
  8175. }
  8176. nextIdx++;
  8177. });
  8178. }
  8179. function mappingInReplaceAllMode(result, newCmptOptions) {
  8180. each(newCmptOptions, function (cmptOption) {
  8181. // The feature "reproduce" requires "hole" will also reproduced
  8182. // in case that component index referring are broken.
  8183. result.push({
  8184. newOption: cmptOption,
  8185. brandNew: true,
  8186. existing: null,
  8187. keyInfo: null
  8188. });
  8189. });
  8190. }
  8191. /**
  8192. * Make id and name for mapping result (result of mappingToExists)
  8193. * into `keyInfo` field.
  8194. */
  8195. function makeIdAndName(mapResult) {
  8196. // We use this id to hash component models and view instances
  8197. // in echarts. id can be specified by user, or auto generated.
  8198. // The id generation rule ensures new view instance are able
  8199. // to mapped to old instance when setOption are called in
  8200. // no-merge mode. So we generate model id by name and plus
  8201. // type in view id.
  8202. // name can be duplicated among components, which is convenient
  8203. // to specify multi components (like series) by one name.
  8204. // Ensure that each id is distinct.
  8205. var idMap = createHashMap();
  8206. each(mapResult, function (item) {
  8207. var existing = item.existing;
  8208. existing && idMap.set(existing.id, item);
  8209. });
  8210. each(mapResult, function (item) {
  8211. var opt = item.newOption;
  8212. // Force ensure id not duplicated.
  8213. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8214. opt && opt.id != null && idMap.set(opt.id, item);
  8215. !item.keyInfo && (item.keyInfo = {});
  8216. });
  8217. // Make name and id.
  8218. each(mapResult, function (item, index) {
  8219. var existing = item.existing;
  8220. var opt = item.newOption;
  8221. var keyInfo = item.keyInfo;
  8222. if (!isObject(opt)) {
  8223. return;
  8224. }
  8225. // Name can be overwritten. Consider case: axis.name = '20km'.
  8226. // But id generated by name will not be changed, which affect
  8227. // only in that case: setOption with 'not merge mode' and view
  8228. // instance will be recreated, which can be accepted.
  8229. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name
  8230. // Avoid that different series has the same name,
  8231. // because name may be used like in color pallet.
  8232. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8233. if (existing) {
  8234. keyInfo.id = makeComparableKey(existing.id);
  8235. } else if (opt.id != null) {
  8236. keyInfo.id = makeComparableKey(opt.id);
  8237. } else {
  8238. // Consider this situatoin:
  8239. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8240. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8241. // Series with the same name between optionA and optionB
  8242. // should be mapped.
  8243. var idNum = 0;
  8244. do {
  8245. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8246. } while (idMap.get(keyInfo.id));
  8247. }
  8248. idMap.set(keyInfo.id, item);
  8249. });
  8250. }
  8251. function keyExistAndEqual(attr, obj1, obj2) {
  8252. var key1 = convertOptionIdName(obj1[attr], null);
  8253. var key2 = convertOptionIdName(obj2[attr], null);
  8254. // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8255. return key1 != null && key2 != null && key1 === key2;
  8256. }
  8257. /**
  8258. * @return return null if not exist.
  8259. */
  8260. function makeComparableKey(val) {
  8261. if ("development" !== 'production') {
  8262. if (val == null) {
  8263. throw new Error();
  8264. }
  8265. }
  8266. return convertOptionIdName(val, '');
  8267. }
  8268. function convertOptionIdName(idOrName, defaultValue) {
  8269. if (idOrName == null) {
  8270. return defaultValue;
  8271. }
  8272. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8273. }
  8274. function warnInvalidateIdOrName(idOrName) {
  8275. if ("development" !== 'production') {
  8276. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8277. }
  8278. }
  8279. function isValidIdOrName(idOrName) {
  8280. return isStringSafe(idOrName) || isNumeric(idOrName);
  8281. }
  8282. function isNameSpecified(componentModel) {
  8283. var name = componentModel.name;
  8284. // Is specified when `indexOf` get -1 or > 0.
  8285. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8286. }
  8287. /**
  8288. * @public
  8289. * @param {Object} cmptOption
  8290. * @return {boolean}
  8291. */
  8292. function isComponentIdInternal(cmptOption) {
  8293. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8294. }
  8295. function makeInternalComponentId(idSuffix) {
  8296. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8297. }
  8298. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8299. // Set mainType and complete subType.
  8300. each(mappingResult, function (item) {
  8301. var newOption = item.newOption;
  8302. if (isObject(newOption)) {
  8303. item.keyInfo.mainType = mainType;
  8304. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8305. }
  8306. });
  8307. }
  8308. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8309. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType
  8310. // Use determineSubType only when there is no existComponent.
  8311. : componentModelCtor.determineSubType(mainType, newCmptOption);
  8312. // tooltip, markline, markpoint may always has no subType
  8313. return subType;
  8314. }
  8315. /**
  8316. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8317. * each of which can be Array or primary type.
  8318. * @return dataIndex If not found, return undefined/null.
  8319. */
  8320. function queryDataIndex(data, payload) {
  8321. if (payload.dataIndexInside != null) {
  8322. return payload.dataIndexInside;
  8323. } else if (payload.dataIndex != null) {
  8324. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8325. return data.indexOfRawIndex(value);
  8326. }) : data.indexOfRawIndex(payload.dataIndex);
  8327. } else if (payload.name != null) {
  8328. return isArray(payload.name) ? map(payload.name, function (value) {
  8329. return data.indexOfName(value);
  8330. }) : data.indexOfName(payload.name);
  8331. }
  8332. }
  8333. /**
  8334. * Enable property storage to any host object.
  8335. * Notice: Serialization is not supported.
  8336. *
  8337. * For example:
  8338. * let inner = zrUitl.makeInner();
  8339. *
  8340. * function some1(hostObj) {
  8341. * inner(hostObj).someProperty = 1212;
  8342. * ...
  8343. * }
  8344. * function some2() {
  8345. * let fields = inner(this);
  8346. * fields.someProperty1 = 1212;
  8347. * fields.someProperty2 = 'xx';
  8348. * ...
  8349. * }
  8350. *
  8351. * @return {Function}
  8352. */
  8353. function makeInner() {
  8354. var key = '__ec_inner_' + innerUniqueIndex++;
  8355. return function (hostObj) {
  8356. return hostObj[key] || (hostObj[key] = {});
  8357. };
  8358. }
  8359. var innerUniqueIndex = getRandomIdBase();
  8360. /**
  8361. * The same behavior as `component.getReferringComponents`.
  8362. */
  8363. function parseFinder(ecModel, finderInput, opt) {
  8364. var _a = preParseFinder(finderInput, opt),
  8365. mainTypeSpecified = _a.mainTypeSpecified,
  8366. queryOptionMap = _a.queryOptionMap,
  8367. others = _a.others;
  8368. var result = others;
  8369. var defaultMainType = opt ? opt.defaultMainType : null;
  8370. if (!mainTypeSpecified && defaultMainType) {
  8371. queryOptionMap.set(defaultMainType, {});
  8372. }
  8373. queryOptionMap.each(function (queryOption, mainType) {
  8374. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8375. useDefault: defaultMainType === mainType,
  8376. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8377. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8378. });
  8379. result[mainType + 'Models'] = queryResult.models;
  8380. result[mainType + 'Model'] = queryResult.models[0];
  8381. });
  8382. return result;
  8383. }
  8384. function preParseFinder(finderInput, opt) {
  8385. var finder;
  8386. if (isString(finderInput)) {
  8387. var obj = {};
  8388. obj[finderInput + 'Index'] = 0;
  8389. finder = obj;
  8390. } else {
  8391. finder = finderInput;
  8392. }
  8393. var queryOptionMap = createHashMap();
  8394. var others = {};
  8395. var mainTypeSpecified = false;
  8396. each(finder, function (value, key) {
  8397. // Exclude 'dataIndex' and other illgal keys.
  8398. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8399. others[key] = value;
  8400. return;
  8401. }
  8402. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8403. var mainType = parsedKey[1];
  8404. var queryType = (parsedKey[2] || '').toLowerCase();
  8405. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8406. return;
  8407. }
  8408. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8409. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8410. queryOption[queryType] = value;
  8411. });
  8412. return {
  8413. mainTypeSpecified: mainTypeSpecified,
  8414. queryOptionMap: queryOptionMap,
  8415. others: others
  8416. };
  8417. }
  8418. var SINGLE_REFERRING = {
  8419. useDefault: true,
  8420. enableAll: false,
  8421. enableNone: false
  8422. };
  8423. var MULTIPLE_REFERRING = {
  8424. useDefault: false,
  8425. enableAll: true,
  8426. enableNone: true
  8427. };
  8428. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8429. opt = opt || SINGLE_REFERRING;
  8430. var indexOption = userOption.index;
  8431. var idOption = userOption.id;
  8432. var nameOption = userOption.name;
  8433. var result = {
  8434. models: null,
  8435. specified: indexOption != null || idOption != null || nameOption != null
  8436. };
  8437. if (!result.specified) {
  8438. // Use the first as default if `useDefault`.
  8439. var firstCmpt = void 0;
  8440. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8441. return result;
  8442. }
  8443. if (indexOption === 'none' || indexOption === false) {
  8444. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8445. result.models = [];
  8446. return result;
  8447. }
  8448. // `queryComponents` will return all components if
  8449. // both all of index/id/name are null/undefined.
  8450. if (indexOption === 'all') {
  8451. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8452. indexOption = idOption = nameOption = null;
  8453. }
  8454. result.models = ecModel.queryComponents({
  8455. mainType: mainType,
  8456. index: indexOption,
  8457. id: idOption,
  8458. name: nameOption
  8459. });
  8460. return result;
  8461. }
  8462. function setAttribute(dom, key, value) {
  8463. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8464. }
  8465. function getAttribute(dom, key) {
  8466. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8467. }
  8468. function getTooltipRenderMode(renderModeOption) {
  8469. if (renderModeOption === 'auto') {
  8470. // Using html when `document` exists, use richText otherwise
  8471. return env.domSupported ? 'html' : 'richText';
  8472. } else {
  8473. return renderModeOption || 'html';
  8474. }
  8475. }
  8476. /**
  8477. * Interpolate raw values of a series with percent
  8478. *
  8479. * @param data data
  8480. * @param labelModel label model of the text element
  8481. * @param sourceValue start value. May be null/undefined when init.
  8482. * @param targetValue end value
  8483. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8484. * @return interpolated values
  8485. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8486. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8487. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8488. * Other cases do not supported.
  8489. */
  8490. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8491. var isAutoPrecision = precision == null || precision === 'auto';
  8492. if (targetValue == null) {
  8493. return targetValue;
  8494. }
  8495. if (isNumber(targetValue)) {
  8496. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8497. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8498. } else if (isString(targetValue)) {
  8499. return percent < 1 ? sourceValue : targetValue;
  8500. } else {
  8501. var interpolated = [];
  8502. var leftArr = sourceValue;
  8503. var rightArr = targetValue;
  8504. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8505. for (var i = 0; i < length_1; ++i) {
  8506. var info = data.getDimensionInfo(i);
  8507. // Don't interpolate ordinal dims
  8508. if (info && info.type === 'ordinal') {
  8509. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8510. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8511. } else {
  8512. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8513. var rightVal = rightArr[i];
  8514. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8515. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8516. }
  8517. }
  8518. return interpolated;
  8519. }
  8520. }
  8521. var TYPE_DELIMITER = '.';
  8522. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8523. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8524. /**
  8525. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8526. * @public
  8527. */
  8528. function parseClassType(componentType) {
  8529. var ret = {
  8530. main: '',
  8531. sub: ''
  8532. };
  8533. if (componentType) {
  8534. var typeArr = componentType.split(TYPE_DELIMITER);
  8535. ret.main = typeArr[0] || '';
  8536. ret.sub = typeArr[1] || '';
  8537. }
  8538. return ret;
  8539. }
  8540. /**
  8541. * @public
  8542. */
  8543. function checkClassType(componentType) {
  8544. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8545. }
  8546. function isExtendedClass(clz) {
  8547. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8548. }
  8549. /**
  8550. * Implements `ExtendableConstructor` for `rootClz`.
  8551. *
  8552. * @usage
  8553. * ```ts
  8554. * class Xxx {}
  8555. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8556. * enableClassExtend(Xxx as XxxConstructor);
  8557. * ```
  8558. */
  8559. function enableClassExtend(rootClz, mandatoryMethods) {
  8560. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8561. rootClz.extend = function (proto) {
  8562. if ("development" !== 'production') {
  8563. each(mandatoryMethods, function (method) {
  8564. if (!proto[method]) {
  8565. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8566. }
  8567. });
  8568. }
  8569. var superClass = this;
  8570. var ExtendedClass;
  8571. if (isESClass(superClass)) {
  8572. ExtendedClass = /** @class */function (_super) {
  8573. __extends(class_1, _super);
  8574. function class_1() {
  8575. return _super.apply(this, arguments) || this;
  8576. }
  8577. return class_1;
  8578. }(superClass);
  8579. } else {
  8580. // For backward compat, we both support ts class inheritance and this
  8581. // "extend" approach.
  8582. // The constructor should keep the same behavior as ts class inheritance:
  8583. // If this constructor/$constructor is not declared, auto invoke the super
  8584. // constructor.
  8585. // If this constructor/$constructor is declared, it is responsible for
  8586. // calling the super constructor.
  8587. ExtendedClass = function () {
  8588. (proto.$constructor || superClass).apply(this, arguments);
  8589. };
  8590. inherits(ExtendedClass, this);
  8591. }
  8592. extend(ExtendedClass.prototype, proto);
  8593. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8594. ExtendedClass.extend = this.extend;
  8595. ExtendedClass.superCall = superCall;
  8596. ExtendedClass.superApply = superApply;
  8597. ExtendedClass.superClass = superClass;
  8598. return ExtendedClass;
  8599. };
  8600. }
  8601. function isESClass(fn) {
  8602. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8603. }
  8604. /**
  8605. * A work around to both support ts extend and this extend mechanism.
  8606. * on sub-class.
  8607. * @usage
  8608. * ```ts
  8609. * class Component { ... }
  8610. * classUtil.enableClassExtend(Component);
  8611. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8612. *
  8613. * class Series extends Component { ... }
  8614. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8615. * Component.markExtend(Series);
  8616. * ```
  8617. */
  8618. function mountExtend(SubClz, SupperClz) {
  8619. SubClz.extend = SupperClz.extend;
  8620. }
  8621. // A random offset.
  8622. var classBase = Math.round(Math.random() * 10);
  8623. /**
  8624. * Implements `CheckableConstructor` for `target`.
  8625. * Can not use instanceof, consider different scope by
  8626. * cross domain or es module import in ec extensions.
  8627. * Mount a method "isInstance()" to Clz.
  8628. *
  8629. * @usage
  8630. * ```ts
  8631. * class Xxx {}
  8632. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8633. * enableClassCheck(Xxx as XxxConstructor)
  8634. * ```
  8635. */
  8636. function enableClassCheck(target) {
  8637. var classAttr = ['__\0is_clz', classBase++].join('_');
  8638. target.prototype[classAttr] = true;
  8639. if ("development" !== 'production') {
  8640. assert(!target.isInstance, 'The method "is" can not be defined.');
  8641. }
  8642. target.isInstance = function (obj) {
  8643. return !!(obj && obj[classAttr]);
  8644. };
  8645. }
  8646. // superCall should have class info, which can not be fetched from 'this'.
  8647. // Consider this case:
  8648. // class A has method f,
  8649. // class B inherits class A, overrides method f, f call superApply('f'),
  8650. // class C inherits class B, does not override method f,
  8651. // then when method of class C is called, dead loop occurred.
  8652. function superCall(context, methodName) {
  8653. var args = [];
  8654. for (var _i = 2; _i < arguments.length; _i++) {
  8655. args[_i - 2] = arguments[_i];
  8656. }
  8657. return this.superClass.prototype[methodName].apply(context, args);
  8658. }
  8659. function superApply(context, methodName, args) {
  8660. return this.superClass.prototype[methodName].apply(context, args);
  8661. }
  8662. /**
  8663. * Implements `ClassManager` for `target`
  8664. *
  8665. * @usage
  8666. * ```ts
  8667. * class Xxx {}
  8668. * type XxxConstructor = typeof Xxx & ClassManager
  8669. * enableClassManagement(Xxx as XxxConstructor);
  8670. * ```
  8671. */
  8672. function enableClassManagement(target) {
  8673. /**
  8674. * Component model classes
  8675. * key: componentType,
  8676. * value:
  8677. * componentClass, when componentType is 'a'
  8678. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8679. */
  8680. var storage = {};
  8681. target.registerClass = function (clz) {
  8682. // `type` should not be a "instance member".
  8683. // If using TS class, should better declared as `static type = 'series.pie'`.
  8684. // otherwise users have to mount `type` on prototype manually.
  8685. // For backward compat and enable instance visit type via `this.type`,
  8686. // we still support fetch `type` from prototype.
  8687. var componentFullType = clz.type || clz.prototype.type;
  8688. if (componentFullType) {
  8689. checkClassType(componentFullType);
  8690. // If only static type declared, we assign it to prototype mandatorily.
  8691. clz.prototype.type = componentFullType;
  8692. var componentTypeInfo = parseClassType(componentFullType);
  8693. if (!componentTypeInfo.sub) {
  8694. if ("development" !== 'production') {
  8695. if (storage[componentTypeInfo.main]) {
  8696. console.warn(componentTypeInfo.main + ' exists.');
  8697. }
  8698. }
  8699. storage[componentTypeInfo.main] = clz;
  8700. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8701. var container = makeContainer(componentTypeInfo);
  8702. container[componentTypeInfo.sub] = clz;
  8703. }
  8704. }
  8705. return clz;
  8706. };
  8707. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8708. var clz = storage[mainType];
  8709. if (clz && clz[IS_CONTAINER]) {
  8710. clz = subType ? clz[subType] : null;
  8711. }
  8712. if (throwWhenNotFound && !clz) {
  8713. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8714. }
  8715. return clz;
  8716. };
  8717. target.getClassesByMainType = function (componentType) {
  8718. var componentTypeInfo = parseClassType(componentType);
  8719. var result = [];
  8720. var obj = storage[componentTypeInfo.main];
  8721. if (obj && obj[IS_CONTAINER]) {
  8722. each(obj, function (o, type) {
  8723. type !== IS_CONTAINER && result.push(o);
  8724. });
  8725. } else {
  8726. result.push(obj);
  8727. }
  8728. return result;
  8729. };
  8730. target.hasClass = function (componentType) {
  8731. // Just consider componentType.main.
  8732. var componentTypeInfo = parseClassType(componentType);
  8733. return !!storage[componentTypeInfo.main];
  8734. };
  8735. /**
  8736. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8737. */
  8738. target.getAllClassMainTypes = function () {
  8739. var types = [];
  8740. each(storage, function (obj, type) {
  8741. types.push(type);
  8742. });
  8743. return types;
  8744. };
  8745. /**
  8746. * If a main type is container and has sub types
  8747. */
  8748. target.hasSubTypes = function (componentType) {
  8749. var componentTypeInfo = parseClassType(componentType);
  8750. var obj = storage[componentTypeInfo.main];
  8751. return obj && obj[IS_CONTAINER];
  8752. };
  8753. function makeContainer(componentTypeInfo) {
  8754. var container = storage[componentTypeInfo.main];
  8755. if (!container || !container[IS_CONTAINER]) {
  8756. container = storage[componentTypeInfo.main] = {};
  8757. container[IS_CONTAINER] = true;
  8758. }
  8759. return container;
  8760. }
  8761. }
  8762. // /**
  8763. // * @param {string|Array.<string>} properties
  8764. // */
  8765. // export function setReadOnly(obj, properties) {
  8766. // FIXME It seems broken in IE8 simulation of IE11
  8767. // if (!zrUtil.isArray(properties)) {
  8768. // properties = properties != null ? [properties] : [];
  8769. // }
  8770. // zrUtil.each(properties, function (prop) {
  8771. // let value = obj[prop];
  8772. // Object.defineProperty
  8773. // && Object.defineProperty(obj, prop, {
  8774. // value: value, writable: false
  8775. // });
  8776. // zrUtil.isArray(obj[prop])
  8777. // && Object.freeze
  8778. // && Object.freeze(obj[prop]);
  8779. // });
  8780. // }
  8781. function makeStyleMapper(properties, ignoreParent) {
  8782. // Normalize
  8783. for (var i = 0; i < properties.length; i++) {
  8784. if (!properties[i][1]) {
  8785. properties[i][1] = properties[i][0];
  8786. }
  8787. }
  8788. ignoreParent = ignoreParent || false;
  8789. return function (model, excludes, includes) {
  8790. var style = {};
  8791. for (var i = 0; i < properties.length; i++) {
  8792. var propName = properties[i][1];
  8793. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8794. continue;
  8795. }
  8796. var val = model.getShallow(propName, ignoreParent);
  8797. if (val != null) {
  8798. style[properties[i][0]] = val;
  8799. }
  8800. }
  8801. // TODO Text or image?
  8802. return style;
  8803. };
  8804. }
  8805. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']
  8806. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8807. // So do not transfer decal directly.
  8808. ];
  8809. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8810. var AreaStyleMixin = /** @class */function () {
  8811. function AreaStyleMixin() {}
  8812. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8813. return getAreaStyle(this, excludes, includes);
  8814. };
  8815. return AreaStyleMixin;
  8816. }();
  8817. var globalImageCache = new LRU(50);
  8818. function findExistImage(newImageOrSrc) {
  8819. if (typeof newImageOrSrc === 'string') {
  8820. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8821. return cachedImgObj && cachedImgObj.image;
  8822. }
  8823. else {
  8824. return newImageOrSrc;
  8825. }
  8826. }
  8827. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8828. if (!newImageOrSrc) {
  8829. return image;
  8830. }
  8831. else if (typeof newImageOrSrc === 'string') {
  8832. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8833. return image;
  8834. }
  8835. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8836. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8837. if (cachedImgObj) {
  8838. image = cachedImgObj.image;
  8839. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8840. }
  8841. else {
  8842. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8843. image.__zrImageSrc = newImageOrSrc;
  8844. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8845. image: image,
  8846. pending: [pendingWrap]
  8847. });
  8848. }
  8849. return image;
  8850. }
  8851. else {
  8852. return newImageOrSrc;
  8853. }
  8854. }
  8855. function imageOnLoad() {
  8856. var cachedImgObj = this.__cachedImgObj;
  8857. this.onload = this.onerror = this.__cachedImgObj = null;
  8858. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8859. var pendingWrap = cachedImgObj.pending[i];
  8860. var cb = pendingWrap.cb;
  8861. cb && cb(this, pendingWrap.cbPayload);
  8862. pendingWrap.hostEl.dirty();
  8863. }
  8864. cachedImgObj.pending.length = 0;
  8865. }
  8866. function isImageReady(image) {
  8867. return image && image.width && image.height;
  8868. }
  8869. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8870. function truncateText(text, containerWidth, font, ellipsis, options) {
  8871. var out = {};
  8872. truncateText2(out, text, containerWidth, font, ellipsis, options);
  8873. return out.text;
  8874. }
  8875. function truncateText2(out, text, containerWidth, font, ellipsis, options) {
  8876. if (!containerWidth) {
  8877. out.text = '';
  8878. out.isTruncated = false;
  8879. return;
  8880. }
  8881. var textLines = (text + '').split('\n');
  8882. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8883. var isTruncated = false;
  8884. var truncateOut = {};
  8885. for (var i = 0, len = textLines.length; i < len; i++) {
  8886. truncateSingleLine(truncateOut, textLines[i], options);
  8887. textLines[i] = truncateOut.textLine;
  8888. isTruncated = isTruncated || truncateOut.isTruncated;
  8889. }
  8890. out.text = textLines.join('\n');
  8891. out.isTruncated = isTruncated;
  8892. }
  8893. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8894. options = options || {};
  8895. var preparedOpts = extend({}, options);
  8896. preparedOpts.font = font;
  8897. ellipsis = retrieve2(ellipsis, '...');
  8898. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8899. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8900. preparedOpts.cnCharWidth = getWidth('国', font);
  8901. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8902. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8903. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8904. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8905. contentWidth -= ascCharWidth;
  8906. }
  8907. var ellipsisWidth = getWidth(ellipsis, font);
  8908. if (ellipsisWidth > contentWidth) {
  8909. ellipsis = '';
  8910. ellipsisWidth = 0;
  8911. }
  8912. contentWidth = containerWidth - ellipsisWidth;
  8913. preparedOpts.ellipsis = ellipsis;
  8914. preparedOpts.ellipsisWidth = ellipsisWidth;
  8915. preparedOpts.contentWidth = contentWidth;
  8916. preparedOpts.containerWidth = containerWidth;
  8917. return preparedOpts;
  8918. }
  8919. function truncateSingleLine(out, textLine, options) {
  8920. var containerWidth = options.containerWidth;
  8921. var font = options.font;
  8922. var contentWidth = options.contentWidth;
  8923. if (!containerWidth) {
  8924. out.textLine = '';
  8925. out.isTruncated = false;
  8926. return;
  8927. }
  8928. var lineWidth = getWidth(textLine, font);
  8929. if (lineWidth <= containerWidth) {
  8930. out.textLine = textLine;
  8931. out.isTruncated = false;
  8932. return;
  8933. }
  8934. for (var j = 0;; j++) {
  8935. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8936. textLine += options.ellipsis;
  8937. break;
  8938. }
  8939. var subLength = j === 0
  8940. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8941. : lineWidth > 0
  8942. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8943. : 0;
  8944. textLine = textLine.substr(0, subLength);
  8945. lineWidth = getWidth(textLine, font);
  8946. }
  8947. if (textLine === '') {
  8948. textLine = options.placeholder;
  8949. }
  8950. out.textLine = textLine;
  8951. out.isTruncated = true;
  8952. }
  8953. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8954. var width = 0;
  8955. var i = 0;
  8956. for (var len = text.length; i < len && width < contentWidth; i++) {
  8957. var charCode = text.charCodeAt(i);
  8958. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8959. }
  8960. return i;
  8961. }
  8962. function parsePlainText(text, style) {
  8963. text != null && (text += '');
  8964. var overflow = style.overflow;
  8965. var padding = style.padding;
  8966. var font = style.font;
  8967. var truncate = overflow === 'truncate';
  8968. var calculatedLineHeight = getLineHeight(font);
  8969. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8970. var bgColorDrawn = !!(style.backgroundColor);
  8971. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8972. var isTruncated = false;
  8973. var width = style.width;
  8974. var lines;
  8975. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8976. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8977. }
  8978. else {
  8979. lines = text ? text.split('\n') : [];
  8980. }
  8981. var contentHeight = lines.length * lineHeight;
  8982. var height = retrieve2(style.height, contentHeight);
  8983. if (contentHeight > height && truncateLineOverflow) {
  8984. var lineCount = Math.floor(height / lineHeight);
  8985. isTruncated = isTruncated || (lines.length > lineCount);
  8986. lines = lines.slice(0, lineCount);
  8987. }
  8988. if (text && truncate && width != null) {
  8989. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8990. minChar: style.truncateMinChar,
  8991. placeholder: style.placeholder
  8992. });
  8993. var singleOut = {};
  8994. for (var i = 0; i < lines.length; i++) {
  8995. truncateSingleLine(singleOut, lines[i], options);
  8996. lines[i] = singleOut.textLine;
  8997. isTruncated = isTruncated || singleOut.isTruncated;
  8998. }
  8999. }
  9000. var outerHeight = height;
  9001. var contentWidth = 0;
  9002. for (var i = 0; i < lines.length; i++) {
  9003. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  9004. }
  9005. if (width == null) {
  9006. width = contentWidth;
  9007. }
  9008. var outerWidth = contentWidth;
  9009. if (padding) {
  9010. outerHeight += padding[0] + padding[2];
  9011. outerWidth += padding[1] + padding[3];
  9012. width += padding[1] + padding[3];
  9013. }
  9014. if (bgColorDrawn) {
  9015. outerWidth = width;
  9016. }
  9017. return {
  9018. lines: lines,
  9019. height: height,
  9020. outerWidth: outerWidth,
  9021. outerHeight: outerHeight,
  9022. lineHeight: lineHeight,
  9023. calculatedLineHeight: calculatedLineHeight,
  9024. contentWidth: contentWidth,
  9025. contentHeight: contentHeight,
  9026. width: width,
  9027. isTruncated: isTruncated
  9028. };
  9029. }
  9030. var RichTextToken = (function () {
  9031. function RichTextToken() {
  9032. }
  9033. return RichTextToken;
  9034. }());
  9035. var RichTextLine = (function () {
  9036. function RichTextLine(tokens) {
  9037. this.tokens = [];
  9038. if (tokens) {
  9039. this.tokens = tokens;
  9040. }
  9041. }
  9042. return RichTextLine;
  9043. }());
  9044. var RichTextContentBlock = (function () {
  9045. function RichTextContentBlock() {
  9046. this.width = 0;
  9047. this.height = 0;
  9048. this.contentWidth = 0;
  9049. this.contentHeight = 0;
  9050. this.outerWidth = 0;
  9051. this.outerHeight = 0;
  9052. this.lines = [];
  9053. this.isTruncated = false;
  9054. }
  9055. return RichTextContentBlock;
  9056. }());
  9057. function parseRichText(text, style) {
  9058. var contentBlock = new RichTextContentBlock();
  9059. text != null && (text += '');
  9060. if (!text) {
  9061. return contentBlock;
  9062. }
  9063. var topWidth = style.width;
  9064. var topHeight = style.height;
  9065. var overflow = style.overflow;
  9066. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  9067. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  9068. : null;
  9069. var lastIndex = STYLE_REG.lastIndex = 0;
  9070. var result;
  9071. while ((result = STYLE_REG.exec(text)) != null) {
  9072. var matchedIndex = result.index;
  9073. if (matchedIndex > lastIndex) {
  9074. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  9075. }
  9076. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  9077. lastIndex = STYLE_REG.lastIndex;
  9078. }
  9079. if (lastIndex < text.length) {
  9080. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  9081. }
  9082. var pendingList = [];
  9083. var calculatedHeight = 0;
  9084. var calculatedWidth = 0;
  9085. var stlPadding = style.padding;
  9086. var truncate = overflow === 'truncate';
  9087. var truncateLine = style.lineOverflow === 'truncate';
  9088. var tmpTruncateOut = {};
  9089. function finishLine(line, lineWidth, lineHeight) {
  9090. line.width = lineWidth;
  9091. line.lineHeight = lineHeight;
  9092. calculatedHeight += lineHeight;
  9093. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  9094. }
  9095. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  9096. var line = contentBlock.lines[i];
  9097. var lineHeight = 0;
  9098. var lineWidth = 0;
  9099. for (var j = 0; j < line.tokens.length; j++) {
  9100. var token = line.tokens[j];
  9101. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  9102. var textPadding = token.textPadding = tokenStyle.padding;
  9103. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  9104. var font = token.font = tokenStyle.font || style.font;
  9105. token.contentHeight = getLineHeight(font);
  9106. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  9107. token.innerHeight = tokenHeight;
  9108. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9109. token.height = tokenHeight;
  9110. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9111. token.align = tokenStyle && tokenStyle.align || style.align;
  9112. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9113. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9114. var originalLength = contentBlock.lines.length;
  9115. if (j > 0) {
  9116. line.tokens = line.tokens.slice(0, j);
  9117. finishLine(line, lineWidth, lineHeight);
  9118. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9119. }
  9120. else {
  9121. contentBlock.lines = contentBlock.lines.slice(0, i);
  9122. }
  9123. contentBlock.isTruncated = contentBlock.isTruncated || (contentBlock.lines.length < originalLength);
  9124. break outer;
  9125. }
  9126. var styleTokenWidth = tokenStyle.width;
  9127. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9128. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9129. token.percentWidth = styleTokenWidth;
  9130. pendingList.push(token);
  9131. token.contentWidth = getWidth(token.text, font);
  9132. }
  9133. else {
  9134. if (tokenWidthNotSpecified) {
  9135. var textBackgroundColor = tokenStyle.backgroundColor;
  9136. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9137. if (bgImg) {
  9138. bgImg = findExistImage(bgImg);
  9139. if (isImageReady(bgImg)) {
  9140. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9141. }
  9142. }
  9143. }
  9144. var remainTruncWidth = truncate && topWidth != null
  9145. ? topWidth - lineWidth : null;
  9146. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9147. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9148. token.text = '';
  9149. token.width = token.contentWidth = 0;
  9150. }
  9151. else {
  9152. truncateText2(tmpTruncateOut, token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9153. token.text = tmpTruncateOut.text;
  9154. contentBlock.isTruncated = contentBlock.isTruncated || tmpTruncateOut.isTruncated;
  9155. token.width = token.contentWidth = getWidth(token.text, font);
  9156. }
  9157. }
  9158. else {
  9159. token.contentWidth = getWidth(token.text, font);
  9160. }
  9161. }
  9162. token.width += paddingH;
  9163. lineWidth += token.width;
  9164. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9165. }
  9166. finishLine(line, lineWidth, lineHeight);
  9167. }
  9168. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9169. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9170. contentBlock.contentHeight = calculatedHeight;
  9171. contentBlock.contentWidth = calculatedWidth;
  9172. if (stlPadding) {
  9173. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9174. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9175. }
  9176. for (var i = 0; i < pendingList.length; i++) {
  9177. var token = pendingList[i];
  9178. var percentWidth = token.percentWidth;
  9179. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9180. }
  9181. return contentBlock;
  9182. }
  9183. function pushTokens(block, str, style, wrapInfo, styleName) {
  9184. var isEmptyStr = str === '';
  9185. var tokenStyle = styleName && style.rich[styleName] || {};
  9186. var lines = block.lines;
  9187. var font = tokenStyle.font || style.font;
  9188. var newLine = false;
  9189. var strLines;
  9190. var linesWidths;
  9191. if (wrapInfo) {
  9192. var tokenPadding = tokenStyle.padding;
  9193. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9194. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9195. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9196. if (lines.length > 0) {
  9197. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9198. strLines = str.split('\n');
  9199. newLine = true;
  9200. }
  9201. }
  9202. wrapInfo.accumWidth = outerWidth_1;
  9203. }
  9204. else {
  9205. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9206. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9207. linesWidths = res.linesWidths;
  9208. strLines = res.lines;
  9209. }
  9210. }
  9211. else {
  9212. strLines = str.split('\n');
  9213. }
  9214. for (var i = 0; i < strLines.length; i++) {
  9215. var text = strLines[i];
  9216. var token = new RichTextToken();
  9217. token.styleName = styleName;
  9218. token.text = text;
  9219. token.isLineHolder = !text && !isEmptyStr;
  9220. if (typeof tokenStyle.width === 'number') {
  9221. token.width = tokenStyle.width;
  9222. }
  9223. else {
  9224. token.width = linesWidths
  9225. ? linesWidths[i]
  9226. : getWidth(text, font);
  9227. }
  9228. if (!i && !newLine) {
  9229. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9230. var tokensLen = tokens.length;
  9231. (tokensLen === 1 && tokens[0].isLineHolder)
  9232. ? (tokens[0] = token)
  9233. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9234. }
  9235. else {
  9236. lines.push(new RichTextLine([token]));
  9237. }
  9238. }
  9239. }
  9240. function isAlphabeticLetter(ch) {
  9241. var code = ch.charCodeAt(0);
  9242. return code >= 0x20 && code <= 0x24F
  9243. || code >= 0x370 && code <= 0x10FF
  9244. || code >= 0x1200 && code <= 0x13FF
  9245. || code >= 0x1E00 && code <= 0x206F;
  9246. }
  9247. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9248. obj[ch] = true;
  9249. return obj;
  9250. }, {});
  9251. function isWordBreakChar(ch) {
  9252. if (isAlphabeticLetter(ch)) {
  9253. if (breakCharMap[ch]) {
  9254. return true;
  9255. }
  9256. return false;
  9257. }
  9258. return true;
  9259. }
  9260. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9261. var lines = [];
  9262. var linesWidths = [];
  9263. var line = '';
  9264. var currentWord = '';
  9265. var currentWordWidth = 0;
  9266. var accumWidth = 0;
  9267. for (var i = 0; i < text.length; i++) {
  9268. var ch = text.charAt(i);
  9269. if (ch === '\n') {
  9270. if (currentWord) {
  9271. line += currentWord;
  9272. accumWidth += currentWordWidth;
  9273. }
  9274. lines.push(line);
  9275. linesWidths.push(accumWidth);
  9276. line = '';
  9277. currentWord = '';
  9278. currentWordWidth = 0;
  9279. accumWidth = 0;
  9280. continue;
  9281. }
  9282. var chWidth = getWidth(ch, font);
  9283. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9284. if (!lines.length
  9285. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9286. : accumWidth + chWidth > lineWidth) {
  9287. if (!accumWidth) {
  9288. if (inWord) {
  9289. lines.push(currentWord);
  9290. linesWidths.push(currentWordWidth);
  9291. currentWord = ch;
  9292. currentWordWidth = chWidth;
  9293. }
  9294. else {
  9295. lines.push(ch);
  9296. linesWidths.push(chWidth);
  9297. }
  9298. }
  9299. else if (line || currentWord) {
  9300. if (inWord) {
  9301. if (!line) {
  9302. line = currentWord;
  9303. currentWord = '';
  9304. currentWordWidth = 0;
  9305. accumWidth = currentWordWidth;
  9306. }
  9307. lines.push(line);
  9308. linesWidths.push(accumWidth - currentWordWidth);
  9309. currentWord += ch;
  9310. currentWordWidth += chWidth;
  9311. line = '';
  9312. accumWidth = currentWordWidth;
  9313. }
  9314. else {
  9315. if (currentWord) {
  9316. line += currentWord;
  9317. currentWord = '';
  9318. currentWordWidth = 0;
  9319. }
  9320. lines.push(line);
  9321. linesWidths.push(accumWidth);
  9322. line = ch;
  9323. accumWidth = chWidth;
  9324. }
  9325. }
  9326. continue;
  9327. }
  9328. accumWidth += chWidth;
  9329. if (inWord) {
  9330. currentWord += ch;
  9331. currentWordWidth += chWidth;
  9332. }
  9333. else {
  9334. if (currentWord) {
  9335. line += currentWord;
  9336. currentWord = '';
  9337. currentWordWidth = 0;
  9338. }
  9339. line += ch;
  9340. }
  9341. }
  9342. if (!lines.length && !line) {
  9343. line = text;
  9344. currentWord = '';
  9345. currentWordWidth = 0;
  9346. }
  9347. if (currentWord) {
  9348. line += currentWord;
  9349. }
  9350. if (line) {
  9351. lines.push(line);
  9352. linesWidths.push(accumWidth);
  9353. }
  9354. if (lines.length === 1) {
  9355. accumWidth += lastAccumWidth;
  9356. }
  9357. return {
  9358. accumWidth: accumWidth,
  9359. lines: lines,
  9360. linesWidths: linesWidths
  9361. };
  9362. }
  9363. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9364. var DEFAULT_COMMON_STYLE = {
  9365. shadowBlur: 0,
  9366. shadowOffsetX: 0,
  9367. shadowOffsetY: 0,
  9368. shadowColor: '#000',
  9369. opacity: 1,
  9370. blend: 'source-over'
  9371. };
  9372. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9373. style: {
  9374. shadowBlur: true,
  9375. shadowOffsetX: true,
  9376. shadowOffsetY: true,
  9377. shadowColor: true,
  9378. opacity: true
  9379. }
  9380. };
  9381. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9382. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9383. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9384. var Displayable = (function (_super) {
  9385. __extends(Displayable, _super);
  9386. function Displayable(props) {
  9387. return _super.call(this, props) || this;
  9388. }
  9389. Displayable.prototype._init = function (props) {
  9390. var keysArr = keys(props);
  9391. for (var i = 0; i < keysArr.length; i++) {
  9392. var key = keysArr[i];
  9393. if (key === 'style') {
  9394. this.useStyle(props[key]);
  9395. }
  9396. else {
  9397. _super.prototype.attrKV.call(this, key, props[key]);
  9398. }
  9399. }
  9400. if (!this.style) {
  9401. this.useStyle({});
  9402. }
  9403. };
  9404. Displayable.prototype.beforeBrush = function () { };
  9405. Displayable.prototype.afterBrush = function () { };
  9406. Displayable.prototype.innerBeforeBrush = function () { };
  9407. Displayable.prototype.innerAfterBrush = function () { };
  9408. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9409. var m = this.transform;
  9410. if (this.ignore
  9411. || this.invisible
  9412. || this.style.opacity === 0
  9413. || (this.culling
  9414. && isDisplayableCulled(this, viewWidth, viewHeight))
  9415. || (m && !m[0] && !m[3])) {
  9416. return false;
  9417. }
  9418. if (considerClipPath && this.__clipPaths) {
  9419. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9420. if (this.__clipPaths[i].isZeroArea()) {
  9421. return false;
  9422. }
  9423. }
  9424. }
  9425. if (considerAncestors && this.parent) {
  9426. var parent_1 = this.parent;
  9427. while (parent_1) {
  9428. if (parent_1.ignore) {
  9429. return false;
  9430. }
  9431. parent_1 = parent_1.parent;
  9432. }
  9433. }
  9434. return true;
  9435. };
  9436. Displayable.prototype.contain = function (x, y) {
  9437. return this.rectContain(x, y);
  9438. };
  9439. Displayable.prototype.traverse = function (cb, context) {
  9440. cb.call(context, this);
  9441. };
  9442. Displayable.prototype.rectContain = function (x, y) {
  9443. var coord = this.transformCoordToLocal(x, y);
  9444. var rect = this.getBoundingRect();
  9445. return rect.contain(coord[0], coord[1]);
  9446. };
  9447. Displayable.prototype.getPaintRect = function () {
  9448. var rect = this._paintRect;
  9449. if (!this._paintRect || this.__dirty) {
  9450. var transform = this.transform;
  9451. var elRect = this.getBoundingRect();
  9452. var style = this.style;
  9453. var shadowSize = style.shadowBlur || 0;
  9454. var shadowOffsetX = style.shadowOffsetX || 0;
  9455. var shadowOffsetY = style.shadowOffsetY || 0;
  9456. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9457. if (transform) {
  9458. BoundingRect.applyTransform(rect, elRect, transform);
  9459. }
  9460. else {
  9461. rect.copy(elRect);
  9462. }
  9463. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9464. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9465. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9466. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9467. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9468. }
  9469. var tolerance = this.dirtyRectTolerance;
  9470. if (!rect.isZero()) {
  9471. rect.x = Math.floor(rect.x - tolerance);
  9472. rect.y = Math.floor(rect.y - tolerance);
  9473. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9474. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9475. }
  9476. }
  9477. return rect;
  9478. };
  9479. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9480. if (paintRect) {
  9481. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9482. this._prevPaintRect.copy(paintRect);
  9483. }
  9484. else {
  9485. this._prevPaintRect = null;
  9486. }
  9487. };
  9488. Displayable.prototype.getPrevPaintRect = function () {
  9489. return this._prevPaintRect;
  9490. };
  9491. Displayable.prototype.animateStyle = function (loop) {
  9492. return this.animate('style', loop);
  9493. };
  9494. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9495. if (targetKey === 'style') {
  9496. this.dirtyStyle();
  9497. }
  9498. else {
  9499. this.markRedraw();
  9500. }
  9501. };
  9502. Displayable.prototype.attrKV = function (key, value) {
  9503. if (key !== 'style') {
  9504. _super.prototype.attrKV.call(this, key, value);
  9505. }
  9506. else {
  9507. if (!this.style) {
  9508. this.useStyle(value);
  9509. }
  9510. else {
  9511. this.setStyle(value);
  9512. }
  9513. }
  9514. };
  9515. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9516. if (typeof keyOrObj === 'string') {
  9517. this.style[keyOrObj] = value;
  9518. }
  9519. else {
  9520. extend(this.style, keyOrObj);
  9521. }
  9522. this.dirtyStyle();
  9523. return this;
  9524. };
  9525. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9526. if (!notRedraw) {
  9527. this.markRedraw();
  9528. }
  9529. this.__dirty |= STYLE_CHANGED_BIT;
  9530. if (this._rect) {
  9531. this._rect = null;
  9532. }
  9533. };
  9534. Displayable.prototype.dirty = function () {
  9535. this.dirtyStyle();
  9536. };
  9537. Displayable.prototype.styleChanged = function () {
  9538. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9539. };
  9540. Displayable.prototype.styleUpdated = function () {
  9541. this.__dirty &= ~STYLE_CHANGED_BIT;
  9542. };
  9543. Displayable.prototype.createStyle = function (obj) {
  9544. return createObject(DEFAULT_COMMON_STYLE, obj);
  9545. };
  9546. Displayable.prototype.useStyle = function (obj) {
  9547. if (!obj[STYLE_MAGIC_KEY]) {
  9548. obj = this.createStyle(obj);
  9549. }
  9550. if (this.__inHover) {
  9551. this.__hoverStyle = obj;
  9552. }
  9553. else {
  9554. this.style = obj;
  9555. }
  9556. this.dirtyStyle();
  9557. };
  9558. Displayable.prototype.isStyleObject = function (obj) {
  9559. return obj[STYLE_MAGIC_KEY];
  9560. };
  9561. Displayable.prototype._innerSaveToNormal = function (toState) {
  9562. _super.prototype._innerSaveToNormal.call(this, toState);
  9563. var normalState = this._normalState;
  9564. if (toState.style && !normalState.style) {
  9565. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9566. }
  9567. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9568. };
  9569. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9570. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9571. var needsRestoreToNormal = !(state && keepCurrentStates);
  9572. var targetStyle;
  9573. if (state && state.style) {
  9574. if (transition) {
  9575. if (keepCurrentStates) {
  9576. targetStyle = state.style;
  9577. }
  9578. else {
  9579. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9580. this._mergeStyle(targetStyle, state.style);
  9581. }
  9582. }
  9583. else {
  9584. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9585. this._mergeStyle(targetStyle, state.style);
  9586. }
  9587. }
  9588. else if (needsRestoreToNormal) {
  9589. targetStyle = normalState.style;
  9590. }
  9591. if (targetStyle) {
  9592. if (transition) {
  9593. var sourceStyle = this.style;
  9594. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9595. if (needsRestoreToNormal) {
  9596. var changedKeys = keys(sourceStyle);
  9597. for (var i = 0; i < changedKeys.length; i++) {
  9598. var key = changedKeys[i];
  9599. if (key in targetStyle) {
  9600. targetStyle[key] = targetStyle[key];
  9601. this.style[key] = sourceStyle[key];
  9602. }
  9603. }
  9604. }
  9605. var targetKeys = keys(targetStyle);
  9606. for (var i = 0; i < targetKeys.length; i++) {
  9607. var key = targetKeys[i];
  9608. this.style[key] = this.style[key];
  9609. }
  9610. this._transitionState(stateName, {
  9611. style: targetStyle
  9612. }, animationCfg, this.getAnimationStyleProps());
  9613. }
  9614. else {
  9615. this.useStyle(targetStyle);
  9616. }
  9617. }
  9618. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9619. for (var i = 0; i < statesKeys.length; i++) {
  9620. var key = statesKeys[i];
  9621. if (state && state[key] != null) {
  9622. this[key] = state[key];
  9623. }
  9624. else if (needsRestoreToNormal) {
  9625. if (normalState[key] != null) {
  9626. this[key] = normalState[key];
  9627. }
  9628. }
  9629. }
  9630. };
  9631. Displayable.prototype._mergeStates = function (states) {
  9632. var mergedState = _super.prototype._mergeStates.call(this, states);
  9633. var mergedStyle;
  9634. for (var i = 0; i < states.length; i++) {
  9635. var state = states[i];
  9636. if (state.style) {
  9637. mergedStyle = mergedStyle || {};
  9638. this._mergeStyle(mergedStyle, state.style);
  9639. }
  9640. }
  9641. if (mergedStyle) {
  9642. mergedState.style = mergedStyle;
  9643. }
  9644. return mergedState;
  9645. };
  9646. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9647. extend(targetStyle, sourceStyle);
  9648. return targetStyle;
  9649. };
  9650. Displayable.prototype.getAnimationStyleProps = function () {
  9651. return DEFAULT_COMMON_ANIMATION_PROPS;
  9652. };
  9653. Displayable.initDefaultProps = (function () {
  9654. var dispProto = Displayable.prototype;
  9655. dispProto.type = 'displayable';
  9656. dispProto.invisible = false;
  9657. dispProto.z = 0;
  9658. dispProto.z2 = 0;
  9659. dispProto.zlevel = 0;
  9660. dispProto.culling = false;
  9661. dispProto.cursor = 'pointer';
  9662. dispProto.rectHover = false;
  9663. dispProto.incremental = false;
  9664. dispProto._rect = null;
  9665. dispProto.dirtyRectTolerance = 0;
  9666. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9667. })();
  9668. return Displayable;
  9669. }(Element));
  9670. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9671. var viewRect = new BoundingRect(0, 0, 0, 0);
  9672. function isDisplayableCulled(el, width, height) {
  9673. tmpRect$1.copy(el.getBoundingRect());
  9674. if (el.transform) {
  9675. tmpRect$1.applyTransform(el.transform);
  9676. }
  9677. viewRect.width = width;
  9678. viewRect.height = height;
  9679. return !tmpRect$1.intersect(viewRect);
  9680. }
  9681. var mathMin$1 = Math.min;
  9682. var mathMax$1 = Math.max;
  9683. var mathSin = Math.sin;
  9684. var mathCos = Math.cos;
  9685. var PI2 = Math.PI * 2;
  9686. var start = create();
  9687. var end = create();
  9688. var extremity = create();
  9689. function fromLine(x0, y0, x1, y1, min, max) {
  9690. min[0] = mathMin$1(x0, x1);
  9691. min[1] = mathMin$1(y0, y1);
  9692. max[0] = mathMax$1(x0, x1);
  9693. max[1] = mathMax$1(y0, y1);
  9694. }
  9695. var xDim = [];
  9696. var yDim = [];
  9697. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9698. var cubicExtrema$1 = cubicExtrema;
  9699. var cubicAt$1 = cubicAt;
  9700. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9701. min[0] = Infinity;
  9702. min[1] = Infinity;
  9703. max[0] = -Infinity;
  9704. max[1] = -Infinity;
  9705. for (var i = 0; i < n; i++) {
  9706. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9707. min[0] = mathMin$1(x, min[0]);
  9708. max[0] = mathMax$1(x, max[0]);
  9709. }
  9710. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9711. for (var i = 0; i < n; i++) {
  9712. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9713. min[1] = mathMin$1(y, min[1]);
  9714. max[1] = mathMax$1(y, max[1]);
  9715. }
  9716. min[0] = mathMin$1(x0, min[0]);
  9717. max[0] = mathMax$1(x0, max[0]);
  9718. min[0] = mathMin$1(x3, min[0]);
  9719. max[0] = mathMax$1(x3, max[0]);
  9720. min[1] = mathMin$1(y0, min[1]);
  9721. max[1] = mathMax$1(y0, max[1]);
  9722. min[1] = mathMin$1(y3, min[1]);
  9723. max[1] = mathMax$1(y3, max[1]);
  9724. }
  9725. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9726. var quadraticExtremum$1 = quadraticExtremum;
  9727. var quadraticAt$1 = quadraticAt;
  9728. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9729. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9730. var x = quadraticAt$1(x0, x1, x2, tx);
  9731. var y = quadraticAt$1(y0, y1, y2, ty);
  9732. min[0] = mathMin$1(x0, x2, x);
  9733. min[1] = mathMin$1(y0, y2, y);
  9734. max[0] = mathMax$1(x0, x2, x);
  9735. max[1] = mathMax$1(y0, y2, y);
  9736. }
  9737. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9738. var vec2Min = min;
  9739. var vec2Max = max;
  9740. var diff = Math.abs(startAngle - endAngle);
  9741. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9742. min$1[0] = x - rx;
  9743. min$1[1] = y - ry;
  9744. max$1[0] = x + rx;
  9745. max$1[1] = y + ry;
  9746. return;
  9747. }
  9748. start[0] = mathCos(startAngle) * rx + x;
  9749. start[1] = mathSin(startAngle) * ry + y;
  9750. end[0] = mathCos(endAngle) * rx + x;
  9751. end[1] = mathSin(endAngle) * ry + y;
  9752. vec2Min(min$1, start, end);
  9753. vec2Max(max$1, start, end);
  9754. startAngle = startAngle % (PI2);
  9755. if (startAngle < 0) {
  9756. startAngle = startAngle + PI2;
  9757. }
  9758. endAngle = endAngle % (PI2);
  9759. if (endAngle < 0) {
  9760. endAngle = endAngle + PI2;
  9761. }
  9762. if (startAngle > endAngle && !anticlockwise) {
  9763. endAngle += PI2;
  9764. }
  9765. else if (startAngle < endAngle && anticlockwise) {
  9766. startAngle += PI2;
  9767. }
  9768. if (anticlockwise) {
  9769. var tmp = endAngle;
  9770. endAngle = startAngle;
  9771. startAngle = tmp;
  9772. }
  9773. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9774. if (angle > startAngle) {
  9775. extremity[0] = mathCos(angle) * rx + x;
  9776. extremity[1] = mathSin(angle) * ry + y;
  9777. vec2Min(min$1, extremity, min$1);
  9778. vec2Max(max$1, extremity, max$1);
  9779. }
  9780. }
  9781. }
  9782. var CMD = {
  9783. M: 1,
  9784. L: 2,
  9785. C: 3,
  9786. Q: 4,
  9787. A: 5,
  9788. Z: 6,
  9789. R: 7
  9790. };
  9791. var tmpOutX = [];
  9792. var tmpOutY = [];
  9793. var min$1 = [];
  9794. var max$1 = [];
  9795. var min2 = [];
  9796. var max2 = [];
  9797. var mathMin$2 = Math.min;
  9798. var mathMax$2 = Math.max;
  9799. var mathCos$1 = Math.cos;
  9800. var mathSin$1 = Math.sin;
  9801. var mathAbs = Math.abs;
  9802. var PI = Math.PI;
  9803. var PI2$1 = PI * 2;
  9804. var hasTypedArray = typeof Float32Array !== 'undefined';
  9805. var tmpAngles = [];
  9806. function modPI2(radian) {
  9807. var n = Math.round(radian / PI * 1e8) / 1e8;
  9808. return (n % 2) * PI;
  9809. }
  9810. function normalizeArcAngles(angles, anticlockwise) {
  9811. var newStartAngle = modPI2(angles[0]);
  9812. if (newStartAngle < 0) {
  9813. newStartAngle += PI2$1;
  9814. }
  9815. var delta = newStartAngle - angles[0];
  9816. var newEndAngle = angles[1];
  9817. newEndAngle += delta;
  9818. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9819. newEndAngle = newStartAngle + PI2$1;
  9820. }
  9821. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9822. newEndAngle = newStartAngle - PI2$1;
  9823. }
  9824. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9825. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9826. }
  9827. else if (anticlockwise && newStartAngle < newEndAngle) {
  9828. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9829. }
  9830. angles[0] = newStartAngle;
  9831. angles[1] = newEndAngle;
  9832. }
  9833. var PathProxy = (function () {
  9834. function PathProxy(notSaveData) {
  9835. this.dpr = 1;
  9836. this._xi = 0;
  9837. this._yi = 0;
  9838. this._x0 = 0;
  9839. this._y0 = 0;
  9840. this._len = 0;
  9841. if (notSaveData) {
  9842. this._saveData = false;
  9843. }
  9844. if (this._saveData) {
  9845. this.data = [];
  9846. }
  9847. }
  9848. PathProxy.prototype.increaseVersion = function () {
  9849. this._version++;
  9850. };
  9851. PathProxy.prototype.getVersion = function () {
  9852. return this._version;
  9853. };
  9854. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9855. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9856. if (segmentIgnoreThreshold > 0) {
  9857. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9858. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9859. }
  9860. };
  9861. PathProxy.prototype.setDPR = function (dpr) {
  9862. this.dpr = dpr;
  9863. };
  9864. PathProxy.prototype.setContext = function (ctx) {
  9865. this._ctx = ctx;
  9866. };
  9867. PathProxy.prototype.getContext = function () {
  9868. return this._ctx;
  9869. };
  9870. PathProxy.prototype.beginPath = function () {
  9871. this._ctx && this._ctx.beginPath();
  9872. this.reset();
  9873. return this;
  9874. };
  9875. PathProxy.prototype.reset = function () {
  9876. if (this._saveData) {
  9877. this._len = 0;
  9878. }
  9879. if (this._pathSegLen) {
  9880. this._pathSegLen = null;
  9881. this._pathLen = 0;
  9882. }
  9883. this._version++;
  9884. };
  9885. PathProxy.prototype.moveTo = function (x, y) {
  9886. this._drawPendingPt();
  9887. this.addData(CMD.M, x, y);
  9888. this._ctx && this._ctx.moveTo(x, y);
  9889. this._x0 = x;
  9890. this._y0 = y;
  9891. this._xi = x;
  9892. this._yi = y;
  9893. return this;
  9894. };
  9895. PathProxy.prototype.lineTo = function (x, y) {
  9896. var dx = mathAbs(x - this._xi);
  9897. var dy = mathAbs(y - this._yi);
  9898. var exceedUnit = dx > this._ux || dy > this._uy;
  9899. this.addData(CMD.L, x, y);
  9900. if (this._ctx && exceedUnit) {
  9901. this._ctx.lineTo(x, y);
  9902. }
  9903. if (exceedUnit) {
  9904. this._xi = x;
  9905. this._yi = y;
  9906. this._pendingPtDist = 0;
  9907. }
  9908. else {
  9909. var d2 = dx * dx + dy * dy;
  9910. if (d2 > this._pendingPtDist) {
  9911. this._pendingPtX = x;
  9912. this._pendingPtY = y;
  9913. this._pendingPtDist = d2;
  9914. }
  9915. }
  9916. return this;
  9917. };
  9918. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9919. this._drawPendingPt();
  9920. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9921. if (this._ctx) {
  9922. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9923. }
  9924. this._xi = x3;
  9925. this._yi = y3;
  9926. return this;
  9927. };
  9928. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9929. this._drawPendingPt();
  9930. this.addData(CMD.Q, x1, y1, x2, y2);
  9931. if (this._ctx) {
  9932. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9933. }
  9934. this._xi = x2;
  9935. this._yi = y2;
  9936. return this;
  9937. };
  9938. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9939. this._drawPendingPt();
  9940. tmpAngles[0] = startAngle;
  9941. tmpAngles[1] = endAngle;
  9942. normalizeArcAngles(tmpAngles, anticlockwise);
  9943. startAngle = tmpAngles[0];
  9944. endAngle = tmpAngles[1];
  9945. var delta = endAngle - startAngle;
  9946. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9947. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9948. this._xi = mathCos$1(endAngle) * r + cx;
  9949. this._yi = mathSin$1(endAngle) * r + cy;
  9950. return this;
  9951. };
  9952. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9953. this._drawPendingPt();
  9954. if (this._ctx) {
  9955. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9956. }
  9957. return this;
  9958. };
  9959. PathProxy.prototype.rect = function (x, y, w, h) {
  9960. this._drawPendingPt();
  9961. this._ctx && this._ctx.rect(x, y, w, h);
  9962. this.addData(CMD.R, x, y, w, h);
  9963. return this;
  9964. };
  9965. PathProxy.prototype.closePath = function () {
  9966. this._drawPendingPt();
  9967. this.addData(CMD.Z);
  9968. var ctx = this._ctx;
  9969. var x0 = this._x0;
  9970. var y0 = this._y0;
  9971. if (ctx) {
  9972. ctx.closePath();
  9973. }
  9974. this._xi = x0;
  9975. this._yi = y0;
  9976. return this;
  9977. };
  9978. PathProxy.prototype.fill = function (ctx) {
  9979. ctx && ctx.fill();
  9980. this.toStatic();
  9981. };
  9982. PathProxy.prototype.stroke = function (ctx) {
  9983. ctx && ctx.stroke();
  9984. this.toStatic();
  9985. };
  9986. PathProxy.prototype.len = function () {
  9987. return this._len;
  9988. };
  9989. PathProxy.prototype.setData = function (data) {
  9990. var len = data.length;
  9991. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9992. this.data = new Float32Array(len);
  9993. }
  9994. for (var i = 0; i < len; i++) {
  9995. this.data[i] = data[i];
  9996. }
  9997. this._len = len;
  9998. };
  9999. PathProxy.prototype.appendPath = function (path) {
  10000. if (!(path instanceof Array)) {
  10001. path = [path];
  10002. }
  10003. var len = path.length;
  10004. var appendSize = 0;
  10005. var offset = this._len;
  10006. for (var i = 0; i < len; i++) {
  10007. appendSize += path[i].len();
  10008. }
  10009. if (hasTypedArray && (this.data instanceof Float32Array)) {
  10010. this.data = new Float32Array(offset + appendSize);
  10011. }
  10012. for (var i = 0; i < len; i++) {
  10013. var appendPathData = path[i].data;
  10014. for (var k = 0; k < appendPathData.length; k++) {
  10015. this.data[offset++] = appendPathData[k];
  10016. }
  10017. }
  10018. this._len = offset;
  10019. };
  10020. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  10021. if (!this._saveData) {
  10022. return;
  10023. }
  10024. var data = this.data;
  10025. if (this._len + arguments.length > data.length) {
  10026. this._expandData();
  10027. data = this.data;
  10028. }
  10029. for (var i = 0; i < arguments.length; i++) {
  10030. data[this._len++] = arguments[i];
  10031. }
  10032. };
  10033. PathProxy.prototype._drawPendingPt = function () {
  10034. if (this._pendingPtDist > 0) {
  10035. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  10036. this._pendingPtDist = 0;
  10037. }
  10038. };
  10039. PathProxy.prototype._expandData = function () {
  10040. if (!(this.data instanceof Array)) {
  10041. var newData = [];
  10042. for (var i = 0; i < this._len; i++) {
  10043. newData[i] = this.data[i];
  10044. }
  10045. this.data = newData;
  10046. }
  10047. };
  10048. PathProxy.prototype.toStatic = function () {
  10049. if (!this._saveData) {
  10050. return;
  10051. }
  10052. this._drawPendingPt();
  10053. var data = this.data;
  10054. if (data instanceof Array) {
  10055. data.length = this._len;
  10056. if (hasTypedArray && this._len > 11) {
  10057. this.data = new Float32Array(data);
  10058. }
  10059. }
  10060. };
  10061. PathProxy.prototype.getBoundingRect = function () {
  10062. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  10063. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  10064. var data = this.data;
  10065. var xi = 0;
  10066. var yi = 0;
  10067. var x0 = 0;
  10068. var y0 = 0;
  10069. var i;
  10070. for (i = 0; i < this._len;) {
  10071. var cmd = data[i++];
  10072. var isFirst = i === 1;
  10073. if (isFirst) {
  10074. xi = data[i];
  10075. yi = data[i + 1];
  10076. x0 = xi;
  10077. y0 = yi;
  10078. }
  10079. switch (cmd) {
  10080. case CMD.M:
  10081. xi = x0 = data[i++];
  10082. yi = y0 = data[i++];
  10083. min2[0] = x0;
  10084. min2[1] = y0;
  10085. max2[0] = x0;
  10086. max2[1] = y0;
  10087. break;
  10088. case CMD.L:
  10089. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10090. xi = data[i++];
  10091. yi = data[i++];
  10092. break;
  10093. case CMD.C:
  10094. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10095. xi = data[i++];
  10096. yi = data[i++];
  10097. break;
  10098. case CMD.Q:
  10099. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10100. xi = data[i++];
  10101. yi = data[i++];
  10102. break;
  10103. case CMD.A:
  10104. var cx = data[i++];
  10105. var cy = data[i++];
  10106. var rx = data[i++];
  10107. var ry = data[i++];
  10108. var startAngle = data[i++];
  10109. var endAngle = data[i++] + startAngle;
  10110. i += 1;
  10111. var anticlockwise = !data[i++];
  10112. if (isFirst) {
  10113. x0 = mathCos$1(startAngle) * rx + cx;
  10114. y0 = mathSin$1(startAngle) * ry + cy;
  10115. }
  10116. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10117. xi = mathCos$1(endAngle) * rx + cx;
  10118. yi = mathSin$1(endAngle) * ry + cy;
  10119. break;
  10120. case CMD.R:
  10121. x0 = xi = data[i++];
  10122. y0 = yi = data[i++];
  10123. var width = data[i++];
  10124. var height = data[i++];
  10125. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10126. break;
  10127. case CMD.Z:
  10128. xi = x0;
  10129. yi = y0;
  10130. break;
  10131. }
  10132. min(min$1, min$1, min2);
  10133. max(max$1, max$1, max2);
  10134. }
  10135. if (i === 0) {
  10136. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10137. }
  10138. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10139. };
  10140. PathProxy.prototype._calculateLength = function () {
  10141. var data = this.data;
  10142. var len = this._len;
  10143. var ux = this._ux;
  10144. var uy = this._uy;
  10145. var xi = 0;
  10146. var yi = 0;
  10147. var x0 = 0;
  10148. var y0 = 0;
  10149. if (!this._pathSegLen) {
  10150. this._pathSegLen = [];
  10151. }
  10152. var pathSegLen = this._pathSegLen;
  10153. var pathTotalLen = 0;
  10154. var segCount = 0;
  10155. for (var i = 0; i < len;) {
  10156. var cmd = data[i++];
  10157. var isFirst = i === 1;
  10158. if (isFirst) {
  10159. xi = data[i];
  10160. yi = data[i + 1];
  10161. x0 = xi;
  10162. y0 = yi;
  10163. }
  10164. var l = -1;
  10165. switch (cmd) {
  10166. case CMD.M:
  10167. xi = x0 = data[i++];
  10168. yi = y0 = data[i++];
  10169. break;
  10170. case CMD.L: {
  10171. var x2 = data[i++];
  10172. var y2 = data[i++];
  10173. var dx = x2 - xi;
  10174. var dy = y2 - yi;
  10175. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10176. l = Math.sqrt(dx * dx + dy * dy);
  10177. xi = x2;
  10178. yi = y2;
  10179. }
  10180. break;
  10181. }
  10182. case CMD.C: {
  10183. var x1 = data[i++];
  10184. var y1 = data[i++];
  10185. var x2 = data[i++];
  10186. var y2 = data[i++];
  10187. var x3 = data[i++];
  10188. var y3 = data[i++];
  10189. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10190. xi = x3;
  10191. yi = y3;
  10192. break;
  10193. }
  10194. case CMD.Q: {
  10195. var x1 = data[i++];
  10196. var y1 = data[i++];
  10197. var x2 = data[i++];
  10198. var y2 = data[i++];
  10199. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10200. xi = x2;
  10201. yi = y2;
  10202. break;
  10203. }
  10204. case CMD.A:
  10205. var cx = data[i++];
  10206. var cy = data[i++];
  10207. var rx = data[i++];
  10208. var ry = data[i++];
  10209. var startAngle = data[i++];
  10210. var delta = data[i++];
  10211. var endAngle = delta + startAngle;
  10212. i += 1;
  10213. if (isFirst) {
  10214. x0 = mathCos$1(startAngle) * rx + cx;
  10215. y0 = mathSin$1(startAngle) * ry + cy;
  10216. }
  10217. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10218. xi = mathCos$1(endAngle) * rx + cx;
  10219. yi = mathSin$1(endAngle) * ry + cy;
  10220. break;
  10221. case CMD.R: {
  10222. x0 = xi = data[i++];
  10223. y0 = yi = data[i++];
  10224. var width = data[i++];
  10225. var height = data[i++];
  10226. l = width * 2 + height * 2;
  10227. break;
  10228. }
  10229. case CMD.Z: {
  10230. var dx = x0 - xi;
  10231. var dy = y0 - yi;
  10232. l = Math.sqrt(dx * dx + dy * dy);
  10233. xi = x0;
  10234. yi = y0;
  10235. break;
  10236. }
  10237. }
  10238. if (l >= 0) {
  10239. pathSegLen[segCount++] = l;
  10240. pathTotalLen += l;
  10241. }
  10242. }
  10243. this._pathLen = pathTotalLen;
  10244. return pathTotalLen;
  10245. };
  10246. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10247. var d = this.data;
  10248. var ux = this._ux;
  10249. var uy = this._uy;
  10250. var len = this._len;
  10251. var x0;
  10252. var y0;
  10253. var xi;
  10254. var yi;
  10255. var x;
  10256. var y;
  10257. var drawPart = percent < 1;
  10258. var pathSegLen;
  10259. var pathTotalLen;
  10260. var accumLength = 0;
  10261. var segCount = 0;
  10262. var displayedLength;
  10263. var pendingPtDist = 0;
  10264. var pendingPtX;
  10265. var pendingPtY;
  10266. if (drawPart) {
  10267. if (!this._pathSegLen) {
  10268. this._calculateLength();
  10269. }
  10270. pathSegLen = this._pathSegLen;
  10271. pathTotalLen = this._pathLen;
  10272. displayedLength = percent * pathTotalLen;
  10273. if (!displayedLength) {
  10274. return;
  10275. }
  10276. }
  10277. lo: for (var i = 0; i < len;) {
  10278. var cmd = d[i++];
  10279. var isFirst = i === 1;
  10280. if (isFirst) {
  10281. xi = d[i];
  10282. yi = d[i + 1];
  10283. x0 = xi;
  10284. y0 = yi;
  10285. }
  10286. if (cmd !== CMD.L && pendingPtDist > 0) {
  10287. ctx.lineTo(pendingPtX, pendingPtY);
  10288. pendingPtDist = 0;
  10289. }
  10290. switch (cmd) {
  10291. case CMD.M:
  10292. x0 = xi = d[i++];
  10293. y0 = yi = d[i++];
  10294. ctx.moveTo(xi, yi);
  10295. break;
  10296. case CMD.L: {
  10297. x = d[i++];
  10298. y = d[i++];
  10299. var dx = mathAbs(x - xi);
  10300. var dy = mathAbs(y - yi);
  10301. if (dx > ux || dy > uy) {
  10302. if (drawPart) {
  10303. var l = pathSegLen[segCount++];
  10304. if (accumLength + l > displayedLength) {
  10305. var t = (displayedLength - accumLength) / l;
  10306. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10307. break lo;
  10308. }
  10309. accumLength += l;
  10310. }
  10311. ctx.lineTo(x, y);
  10312. xi = x;
  10313. yi = y;
  10314. pendingPtDist = 0;
  10315. }
  10316. else {
  10317. var d2 = dx * dx + dy * dy;
  10318. if (d2 > pendingPtDist) {
  10319. pendingPtX = x;
  10320. pendingPtY = y;
  10321. pendingPtDist = d2;
  10322. }
  10323. }
  10324. break;
  10325. }
  10326. case CMD.C: {
  10327. var x1 = d[i++];
  10328. var y1 = d[i++];
  10329. var x2 = d[i++];
  10330. var y2 = d[i++];
  10331. var x3 = d[i++];
  10332. var y3 = d[i++];
  10333. if (drawPart) {
  10334. var l = pathSegLen[segCount++];
  10335. if (accumLength + l > displayedLength) {
  10336. var t = (displayedLength - accumLength) / l;
  10337. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10338. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10339. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10340. break lo;
  10341. }
  10342. accumLength += l;
  10343. }
  10344. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10345. xi = x3;
  10346. yi = y3;
  10347. break;
  10348. }
  10349. case CMD.Q: {
  10350. var x1 = d[i++];
  10351. var y1 = d[i++];
  10352. var x2 = d[i++];
  10353. var y2 = d[i++];
  10354. if (drawPart) {
  10355. var l = pathSegLen[segCount++];
  10356. if (accumLength + l > displayedLength) {
  10357. var t = (displayedLength - accumLength) / l;
  10358. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10359. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10360. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10361. break lo;
  10362. }
  10363. accumLength += l;
  10364. }
  10365. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10366. xi = x2;
  10367. yi = y2;
  10368. break;
  10369. }
  10370. case CMD.A:
  10371. var cx = d[i++];
  10372. var cy = d[i++];
  10373. var rx = d[i++];
  10374. var ry = d[i++];
  10375. var startAngle = d[i++];
  10376. var delta = d[i++];
  10377. var psi = d[i++];
  10378. var anticlockwise = !d[i++];
  10379. var r = (rx > ry) ? rx : ry;
  10380. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10381. var endAngle = startAngle + delta;
  10382. var breakBuild = false;
  10383. if (drawPart) {
  10384. var l = pathSegLen[segCount++];
  10385. if (accumLength + l > displayedLength) {
  10386. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10387. breakBuild = true;
  10388. }
  10389. accumLength += l;
  10390. }
  10391. if (isEllipse && ctx.ellipse) {
  10392. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10393. }
  10394. else {
  10395. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10396. }
  10397. if (breakBuild) {
  10398. break lo;
  10399. }
  10400. if (isFirst) {
  10401. x0 = mathCos$1(startAngle) * rx + cx;
  10402. y0 = mathSin$1(startAngle) * ry + cy;
  10403. }
  10404. xi = mathCos$1(endAngle) * rx + cx;
  10405. yi = mathSin$1(endAngle) * ry + cy;
  10406. break;
  10407. case CMD.R:
  10408. x0 = xi = d[i];
  10409. y0 = yi = d[i + 1];
  10410. x = d[i++];
  10411. y = d[i++];
  10412. var width = d[i++];
  10413. var height = d[i++];
  10414. if (drawPart) {
  10415. var l = pathSegLen[segCount++];
  10416. if (accumLength + l > displayedLength) {
  10417. var d_1 = displayedLength - accumLength;
  10418. ctx.moveTo(x, y);
  10419. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10420. d_1 -= width;
  10421. if (d_1 > 0) {
  10422. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10423. }
  10424. d_1 -= height;
  10425. if (d_1 > 0) {
  10426. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10427. }
  10428. d_1 -= width;
  10429. if (d_1 > 0) {
  10430. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10431. }
  10432. break lo;
  10433. }
  10434. accumLength += l;
  10435. }
  10436. ctx.rect(x, y, width, height);
  10437. break;
  10438. case CMD.Z:
  10439. if (drawPart) {
  10440. var l = pathSegLen[segCount++];
  10441. if (accumLength + l > displayedLength) {
  10442. var t = (displayedLength - accumLength) / l;
  10443. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10444. break lo;
  10445. }
  10446. accumLength += l;
  10447. }
  10448. ctx.closePath();
  10449. xi = x0;
  10450. yi = y0;
  10451. }
  10452. }
  10453. };
  10454. PathProxy.prototype.clone = function () {
  10455. var newProxy = new PathProxy();
  10456. var data = this.data;
  10457. newProxy.data = data.slice ? data.slice()
  10458. : Array.prototype.slice.call(data);
  10459. newProxy._len = this._len;
  10460. return newProxy;
  10461. };
  10462. PathProxy.CMD = CMD;
  10463. PathProxy.initDefaultProps = (function () {
  10464. var proto = PathProxy.prototype;
  10465. proto._saveData = true;
  10466. proto._ux = 0;
  10467. proto._uy = 0;
  10468. proto._pendingPtDist = 0;
  10469. proto._version = 0;
  10470. })();
  10471. return PathProxy;
  10472. }());
  10473. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10474. if (lineWidth === 0) {
  10475. return false;
  10476. }
  10477. var _l = lineWidth;
  10478. var _a = 0;
  10479. var _b = x0;
  10480. if ((y > y0 + _l && y > y1 + _l)
  10481. || (y < y0 - _l && y < y1 - _l)
  10482. || (x > x0 + _l && x > x1 + _l)
  10483. || (x < x0 - _l && x < x1 - _l)) {
  10484. return false;
  10485. }
  10486. if (x0 !== x1) {
  10487. _a = (y0 - y1) / (x0 - x1);
  10488. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10489. }
  10490. else {
  10491. return Math.abs(x - x0) <= _l / 2;
  10492. }
  10493. var tmp = _a * x - y + _b;
  10494. var _s = tmp * tmp / (_a * _a + 1);
  10495. return _s <= _l / 2 * _l / 2;
  10496. }
  10497. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10498. if (lineWidth === 0) {
  10499. return false;
  10500. }
  10501. var _l = lineWidth;
  10502. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10503. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10504. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10505. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10506. return false;
  10507. }
  10508. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10509. return d <= _l / 2;
  10510. }
  10511. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10512. if (lineWidth === 0) {
  10513. return false;
  10514. }
  10515. var _l = lineWidth;
  10516. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10517. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10518. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10519. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10520. return false;
  10521. }
  10522. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10523. return d <= _l / 2;
  10524. }
  10525. var PI2$2 = Math.PI * 2;
  10526. function normalizeRadian(angle) {
  10527. angle %= PI2$2;
  10528. if (angle < 0) {
  10529. angle += PI2$2;
  10530. }
  10531. return angle;
  10532. }
  10533. var PI2$3 = Math.PI * 2;
  10534. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10535. if (lineWidth === 0) {
  10536. return false;
  10537. }
  10538. var _l = lineWidth;
  10539. x -= cx;
  10540. y -= cy;
  10541. var d = Math.sqrt(x * x + y * y);
  10542. if ((d - _l > r) || (d + _l < r)) {
  10543. return false;
  10544. }
  10545. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10546. return true;
  10547. }
  10548. if (anticlockwise) {
  10549. var tmp = startAngle;
  10550. startAngle = normalizeRadian(endAngle);
  10551. endAngle = normalizeRadian(tmp);
  10552. }
  10553. else {
  10554. startAngle = normalizeRadian(startAngle);
  10555. endAngle = normalizeRadian(endAngle);
  10556. }
  10557. if (startAngle > endAngle) {
  10558. endAngle += PI2$3;
  10559. }
  10560. var angle = Math.atan2(y, x);
  10561. if (angle < 0) {
  10562. angle += PI2$3;
  10563. }
  10564. return (angle >= startAngle && angle <= endAngle)
  10565. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10566. }
  10567. function windingLine(x0, y0, x1, y1, x, y) {
  10568. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10569. return 0;
  10570. }
  10571. if (y1 === y0) {
  10572. return 0;
  10573. }
  10574. var t = (y - y0) / (y1 - y0);
  10575. var dir = y1 < y0 ? 1 : -1;
  10576. if (t === 1 || t === 0) {
  10577. dir = y1 < y0 ? 0.5 : -0.5;
  10578. }
  10579. var x_ = t * (x1 - x0) + x0;
  10580. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10581. }
  10582. var CMD$1 = PathProxy.CMD;
  10583. var PI2$4 = Math.PI * 2;
  10584. var EPSILON$3 = 1e-4;
  10585. function isAroundEqual(a, b) {
  10586. return Math.abs(a - b) < EPSILON$3;
  10587. }
  10588. var roots = [-1, -1, -1];
  10589. var extrema = [-1, -1];
  10590. function swapExtrema() {
  10591. var tmp = extrema[0];
  10592. extrema[0] = extrema[1];
  10593. extrema[1] = tmp;
  10594. }
  10595. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10596. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10597. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10598. return 0;
  10599. }
  10600. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10601. if (nRoots === 0) {
  10602. return 0;
  10603. }
  10604. else {
  10605. var w = 0;
  10606. var nExtrema = -1;
  10607. var y0_ = void 0;
  10608. var y1_ = void 0;
  10609. for (var i = 0; i < nRoots; i++) {
  10610. var t = roots[i];
  10611. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10612. var x_ = cubicAt(x0, x1, x2, x3, t);
  10613. if (x_ < x) {
  10614. continue;
  10615. }
  10616. if (nExtrema < 0) {
  10617. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10618. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10619. swapExtrema();
  10620. }
  10621. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10622. if (nExtrema > 1) {
  10623. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10624. }
  10625. }
  10626. if (nExtrema === 2) {
  10627. if (t < extrema[0]) {
  10628. w += y0_ < y0 ? unit : -unit;
  10629. }
  10630. else if (t < extrema[1]) {
  10631. w += y1_ < y0_ ? unit : -unit;
  10632. }
  10633. else {
  10634. w += y3 < y1_ ? unit : -unit;
  10635. }
  10636. }
  10637. else {
  10638. if (t < extrema[0]) {
  10639. w += y0_ < y0 ? unit : -unit;
  10640. }
  10641. else {
  10642. w += y3 < y0_ ? unit : -unit;
  10643. }
  10644. }
  10645. }
  10646. return w;
  10647. }
  10648. }
  10649. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10650. if ((y > y0 && y > y1 && y > y2)
  10651. || (y < y0 && y < y1 && y < y2)) {
  10652. return 0;
  10653. }
  10654. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10655. if (nRoots === 0) {
  10656. return 0;
  10657. }
  10658. else {
  10659. var t = quadraticExtremum(y0, y1, y2);
  10660. if (t >= 0 && t <= 1) {
  10661. var w = 0;
  10662. var y_ = quadraticAt(y0, y1, y2, t);
  10663. for (var i = 0; i < nRoots; i++) {
  10664. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10665. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10666. if (x_ < x) {
  10667. continue;
  10668. }
  10669. if (roots[i] < t) {
  10670. w += y_ < y0 ? unit : -unit;
  10671. }
  10672. else {
  10673. w += y2 < y_ ? unit : -unit;
  10674. }
  10675. }
  10676. return w;
  10677. }
  10678. else {
  10679. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10680. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10681. if (x_ < x) {
  10682. return 0;
  10683. }
  10684. return y2 < y0 ? unit : -unit;
  10685. }
  10686. }
  10687. }
  10688. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10689. y -= cy;
  10690. if (y > r || y < -r) {
  10691. return 0;
  10692. }
  10693. var tmp = Math.sqrt(r * r - y * y);
  10694. roots[0] = -tmp;
  10695. roots[1] = tmp;
  10696. var dTheta = Math.abs(startAngle - endAngle);
  10697. if (dTheta < 1e-4) {
  10698. return 0;
  10699. }
  10700. if (dTheta >= PI2$4 - 1e-4) {
  10701. startAngle = 0;
  10702. endAngle = PI2$4;
  10703. var dir = anticlockwise ? 1 : -1;
  10704. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10705. return dir;
  10706. }
  10707. else {
  10708. return 0;
  10709. }
  10710. }
  10711. if (startAngle > endAngle) {
  10712. var tmp_1 = startAngle;
  10713. startAngle = endAngle;
  10714. endAngle = tmp_1;
  10715. }
  10716. if (startAngle < 0) {
  10717. startAngle += PI2$4;
  10718. endAngle += PI2$4;
  10719. }
  10720. var w = 0;
  10721. for (var i = 0; i < 2; i++) {
  10722. var x_ = roots[i];
  10723. if (x_ + cx > x) {
  10724. var angle = Math.atan2(y, x_);
  10725. var dir = anticlockwise ? 1 : -1;
  10726. if (angle < 0) {
  10727. angle = PI2$4 + angle;
  10728. }
  10729. if ((angle >= startAngle && angle <= endAngle)
  10730. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10731. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10732. dir = -dir;
  10733. }
  10734. w += dir;
  10735. }
  10736. }
  10737. }
  10738. return w;
  10739. }
  10740. function containPath(path, lineWidth, isStroke, x, y) {
  10741. var data = path.data;
  10742. var len = path.len();
  10743. var w = 0;
  10744. var xi = 0;
  10745. var yi = 0;
  10746. var x0 = 0;
  10747. var y0 = 0;
  10748. var x1;
  10749. var y1;
  10750. for (var i = 0; i < len;) {
  10751. var cmd = data[i++];
  10752. var isFirst = i === 1;
  10753. if (cmd === CMD$1.M && i > 1) {
  10754. if (!isStroke) {
  10755. w += windingLine(xi, yi, x0, y0, x, y);
  10756. }
  10757. }
  10758. if (isFirst) {
  10759. xi = data[i];
  10760. yi = data[i + 1];
  10761. x0 = xi;
  10762. y0 = yi;
  10763. }
  10764. switch (cmd) {
  10765. case CMD$1.M:
  10766. x0 = data[i++];
  10767. y0 = data[i++];
  10768. xi = x0;
  10769. yi = y0;
  10770. break;
  10771. case CMD$1.L:
  10772. if (isStroke) {
  10773. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10774. return true;
  10775. }
  10776. }
  10777. else {
  10778. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10779. }
  10780. xi = data[i++];
  10781. yi = data[i++];
  10782. break;
  10783. case CMD$1.C:
  10784. if (isStroke) {
  10785. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10786. return true;
  10787. }
  10788. }
  10789. else {
  10790. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10791. }
  10792. xi = data[i++];
  10793. yi = data[i++];
  10794. break;
  10795. case CMD$1.Q:
  10796. if (isStroke) {
  10797. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10798. return true;
  10799. }
  10800. }
  10801. else {
  10802. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10803. }
  10804. xi = data[i++];
  10805. yi = data[i++];
  10806. break;
  10807. case CMD$1.A:
  10808. var cx = data[i++];
  10809. var cy = data[i++];
  10810. var rx = data[i++];
  10811. var ry = data[i++];
  10812. var theta = data[i++];
  10813. var dTheta = data[i++];
  10814. i += 1;
  10815. var anticlockwise = !!(1 - data[i++]);
  10816. x1 = Math.cos(theta) * rx + cx;
  10817. y1 = Math.sin(theta) * ry + cy;
  10818. if (!isFirst) {
  10819. w += windingLine(xi, yi, x1, y1, x, y);
  10820. }
  10821. else {
  10822. x0 = x1;
  10823. y0 = y1;
  10824. }
  10825. var _x = (x - cx) * ry / rx + cx;
  10826. if (isStroke) {
  10827. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10828. return true;
  10829. }
  10830. }
  10831. else {
  10832. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10833. }
  10834. xi = Math.cos(theta + dTheta) * rx + cx;
  10835. yi = Math.sin(theta + dTheta) * ry + cy;
  10836. break;
  10837. case CMD$1.R:
  10838. x0 = xi = data[i++];
  10839. y0 = yi = data[i++];
  10840. var width = data[i++];
  10841. var height = data[i++];
  10842. x1 = x0 + width;
  10843. y1 = y0 + height;
  10844. if (isStroke) {
  10845. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10846. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10847. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10848. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10849. return true;
  10850. }
  10851. }
  10852. else {
  10853. w += windingLine(x1, y0, x1, y1, x, y);
  10854. w += windingLine(x0, y1, x0, y0, x, y);
  10855. }
  10856. break;
  10857. case CMD$1.Z:
  10858. if (isStroke) {
  10859. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10860. return true;
  10861. }
  10862. }
  10863. else {
  10864. w += windingLine(xi, yi, x0, y0, x, y);
  10865. }
  10866. xi = x0;
  10867. yi = y0;
  10868. break;
  10869. }
  10870. }
  10871. if (!isStroke && !isAroundEqual(yi, y0)) {
  10872. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10873. }
  10874. return w !== 0;
  10875. }
  10876. function contain(pathProxy, x, y) {
  10877. return containPath(pathProxy, 0, false, x, y);
  10878. }
  10879. function containStroke$4(pathProxy, lineWidth, x, y) {
  10880. return containPath(pathProxy, lineWidth, true, x, y);
  10881. }
  10882. var DEFAULT_PATH_STYLE = defaults({
  10883. fill: '#000',
  10884. stroke: null,
  10885. strokePercent: 1,
  10886. fillOpacity: 1,
  10887. strokeOpacity: 1,
  10888. lineDashOffset: 0,
  10889. lineWidth: 1,
  10890. lineCap: 'butt',
  10891. miterLimit: 10,
  10892. strokeNoScale: false,
  10893. strokeFirst: false
  10894. }, DEFAULT_COMMON_STYLE);
  10895. var DEFAULT_PATH_ANIMATION_PROPS = {
  10896. style: defaults({
  10897. fill: true,
  10898. stroke: true,
  10899. strokePercent: true,
  10900. fillOpacity: true,
  10901. strokeOpacity: true,
  10902. lineDashOffset: true,
  10903. lineWidth: true,
  10904. miterLimit: true
  10905. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10906. };
  10907. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10908. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10909. ]);
  10910. var Path = (function (_super) {
  10911. __extends(Path, _super);
  10912. function Path(opts) {
  10913. return _super.call(this, opts) || this;
  10914. }
  10915. Path.prototype.update = function () {
  10916. var _this = this;
  10917. _super.prototype.update.call(this);
  10918. var style = this.style;
  10919. if (style.decal) {
  10920. var decalEl = this._decalEl = this._decalEl || new Path();
  10921. if (decalEl.buildPath === Path.prototype.buildPath) {
  10922. decalEl.buildPath = function (ctx) {
  10923. _this.buildPath(ctx, _this.shape);
  10924. };
  10925. }
  10926. decalEl.silent = true;
  10927. var decalElStyle = decalEl.style;
  10928. for (var key in style) {
  10929. if (decalElStyle[key] !== style[key]) {
  10930. decalElStyle[key] = style[key];
  10931. }
  10932. }
  10933. decalElStyle.fill = style.fill ? style.decal : null;
  10934. decalElStyle.decal = null;
  10935. decalElStyle.shadowColor = null;
  10936. style.strokeFirst && (decalElStyle.stroke = null);
  10937. for (var i = 0; i < pathCopyParams.length; ++i) {
  10938. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10939. }
  10940. decalEl.__dirty |= REDRAW_BIT;
  10941. }
  10942. else if (this._decalEl) {
  10943. this._decalEl = null;
  10944. }
  10945. };
  10946. Path.prototype.getDecalElement = function () {
  10947. return this._decalEl;
  10948. };
  10949. Path.prototype._init = function (props) {
  10950. var keysArr = keys(props);
  10951. this.shape = this.getDefaultShape();
  10952. var defaultStyle = this.getDefaultStyle();
  10953. if (defaultStyle) {
  10954. this.useStyle(defaultStyle);
  10955. }
  10956. for (var i = 0; i < keysArr.length; i++) {
  10957. var key = keysArr[i];
  10958. var value = props[key];
  10959. if (key === 'style') {
  10960. if (!this.style) {
  10961. this.useStyle(value);
  10962. }
  10963. else {
  10964. extend(this.style, value);
  10965. }
  10966. }
  10967. else if (key === 'shape') {
  10968. extend(this.shape, value);
  10969. }
  10970. else {
  10971. _super.prototype.attrKV.call(this, key, value);
  10972. }
  10973. }
  10974. if (!this.style) {
  10975. this.useStyle({});
  10976. }
  10977. };
  10978. Path.prototype.getDefaultStyle = function () {
  10979. return null;
  10980. };
  10981. Path.prototype.getDefaultShape = function () {
  10982. return {};
  10983. };
  10984. Path.prototype.canBeInsideText = function () {
  10985. return this.hasFill();
  10986. };
  10987. Path.prototype.getInsideTextFill = function () {
  10988. var pathFill = this.style.fill;
  10989. if (pathFill !== 'none') {
  10990. if (isString(pathFill)) {
  10991. var fillLum = lum(pathFill, 0);
  10992. if (fillLum > 0.5) {
  10993. return DARK_LABEL_COLOR;
  10994. }
  10995. else if (fillLum > 0.2) {
  10996. return LIGHTER_LABEL_COLOR;
  10997. }
  10998. return LIGHT_LABEL_COLOR;
  10999. }
  11000. else if (pathFill) {
  11001. return LIGHT_LABEL_COLOR;
  11002. }
  11003. }
  11004. return DARK_LABEL_COLOR;
  11005. };
  11006. Path.prototype.getInsideTextStroke = function (textFill) {
  11007. var pathFill = this.style.fill;
  11008. if (isString(pathFill)) {
  11009. var zr = this.__zr;
  11010. var isDarkMode = !!(zr && zr.isDarkMode());
  11011. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  11012. if (isDarkMode === isDarkLabel) {
  11013. return pathFill;
  11014. }
  11015. }
  11016. };
  11017. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  11018. Path.prototype.pathUpdated = function () {
  11019. this.__dirty &= ~SHAPE_CHANGED_BIT;
  11020. };
  11021. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  11022. !this.path && this.createPathProxy();
  11023. this.path.beginPath();
  11024. this.buildPath(this.path, this.shape, inBatch);
  11025. return this.path;
  11026. };
  11027. Path.prototype.createPathProxy = function () {
  11028. this.path = new PathProxy(false);
  11029. };
  11030. Path.prototype.hasStroke = function () {
  11031. var style = this.style;
  11032. var stroke = style.stroke;
  11033. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  11034. };
  11035. Path.prototype.hasFill = function () {
  11036. var style = this.style;
  11037. var fill = style.fill;
  11038. return fill != null && fill !== 'none';
  11039. };
  11040. Path.prototype.getBoundingRect = function () {
  11041. var rect = this._rect;
  11042. var style = this.style;
  11043. var needsUpdateRect = !rect;
  11044. if (needsUpdateRect) {
  11045. var firstInvoke = false;
  11046. if (!this.path) {
  11047. firstInvoke = true;
  11048. this.createPathProxy();
  11049. }
  11050. var path = this.path;
  11051. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  11052. path.beginPath();
  11053. this.buildPath(path, this.shape, false);
  11054. this.pathUpdated();
  11055. }
  11056. rect = path.getBoundingRect();
  11057. }
  11058. this._rect = rect;
  11059. if (this.hasStroke() && this.path && this.path.len() > 0) {
  11060. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  11061. if (this.__dirty || needsUpdateRect) {
  11062. rectStroke.copy(rect);
  11063. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11064. var w = style.lineWidth;
  11065. if (!this.hasFill()) {
  11066. var strokeContainThreshold = this.strokeContainThreshold;
  11067. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  11068. }
  11069. if (lineScale > 1e-10) {
  11070. rectStroke.width += w / lineScale;
  11071. rectStroke.height += w / lineScale;
  11072. rectStroke.x -= w / lineScale / 2;
  11073. rectStroke.y -= w / lineScale / 2;
  11074. }
  11075. }
  11076. return rectStroke;
  11077. }
  11078. return rect;
  11079. };
  11080. Path.prototype.contain = function (x, y) {
  11081. var localPos = this.transformCoordToLocal(x, y);
  11082. var rect = this.getBoundingRect();
  11083. var style = this.style;
  11084. x = localPos[0];
  11085. y = localPos[1];
  11086. if (rect.contain(x, y)) {
  11087. var pathProxy = this.path;
  11088. if (this.hasStroke()) {
  11089. var lineWidth = style.lineWidth;
  11090. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11091. if (lineScale > 1e-10) {
  11092. if (!this.hasFill()) {
  11093. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11094. }
  11095. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11096. return true;
  11097. }
  11098. }
  11099. }
  11100. if (this.hasFill()) {
  11101. return contain(pathProxy, x, y);
  11102. }
  11103. }
  11104. return false;
  11105. };
  11106. Path.prototype.dirtyShape = function () {
  11107. this.__dirty |= SHAPE_CHANGED_BIT;
  11108. if (this._rect) {
  11109. this._rect = null;
  11110. }
  11111. if (this._decalEl) {
  11112. this._decalEl.dirtyShape();
  11113. }
  11114. this.markRedraw();
  11115. };
  11116. Path.prototype.dirty = function () {
  11117. this.dirtyStyle();
  11118. this.dirtyShape();
  11119. };
  11120. Path.prototype.animateShape = function (loop) {
  11121. return this.animate('shape', loop);
  11122. };
  11123. Path.prototype.updateDuringAnimation = function (targetKey) {
  11124. if (targetKey === 'style') {
  11125. this.dirtyStyle();
  11126. }
  11127. else if (targetKey === 'shape') {
  11128. this.dirtyShape();
  11129. }
  11130. else {
  11131. this.markRedraw();
  11132. }
  11133. };
  11134. Path.prototype.attrKV = function (key, value) {
  11135. if (key === 'shape') {
  11136. this.setShape(value);
  11137. }
  11138. else {
  11139. _super.prototype.attrKV.call(this, key, value);
  11140. }
  11141. };
  11142. Path.prototype.setShape = function (keyOrObj, value) {
  11143. var shape = this.shape;
  11144. if (!shape) {
  11145. shape = this.shape = {};
  11146. }
  11147. if (typeof keyOrObj === 'string') {
  11148. shape[keyOrObj] = value;
  11149. }
  11150. else {
  11151. extend(shape, keyOrObj);
  11152. }
  11153. this.dirtyShape();
  11154. return this;
  11155. };
  11156. Path.prototype.shapeChanged = function () {
  11157. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11158. };
  11159. Path.prototype.createStyle = function (obj) {
  11160. return createObject(DEFAULT_PATH_STYLE, obj);
  11161. };
  11162. Path.prototype._innerSaveToNormal = function (toState) {
  11163. _super.prototype._innerSaveToNormal.call(this, toState);
  11164. var normalState = this._normalState;
  11165. if (toState.shape && !normalState.shape) {
  11166. normalState.shape = extend({}, this.shape);
  11167. }
  11168. };
  11169. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11170. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11171. var needsRestoreToNormal = !(state && keepCurrentStates);
  11172. var targetShape;
  11173. if (state && state.shape) {
  11174. if (transition) {
  11175. if (keepCurrentStates) {
  11176. targetShape = state.shape;
  11177. }
  11178. else {
  11179. targetShape = extend({}, normalState.shape);
  11180. extend(targetShape, state.shape);
  11181. }
  11182. }
  11183. else {
  11184. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11185. extend(targetShape, state.shape);
  11186. }
  11187. }
  11188. else if (needsRestoreToNormal) {
  11189. targetShape = normalState.shape;
  11190. }
  11191. if (targetShape) {
  11192. if (transition) {
  11193. this.shape = extend({}, this.shape);
  11194. var targetShapePrimaryProps = {};
  11195. var shapeKeys = keys(targetShape);
  11196. for (var i = 0; i < shapeKeys.length; i++) {
  11197. var key = shapeKeys[i];
  11198. if (typeof targetShape[key] === 'object') {
  11199. this.shape[key] = targetShape[key];
  11200. }
  11201. else {
  11202. targetShapePrimaryProps[key] = targetShape[key];
  11203. }
  11204. }
  11205. this._transitionState(stateName, {
  11206. shape: targetShapePrimaryProps
  11207. }, animationCfg);
  11208. }
  11209. else {
  11210. this.shape = targetShape;
  11211. this.dirtyShape();
  11212. }
  11213. }
  11214. };
  11215. Path.prototype._mergeStates = function (states) {
  11216. var mergedState = _super.prototype._mergeStates.call(this, states);
  11217. var mergedShape;
  11218. for (var i = 0; i < states.length; i++) {
  11219. var state = states[i];
  11220. if (state.shape) {
  11221. mergedShape = mergedShape || {};
  11222. this._mergeStyle(mergedShape, state.shape);
  11223. }
  11224. }
  11225. if (mergedShape) {
  11226. mergedState.shape = mergedShape;
  11227. }
  11228. return mergedState;
  11229. };
  11230. Path.prototype.getAnimationStyleProps = function () {
  11231. return DEFAULT_PATH_ANIMATION_PROPS;
  11232. };
  11233. Path.prototype.isZeroArea = function () {
  11234. return false;
  11235. };
  11236. Path.extend = function (defaultProps) {
  11237. var Sub = (function (_super) {
  11238. __extends(Sub, _super);
  11239. function Sub(opts) {
  11240. var _this = _super.call(this, opts) || this;
  11241. defaultProps.init && defaultProps.init.call(_this, opts);
  11242. return _this;
  11243. }
  11244. Sub.prototype.getDefaultStyle = function () {
  11245. return clone(defaultProps.style);
  11246. };
  11247. Sub.prototype.getDefaultShape = function () {
  11248. return clone(defaultProps.shape);
  11249. };
  11250. return Sub;
  11251. }(Path));
  11252. for (var key in defaultProps) {
  11253. if (typeof defaultProps[key] === 'function') {
  11254. Sub.prototype[key] = defaultProps[key];
  11255. }
  11256. }
  11257. return Sub;
  11258. };
  11259. Path.initDefaultProps = (function () {
  11260. var pathProto = Path.prototype;
  11261. pathProto.type = 'path';
  11262. pathProto.strokeContainThreshold = 5;
  11263. pathProto.segmentIgnoreThreshold = 0;
  11264. pathProto.subPixelOptimize = false;
  11265. pathProto.autoBatch = false;
  11266. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11267. })();
  11268. return Path;
  11269. }(Displayable));
  11270. var DEFAULT_TSPAN_STYLE = defaults({
  11271. strokeFirst: true,
  11272. font: DEFAULT_FONT,
  11273. x: 0,
  11274. y: 0,
  11275. textAlign: 'left',
  11276. textBaseline: 'top',
  11277. miterLimit: 2
  11278. }, DEFAULT_PATH_STYLE);
  11279. var TSpan = (function (_super) {
  11280. __extends(TSpan, _super);
  11281. function TSpan() {
  11282. return _super !== null && _super.apply(this, arguments) || this;
  11283. }
  11284. TSpan.prototype.hasStroke = function () {
  11285. var style = this.style;
  11286. var stroke = style.stroke;
  11287. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11288. };
  11289. TSpan.prototype.hasFill = function () {
  11290. var style = this.style;
  11291. var fill = style.fill;
  11292. return fill != null && fill !== 'none';
  11293. };
  11294. TSpan.prototype.createStyle = function (obj) {
  11295. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11296. };
  11297. TSpan.prototype.setBoundingRect = function (rect) {
  11298. this._rect = rect;
  11299. };
  11300. TSpan.prototype.getBoundingRect = function () {
  11301. var style = this.style;
  11302. if (!this._rect) {
  11303. var text = style.text;
  11304. text != null ? (text += '') : (text = '');
  11305. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11306. rect.x += style.x || 0;
  11307. rect.y += style.y || 0;
  11308. if (this.hasStroke()) {
  11309. var w = style.lineWidth;
  11310. rect.x -= w / 2;
  11311. rect.y -= w / 2;
  11312. rect.width += w;
  11313. rect.height += w;
  11314. }
  11315. this._rect = rect;
  11316. }
  11317. return this._rect;
  11318. };
  11319. TSpan.initDefaultProps = (function () {
  11320. var tspanProto = TSpan.prototype;
  11321. tspanProto.dirtyRectTolerance = 10;
  11322. })();
  11323. return TSpan;
  11324. }(Displayable));
  11325. TSpan.prototype.type = 'tspan';
  11326. var DEFAULT_IMAGE_STYLE = defaults({
  11327. x: 0,
  11328. y: 0
  11329. }, DEFAULT_COMMON_STYLE);
  11330. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11331. style: defaults({
  11332. x: true,
  11333. y: true,
  11334. width: true,
  11335. height: true,
  11336. sx: true,
  11337. sy: true,
  11338. sWidth: true,
  11339. sHeight: true
  11340. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11341. };
  11342. function isImageLike(source) {
  11343. return !!(source
  11344. && typeof source !== 'string'
  11345. && source.width && source.height);
  11346. }
  11347. var ZRImage = (function (_super) {
  11348. __extends(ZRImage, _super);
  11349. function ZRImage() {
  11350. return _super !== null && _super.apply(this, arguments) || this;
  11351. }
  11352. ZRImage.prototype.createStyle = function (obj) {
  11353. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11354. };
  11355. ZRImage.prototype._getSize = function (dim) {
  11356. var style = this.style;
  11357. var size = style[dim];
  11358. if (size != null) {
  11359. return size;
  11360. }
  11361. var imageSource = isImageLike(style.image)
  11362. ? style.image : this.__image;
  11363. if (!imageSource) {
  11364. return 0;
  11365. }
  11366. var otherDim = dim === 'width' ? 'height' : 'width';
  11367. var otherDimSize = style[otherDim];
  11368. if (otherDimSize == null) {
  11369. return imageSource[dim];
  11370. }
  11371. else {
  11372. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11373. }
  11374. };
  11375. ZRImage.prototype.getWidth = function () {
  11376. return this._getSize('width');
  11377. };
  11378. ZRImage.prototype.getHeight = function () {
  11379. return this._getSize('height');
  11380. };
  11381. ZRImage.prototype.getAnimationStyleProps = function () {
  11382. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11383. };
  11384. ZRImage.prototype.getBoundingRect = function () {
  11385. var style = this.style;
  11386. if (!this._rect) {
  11387. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11388. }
  11389. return this._rect;
  11390. };
  11391. return ZRImage;
  11392. }(Displayable));
  11393. ZRImage.prototype.type = 'image';
  11394. function buildPath(ctx, shape) {
  11395. var x = shape.x;
  11396. var y = shape.y;
  11397. var width = shape.width;
  11398. var height = shape.height;
  11399. var r = shape.r;
  11400. var r1;
  11401. var r2;
  11402. var r3;
  11403. var r4;
  11404. if (width < 0) {
  11405. x = x + width;
  11406. width = -width;
  11407. }
  11408. if (height < 0) {
  11409. y = y + height;
  11410. height = -height;
  11411. }
  11412. if (typeof r === 'number') {
  11413. r1 = r2 = r3 = r4 = r;
  11414. }
  11415. else if (r instanceof Array) {
  11416. if (r.length === 1) {
  11417. r1 = r2 = r3 = r4 = r[0];
  11418. }
  11419. else if (r.length === 2) {
  11420. r1 = r3 = r[0];
  11421. r2 = r4 = r[1];
  11422. }
  11423. else if (r.length === 3) {
  11424. r1 = r[0];
  11425. r2 = r4 = r[1];
  11426. r3 = r[2];
  11427. }
  11428. else {
  11429. r1 = r[0];
  11430. r2 = r[1];
  11431. r3 = r[2];
  11432. r4 = r[3];
  11433. }
  11434. }
  11435. else {
  11436. r1 = r2 = r3 = r4 = 0;
  11437. }
  11438. var total;
  11439. if (r1 + r2 > width) {
  11440. total = r1 + r2;
  11441. r1 *= width / total;
  11442. r2 *= width / total;
  11443. }
  11444. if (r3 + r4 > width) {
  11445. total = r3 + r4;
  11446. r3 *= width / total;
  11447. r4 *= width / total;
  11448. }
  11449. if (r2 + r3 > height) {
  11450. total = r2 + r3;
  11451. r2 *= height / total;
  11452. r3 *= height / total;
  11453. }
  11454. if (r1 + r4 > height) {
  11455. total = r1 + r4;
  11456. r1 *= height / total;
  11457. r4 *= height / total;
  11458. }
  11459. ctx.moveTo(x + r1, y);
  11460. ctx.lineTo(x + width - r2, y);
  11461. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11462. ctx.lineTo(x + width, y + height - r3);
  11463. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11464. ctx.lineTo(x + r4, y + height);
  11465. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11466. ctx.lineTo(x, y + r1);
  11467. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11468. }
  11469. var round$1 = Math.round;
  11470. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11471. if (!inputShape) {
  11472. return;
  11473. }
  11474. var x1 = inputShape.x1;
  11475. var x2 = inputShape.x2;
  11476. var y1 = inputShape.y1;
  11477. var y2 = inputShape.y2;
  11478. outputShape.x1 = x1;
  11479. outputShape.x2 = x2;
  11480. outputShape.y1 = y1;
  11481. outputShape.y2 = y2;
  11482. var lineWidth = style && style.lineWidth;
  11483. if (!lineWidth) {
  11484. return outputShape;
  11485. }
  11486. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11487. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11488. }
  11489. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11490. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11491. }
  11492. return outputShape;
  11493. }
  11494. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11495. if (!inputShape) {
  11496. return;
  11497. }
  11498. var originX = inputShape.x;
  11499. var originY = inputShape.y;
  11500. var originWidth = inputShape.width;
  11501. var originHeight = inputShape.height;
  11502. outputShape.x = originX;
  11503. outputShape.y = originY;
  11504. outputShape.width = originWidth;
  11505. outputShape.height = originHeight;
  11506. var lineWidth = style && style.lineWidth;
  11507. if (!lineWidth) {
  11508. return outputShape;
  11509. }
  11510. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11511. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11512. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11513. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11514. return outputShape;
  11515. }
  11516. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11517. if (!lineWidth) {
  11518. return position;
  11519. }
  11520. var doubledPosition = round$1(position * 2);
  11521. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11522. ? doubledPosition / 2
  11523. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11524. }
  11525. var RectShape = (function () {
  11526. function RectShape() {
  11527. this.x = 0;
  11528. this.y = 0;
  11529. this.width = 0;
  11530. this.height = 0;
  11531. }
  11532. return RectShape;
  11533. }());
  11534. var subPixelOptimizeOutputShape = {};
  11535. var Rect = (function (_super) {
  11536. __extends(Rect, _super);
  11537. function Rect(opts) {
  11538. return _super.call(this, opts) || this;
  11539. }
  11540. Rect.prototype.getDefaultShape = function () {
  11541. return new RectShape();
  11542. };
  11543. Rect.prototype.buildPath = function (ctx, shape) {
  11544. var x;
  11545. var y;
  11546. var width;
  11547. var height;
  11548. if (this.subPixelOptimize) {
  11549. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11550. x = optimizedShape.x;
  11551. y = optimizedShape.y;
  11552. width = optimizedShape.width;
  11553. height = optimizedShape.height;
  11554. optimizedShape.r = shape.r;
  11555. shape = optimizedShape;
  11556. }
  11557. else {
  11558. x = shape.x;
  11559. y = shape.y;
  11560. width = shape.width;
  11561. height = shape.height;
  11562. }
  11563. if (!shape.r) {
  11564. ctx.rect(x, y, width, height);
  11565. }
  11566. else {
  11567. buildPath(ctx, shape);
  11568. }
  11569. };
  11570. Rect.prototype.isZeroArea = function () {
  11571. return !this.shape.width || !this.shape.height;
  11572. };
  11573. return Rect;
  11574. }(Path));
  11575. Rect.prototype.type = 'rect';
  11576. var DEFAULT_RICH_TEXT_COLOR = {
  11577. fill: '#000'
  11578. };
  11579. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11580. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11581. style: defaults({
  11582. fill: true,
  11583. stroke: true,
  11584. fillOpacity: true,
  11585. strokeOpacity: true,
  11586. lineWidth: true,
  11587. fontSize: true,
  11588. lineHeight: true,
  11589. width: true,
  11590. height: true,
  11591. textShadowColor: true,
  11592. textShadowBlur: true,
  11593. textShadowOffsetX: true,
  11594. textShadowOffsetY: true,
  11595. backgroundColor: true,
  11596. padding: true,
  11597. borderColor: true,
  11598. borderWidth: true,
  11599. borderRadius: true
  11600. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11601. };
  11602. var ZRText = (function (_super) {
  11603. __extends(ZRText, _super);
  11604. function ZRText(opts) {
  11605. var _this = _super.call(this) || this;
  11606. _this.type = 'text';
  11607. _this._children = [];
  11608. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11609. _this.attr(opts);
  11610. return _this;
  11611. }
  11612. ZRText.prototype.childrenRef = function () {
  11613. return this._children;
  11614. };
  11615. ZRText.prototype.update = function () {
  11616. _super.prototype.update.call(this);
  11617. if (this.styleChanged()) {
  11618. this._updateSubTexts();
  11619. }
  11620. for (var i = 0; i < this._children.length; i++) {
  11621. var child = this._children[i];
  11622. child.zlevel = this.zlevel;
  11623. child.z = this.z;
  11624. child.z2 = this.z2;
  11625. child.culling = this.culling;
  11626. child.cursor = this.cursor;
  11627. child.invisible = this.invisible;
  11628. }
  11629. };
  11630. ZRText.prototype.updateTransform = function () {
  11631. var innerTransformable = this.innerTransformable;
  11632. if (innerTransformable) {
  11633. innerTransformable.updateTransform();
  11634. if (innerTransformable.transform) {
  11635. this.transform = innerTransformable.transform;
  11636. }
  11637. }
  11638. else {
  11639. _super.prototype.updateTransform.call(this);
  11640. }
  11641. };
  11642. ZRText.prototype.getLocalTransform = function (m) {
  11643. var innerTransformable = this.innerTransformable;
  11644. return innerTransformable
  11645. ? innerTransformable.getLocalTransform(m)
  11646. : _super.prototype.getLocalTransform.call(this, m);
  11647. };
  11648. ZRText.prototype.getComputedTransform = function () {
  11649. if (this.__hostTarget) {
  11650. this.__hostTarget.getComputedTransform();
  11651. this.__hostTarget.updateInnerText(true);
  11652. }
  11653. return _super.prototype.getComputedTransform.call(this);
  11654. };
  11655. ZRText.prototype._updateSubTexts = function () {
  11656. this._childCursor = 0;
  11657. normalizeTextStyle(this.style);
  11658. this.style.rich
  11659. ? this._updateRichTexts()
  11660. : this._updatePlainTexts();
  11661. this._children.length = this._childCursor;
  11662. this.styleUpdated();
  11663. };
  11664. ZRText.prototype.addSelfToZr = function (zr) {
  11665. _super.prototype.addSelfToZr.call(this, zr);
  11666. for (var i = 0; i < this._children.length; i++) {
  11667. this._children[i].__zr = zr;
  11668. }
  11669. };
  11670. ZRText.prototype.removeSelfFromZr = function (zr) {
  11671. _super.prototype.removeSelfFromZr.call(this, zr);
  11672. for (var i = 0; i < this._children.length; i++) {
  11673. this._children[i].__zr = null;
  11674. }
  11675. };
  11676. ZRText.prototype.getBoundingRect = function () {
  11677. if (this.styleChanged()) {
  11678. this._updateSubTexts();
  11679. }
  11680. if (!this._rect) {
  11681. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11682. var children = this._children;
  11683. var tmpMat = [];
  11684. var rect = null;
  11685. for (var i = 0; i < children.length; i++) {
  11686. var child = children[i];
  11687. var childRect = child.getBoundingRect();
  11688. var transform = child.getLocalTransform(tmpMat);
  11689. if (transform) {
  11690. tmpRect.copy(childRect);
  11691. tmpRect.applyTransform(transform);
  11692. rect = rect || tmpRect.clone();
  11693. rect.union(tmpRect);
  11694. }
  11695. else {
  11696. rect = rect || childRect.clone();
  11697. rect.union(childRect);
  11698. }
  11699. }
  11700. this._rect = rect || tmpRect;
  11701. }
  11702. return this._rect;
  11703. };
  11704. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11705. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11706. };
  11707. ZRText.prototype.setTextContent = function (textContent) {
  11708. if ("development" !== 'production') {
  11709. throw new Error('Can\'t attach text on another text');
  11710. }
  11711. };
  11712. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11713. if (!sourceStyle) {
  11714. return targetStyle;
  11715. }
  11716. var sourceRich = sourceStyle.rich;
  11717. var targetRich = targetStyle.rich || (sourceRich && {});
  11718. extend(targetStyle, sourceStyle);
  11719. if (sourceRich && targetRich) {
  11720. this._mergeRich(targetRich, sourceRich);
  11721. targetStyle.rich = targetRich;
  11722. }
  11723. else if (targetRich) {
  11724. targetStyle.rich = targetRich;
  11725. }
  11726. return targetStyle;
  11727. };
  11728. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11729. var richNames = keys(sourceRich);
  11730. for (var i = 0; i < richNames.length; i++) {
  11731. var richName = richNames[i];
  11732. targetRich[richName] = targetRich[richName] || {};
  11733. extend(targetRich[richName], sourceRich[richName]);
  11734. }
  11735. };
  11736. ZRText.prototype.getAnimationStyleProps = function () {
  11737. return DEFAULT_TEXT_ANIMATION_PROPS;
  11738. };
  11739. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11740. var child = this._children[this._childCursor];
  11741. if (!child || !(child instanceof Ctor)) {
  11742. child = new Ctor();
  11743. }
  11744. this._children[this._childCursor++] = child;
  11745. child.__zr = this.__zr;
  11746. child.parent = this;
  11747. return child;
  11748. };
  11749. ZRText.prototype._updatePlainTexts = function () {
  11750. var style = this.style;
  11751. var textFont = style.font || DEFAULT_FONT;
  11752. var textPadding = style.padding;
  11753. var text = getStyleText(style);
  11754. var contentBlock = parsePlainText(text, style);
  11755. var needDrawBg = needDrawBackground(style);
  11756. var bgColorDrawn = !!(style.backgroundColor);
  11757. var outerHeight = contentBlock.outerHeight;
  11758. var outerWidth = contentBlock.outerWidth;
  11759. var contentWidth = contentBlock.contentWidth;
  11760. var textLines = contentBlock.lines;
  11761. var lineHeight = contentBlock.lineHeight;
  11762. var defaultStyle = this._defaultStyle;
  11763. this.isTruncated = !!contentBlock.isTruncated;
  11764. var baseX = style.x || 0;
  11765. var baseY = style.y || 0;
  11766. var textAlign = style.align || defaultStyle.align || 'left';
  11767. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11768. var textX = baseX;
  11769. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11770. if (needDrawBg || textPadding) {
  11771. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11772. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11773. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11774. }
  11775. textY += lineHeight / 2;
  11776. if (textPadding) {
  11777. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11778. if (verticalAlign === 'top') {
  11779. textY += textPadding[0];
  11780. }
  11781. else if (verticalAlign === 'bottom') {
  11782. textY -= textPadding[2];
  11783. }
  11784. }
  11785. var defaultLineWidth = 0;
  11786. var useDefaultFill = false;
  11787. var textFill = getFill('fill' in style
  11788. ? style.fill
  11789. : (useDefaultFill = true, defaultStyle.fill));
  11790. var textStroke = getStroke('stroke' in style
  11791. ? style.stroke
  11792. : (!bgColorDrawn
  11793. && (!defaultStyle.autoStroke || useDefaultFill))
  11794. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11795. : null);
  11796. var hasShadow = style.textShadowBlur > 0;
  11797. var fixedBoundingRect = style.width != null
  11798. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11799. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11800. for (var i = 0; i < textLines.length; i++) {
  11801. var el = this._getOrCreateChild(TSpan);
  11802. var subElStyle = el.createStyle();
  11803. el.useStyle(subElStyle);
  11804. subElStyle.text = textLines[i];
  11805. subElStyle.x = textX;
  11806. subElStyle.y = textY;
  11807. if (textAlign) {
  11808. subElStyle.textAlign = textAlign;
  11809. }
  11810. subElStyle.textBaseline = 'middle';
  11811. subElStyle.opacity = style.opacity;
  11812. subElStyle.strokeFirst = true;
  11813. if (hasShadow) {
  11814. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11815. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11816. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11817. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11818. }
  11819. subElStyle.stroke = textStroke;
  11820. subElStyle.fill = textFill;
  11821. if (textStroke) {
  11822. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11823. subElStyle.lineDash = style.lineDash;
  11824. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11825. }
  11826. subElStyle.font = textFont;
  11827. setSeparateFont(subElStyle, style);
  11828. textY += lineHeight;
  11829. if (fixedBoundingRect) {
  11830. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, contentWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11831. }
  11832. }
  11833. };
  11834. ZRText.prototype._updateRichTexts = function () {
  11835. var style = this.style;
  11836. var text = getStyleText(style);
  11837. var contentBlock = parseRichText(text, style);
  11838. var contentWidth = contentBlock.width;
  11839. var outerWidth = contentBlock.outerWidth;
  11840. var outerHeight = contentBlock.outerHeight;
  11841. var textPadding = style.padding;
  11842. var baseX = style.x || 0;
  11843. var baseY = style.y || 0;
  11844. var defaultStyle = this._defaultStyle;
  11845. var textAlign = style.align || defaultStyle.align;
  11846. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11847. this.isTruncated = !!contentBlock.isTruncated;
  11848. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11849. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11850. var xLeft = boxX;
  11851. var lineTop = boxY;
  11852. if (textPadding) {
  11853. xLeft += textPadding[3];
  11854. lineTop += textPadding[0];
  11855. }
  11856. var xRight = xLeft + contentWidth;
  11857. if (needDrawBackground(style)) {
  11858. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11859. }
  11860. var bgColorDrawn = !!(style.backgroundColor);
  11861. for (var i = 0; i < contentBlock.lines.length; i++) {
  11862. var line = contentBlock.lines[i];
  11863. var tokens = line.tokens;
  11864. var tokenCount = tokens.length;
  11865. var lineHeight = line.lineHeight;
  11866. var remainedWidth = line.width;
  11867. var leftIndex = 0;
  11868. var lineXLeft = xLeft;
  11869. var lineXRight = xRight;
  11870. var rightIndex = tokenCount - 1;
  11871. var token = void 0;
  11872. while (leftIndex < tokenCount
  11873. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11874. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11875. remainedWidth -= token.width;
  11876. lineXLeft += token.width;
  11877. leftIndex++;
  11878. }
  11879. while (rightIndex >= 0
  11880. && (token = tokens[rightIndex], token.align === 'right')) {
  11881. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11882. remainedWidth -= token.width;
  11883. lineXRight -= token.width;
  11884. rightIndex--;
  11885. }
  11886. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11887. while (leftIndex <= rightIndex) {
  11888. token = tokens[leftIndex];
  11889. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11890. lineXLeft += token.width;
  11891. leftIndex++;
  11892. }
  11893. lineTop += lineHeight;
  11894. }
  11895. };
  11896. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11897. var tokenStyle = style.rich[token.styleName] || {};
  11898. tokenStyle.text = token.text;
  11899. var verticalAlign = token.verticalAlign;
  11900. var y = lineTop + lineHeight / 2;
  11901. if (verticalAlign === 'top') {
  11902. y = lineTop + token.height / 2;
  11903. }
  11904. else if (verticalAlign === 'bottom') {
  11905. y = lineTop + lineHeight - token.height / 2;
  11906. }
  11907. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11908. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11909. ? x - token.width
  11910. : textAlign === 'center'
  11911. ? x - token.width / 2
  11912. : x, y - token.height / 2, token.width, token.height);
  11913. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11914. var textPadding = token.textPadding;
  11915. if (textPadding) {
  11916. x = getTextXForPadding(x, textAlign, textPadding);
  11917. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11918. }
  11919. var el = this._getOrCreateChild(TSpan);
  11920. var subElStyle = el.createStyle();
  11921. el.useStyle(subElStyle);
  11922. var defaultStyle = this._defaultStyle;
  11923. var useDefaultFill = false;
  11924. var defaultLineWidth = 0;
  11925. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11926. : 'fill' in style ? style.fill
  11927. : (useDefaultFill = true, defaultStyle.fill));
  11928. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11929. : 'stroke' in style ? style.stroke
  11930. : (!bgColorDrawn
  11931. && !parentBgColorDrawn
  11932. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11933. : null);
  11934. var hasShadow = tokenStyle.textShadowBlur > 0
  11935. || style.textShadowBlur > 0;
  11936. subElStyle.text = token.text;
  11937. subElStyle.x = x;
  11938. subElStyle.y = y;
  11939. if (hasShadow) {
  11940. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11941. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11942. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11943. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11944. }
  11945. subElStyle.textAlign = textAlign;
  11946. subElStyle.textBaseline = 'middle';
  11947. subElStyle.font = token.font || DEFAULT_FONT;
  11948. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11949. setSeparateFont(subElStyle, tokenStyle);
  11950. if (textStroke) {
  11951. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11952. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11953. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11954. subElStyle.stroke = textStroke;
  11955. }
  11956. if (textFill) {
  11957. subElStyle.fill = textFill;
  11958. }
  11959. var textWidth = token.contentWidth;
  11960. var textHeight = token.contentHeight;
  11961. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11962. };
  11963. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11964. var textBackgroundColor = style.backgroundColor;
  11965. var textBorderWidth = style.borderWidth;
  11966. var textBorderColor = style.borderColor;
  11967. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11968. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11969. var textBorderRadius = style.borderRadius;
  11970. var self = this;
  11971. var rectEl;
  11972. var imgEl;
  11973. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11974. rectEl = this._getOrCreateChild(Rect);
  11975. rectEl.useStyle(rectEl.createStyle());
  11976. rectEl.style.fill = null;
  11977. var rectShape = rectEl.shape;
  11978. rectShape.x = x;
  11979. rectShape.y = y;
  11980. rectShape.width = width;
  11981. rectShape.height = height;
  11982. rectShape.r = textBorderRadius;
  11983. rectEl.dirtyShape();
  11984. }
  11985. if (isPlainOrGradientBg) {
  11986. var rectStyle = rectEl.style;
  11987. rectStyle.fill = textBackgroundColor || null;
  11988. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11989. }
  11990. else if (isImageBg) {
  11991. imgEl = this._getOrCreateChild(ZRImage);
  11992. imgEl.onload = function () {
  11993. self.dirtyStyle();
  11994. };
  11995. var imgStyle = imgEl.style;
  11996. imgStyle.image = textBackgroundColor.image;
  11997. imgStyle.x = x;
  11998. imgStyle.y = y;
  11999. imgStyle.width = width;
  12000. imgStyle.height = height;
  12001. }
  12002. if (textBorderWidth && textBorderColor) {
  12003. var rectStyle = rectEl.style;
  12004. rectStyle.lineWidth = textBorderWidth;
  12005. rectStyle.stroke = textBorderColor;
  12006. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  12007. rectStyle.lineDash = style.borderDash;
  12008. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  12009. rectEl.strokeContainThreshold = 0;
  12010. if (rectEl.hasFill() && rectEl.hasStroke()) {
  12011. rectStyle.strokeFirst = true;
  12012. rectStyle.lineWidth *= 2;
  12013. }
  12014. }
  12015. var commonStyle = (rectEl || imgEl).style;
  12016. commonStyle.shadowBlur = style.shadowBlur || 0;
  12017. commonStyle.shadowColor = style.shadowColor || 'transparent';
  12018. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  12019. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  12020. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  12021. };
  12022. ZRText.makeFont = function (style) {
  12023. var font = '';
  12024. if (hasSeparateFont(style)) {
  12025. font = [
  12026. style.fontStyle,
  12027. style.fontWeight,
  12028. parseFontSize(style.fontSize),
  12029. style.fontFamily || 'sans-serif'
  12030. ].join(' ');
  12031. }
  12032. return font && trim(font) || style.textFont || style.font;
  12033. };
  12034. return ZRText;
  12035. }(Displayable));
  12036. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  12037. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  12038. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  12039. function parseFontSize(fontSize) {
  12040. if (typeof fontSize === 'string'
  12041. && (fontSize.indexOf('px') !== -1
  12042. || fontSize.indexOf('rem') !== -1
  12043. || fontSize.indexOf('em') !== -1)) {
  12044. return fontSize;
  12045. }
  12046. else if (!isNaN(+fontSize)) {
  12047. return fontSize + 'px';
  12048. }
  12049. else {
  12050. return DEFAULT_FONT_SIZE + 'px';
  12051. }
  12052. }
  12053. function setSeparateFont(targetStyle, sourceStyle) {
  12054. for (var i = 0; i < FONT_PARTS.length; i++) {
  12055. var fontProp = FONT_PARTS[i];
  12056. var val = sourceStyle[fontProp];
  12057. if (val != null) {
  12058. targetStyle[fontProp] = val;
  12059. }
  12060. }
  12061. }
  12062. function hasSeparateFont(style) {
  12063. return style.fontSize != null || style.fontFamily || style.fontWeight;
  12064. }
  12065. function normalizeTextStyle(style) {
  12066. normalizeStyle(style);
  12067. each(style.rich, normalizeStyle);
  12068. return style;
  12069. }
  12070. function normalizeStyle(style) {
  12071. if (style) {
  12072. style.font = ZRText.makeFont(style);
  12073. var textAlign = style.align;
  12074. textAlign === 'middle' && (textAlign = 'center');
  12075. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  12076. var verticalAlign = style.verticalAlign;
  12077. verticalAlign === 'center' && (verticalAlign = 'middle');
  12078. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  12079. var textPadding = style.padding;
  12080. if (textPadding) {
  12081. style.padding = normalizeCssArray(style.padding);
  12082. }
  12083. }
  12084. }
  12085. function getStroke(stroke, lineWidth) {
  12086. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  12087. ? null
  12088. : (stroke.image || stroke.colorStops)
  12089. ? '#000'
  12090. : stroke;
  12091. }
  12092. function getFill(fill) {
  12093. return (fill == null || fill === 'none')
  12094. ? null
  12095. : (fill.image || fill.colorStops)
  12096. ? '#000'
  12097. : fill;
  12098. }
  12099. function getTextXForPadding(x, textAlign, textPadding) {
  12100. return textAlign === 'right'
  12101. ? (x - textPadding[1])
  12102. : textAlign === 'center'
  12103. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12104. : (x + textPadding[3]);
  12105. }
  12106. function getStyleText(style) {
  12107. var text = style.text;
  12108. text != null && (text += '');
  12109. return text;
  12110. }
  12111. function needDrawBackground(style) {
  12112. return !!(style.backgroundColor
  12113. || style.lineHeight
  12114. || (style.borderWidth && style.borderColor));
  12115. }
  12116. var getECData = makeInner();
  12117. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12118. if (el) {
  12119. var ecData = getECData(el);
  12120. // Add data index and series index for indexing the data by element
  12121. // Useful in tooltip
  12122. ecData.dataIndex = dataIdx;
  12123. ecData.dataType = dataType;
  12124. ecData.seriesIndex = seriesIndex;
  12125. ecData.ssrType = 'chart';
  12126. // TODO: not store dataIndex on children.
  12127. if (el.type === 'group') {
  12128. el.traverse(function (child) {
  12129. var childECData = getECData(child);
  12130. childECData.seriesIndex = seriesIndex;
  12131. childECData.dataIndex = dataIdx;
  12132. childECData.dataType = dataType;
  12133. childECData.ssrType = 'chart';
  12134. });
  12135. }
  12136. }
  12137. };
  12138. // Reserve 0 as default.
  12139. var _highlightNextDigit = 1;
  12140. var _highlightKeyMap = {};
  12141. var getSavedStates = makeInner();
  12142. var getComponentStates = makeInner();
  12143. var HOVER_STATE_NORMAL = 0;
  12144. var HOVER_STATE_BLUR = 1;
  12145. var HOVER_STATE_EMPHASIS = 2;
  12146. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12147. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12148. var Z2_EMPHASIS_LIFT = 10;
  12149. var Z2_SELECT_LIFT = 9;
  12150. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12151. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12152. var SELECT_ACTION_TYPE = 'select';
  12153. var UNSELECT_ACTION_TYPE = 'unselect';
  12154. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12155. function hasFillOrStroke(fillOrStroke) {
  12156. return fillOrStroke != null && fillOrStroke !== 'none';
  12157. }
  12158. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12159. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12160. el.onHoverStateChange(stateName);
  12161. }
  12162. el.hoverState = hoverStateEnum;
  12163. }
  12164. function singleEnterEmphasis(el) {
  12165. // Only mark the flag.
  12166. // States will be applied in the echarts.ts in next frame.
  12167. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12168. }
  12169. function singleLeaveEmphasis(el) {
  12170. // Only mark the flag.
  12171. // States will be applied in the echarts.ts in next frame.
  12172. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12173. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12174. }
  12175. }
  12176. function singleEnterBlur(el) {
  12177. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12178. }
  12179. function singleLeaveBlur(el) {
  12180. if (el.hoverState === HOVER_STATE_BLUR) {
  12181. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12182. }
  12183. }
  12184. function singleEnterSelect(el) {
  12185. el.selected = true;
  12186. }
  12187. function singleLeaveSelect(el) {
  12188. el.selected = false;
  12189. }
  12190. function updateElementState(el, updater, commonParam) {
  12191. updater(el, commonParam);
  12192. }
  12193. function traverseUpdateState(el, updater, commonParam) {
  12194. updateElementState(el, updater, commonParam);
  12195. el.isGroup && el.traverse(function (child) {
  12196. updateElementState(child, updater, commonParam);
  12197. });
  12198. }
  12199. function setStatesFlag(el, stateName) {
  12200. switch (stateName) {
  12201. case 'emphasis':
  12202. el.hoverState = HOVER_STATE_EMPHASIS;
  12203. break;
  12204. case 'normal':
  12205. el.hoverState = HOVER_STATE_NORMAL;
  12206. break;
  12207. case 'blur':
  12208. el.hoverState = HOVER_STATE_BLUR;
  12209. break;
  12210. case 'select':
  12211. el.selected = true;
  12212. }
  12213. }
  12214. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12215. var style = el.style;
  12216. var fromState = {};
  12217. for (var i = 0; i < props.length; i++) {
  12218. var propName = props[i];
  12219. var val = style[propName];
  12220. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12221. }
  12222. for (var i = 0; i < el.animators.length; i++) {
  12223. var animator = el.animators[i];
  12224. if (animator.__fromStateTransition
  12225. // Don't consider the animation to emphasis state.
  12226. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12227. animator.saveTo(fromState, props);
  12228. }
  12229. }
  12230. return fromState;
  12231. }
  12232. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12233. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12234. var cloned = false;
  12235. if (el instanceof Path) {
  12236. var store = getSavedStates(el);
  12237. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12238. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12239. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12240. state = state || {};
  12241. var emphasisStyle = state.style || {};
  12242. // inherit case
  12243. if (emphasisStyle.fill === 'inherit') {
  12244. cloned = true;
  12245. state = extend({}, state);
  12246. emphasisStyle = extend({}, emphasisStyle);
  12247. emphasisStyle.fill = fromFill;
  12248. }
  12249. // Apply default color lift
  12250. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12251. cloned = true;
  12252. // Not modify the original value.
  12253. state = extend({}, state);
  12254. emphasisStyle = extend({}, emphasisStyle);
  12255. // Already being applied 'emphasis'. DON'T lift color multiple times.
  12256. emphasisStyle.fill = liftColor(fromFill);
  12257. }
  12258. // Not highlight stroke if fill has been highlighted.
  12259. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12260. if (!cloned) {
  12261. state = extend({}, state);
  12262. emphasisStyle = extend({}, emphasisStyle);
  12263. }
  12264. emphasisStyle.stroke = liftColor(fromStroke);
  12265. }
  12266. state.style = emphasisStyle;
  12267. }
  12268. }
  12269. if (state) {
  12270. // TODO Share with textContent?
  12271. if (state.z2 == null) {
  12272. if (!cloned) {
  12273. state = extend({}, state);
  12274. }
  12275. var z2EmphasisLift = el.z2EmphasisLift;
  12276. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12277. }
  12278. }
  12279. return state;
  12280. }
  12281. function createSelectDefaultState(el, stateName, state) {
  12282. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12283. if (state) {
  12284. // TODO Share with textContent?
  12285. if (state.z2 == null) {
  12286. state = extend({}, state);
  12287. var z2SelectLift = el.z2SelectLift;
  12288. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12289. }
  12290. }
  12291. return state;
  12292. }
  12293. function createBlurDefaultState(el, stateName, state) {
  12294. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12295. var currentOpacity = el.style.opacity;
  12296. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12297. opacity: 1
  12298. }) : null;
  12299. state = state || {};
  12300. var blurStyle = state.style || {};
  12301. if (blurStyle.opacity == null) {
  12302. // clone state
  12303. state = extend({}, state);
  12304. blurStyle = extend({
  12305. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12306. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12307. }, blurStyle);
  12308. state.style = blurStyle;
  12309. }
  12310. return state;
  12311. }
  12312. function elementStateProxy(stateName, targetStates) {
  12313. var state = this.states[stateName];
  12314. if (this.style) {
  12315. if (stateName === 'emphasis') {
  12316. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12317. } else if (stateName === 'blur') {
  12318. return createBlurDefaultState(this, stateName, state);
  12319. } else if (stateName === 'select') {
  12320. return createSelectDefaultState(this, stateName, state);
  12321. }
  12322. }
  12323. return state;
  12324. }
  12325. /**
  12326. * Set hover style (namely "emphasis style") of element.
  12327. * @param el Should not be `zrender/graphic/Group`.
  12328. * @param focus 'self' | 'selfInSeries' | 'series'
  12329. */
  12330. function setDefaultStateProxy(el) {
  12331. el.stateProxy = elementStateProxy;
  12332. var textContent = el.getTextContent();
  12333. var textGuide = el.getTextGuideLine();
  12334. if (textContent) {
  12335. textContent.stateProxy = elementStateProxy;
  12336. }
  12337. if (textGuide) {
  12338. textGuide.stateProxy = elementStateProxy;
  12339. }
  12340. }
  12341. function enterEmphasisWhenMouseOver(el, e) {
  12342. !shouldSilent(el, e)
  12343. // "emphasis" event highlight has higher priority than mouse highlight.
  12344. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12345. }
  12346. function leaveEmphasisWhenMouseOut(el, e) {
  12347. !shouldSilent(el, e)
  12348. // "emphasis" event highlight has higher priority than mouse highlight.
  12349. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12350. }
  12351. function enterEmphasis(el, highlightDigit) {
  12352. el.__highByOuter |= 1 << (highlightDigit || 0);
  12353. traverseUpdateState(el, singleEnterEmphasis);
  12354. }
  12355. function leaveEmphasis(el, highlightDigit) {
  12356. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12357. }
  12358. function enterBlur(el) {
  12359. traverseUpdateState(el, singleEnterBlur);
  12360. }
  12361. function leaveBlur(el) {
  12362. traverseUpdateState(el, singleLeaveBlur);
  12363. }
  12364. function enterSelect(el) {
  12365. traverseUpdateState(el, singleEnterSelect);
  12366. }
  12367. function leaveSelect(el) {
  12368. traverseUpdateState(el, singleLeaveSelect);
  12369. }
  12370. function shouldSilent(el, e) {
  12371. return el.__highDownSilentOnTouch && e.zrByTouch;
  12372. }
  12373. function allLeaveBlur(api) {
  12374. var model = api.getModel();
  12375. var leaveBlurredSeries = [];
  12376. var allComponentViews = [];
  12377. model.eachComponent(function (componentType, componentModel) {
  12378. var componentStates = getComponentStates(componentModel);
  12379. var isSeries = componentType === 'series';
  12380. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12381. !isSeries && allComponentViews.push(view);
  12382. if (componentStates.isBlured) {
  12383. // Leave blur anyway
  12384. view.group.traverse(function (child) {
  12385. singleLeaveBlur(child);
  12386. });
  12387. isSeries && leaveBlurredSeries.push(componentModel);
  12388. }
  12389. componentStates.isBlured = false;
  12390. });
  12391. each(allComponentViews, function (view) {
  12392. if (view && view.toggleBlurSeries) {
  12393. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12394. }
  12395. });
  12396. }
  12397. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12398. var ecModel = api.getModel();
  12399. blurScope = blurScope || 'coordinateSystem';
  12400. function leaveBlurOfIndices(data, dataIndices) {
  12401. for (var i = 0; i < dataIndices.length; i++) {
  12402. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12403. itemEl && leaveBlur(itemEl);
  12404. }
  12405. }
  12406. if (targetSeriesIndex == null) {
  12407. return;
  12408. }
  12409. if (!focus || focus === 'none') {
  12410. return;
  12411. }
  12412. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12413. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12414. if (targetCoordSys && targetCoordSys.master) {
  12415. targetCoordSys = targetCoordSys.master;
  12416. }
  12417. var blurredSeries = [];
  12418. ecModel.eachSeries(function (seriesModel) {
  12419. var sameSeries = targetSeriesModel === seriesModel;
  12420. var coordSys = seriesModel.coordinateSystem;
  12421. if (coordSys && coordSys.master) {
  12422. coordSys = coordSys.master;
  12423. }
  12424. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12425. if (!(
  12426. // Not blur other series if blurScope series
  12427. blurScope === 'series' && !sameSeries
  12428. // Not blur other coordinate system if blurScope is coordinateSystem
  12429. || blurScope === 'coordinateSystem' && !sameCoordSys
  12430. // Not blur self series if focus is series.
  12431. || focus === 'series' && sameSeries
  12432. // TODO blurScope: coordinate system
  12433. )) {
  12434. var view = api.getViewOfSeriesModel(seriesModel);
  12435. view.group.traverse(function (child) {
  12436. // For the elements that have been triggered by other components,
  12437. // and are still required to be highlighted,
  12438. // because the current is directly forced to blur the element,
  12439. // it will cause the focus self to be unable to highlight, so skip the blur of this element.
  12440. if (child.__highByOuter && sameSeries && focus === 'self') {
  12441. return;
  12442. }
  12443. singleEnterBlur(child);
  12444. });
  12445. if (isArrayLike(focus)) {
  12446. leaveBlurOfIndices(seriesModel.getData(), focus);
  12447. } else if (isObject(focus)) {
  12448. var dataTypes = keys(focus);
  12449. for (var d = 0; d < dataTypes.length; d++) {
  12450. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12451. }
  12452. }
  12453. blurredSeries.push(seriesModel);
  12454. getComponentStates(seriesModel).isBlured = true;
  12455. }
  12456. });
  12457. ecModel.eachComponent(function (componentType, componentModel) {
  12458. if (componentType === 'series') {
  12459. return;
  12460. }
  12461. var view = api.getViewOfComponentModel(componentModel);
  12462. if (view && view.toggleBlurSeries) {
  12463. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12464. }
  12465. });
  12466. }
  12467. function blurComponent(componentMainType, componentIndex, api) {
  12468. if (componentMainType == null || componentIndex == null) {
  12469. return;
  12470. }
  12471. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12472. if (!componentModel) {
  12473. return;
  12474. }
  12475. getComponentStates(componentModel).isBlured = true;
  12476. var view = api.getViewOfComponentModel(componentModel);
  12477. if (!view || !view.focusBlurEnabled) {
  12478. return;
  12479. }
  12480. view.group.traverse(function (child) {
  12481. singleEnterBlur(child);
  12482. });
  12483. }
  12484. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12485. var seriesIndex = seriesModel.seriesIndex;
  12486. var data = seriesModel.getData(payload.dataType);
  12487. if (!data) {
  12488. if ("development" !== 'production') {
  12489. error("Unknown dataType " + payload.dataType);
  12490. }
  12491. return;
  12492. }
  12493. var dataIndex = queryDataIndex(data, payload);
  12494. // Pick the first one if there is multiple/none exists.
  12495. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12496. var el = data.getItemGraphicEl(dataIndex);
  12497. if (!el) {
  12498. var count = data.count();
  12499. var current = 0;
  12500. // If data on dataIndex is NaN.
  12501. while (!el && current < count) {
  12502. el = data.getItemGraphicEl(current++);
  12503. }
  12504. }
  12505. if (el) {
  12506. var ecData = getECData(el);
  12507. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12508. } else {
  12509. // If there is no element put on the data. Try getting it from raw option
  12510. // TODO Should put it on seriesModel?
  12511. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12512. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12513. if (focus_1 != null) {
  12514. blurSeries(seriesIndex, focus_1, blurScope, api);
  12515. }
  12516. }
  12517. }
  12518. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12519. var ret = {
  12520. focusSelf: false,
  12521. dispatchers: null
  12522. };
  12523. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12524. return ret;
  12525. }
  12526. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12527. if (!componentModel) {
  12528. return ret;
  12529. }
  12530. var view = api.getViewOfComponentModel(componentModel);
  12531. if (!view || !view.findHighDownDispatchers) {
  12532. return ret;
  12533. }
  12534. var dispatchers = view.findHighDownDispatchers(name);
  12535. // At presnet, the component (like Geo) only blur inside itself.
  12536. // So we do not use `blurScope` in component.
  12537. var focusSelf;
  12538. for (var i = 0; i < dispatchers.length; i++) {
  12539. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12540. error('param should be highDownDispatcher');
  12541. }
  12542. if (getECData(dispatchers[i]).focus === 'self') {
  12543. focusSelf = true;
  12544. break;
  12545. }
  12546. }
  12547. return {
  12548. focusSelf: focusSelf,
  12549. dispatchers: dispatchers
  12550. };
  12551. }
  12552. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12553. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12554. error('param should be highDownDispatcher');
  12555. }
  12556. var ecData = getECData(dispatcher);
  12557. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12558. dispatchers = _a.dispatchers,
  12559. focusSelf = _a.focusSelf;
  12560. // If `findHighDownDispatchers` is supported on the component,
  12561. // highlight/downplay elements with the same name.
  12562. if (dispatchers) {
  12563. if (focusSelf) {
  12564. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12565. }
  12566. each(dispatchers, function (dispatcher) {
  12567. return enterEmphasisWhenMouseOver(dispatcher, e);
  12568. });
  12569. } else {
  12570. // Try blur all in the related series. Then emphasis the hoverred.
  12571. // TODO. progressive mode.
  12572. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12573. if (ecData.focus === 'self') {
  12574. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12575. }
  12576. // Other than series, component that not support `findHighDownDispatcher` will
  12577. // also use it. But in this case, highlight/downplay are only supported in
  12578. // mouse hover but not in dispatchAction.
  12579. enterEmphasisWhenMouseOver(dispatcher, e);
  12580. }
  12581. }
  12582. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12583. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12584. error('param should be highDownDispatcher');
  12585. }
  12586. allLeaveBlur(api);
  12587. var ecData = getECData(dispatcher);
  12588. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12589. if (dispatchers) {
  12590. each(dispatchers, function (dispatcher) {
  12591. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12592. });
  12593. } else {
  12594. leaveEmphasisWhenMouseOut(dispatcher, e);
  12595. }
  12596. }
  12597. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12598. if (!isSelectChangePayload(payload)) {
  12599. return;
  12600. }
  12601. var dataType = payload.dataType;
  12602. var data = seriesModel.getData(dataType);
  12603. var dataIndex = queryDataIndex(data, payload);
  12604. if (!isArray(dataIndex)) {
  12605. dataIndex = [dataIndex];
  12606. }
  12607. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12608. }
  12609. function updateSeriesElementSelection(seriesModel) {
  12610. var allData = seriesModel.getAllData();
  12611. each(allData, function (_a) {
  12612. var data = _a.data,
  12613. type = _a.type;
  12614. data.eachItemGraphicEl(function (el, idx) {
  12615. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12616. });
  12617. });
  12618. }
  12619. function getAllSelectedIndices(ecModel) {
  12620. var ret = [];
  12621. ecModel.eachSeries(function (seriesModel) {
  12622. var allData = seriesModel.getAllData();
  12623. each(allData, function (_a) {
  12624. var data = _a.data,
  12625. type = _a.type;
  12626. var dataIndices = seriesModel.getSelectedDataIndices();
  12627. if (dataIndices.length > 0) {
  12628. var item = {
  12629. dataIndex: dataIndices,
  12630. seriesIndex: seriesModel.seriesIndex
  12631. };
  12632. if (type != null) {
  12633. item.dataType = type;
  12634. }
  12635. ret.push(item);
  12636. }
  12637. });
  12638. });
  12639. return ret;
  12640. }
  12641. /**
  12642. * Enable the function that mouseover will trigger the emphasis state.
  12643. *
  12644. * NOTE:
  12645. * This function should be used on the element with dataIndex, seriesIndex.
  12646. *
  12647. */
  12648. function enableHoverEmphasis(el, focus, blurScope) {
  12649. setAsHighDownDispatcher(el, true);
  12650. traverseUpdateState(el, setDefaultStateProxy);
  12651. enableHoverFocus(el, focus, blurScope);
  12652. }
  12653. function disableHoverEmphasis(el) {
  12654. setAsHighDownDispatcher(el, false);
  12655. }
  12656. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12657. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12658. }
  12659. function enableHoverFocus(el, focus, blurScope) {
  12660. var ecData = getECData(el);
  12661. if (focus != null) {
  12662. // TODO dataIndex may be set after this function. This check is not useful.
  12663. // if (ecData.dataIndex == null) {
  12664. // if (__DEV__) {
  12665. // console.warn('focus can only been set on element with dataIndex');
  12666. // }
  12667. // }
  12668. // else {
  12669. ecData.focus = focus;
  12670. ecData.blurScope = blurScope;
  12671. // }
  12672. } else if (ecData.focus) {
  12673. ecData.focus = null;
  12674. }
  12675. }
  12676. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12677. var defaultStyleGetterMap = {
  12678. itemStyle: 'getItemStyle',
  12679. lineStyle: 'getLineStyle',
  12680. areaStyle: 'getAreaStyle'
  12681. };
  12682. /**
  12683. * Set emphasis/blur/selected states of element.
  12684. */
  12685. function setStatesStylesFromModel(el, itemModel, styleType,
  12686. // default itemStyle
  12687. getter) {
  12688. styleType = styleType || 'itemStyle';
  12689. for (var i = 0; i < OTHER_STATES.length; i++) {
  12690. var stateName = OTHER_STATES[i];
  12691. var model = itemModel.getModel([stateName, styleType]);
  12692. var state = el.ensureState(stateName);
  12693. // Let it throw error if getterType is not found.
  12694. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12695. }
  12696. }
  12697. /**
  12698. *
  12699. * Set element as highlight / downplay dispatcher.
  12700. * It will be checked when element received mouseover event or from highlight action.
  12701. * It's in change of all highlight/downplay behavior of it's children.
  12702. *
  12703. * @param el
  12704. * @param el.highDownSilentOnTouch
  12705. * In touch device, mouseover event will be trigger on touchstart event
  12706. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12707. * conveniently use hoverStyle when tap on touch screen without additional
  12708. * code for compatibility.
  12709. * But if the chart/component has select feature, which usually also use
  12710. * hoverStyle, there might be conflict between 'select-highlight' and
  12711. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12712. * In this case, `highDownSilentOnTouch` should be used to disable
  12713. * hover-highlight on touch device.
  12714. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12715. */
  12716. function setAsHighDownDispatcher(el, asDispatcher) {
  12717. var disable = asDispatcher === false;
  12718. var extendedEl = el;
  12719. // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12720. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12721. if (el.highDownSilentOnTouch) {
  12722. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12723. }
  12724. // Simple optimize, since this method might be
  12725. // called for each elements of a group in some cases.
  12726. if (!disable || extendedEl.__highDownDispatcher) {
  12727. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12728. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12729. // Also keep previous record.
  12730. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12731. extendedEl.__highDownDispatcher = !disable;
  12732. }
  12733. }
  12734. function isHighDownDispatcher(el) {
  12735. return !!(el && el.__highDownDispatcher);
  12736. }
  12737. /**
  12738. * Support highlight/downplay record on each elements.
  12739. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12740. * user triggered highlight/downplay should not conflict.
  12741. * Only all of the highlightDigit cleared, return to normal.
  12742. * @param {string} highlightKey
  12743. * @return {number} highlightDigit
  12744. */
  12745. function getHighlightDigit(highlightKey) {
  12746. var highlightDigit = _highlightKeyMap[highlightKey];
  12747. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12748. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12749. }
  12750. return highlightDigit;
  12751. }
  12752. function isSelectChangePayload(payload) {
  12753. var payloadType = payload.type;
  12754. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12755. }
  12756. function isHighDownPayload(payload) {
  12757. var payloadType = payload.type;
  12758. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12759. }
  12760. function savePathStates(el) {
  12761. var store = getSavedStates(el);
  12762. store.normalFill = el.style.fill;
  12763. store.normalStroke = el.style.stroke;
  12764. var selectState = el.states.select || {};
  12765. store.selectFill = selectState.style && selectState.style.fill || null;
  12766. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12767. }
  12768. var CMD$2 = PathProxy.CMD;
  12769. var points = [[], [], []];
  12770. var mathSqrt$1 = Math.sqrt;
  12771. var mathAtan2 = Math.atan2;
  12772. function transformPath(path, m) {
  12773. if (!m) {
  12774. return;
  12775. }
  12776. var data = path.data;
  12777. var len = path.len();
  12778. var cmd;
  12779. var nPoint;
  12780. var i;
  12781. var j;
  12782. var k;
  12783. var p;
  12784. var M = CMD$2.M;
  12785. var C = CMD$2.C;
  12786. var L = CMD$2.L;
  12787. var R = CMD$2.R;
  12788. var A = CMD$2.A;
  12789. var Q = CMD$2.Q;
  12790. for (i = 0, j = 0; i < len;) {
  12791. cmd = data[i++];
  12792. j = i;
  12793. nPoint = 0;
  12794. switch (cmd) {
  12795. case M:
  12796. nPoint = 1;
  12797. break;
  12798. case L:
  12799. nPoint = 1;
  12800. break;
  12801. case C:
  12802. nPoint = 3;
  12803. break;
  12804. case Q:
  12805. nPoint = 2;
  12806. break;
  12807. case A:
  12808. var x = m[4];
  12809. var y = m[5];
  12810. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12811. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12812. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12813. data[i] *= sx;
  12814. data[i++] += x;
  12815. data[i] *= sy;
  12816. data[i++] += y;
  12817. data[i++] *= sx;
  12818. data[i++] *= sy;
  12819. data[i++] += angle;
  12820. data[i++] += angle;
  12821. i += 2;
  12822. j = i;
  12823. break;
  12824. case R:
  12825. p[0] = data[i++];
  12826. p[1] = data[i++];
  12827. applyTransform(p, p, m);
  12828. data[j++] = p[0];
  12829. data[j++] = p[1];
  12830. p[0] += data[i++];
  12831. p[1] += data[i++];
  12832. applyTransform(p, p, m);
  12833. data[j++] = p[0];
  12834. data[j++] = p[1];
  12835. }
  12836. for (k = 0; k < nPoint; k++) {
  12837. var p_1 = points[k];
  12838. p_1[0] = data[i++];
  12839. p_1[1] = data[i++];
  12840. applyTransform(p_1, p_1, m);
  12841. data[j++] = p_1[0];
  12842. data[j++] = p_1[1];
  12843. }
  12844. }
  12845. path.increaseVersion();
  12846. }
  12847. var mathSqrt$2 = Math.sqrt;
  12848. var mathSin$2 = Math.sin;
  12849. var mathCos$2 = Math.cos;
  12850. var PI$1 = Math.PI;
  12851. function vMag(v) {
  12852. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12853. }
  12854. function vRatio(u, v) {
  12855. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12856. }
  12857. function vAngle(u, v) {
  12858. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12859. * Math.acos(vRatio(u, v));
  12860. }
  12861. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12862. var psi = psiDeg * (PI$1 / 180.0);
  12863. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12864. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12865. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12866. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12867. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12868. if (lambda > 1) {
  12869. rx *= mathSqrt$2(lambda);
  12870. ry *= mathSqrt$2(lambda);
  12871. }
  12872. var f = (fa === fs ? -1 : 1)
  12873. * mathSqrt$2((((rx * rx) * (ry * ry))
  12874. - ((rx * rx) * (yp * yp))
  12875. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12876. + (ry * ry) * (xp * xp))) || 0;
  12877. var cxp = f * rx * yp / ry;
  12878. var cyp = f * -ry * xp / rx;
  12879. var cx = (x1 + x2) / 2.0
  12880. + mathCos$2(psi) * cxp
  12881. - mathSin$2(psi) * cyp;
  12882. var cy = (y1 + y2) / 2.0
  12883. + mathSin$2(psi) * cxp
  12884. + mathCos$2(psi) * cyp;
  12885. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12886. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12887. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12888. var dTheta = vAngle(u, v);
  12889. if (vRatio(u, v) <= -1) {
  12890. dTheta = PI$1;
  12891. }
  12892. if (vRatio(u, v) >= 1) {
  12893. dTheta = 0;
  12894. }
  12895. if (dTheta < 0) {
  12896. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12897. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12898. }
  12899. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12900. }
  12901. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12902. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12903. function createPathProxyFromString(data) {
  12904. var path = new PathProxy();
  12905. if (!data) {
  12906. return path;
  12907. }
  12908. var cpx = 0;
  12909. var cpy = 0;
  12910. var subpathX = cpx;
  12911. var subpathY = cpy;
  12912. var prevCmd;
  12913. var CMD = PathProxy.CMD;
  12914. var cmdList = data.match(commandReg);
  12915. if (!cmdList) {
  12916. return path;
  12917. }
  12918. for (var l = 0; l < cmdList.length; l++) {
  12919. var cmdText = cmdList[l];
  12920. var cmdStr = cmdText.charAt(0);
  12921. var cmd = void 0;
  12922. var p = cmdText.match(numberReg) || [];
  12923. var pLen = p.length;
  12924. for (var i = 0; i < pLen; i++) {
  12925. p[i] = parseFloat(p[i]);
  12926. }
  12927. var off = 0;
  12928. while (off < pLen) {
  12929. var ctlPtx = void 0;
  12930. var ctlPty = void 0;
  12931. var rx = void 0;
  12932. var ry = void 0;
  12933. var psi = void 0;
  12934. var fa = void 0;
  12935. var fs = void 0;
  12936. var x1 = cpx;
  12937. var y1 = cpy;
  12938. var len = void 0;
  12939. var pathData = void 0;
  12940. switch (cmdStr) {
  12941. case 'l':
  12942. cpx += p[off++];
  12943. cpy += p[off++];
  12944. cmd = CMD.L;
  12945. path.addData(cmd, cpx, cpy);
  12946. break;
  12947. case 'L':
  12948. cpx = p[off++];
  12949. cpy = p[off++];
  12950. cmd = CMD.L;
  12951. path.addData(cmd, cpx, cpy);
  12952. break;
  12953. case 'm':
  12954. cpx += p[off++];
  12955. cpy += p[off++];
  12956. cmd = CMD.M;
  12957. path.addData(cmd, cpx, cpy);
  12958. subpathX = cpx;
  12959. subpathY = cpy;
  12960. cmdStr = 'l';
  12961. break;
  12962. case 'M':
  12963. cpx = p[off++];
  12964. cpy = p[off++];
  12965. cmd = CMD.M;
  12966. path.addData(cmd, cpx, cpy);
  12967. subpathX = cpx;
  12968. subpathY = cpy;
  12969. cmdStr = 'L';
  12970. break;
  12971. case 'h':
  12972. cpx += p[off++];
  12973. cmd = CMD.L;
  12974. path.addData(cmd, cpx, cpy);
  12975. break;
  12976. case 'H':
  12977. cpx = p[off++];
  12978. cmd = CMD.L;
  12979. path.addData(cmd, cpx, cpy);
  12980. break;
  12981. case 'v':
  12982. cpy += p[off++];
  12983. cmd = CMD.L;
  12984. path.addData(cmd, cpx, cpy);
  12985. break;
  12986. case 'V':
  12987. cpy = p[off++];
  12988. cmd = CMD.L;
  12989. path.addData(cmd, cpx, cpy);
  12990. break;
  12991. case 'C':
  12992. cmd = CMD.C;
  12993. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12994. cpx = p[off - 2];
  12995. cpy = p[off - 1];
  12996. break;
  12997. case 'c':
  12998. cmd = CMD.C;
  12999. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  13000. cpx += p[off - 2];
  13001. cpy += p[off - 1];
  13002. break;
  13003. case 'S':
  13004. ctlPtx = cpx;
  13005. ctlPty = cpy;
  13006. len = path.len();
  13007. pathData = path.data;
  13008. if (prevCmd === CMD.C) {
  13009. ctlPtx += cpx - pathData[len - 4];
  13010. ctlPty += cpy - pathData[len - 3];
  13011. }
  13012. cmd = CMD.C;
  13013. x1 = p[off++];
  13014. y1 = p[off++];
  13015. cpx = p[off++];
  13016. cpy = p[off++];
  13017. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13018. break;
  13019. case 's':
  13020. ctlPtx = cpx;
  13021. ctlPty = cpy;
  13022. len = path.len();
  13023. pathData = path.data;
  13024. if (prevCmd === CMD.C) {
  13025. ctlPtx += cpx - pathData[len - 4];
  13026. ctlPty += cpy - pathData[len - 3];
  13027. }
  13028. cmd = CMD.C;
  13029. x1 = cpx + p[off++];
  13030. y1 = cpy + p[off++];
  13031. cpx += p[off++];
  13032. cpy += p[off++];
  13033. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13034. break;
  13035. case 'Q':
  13036. x1 = p[off++];
  13037. y1 = p[off++];
  13038. cpx = p[off++];
  13039. cpy = p[off++];
  13040. cmd = CMD.Q;
  13041. path.addData(cmd, x1, y1, cpx, cpy);
  13042. break;
  13043. case 'q':
  13044. x1 = p[off++] + cpx;
  13045. y1 = p[off++] + cpy;
  13046. cpx += p[off++];
  13047. cpy += p[off++];
  13048. cmd = CMD.Q;
  13049. path.addData(cmd, x1, y1, cpx, cpy);
  13050. break;
  13051. case 'T':
  13052. ctlPtx = cpx;
  13053. ctlPty = cpy;
  13054. len = path.len();
  13055. pathData = path.data;
  13056. if (prevCmd === CMD.Q) {
  13057. ctlPtx += cpx - pathData[len - 4];
  13058. ctlPty += cpy - pathData[len - 3];
  13059. }
  13060. cpx = p[off++];
  13061. cpy = p[off++];
  13062. cmd = CMD.Q;
  13063. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13064. break;
  13065. case 't':
  13066. ctlPtx = cpx;
  13067. ctlPty = cpy;
  13068. len = path.len();
  13069. pathData = path.data;
  13070. if (prevCmd === CMD.Q) {
  13071. ctlPtx += cpx - pathData[len - 4];
  13072. ctlPty += cpy - pathData[len - 3];
  13073. }
  13074. cpx += p[off++];
  13075. cpy += p[off++];
  13076. cmd = CMD.Q;
  13077. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13078. break;
  13079. case 'A':
  13080. rx = p[off++];
  13081. ry = p[off++];
  13082. psi = p[off++];
  13083. fa = p[off++];
  13084. fs = p[off++];
  13085. x1 = cpx, y1 = cpy;
  13086. cpx = p[off++];
  13087. cpy = p[off++];
  13088. cmd = CMD.A;
  13089. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13090. break;
  13091. case 'a':
  13092. rx = p[off++];
  13093. ry = p[off++];
  13094. psi = p[off++];
  13095. fa = p[off++];
  13096. fs = p[off++];
  13097. x1 = cpx, y1 = cpy;
  13098. cpx += p[off++];
  13099. cpy += p[off++];
  13100. cmd = CMD.A;
  13101. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13102. break;
  13103. }
  13104. }
  13105. if (cmdStr === 'z' || cmdStr === 'Z') {
  13106. cmd = CMD.Z;
  13107. path.addData(cmd);
  13108. cpx = subpathX;
  13109. cpy = subpathY;
  13110. }
  13111. prevCmd = cmd;
  13112. }
  13113. path.toStatic();
  13114. return path;
  13115. }
  13116. var SVGPath = (function (_super) {
  13117. __extends(SVGPath, _super);
  13118. function SVGPath() {
  13119. return _super !== null && _super.apply(this, arguments) || this;
  13120. }
  13121. SVGPath.prototype.applyTransform = function (m) { };
  13122. return SVGPath;
  13123. }(Path));
  13124. function isPathProxy(path) {
  13125. return path.setData != null;
  13126. }
  13127. function createPathOptions(str, opts) {
  13128. var pathProxy = createPathProxyFromString(str);
  13129. var innerOpts = extend({}, opts);
  13130. innerOpts.buildPath = function (path) {
  13131. if (isPathProxy(path)) {
  13132. path.setData(pathProxy.data);
  13133. var ctx = path.getContext();
  13134. if (ctx) {
  13135. path.rebuildPath(ctx, 1);
  13136. }
  13137. }
  13138. else {
  13139. var ctx = path;
  13140. pathProxy.rebuildPath(ctx, 1);
  13141. }
  13142. };
  13143. innerOpts.applyTransform = function (m) {
  13144. transformPath(pathProxy, m);
  13145. this.dirtyShape();
  13146. };
  13147. return innerOpts;
  13148. }
  13149. function createFromString(str, opts) {
  13150. return new SVGPath(createPathOptions(str, opts));
  13151. }
  13152. function extendFromString(str, defaultOpts) {
  13153. var innerOpts = createPathOptions(str, defaultOpts);
  13154. var Sub = (function (_super) {
  13155. __extends(Sub, _super);
  13156. function Sub(opts) {
  13157. var _this = _super.call(this, opts) || this;
  13158. _this.applyTransform = innerOpts.applyTransform;
  13159. _this.buildPath = innerOpts.buildPath;
  13160. return _this;
  13161. }
  13162. return Sub;
  13163. }(SVGPath));
  13164. return Sub;
  13165. }
  13166. function mergePath(pathEls, opts) {
  13167. var pathList = [];
  13168. var len = pathEls.length;
  13169. for (var i = 0; i < len; i++) {
  13170. var pathEl = pathEls[i];
  13171. pathList.push(pathEl.getUpdatedPathProxy(true));
  13172. }
  13173. var pathBundle = new Path(opts);
  13174. pathBundle.createPathProxy();
  13175. pathBundle.buildPath = function (path) {
  13176. if (isPathProxy(path)) {
  13177. path.appendPath(pathList);
  13178. var ctx = path.getContext();
  13179. if (ctx) {
  13180. path.rebuildPath(ctx, 1);
  13181. }
  13182. }
  13183. };
  13184. return pathBundle;
  13185. }
  13186. var CircleShape = (function () {
  13187. function CircleShape() {
  13188. this.cx = 0;
  13189. this.cy = 0;
  13190. this.r = 0;
  13191. }
  13192. return CircleShape;
  13193. }());
  13194. var Circle = (function (_super) {
  13195. __extends(Circle, _super);
  13196. function Circle(opts) {
  13197. return _super.call(this, opts) || this;
  13198. }
  13199. Circle.prototype.getDefaultShape = function () {
  13200. return new CircleShape();
  13201. };
  13202. Circle.prototype.buildPath = function (ctx, shape) {
  13203. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13204. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13205. };
  13206. return Circle;
  13207. }(Path));
  13208. Circle.prototype.type = 'circle';
  13209. var EllipseShape = (function () {
  13210. function EllipseShape() {
  13211. this.cx = 0;
  13212. this.cy = 0;
  13213. this.rx = 0;
  13214. this.ry = 0;
  13215. }
  13216. return EllipseShape;
  13217. }());
  13218. var Ellipse = (function (_super) {
  13219. __extends(Ellipse, _super);
  13220. function Ellipse(opts) {
  13221. return _super.call(this, opts) || this;
  13222. }
  13223. Ellipse.prototype.getDefaultShape = function () {
  13224. return new EllipseShape();
  13225. };
  13226. Ellipse.prototype.buildPath = function (ctx, shape) {
  13227. var k = 0.5522848;
  13228. var x = shape.cx;
  13229. var y = shape.cy;
  13230. var a = shape.rx;
  13231. var b = shape.ry;
  13232. var ox = a * k;
  13233. var oy = b * k;
  13234. ctx.moveTo(x - a, y);
  13235. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13236. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13237. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13238. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13239. ctx.closePath();
  13240. };
  13241. return Ellipse;
  13242. }(Path));
  13243. Ellipse.prototype.type = 'ellipse';
  13244. var PI$2 = Math.PI;
  13245. var PI2$5 = PI$2 * 2;
  13246. var mathSin$3 = Math.sin;
  13247. var mathCos$3 = Math.cos;
  13248. var mathACos = Math.acos;
  13249. var mathATan2 = Math.atan2;
  13250. var mathAbs$1 = Math.abs;
  13251. var mathSqrt$3 = Math.sqrt;
  13252. var mathMax$3 = Math.max;
  13253. var mathMin$3 = Math.min;
  13254. var e = 1e-4;
  13255. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13256. var dx10 = x1 - x0;
  13257. var dy10 = y1 - y0;
  13258. var dx32 = x3 - x2;
  13259. var dy32 = y3 - y2;
  13260. var t = dy32 * dx10 - dx32 * dy10;
  13261. if (t * t < e) {
  13262. return;
  13263. }
  13264. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13265. return [x0 + t * dx10, y0 + t * dy10];
  13266. }
  13267. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13268. var x01 = x0 - x1;
  13269. var y01 = y0 - y1;
  13270. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13271. var ox = lo * y01;
  13272. var oy = -lo * x01;
  13273. var x11 = x0 + ox;
  13274. var y11 = y0 + oy;
  13275. var x10 = x1 + ox;
  13276. var y10 = y1 + oy;
  13277. var x00 = (x11 + x10) / 2;
  13278. var y00 = (y11 + y10) / 2;
  13279. var dx = x10 - x11;
  13280. var dy = y10 - y11;
  13281. var d2 = dx * dx + dy * dy;
  13282. var r = radius - cr;
  13283. var s = x11 * y10 - x10 * y11;
  13284. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13285. var cx0 = (s * dy - dx * d) / d2;
  13286. var cy0 = (-s * dx - dy * d) / d2;
  13287. var cx1 = (s * dy + dx * d) / d2;
  13288. var cy1 = (-s * dx + dy * d) / d2;
  13289. var dx0 = cx0 - x00;
  13290. var dy0 = cy0 - y00;
  13291. var dx1 = cx1 - x00;
  13292. var dy1 = cy1 - y00;
  13293. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13294. cx0 = cx1;
  13295. cy0 = cy1;
  13296. }
  13297. return {
  13298. cx: cx0,
  13299. cy: cy0,
  13300. x0: -ox,
  13301. y0: -oy,
  13302. x1: cx0 * (radius / r - 1),
  13303. y1: cy0 * (radius / r - 1)
  13304. };
  13305. }
  13306. function normalizeCornerRadius(cr) {
  13307. var arr;
  13308. if (isArray(cr)) {
  13309. var len = cr.length;
  13310. if (!len) {
  13311. return cr;
  13312. }
  13313. if (len === 1) {
  13314. arr = [cr[0], cr[0], 0, 0];
  13315. }
  13316. else if (len === 2) {
  13317. arr = [cr[0], cr[0], cr[1], cr[1]];
  13318. }
  13319. else if (len === 3) {
  13320. arr = cr.concat(cr[2]);
  13321. }
  13322. else {
  13323. arr = cr;
  13324. }
  13325. }
  13326. else {
  13327. arr = [cr, cr, cr, cr];
  13328. }
  13329. return arr;
  13330. }
  13331. function buildPath$1(ctx, shape) {
  13332. var _a;
  13333. var radius = mathMax$3(shape.r, 0);
  13334. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13335. var hasRadius = radius > 0;
  13336. var hasInnerRadius = innerRadius > 0;
  13337. if (!hasRadius && !hasInnerRadius) {
  13338. return;
  13339. }
  13340. if (!hasRadius) {
  13341. radius = innerRadius;
  13342. innerRadius = 0;
  13343. }
  13344. if (innerRadius > radius) {
  13345. var tmp = radius;
  13346. radius = innerRadius;
  13347. innerRadius = tmp;
  13348. }
  13349. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13350. if (isNaN(startAngle) || isNaN(endAngle)) {
  13351. return;
  13352. }
  13353. var cx = shape.cx, cy = shape.cy;
  13354. var clockwise = !!shape.clockwise;
  13355. var arc = mathAbs$1(endAngle - startAngle);
  13356. var mod = arc > PI2$5 && arc % PI2$5;
  13357. mod > e && (arc = mod);
  13358. if (!(radius > e)) {
  13359. ctx.moveTo(cx, cy);
  13360. }
  13361. else if (arc > PI2$5 - e) {
  13362. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13363. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13364. if (innerRadius > e) {
  13365. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13366. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13367. }
  13368. }
  13369. else {
  13370. var icrStart = void 0;
  13371. var icrEnd = void 0;
  13372. var ocrStart = void 0;
  13373. var ocrEnd = void 0;
  13374. var ocrs = void 0;
  13375. var ocre = void 0;
  13376. var icrs = void 0;
  13377. var icre = void 0;
  13378. var ocrMax = void 0;
  13379. var icrMax = void 0;
  13380. var limitedOcrMax = void 0;
  13381. var limitedIcrMax = void 0;
  13382. var xre = void 0;
  13383. var yre = void 0;
  13384. var xirs = void 0;
  13385. var yirs = void 0;
  13386. var xrs = radius * mathCos$3(startAngle);
  13387. var yrs = radius * mathSin$3(startAngle);
  13388. var xire = innerRadius * mathCos$3(endAngle);
  13389. var yire = innerRadius * mathSin$3(endAngle);
  13390. var hasArc = arc > e;
  13391. if (hasArc) {
  13392. var cornerRadius = shape.cornerRadius;
  13393. if (cornerRadius) {
  13394. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13395. }
  13396. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13397. ocrs = mathMin$3(halfRd, ocrStart);
  13398. ocre = mathMin$3(halfRd, ocrEnd);
  13399. icrs = mathMin$3(halfRd, icrStart);
  13400. icre = mathMin$3(halfRd, icrEnd);
  13401. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13402. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13403. if (ocrMax > e || icrMax > e) {
  13404. xre = radius * mathCos$3(endAngle);
  13405. yre = radius * mathSin$3(endAngle);
  13406. xirs = innerRadius * mathCos$3(startAngle);
  13407. yirs = innerRadius * mathSin$3(startAngle);
  13408. if (arc < PI$2) {
  13409. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13410. if (it_1) {
  13411. var x0 = xrs - it_1[0];
  13412. var y0 = yrs - it_1[1];
  13413. var x1 = xre - it_1[0];
  13414. var y1 = yre - it_1[1];
  13415. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13416. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13417. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13418. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13419. }
  13420. }
  13421. }
  13422. }
  13423. if (!hasArc) {
  13424. ctx.moveTo(cx + xrs, cy + yrs);
  13425. }
  13426. else if (limitedOcrMax > e) {
  13427. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13428. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13429. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13430. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13431. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13432. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13433. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13434. }
  13435. else {
  13436. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13437. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13438. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13439. }
  13440. }
  13441. else {
  13442. ctx.moveTo(cx + xrs, cy + yrs);
  13443. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13444. }
  13445. if (!(innerRadius > e) || !hasArc) {
  13446. ctx.lineTo(cx + xire, cy + yire);
  13447. }
  13448. else if (limitedIcrMax > e) {
  13449. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13450. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13451. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13452. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13453. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13454. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13455. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13456. }
  13457. else {
  13458. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13459. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13460. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13461. }
  13462. }
  13463. else {
  13464. ctx.lineTo(cx + xire, cy + yire);
  13465. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13466. }
  13467. }
  13468. ctx.closePath();
  13469. }
  13470. var SectorShape = (function () {
  13471. function SectorShape() {
  13472. this.cx = 0;
  13473. this.cy = 0;
  13474. this.r0 = 0;
  13475. this.r = 0;
  13476. this.startAngle = 0;
  13477. this.endAngle = Math.PI * 2;
  13478. this.clockwise = true;
  13479. this.cornerRadius = 0;
  13480. }
  13481. return SectorShape;
  13482. }());
  13483. var Sector = (function (_super) {
  13484. __extends(Sector, _super);
  13485. function Sector(opts) {
  13486. return _super.call(this, opts) || this;
  13487. }
  13488. Sector.prototype.getDefaultShape = function () {
  13489. return new SectorShape();
  13490. };
  13491. Sector.prototype.buildPath = function (ctx, shape) {
  13492. buildPath$1(ctx, shape);
  13493. };
  13494. Sector.prototype.isZeroArea = function () {
  13495. return this.shape.startAngle === this.shape.endAngle
  13496. || this.shape.r === this.shape.r0;
  13497. };
  13498. return Sector;
  13499. }(Path));
  13500. Sector.prototype.type = 'sector';
  13501. var RingShape = (function () {
  13502. function RingShape() {
  13503. this.cx = 0;
  13504. this.cy = 0;
  13505. this.r = 0;
  13506. this.r0 = 0;
  13507. }
  13508. return RingShape;
  13509. }());
  13510. var Ring = (function (_super) {
  13511. __extends(Ring, _super);
  13512. function Ring(opts) {
  13513. return _super.call(this, opts) || this;
  13514. }
  13515. Ring.prototype.getDefaultShape = function () {
  13516. return new RingShape();
  13517. };
  13518. Ring.prototype.buildPath = function (ctx, shape) {
  13519. var x = shape.cx;
  13520. var y = shape.cy;
  13521. var PI2 = Math.PI * 2;
  13522. ctx.moveTo(x + shape.r, y);
  13523. ctx.arc(x, y, shape.r, 0, PI2, false);
  13524. ctx.moveTo(x + shape.r0, y);
  13525. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13526. };
  13527. return Ring;
  13528. }(Path));
  13529. Ring.prototype.type = 'ring';
  13530. function smoothBezier(points, smooth, isLoop, constraint) {
  13531. var cps = [];
  13532. var v = [];
  13533. var v1 = [];
  13534. var v2 = [];
  13535. var prevPoint;
  13536. var nextPoint;
  13537. var min$1;
  13538. var max$1;
  13539. if (constraint) {
  13540. min$1 = [Infinity, Infinity];
  13541. max$1 = [-Infinity, -Infinity];
  13542. for (var i = 0, len = points.length; i < len; i++) {
  13543. min(min$1, min$1, points[i]);
  13544. max(max$1, max$1, points[i]);
  13545. }
  13546. min(min$1, min$1, constraint[0]);
  13547. max(max$1, max$1, constraint[1]);
  13548. }
  13549. for (var i = 0, len = points.length; i < len; i++) {
  13550. var point = points[i];
  13551. if (isLoop) {
  13552. prevPoint = points[i ? i - 1 : len - 1];
  13553. nextPoint = points[(i + 1) % len];
  13554. }
  13555. else {
  13556. if (i === 0 || i === len - 1) {
  13557. cps.push(clone$1(points[i]));
  13558. continue;
  13559. }
  13560. else {
  13561. prevPoint = points[i - 1];
  13562. nextPoint = points[i + 1];
  13563. }
  13564. }
  13565. sub(v, nextPoint, prevPoint);
  13566. scale(v, v, smooth);
  13567. var d0 = distance(point, prevPoint);
  13568. var d1 = distance(point, nextPoint);
  13569. var sum = d0 + d1;
  13570. if (sum !== 0) {
  13571. d0 /= sum;
  13572. d1 /= sum;
  13573. }
  13574. scale(v1, v, -d0);
  13575. scale(v2, v, d1);
  13576. var cp0 = add([], point, v1);
  13577. var cp1 = add([], point, v2);
  13578. if (constraint) {
  13579. max(cp0, cp0, min$1);
  13580. min(cp0, cp0, max$1);
  13581. max(cp1, cp1, min$1);
  13582. min(cp1, cp1, max$1);
  13583. }
  13584. cps.push(cp0);
  13585. cps.push(cp1);
  13586. }
  13587. if (isLoop) {
  13588. cps.push(cps.shift());
  13589. }
  13590. return cps;
  13591. }
  13592. function buildPath$2(ctx, shape, closePath) {
  13593. var smooth = shape.smooth;
  13594. var points = shape.points;
  13595. if (points && points.length >= 2) {
  13596. if (smooth) {
  13597. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13598. ctx.moveTo(points[0][0], points[0][1]);
  13599. var len = points.length;
  13600. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13601. var cp1 = controlPoints[i * 2];
  13602. var cp2 = controlPoints[i * 2 + 1];
  13603. var p = points[(i + 1) % len];
  13604. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13605. }
  13606. }
  13607. else {
  13608. ctx.moveTo(points[0][0], points[0][1]);
  13609. for (var i = 1, l = points.length; i < l; i++) {
  13610. ctx.lineTo(points[i][0], points[i][1]);
  13611. }
  13612. }
  13613. closePath && ctx.closePath();
  13614. }
  13615. }
  13616. var PolygonShape = (function () {
  13617. function PolygonShape() {
  13618. this.points = null;
  13619. this.smooth = 0;
  13620. this.smoothConstraint = null;
  13621. }
  13622. return PolygonShape;
  13623. }());
  13624. var Polygon = (function (_super) {
  13625. __extends(Polygon, _super);
  13626. function Polygon(opts) {
  13627. return _super.call(this, opts) || this;
  13628. }
  13629. Polygon.prototype.getDefaultShape = function () {
  13630. return new PolygonShape();
  13631. };
  13632. Polygon.prototype.buildPath = function (ctx, shape) {
  13633. buildPath$2(ctx, shape, true);
  13634. };
  13635. return Polygon;
  13636. }(Path));
  13637. Polygon.prototype.type = 'polygon';
  13638. var PolylineShape = (function () {
  13639. function PolylineShape() {
  13640. this.points = null;
  13641. this.percent = 1;
  13642. this.smooth = 0;
  13643. this.smoothConstraint = null;
  13644. }
  13645. return PolylineShape;
  13646. }());
  13647. var Polyline = (function (_super) {
  13648. __extends(Polyline, _super);
  13649. function Polyline(opts) {
  13650. return _super.call(this, opts) || this;
  13651. }
  13652. Polyline.prototype.getDefaultStyle = function () {
  13653. return {
  13654. stroke: '#000',
  13655. fill: null
  13656. };
  13657. };
  13658. Polyline.prototype.getDefaultShape = function () {
  13659. return new PolylineShape();
  13660. };
  13661. Polyline.prototype.buildPath = function (ctx, shape) {
  13662. buildPath$2(ctx, shape, false);
  13663. };
  13664. return Polyline;
  13665. }(Path));
  13666. Polyline.prototype.type = 'polyline';
  13667. var subPixelOptimizeOutputShape$1 = {};
  13668. var LineShape = (function () {
  13669. function LineShape() {
  13670. this.x1 = 0;
  13671. this.y1 = 0;
  13672. this.x2 = 0;
  13673. this.y2 = 0;
  13674. this.percent = 1;
  13675. }
  13676. return LineShape;
  13677. }());
  13678. var Line = (function (_super) {
  13679. __extends(Line, _super);
  13680. function Line(opts) {
  13681. return _super.call(this, opts) || this;
  13682. }
  13683. Line.prototype.getDefaultStyle = function () {
  13684. return {
  13685. stroke: '#000',
  13686. fill: null
  13687. };
  13688. };
  13689. Line.prototype.getDefaultShape = function () {
  13690. return new LineShape();
  13691. };
  13692. Line.prototype.buildPath = function (ctx, shape) {
  13693. var x1;
  13694. var y1;
  13695. var x2;
  13696. var y2;
  13697. if (this.subPixelOptimize) {
  13698. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13699. x1 = optimizedShape.x1;
  13700. y1 = optimizedShape.y1;
  13701. x2 = optimizedShape.x2;
  13702. y2 = optimizedShape.y2;
  13703. }
  13704. else {
  13705. x1 = shape.x1;
  13706. y1 = shape.y1;
  13707. x2 = shape.x2;
  13708. y2 = shape.y2;
  13709. }
  13710. var percent = shape.percent;
  13711. if (percent === 0) {
  13712. return;
  13713. }
  13714. ctx.moveTo(x1, y1);
  13715. if (percent < 1) {
  13716. x2 = x1 * (1 - percent) + x2 * percent;
  13717. y2 = y1 * (1 - percent) + y2 * percent;
  13718. }
  13719. ctx.lineTo(x2, y2);
  13720. };
  13721. Line.prototype.pointAt = function (p) {
  13722. var shape = this.shape;
  13723. return [
  13724. shape.x1 * (1 - p) + shape.x2 * p,
  13725. shape.y1 * (1 - p) + shape.y2 * p
  13726. ];
  13727. };
  13728. return Line;
  13729. }(Path));
  13730. Line.prototype.type = 'line';
  13731. var out = [];
  13732. var BezierCurveShape = (function () {
  13733. function BezierCurveShape() {
  13734. this.x1 = 0;
  13735. this.y1 = 0;
  13736. this.x2 = 0;
  13737. this.y2 = 0;
  13738. this.cpx1 = 0;
  13739. this.cpy1 = 0;
  13740. this.percent = 1;
  13741. }
  13742. return BezierCurveShape;
  13743. }());
  13744. function someVectorAt(shape, t, isTangent) {
  13745. var cpx2 = shape.cpx2;
  13746. var cpy2 = shape.cpy2;
  13747. if (cpx2 != null || cpy2 != null) {
  13748. return [
  13749. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13750. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13751. ];
  13752. }
  13753. else {
  13754. return [
  13755. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13756. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13757. ];
  13758. }
  13759. }
  13760. var BezierCurve = (function (_super) {
  13761. __extends(BezierCurve, _super);
  13762. function BezierCurve(opts) {
  13763. return _super.call(this, opts) || this;
  13764. }
  13765. BezierCurve.prototype.getDefaultStyle = function () {
  13766. return {
  13767. stroke: '#000',
  13768. fill: null
  13769. };
  13770. };
  13771. BezierCurve.prototype.getDefaultShape = function () {
  13772. return new BezierCurveShape();
  13773. };
  13774. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13775. var x1 = shape.x1;
  13776. var y1 = shape.y1;
  13777. var x2 = shape.x2;
  13778. var y2 = shape.y2;
  13779. var cpx1 = shape.cpx1;
  13780. var cpy1 = shape.cpy1;
  13781. var cpx2 = shape.cpx2;
  13782. var cpy2 = shape.cpy2;
  13783. var percent = shape.percent;
  13784. if (percent === 0) {
  13785. return;
  13786. }
  13787. ctx.moveTo(x1, y1);
  13788. if (cpx2 == null || cpy2 == null) {
  13789. if (percent < 1) {
  13790. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13791. cpx1 = out[1];
  13792. x2 = out[2];
  13793. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13794. cpy1 = out[1];
  13795. y2 = out[2];
  13796. }
  13797. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13798. }
  13799. else {
  13800. if (percent < 1) {
  13801. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13802. cpx1 = out[1];
  13803. cpx2 = out[2];
  13804. x2 = out[3];
  13805. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13806. cpy1 = out[1];
  13807. cpy2 = out[2];
  13808. y2 = out[3];
  13809. }
  13810. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13811. }
  13812. };
  13813. BezierCurve.prototype.pointAt = function (t) {
  13814. return someVectorAt(this.shape, t, false);
  13815. };
  13816. BezierCurve.prototype.tangentAt = function (t) {
  13817. var p = someVectorAt(this.shape, t, true);
  13818. return normalize(p, p);
  13819. };
  13820. return BezierCurve;
  13821. }(Path));
  13822. BezierCurve.prototype.type = 'bezier-curve';
  13823. var ArcShape = (function () {
  13824. function ArcShape() {
  13825. this.cx = 0;
  13826. this.cy = 0;
  13827. this.r = 0;
  13828. this.startAngle = 0;
  13829. this.endAngle = Math.PI * 2;
  13830. this.clockwise = true;
  13831. }
  13832. return ArcShape;
  13833. }());
  13834. var Arc = (function (_super) {
  13835. __extends(Arc, _super);
  13836. function Arc(opts) {
  13837. return _super.call(this, opts) || this;
  13838. }
  13839. Arc.prototype.getDefaultStyle = function () {
  13840. return {
  13841. stroke: '#000',
  13842. fill: null
  13843. };
  13844. };
  13845. Arc.prototype.getDefaultShape = function () {
  13846. return new ArcShape();
  13847. };
  13848. Arc.prototype.buildPath = function (ctx, shape) {
  13849. var x = shape.cx;
  13850. var y = shape.cy;
  13851. var r = Math.max(shape.r, 0);
  13852. var startAngle = shape.startAngle;
  13853. var endAngle = shape.endAngle;
  13854. var clockwise = shape.clockwise;
  13855. var unitX = Math.cos(startAngle);
  13856. var unitY = Math.sin(startAngle);
  13857. ctx.moveTo(unitX * r + x, unitY * r + y);
  13858. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13859. };
  13860. return Arc;
  13861. }(Path));
  13862. Arc.prototype.type = 'arc';
  13863. var CompoundPath = (function (_super) {
  13864. __extends(CompoundPath, _super);
  13865. function CompoundPath() {
  13866. var _this = _super !== null && _super.apply(this, arguments) || this;
  13867. _this.type = 'compound';
  13868. return _this;
  13869. }
  13870. CompoundPath.prototype._updatePathDirty = function () {
  13871. var paths = this.shape.paths;
  13872. var dirtyPath = this.shapeChanged();
  13873. for (var i = 0; i < paths.length; i++) {
  13874. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13875. }
  13876. if (dirtyPath) {
  13877. this.dirtyShape();
  13878. }
  13879. };
  13880. CompoundPath.prototype.beforeBrush = function () {
  13881. this._updatePathDirty();
  13882. var paths = this.shape.paths || [];
  13883. var scale = this.getGlobalScale();
  13884. for (var i = 0; i < paths.length; i++) {
  13885. if (!paths[i].path) {
  13886. paths[i].createPathProxy();
  13887. }
  13888. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13889. }
  13890. };
  13891. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13892. var paths = shape.paths || [];
  13893. for (var i = 0; i < paths.length; i++) {
  13894. paths[i].buildPath(ctx, paths[i].shape, true);
  13895. }
  13896. };
  13897. CompoundPath.prototype.afterBrush = function () {
  13898. var paths = this.shape.paths || [];
  13899. for (var i = 0; i < paths.length; i++) {
  13900. paths[i].pathUpdated();
  13901. }
  13902. };
  13903. CompoundPath.prototype.getBoundingRect = function () {
  13904. this._updatePathDirty.call(this);
  13905. return Path.prototype.getBoundingRect.call(this);
  13906. };
  13907. return CompoundPath;
  13908. }(Path));
  13909. var Gradient = (function () {
  13910. function Gradient(colorStops) {
  13911. this.colorStops = colorStops || [];
  13912. }
  13913. Gradient.prototype.addColorStop = function (offset, color) {
  13914. this.colorStops.push({
  13915. offset: offset,
  13916. color: color
  13917. });
  13918. };
  13919. return Gradient;
  13920. }());
  13921. var LinearGradient = (function (_super) {
  13922. __extends(LinearGradient, _super);
  13923. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13924. var _this = _super.call(this, colorStops) || this;
  13925. _this.x = x == null ? 0 : x;
  13926. _this.y = y == null ? 0 : y;
  13927. _this.x2 = x2 == null ? 1 : x2;
  13928. _this.y2 = y2 == null ? 0 : y2;
  13929. _this.type = 'linear';
  13930. _this.global = globalCoord || false;
  13931. return _this;
  13932. }
  13933. return LinearGradient;
  13934. }(Gradient));
  13935. var RadialGradient = (function (_super) {
  13936. __extends(RadialGradient, _super);
  13937. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13938. var _this = _super.call(this, colorStops) || this;
  13939. _this.x = x == null ? 0.5 : x;
  13940. _this.y = y == null ? 0.5 : y;
  13941. _this.r = r == null ? 0.5 : r;
  13942. _this.type = 'radial';
  13943. _this.global = globalCoord || false;
  13944. return _this;
  13945. }
  13946. return RadialGradient;
  13947. }(Gradient));
  13948. var extent = [0, 0];
  13949. var extent2 = [0, 0];
  13950. var minTv$1 = new Point();
  13951. var maxTv$1 = new Point();
  13952. var OrientedBoundingRect = (function () {
  13953. function OrientedBoundingRect(rect, transform) {
  13954. this._corners = [];
  13955. this._axes = [];
  13956. this._origin = [0, 0];
  13957. for (var i = 0; i < 4; i++) {
  13958. this._corners[i] = new Point();
  13959. }
  13960. for (var i = 0; i < 2; i++) {
  13961. this._axes[i] = new Point();
  13962. }
  13963. if (rect) {
  13964. this.fromBoundingRect(rect, transform);
  13965. }
  13966. }
  13967. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13968. var corners = this._corners;
  13969. var axes = this._axes;
  13970. var x = rect.x;
  13971. var y = rect.y;
  13972. var x2 = x + rect.width;
  13973. var y2 = y + rect.height;
  13974. corners[0].set(x, y);
  13975. corners[1].set(x2, y);
  13976. corners[2].set(x2, y2);
  13977. corners[3].set(x, y2);
  13978. if (transform) {
  13979. for (var i = 0; i < 4; i++) {
  13980. corners[i].transform(transform);
  13981. }
  13982. }
  13983. Point.sub(axes[0], corners[1], corners[0]);
  13984. Point.sub(axes[1], corners[3], corners[0]);
  13985. axes[0].normalize();
  13986. axes[1].normalize();
  13987. for (var i = 0; i < 2; i++) {
  13988. this._origin[i] = axes[i].dot(corners[0]);
  13989. }
  13990. };
  13991. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13992. var overlapped = true;
  13993. var noMtv = !mtv;
  13994. minTv$1.set(Infinity, Infinity);
  13995. maxTv$1.set(0, 0);
  13996. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13997. overlapped = false;
  13998. if (noMtv) {
  13999. return overlapped;
  14000. }
  14001. }
  14002. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  14003. overlapped = false;
  14004. if (noMtv) {
  14005. return overlapped;
  14006. }
  14007. }
  14008. if (!noMtv) {
  14009. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  14010. }
  14011. return overlapped;
  14012. };
  14013. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  14014. var overlapped = true;
  14015. for (var i = 0; i < 2; i++) {
  14016. var axis = this._axes[i];
  14017. this._getProjMinMaxOnAxis(i, self._corners, extent);
  14018. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  14019. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  14020. overlapped = false;
  14021. if (noMtv) {
  14022. return overlapped;
  14023. }
  14024. var dist0 = Math.abs(extent2[0] - extent[1]);
  14025. var dist1 = Math.abs(extent[0] - extent2[1]);
  14026. if (Math.min(dist0, dist1) > maxTv.len()) {
  14027. if (dist0 < dist1) {
  14028. Point.scale(maxTv, axis, -dist0 * inverse);
  14029. }
  14030. else {
  14031. Point.scale(maxTv, axis, dist1 * inverse);
  14032. }
  14033. }
  14034. }
  14035. else if (minTv) {
  14036. var dist0 = Math.abs(extent2[0] - extent[1]);
  14037. var dist1 = Math.abs(extent[0] - extent2[1]);
  14038. if (Math.min(dist0, dist1) < minTv.len()) {
  14039. if (dist0 < dist1) {
  14040. Point.scale(minTv, axis, dist0 * inverse);
  14041. }
  14042. else {
  14043. Point.scale(minTv, axis, -dist1 * inverse);
  14044. }
  14045. }
  14046. }
  14047. }
  14048. return overlapped;
  14049. };
  14050. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  14051. var axis = this._axes[dim];
  14052. var origin = this._origin;
  14053. var proj = corners[0].dot(axis) + origin[dim];
  14054. var min = proj;
  14055. var max = proj;
  14056. for (var i = 1; i < corners.length; i++) {
  14057. var proj_1 = corners[i].dot(axis) + origin[dim];
  14058. min = Math.min(proj_1, min);
  14059. max = Math.max(proj_1, max);
  14060. }
  14061. out[0] = min;
  14062. out[1] = max;
  14063. };
  14064. return OrientedBoundingRect;
  14065. }());
  14066. var m = [];
  14067. var IncrementalDisplayable = (function (_super) {
  14068. __extends(IncrementalDisplayable, _super);
  14069. function IncrementalDisplayable() {
  14070. var _this = _super !== null && _super.apply(this, arguments) || this;
  14071. _this.notClear = true;
  14072. _this.incremental = true;
  14073. _this._displayables = [];
  14074. _this._temporaryDisplayables = [];
  14075. _this._cursor = 0;
  14076. return _this;
  14077. }
  14078. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14079. cb.call(context, this);
  14080. };
  14081. IncrementalDisplayable.prototype.useStyle = function () {
  14082. this.style = {};
  14083. };
  14084. IncrementalDisplayable.prototype.getCursor = function () {
  14085. return this._cursor;
  14086. };
  14087. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14088. this._cursor = this._displayables.length;
  14089. };
  14090. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14091. this._displayables = [];
  14092. this._temporaryDisplayables = [];
  14093. this._cursor = 0;
  14094. this.markRedraw();
  14095. this.notClear = false;
  14096. };
  14097. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14098. this._temporaryDisplayables = [];
  14099. };
  14100. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14101. if (notPersistent) {
  14102. this._temporaryDisplayables.push(displayable);
  14103. }
  14104. else {
  14105. this._displayables.push(displayable);
  14106. }
  14107. this.markRedraw();
  14108. };
  14109. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14110. notPersistent = notPersistent || false;
  14111. for (var i = 0; i < displayables.length; i++) {
  14112. this.addDisplayable(displayables[i], notPersistent);
  14113. }
  14114. };
  14115. IncrementalDisplayable.prototype.getDisplayables = function () {
  14116. return this._displayables;
  14117. };
  14118. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14119. return this._temporaryDisplayables;
  14120. };
  14121. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14122. for (var i = this._cursor; i < this._displayables.length; i++) {
  14123. cb && cb(this._displayables[i]);
  14124. }
  14125. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14126. cb && cb(this._temporaryDisplayables[i]);
  14127. }
  14128. };
  14129. IncrementalDisplayable.prototype.update = function () {
  14130. this.updateTransform();
  14131. for (var i = this._cursor; i < this._displayables.length; i++) {
  14132. var displayable = this._displayables[i];
  14133. displayable.parent = this;
  14134. displayable.update();
  14135. displayable.parent = null;
  14136. }
  14137. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14138. var displayable = this._temporaryDisplayables[i];
  14139. displayable.parent = this;
  14140. displayable.update();
  14141. displayable.parent = null;
  14142. }
  14143. };
  14144. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14145. if (!this._rect) {
  14146. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14147. for (var i = 0; i < this._displayables.length; i++) {
  14148. var displayable = this._displayables[i];
  14149. var childRect = displayable.getBoundingRect().clone();
  14150. if (displayable.needLocalTransform()) {
  14151. childRect.applyTransform(displayable.getLocalTransform(m));
  14152. }
  14153. rect.union(childRect);
  14154. }
  14155. this._rect = rect;
  14156. }
  14157. return this._rect;
  14158. };
  14159. IncrementalDisplayable.prototype.contain = function (x, y) {
  14160. var localPos = this.transformCoordToLocal(x, y);
  14161. var rect = this.getBoundingRect();
  14162. if (rect.contain(localPos[0], localPos[1])) {
  14163. for (var i = 0; i < this._displayables.length; i++) {
  14164. var displayable = this._displayables[i];
  14165. if (displayable.contain(x, y)) {
  14166. return true;
  14167. }
  14168. }
  14169. }
  14170. return false;
  14171. };
  14172. return IncrementalDisplayable;
  14173. }(Displayable));
  14174. // Stored properties for further transition.
  14175. var transitionStore = makeInner();
  14176. /**
  14177. * Return null if animation is disabled.
  14178. */
  14179. function getAnimationConfig(animationType, animatableModel, dataIndex,
  14180. // Extra opts can override the option in animatable model.
  14181. extraOpts,
  14182. // TODO It's only for pictorial bar now.
  14183. extraDelayParams) {
  14184. var animationPayload;
  14185. // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14186. // If animation is enabled. Will use this animation config in payload.
  14187. // If animation is disabled. Just ignore it.
  14188. if (animatableModel && animatableModel.ecModel) {
  14189. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14190. animationPayload = updatePayload && updatePayload.animation;
  14191. }
  14192. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14193. var isUpdate = animationType === 'update';
  14194. if (animationEnabled) {
  14195. var duration = void 0;
  14196. var easing = void 0;
  14197. var delay = void 0;
  14198. if (extraOpts) {
  14199. duration = retrieve2(extraOpts.duration, 200);
  14200. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14201. delay = 0;
  14202. } else {
  14203. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14204. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14205. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14206. }
  14207. // animation from payload has highest priority.
  14208. if (animationPayload) {
  14209. animationPayload.duration != null && (duration = animationPayload.duration);
  14210. animationPayload.easing != null && (easing = animationPayload.easing);
  14211. animationPayload.delay != null && (delay = animationPayload.delay);
  14212. }
  14213. if (isFunction(delay)) {
  14214. delay = delay(dataIndex, extraDelayParams);
  14215. }
  14216. if (isFunction(duration)) {
  14217. duration = duration(dataIndex);
  14218. }
  14219. var config = {
  14220. duration: duration || 0,
  14221. delay: delay,
  14222. easing: easing
  14223. };
  14224. return config;
  14225. } else {
  14226. return null;
  14227. }
  14228. }
  14229. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14230. var isFrom = false;
  14231. var removeOpt;
  14232. if (isFunction(dataIndex)) {
  14233. during = cb;
  14234. cb = dataIndex;
  14235. dataIndex = null;
  14236. } else if (isObject(dataIndex)) {
  14237. cb = dataIndex.cb;
  14238. during = dataIndex.during;
  14239. isFrom = dataIndex.isFrom;
  14240. removeOpt = dataIndex.removeOpt;
  14241. dataIndex = dataIndex.dataIndex;
  14242. }
  14243. var isRemove = animationType === 'leave';
  14244. if (!isRemove) {
  14245. // Must stop the remove animation.
  14246. el.stopAnimation('leave');
  14247. }
  14248. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14249. if (animationConfig && animationConfig.duration > 0) {
  14250. var duration = animationConfig.duration;
  14251. var animationDelay = animationConfig.delay;
  14252. var animationEasing = animationConfig.easing;
  14253. var animateConfig = {
  14254. duration: duration,
  14255. delay: animationDelay || 0,
  14256. easing: animationEasing,
  14257. done: cb,
  14258. force: !!cb || !!during,
  14259. // Set to final state in update/init animation.
  14260. // So the post processing based on the path shape can be done correctly.
  14261. setToFinal: !isRemove,
  14262. scope: animationType,
  14263. during: during
  14264. };
  14265. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14266. } else {
  14267. el.stopAnimation();
  14268. // If `isFrom`, the props is the "from" props.
  14269. !isFrom && el.attr(props);
  14270. // Call during at least once.
  14271. during && during(1);
  14272. cb && cb();
  14273. }
  14274. }
  14275. /**
  14276. * Update graphic element properties with or without animation according to the
  14277. * configuration in series.
  14278. *
  14279. * Caution: this method will stop previous animation.
  14280. * So do not use this method to one element twice before
  14281. * animation starts, unless you know what you are doing.
  14282. * @example
  14283. * graphic.updateProps(el, {
  14284. * position: [100, 100]
  14285. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14286. * // Or
  14287. * graphic.updateProps(el, {
  14288. * position: [100, 100]
  14289. * }, seriesModel, function () { console.log('Animation done!'); });
  14290. */
  14291. function updateProps(el, props,
  14292. // TODO: TYPE AnimatableModel
  14293. animatableModel, dataIndex, cb, during) {
  14294. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14295. }
  14296. /**
  14297. * Init graphic element properties with or without animation according to the
  14298. * configuration in series.
  14299. *
  14300. * Caution: this method will stop previous animation.
  14301. * So do not use this method to one element twice before
  14302. * animation starts, unless you know what you are doing.
  14303. */
  14304. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14305. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14306. }
  14307. /**
  14308. * If element is removed.
  14309. * It can determine if element is having remove animation.
  14310. */
  14311. function isElementRemoved(el) {
  14312. if (!el.__zr) {
  14313. return true;
  14314. }
  14315. for (var i = 0; i < el.animators.length; i++) {
  14316. var animator = el.animators[i];
  14317. if (animator.scope === 'leave') {
  14318. return true;
  14319. }
  14320. }
  14321. return false;
  14322. }
  14323. /**
  14324. * Remove graphic element
  14325. */
  14326. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14327. // Don't do remove animation twice.
  14328. if (isElementRemoved(el)) {
  14329. return;
  14330. }
  14331. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14332. }
  14333. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14334. el.removeTextContent();
  14335. el.removeTextGuideLine();
  14336. removeElement(el, {
  14337. style: {
  14338. opacity: 0
  14339. }
  14340. }, animatableModel, dataIndex, done);
  14341. }
  14342. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14343. function doRemove() {
  14344. el.parent && el.parent.remove(el);
  14345. }
  14346. // Hide label and labelLine first
  14347. // TODO Also use fade out animation?
  14348. if (!el.isGroup) {
  14349. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14350. } else {
  14351. el.traverse(function (disp) {
  14352. if (!disp.isGroup) {
  14353. // Can invoke doRemove multiple times.
  14354. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14355. }
  14356. });
  14357. }
  14358. }
  14359. /**
  14360. * Save old style for style transition in universalTransition module.
  14361. * It's used when element will be reused in each render.
  14362. * For chart like map, heatmap, which will always create new element.
  14363. * We don't need to save this because universalTransition can get old style from the old element
  14364. */
  14365. function saveOldStyle(el) {
  14366. transitionStore(el).oldStyle = el.style;
  14367. }
  14368. var mathMax$4 = Math.max;
  14369. var mathMin$4 = Math.min;
  14370. var _customShapeMap = {};
  14371. /**
  14372. * Extend shape with parameters
  14373. */
  14374. function extendShape(opts) {
  14375. return Path.extend(opts);
  14376. }
  14377. var extendPathFromString = extendFromString;
  14378. /**
  14379. * Extend path
  14380. */
  14381. function extendPath(pathData, opts) {
  14382. return extendPathFromString(pathData, opts);
  14383. }
  14384. /**
  14385. * Register a user defined shape.
  14386. * The shape class can be fetched by `getShapeClass`
  14387. * This method will overwrite the registered shapes, including
  14388. * the registered built-in shapes, if using the same `name`.
  14389. * The shape can be used in `custom series` and
  14390. * `graphic component` by declaring `{type: name}`.
  14391. *
  14392. * @param name
  14393. * @param ShapeClass Can be generated by `extendShape`.
  14394. */
  14395. function registerShape(name, ShapeClass) {
  14396. _customShapeMap[name] = ShapeClass;
  14397. }
  14398. /**
  14399. * Find shape class registered by `registerShape`. Usually used in
  14400. * fetching user defined shape.
  14401. *
  14402. * [Caution]:
  14403. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14404. * to use user registered shapes.
  14405. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14406. * `registerShape` by default. That enables users to get both built-in
  14407. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14408. * the built-in shapes by using names like 'circle', 'rect' via calling
  14409. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14410. * in case that it is overwritten by users, except that some features, like
  14411. * `custom series`, `graphic component`, do it deliberately.
  14412. *
  14413. * (2) In the features like `custom series`, `graphic component`, the user input
  14414. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14415. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14416. * are reserved names, that is, if some user registers a shape named `'image'`,
  14417. * the shape will not be used. If we intending to add some more reserved names
  14418. * in feature, that might bring break changes (disable some existing user shape
  14419. * names). But that case probably rarely happens. So we don't make more mechanism
  14420. * to resolve this issue here.
  14421. *
  14422. * @param name
  14423. * @return The shape class. If not found, return nothing.
  14424. */
  14425. function getShapeClass(name) {
  14426. if (_customShapeMap.hasOwnProperty(name)) {
  14427. return _customShapeMap[name];
  14428. }
  14429. }
  14430. /**
  14431. * Create a path element from path data string
  14432. * @param pathData
  14433. * @param opts
  14434. * @param rect
  14435. * @param layout 'center' or 'cover' default to be cover
  14436. */
  14437. function makePath(pathData, opts, rect, layout) {
  14438. var path = createFromString(pathData, opts);
  14439. if (rect) {
  14440. if (layout === 'center') {
  14441. rect = centerGraphic(rect, path.getBoundingRect());
  14442. }
  14443. resizePath(path, rect);
  14444. }
  14445. return path;
  14446. }
  14447. /**
  14448. * Create a image element from image url
  14449. * @param imageUrl image url
  14450. * @param opts options
  14451. * @param rect constrain rect
  14452. * @param layout 'center' or 'cover'. Default to be 'cover'
  14453. */
  14454. function makeImage(imageUrl, rect, layout) {
  14455. var zrImg = new ZRImage({
  14456. style: {
  14457. image: imageUrl,
  14458. x: rect.x,
  14459. y: rect.y,
  14460. width: rect.width,
  14461. height: rect.height
  14462. },
  14463. onload: function (img) {
  14464. if (layout === 'center') {
  14465. var boundingRect = {
  14466. width: img.width,
  14467. height: img.height
  14468. };
  14469. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14470. }
  14471. }
  14472. });
  14473. return zrImg;
  14474. }
  14475. /**
  14476. * Get position of centered element in bounding box.
  14477. *
  14478. * @param rect element local bounding box
  14479. * @param boundingRect constraint bounding box
  14480. * @return element position containing x, y, width, and height
  14481. */
  14482. function centerGraphic(rect, boundingRect) {
  14483. // Set rect to center, keep width / height ratio.
  14484. var aspect = boundingRect.width / boundingRect.height;
  14485. var width = rect.height * aspect;
  14486. var height;
  14487. if (width <= rect.width) {
  14488. height = rect.height;
  14489. } else {
  14490. width = rect.width;
  14491. height = width / aspect;
  14492. }
  14493. var cx = rect.x + rect.width / 2;
  14494. var cy = rect.y + rect.height / 2;
  14495. return {
  14496. x: cx - width / 2,
  14497. y: cy - height / 2,
  14498. width: width,
  14499. height: height
  14500. };
  14501. }
  14502. var mergePath$1 = mergePath;
  14503. /**
  14504. * Resize a path to fit the rect
  14505. * @param path
  14506. * @param rect
  14507. */
  14508. function resizePath(path, rect) {
  14509. if (!path.applyTransform) {
  14510. return;
  14511. }
  14512. var pathRect = path.getBoundingRect();
  14513. var m = pathRect.calculateTransform(rect);
  14514. path.applyTransform(m);
  14515. }
  14516. /**
  14517. * Sub pixel optimize line for canvas
  14518. */
  14519. function subPixelOptimizeLine$1(shape, lineWidth) {
  14520. subPixelOptimizeLine(shape, shape, {
  14521. lineWidth: lineWidth
  14522. });
  14523. return shape;
  14524. }
  14525. /**
  14526. * Sub pixel optimize rect for canvas
  14527. */
  14528. function subPixelOptimizeRect$1(param) {
  14529. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14530. return param;
  14531. }
  14532. /**
  14533. * Sub pixel optimize for canvas
  14534. *
  14535. * @param position Coordinate, such as x, y
  14536. * @param lineWidth Should be nonnegative integer.
  14537. * @param positiveOrNegative Default false (negative).
  14538. * @return Optimized position.
  14539. */
  14540. var subPixelOptimize$1 = subPixelOptimize;
  14541. /**
  14542. * Get transform matrix of target (param target),
  14543. * in coordinate of its ancestor (param ancestor)
  14544. *
  14545. * @param target
  14546. * @param [ancestor]
  14547. */
  14548. function getTransform(target, ancestor) {
  14549. var mat = identity([]);
  14550. while (target && target !== ancestor) {
  14551. mul$1(mat, target.getLocalTransform(), mat);
  14552. target = target.parent;
  14553. }
  14554. return mat;
  14555. }
  14556. /**
  14557. * Apply transform to an vertex.
  14558. * @param target [x, y]
  14559. * @param transform Can be:
  14560. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14561. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14562. * @param invert Whether use invert matrix.
  14563. * @return [x, y]
  14564. */
  14565. function applyTransform$1(target, transform, invert$1) {
  14566. if (transform && !isArrayLike(transform)) {
  14567. transform = Transformable.getLocalTransform(transform);
  14568. }
  14569. if (invert$1) {
  14570. transform = invert([], transform);
  14571. }
  14572. return applyTransform([], target, transform);
  14573. }
  14574. /**
  14575. * @param direction 'left' 'right' 'top' 'bottom'
  14576. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14577. * @param invert Whether use invert matrix.
  14578. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14579. */
  14580. function transformDirection(direction, transform, invert) {
  14581. // Pick a base, ensure that transform result will not be (0, 0).
  14582. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14583. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14584. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14585. vertex = applyTransform$1(vertex, transform, invert);
  14586. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14587. }
  14588. function isNotGroup(el) {
  14589. return !el.isGroup;
  14590. }
  14591. function isPath(el) {
  14592. return el.shape != null;
  14593. }
  14594. /**
  14595. * Apply group transition animation from g1 to g2.
  14596. * If no animatableModel, no animation.
  14597. */
  14598. function groupTransition(g1, g2, animatableModel) {
  14599. if (!g1 || !g2) {
  14600. return;
  14601. }
  14602. function getElMap(g) {
  14603. var elMap = {};
  14604. g.traverse(function (el) {
  14605. if (isNotGroup(el) && el.anid) {
  14606. elMap[el.anid] = el;
  14607. }
  14608. });
  14609. return elMap;
  14610. }
  14611. function getAnimatableProps(el) {
  14612. var obj = {
  14613. x: el.x,
  14614. y: el.y,
  14615. rotation: el.rotation
  14616. };
  14617. if (isPath(el)) {
  14618. obj.shape = extend({}, el.shape);
  14619. }
  14620. return obj;
  14621. }
  14622. var elMap1 = getElMap(g1);
  14623. g2.traverse(function (el) {
  14624. if (isNotGroup(el) && el.anid) {
  14625. var oldEl = elMap1[el.anid];
  14626. if (oldEl) {
  14627. var newProp = getAnimatableProps(el);
  14628. el.attr(getAnimatableProps(oldEl));
  14629. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14630. }
  14631. }
  14632. });
  14633. }
  14634. function clipPointsByRect(points, rect) {
  14635. // FIXME: This way might be incorrect when graphic clipped by a corner
  14636. // and when element has a border.
  14637. return map(points, function (point) {
  14638. var x = point[0];
  14639. x = mathMax$4(x, rect.x);
  14640. x = mathMin$4(x, rect.x + rect.width);
  14641. var y = point[1];
  14642. y = mathMax$4(y, rect.y);
  14643. y = mathMin$4(y, rect.y + rect.height);
  14644. return [x, y];
  14645. });
  14646. }
  14647. /**
  14648. * Return a new clipped rect. If rect size are negative, return undefined.
  14649. */
  14650. function clipRectByRect(targetRect, rect) {
  14651. var x = mathMax$4(targetRect.x, rect.x);
  14652. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14653. var y = mathMax$4(targetRect.y, rect.y);
  14654. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height);
  14655. // If the total rect is cliped, nothing, including the border,
  14656. // should be painted. So return undefined.
  14657. if (x2 >= x && y2 >= y) {
  14658. return {
  14659. x: x,
  14660. y: y,
  14661. width: x2 - x,
  14662. height: y2 - y
  14663. };
  14664. }
  14665. }
  14666. function createIcon(iconStr,
  14667. // Support 'image://' or 'path://' or direct svg path.
  14668. opt, rect) {
  14669. var innerOpts = extend({
  14670. rectHover: true
  14671. }, opt);
  14672. var style = innerOpts.style = {
  14673. strokeNoScale: true
  14674. };
  14675. rect = rect || {
  14676. x: -1,
  14677. y: -1,
  14678. width: 2,
  14679. height: 2
  14680. };
  14681. if (iconStr) {
  14682. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14683. }
  14684. }
  14685. /**
  14686. * Return `true` if the given line (line `a`) and the given polygon
  14687. * are intersect.
  14688. * Note that we do not count colinear as intersect here because no
  14689. * requirement for that. We could do that if required in future.
  14690. */
  14691. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14692. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14693. var p = points[i];
  14694. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14695. return true;
  14696. }
  14697. p2 = p;
  14698. }
  14699. }
  14700. /**
  14701. * Return `true` if the given two lines (line `a` and line `b`)
  14702. * are intersect.
  14703. * Note that we do not count colinear as intersect here because no
  14704. * requirement for that. We could do that if required in future.
  14705. */
  14706. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14707. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14708. var mx = a2x - a1x;
  14709. var my = a2y - a1y;
  14710. var nx = b2x - b1x;
  14711. var ny = b2y - b1y;
  14712. // `vec_m` and `vec_n` are parallel iff
  14713. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14714. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14715. if (nearZero(nmCrossProduct)) {
  14716. return false;
  14717. }
  14718. // `vec_m` and `vec_n` are intersect iff
  14719. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14720. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14721. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14722. var b1a1x = a1x - b1x;
  14723. var b1a1y = a1y - b1y;
  14724. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14725. if (q < 0 || q > 1) {
  14726. return false;
  14727. }
  14728. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14729. if (p < 0 || p > 1) {
  14730. return false;
  14731. }
  14732. return true;
  14733. }
  14734. /**
  14735. * Cross product of 2-dimension vector.
  14736. */
  14737. function crossProduct2d(x1, y1, x2, y2) {
  14738. return x1 * y2 - x2 * y1;
  14739. }
  14740. function nearZero(val) {
  14741. return val <= 1e-6 && val >= -1e-6;
  14742. }
  14743. function setTooltipConfig(opt) {
  14744. var itemTooltipOption = opt.itemTooltipOption;
  14745. var componentModel = opt.componentModel;
  14746. var itemName = opt.itemName;
  14747. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14748. formatter: itemTooltipOption
  14749. } : itemTooltipOption;
  14750. var mainType = componentModel.mainType;
  14751. var componentIndex = componentModel.componentIndex;
  14752. var formatterParams = {
  14753. componentType: mainType,
  14754. name: itemName,
  14755. $vars: ['name']
  14756. };
  14757. formatterParams[mainType + 'Index'] = componentIndex;
  14758. var formatterParamsExtra = opt.formatterParamsExtra;
  14759. if (formatterParamsExtra) {
  14760. each(keys(formatterParamsExtra), function (key) {
  14761. if (!hasOwn(formatterParams, key)) {
  14762. formatterParams[key] = formatterParamsExtra[key];
  14763. formatterParams.$vars.push(key);
  14764. }
  14765. });
  14766. }
  14767. var ecData = getECData(opt.el);
  14768. ecData.componentMainType = mainType;
  14769. ecData.componentIndex = componentIndex;
  14770. ecData.tooltipConfig = {
  14771. name: itemName,
  14772. option: defaults({
  14773. content: itemName,
  14774. encodeHTMLContent: true,
  14775. formatterParams: formatterParams
  14776. }, itemTooltipOptionObj)
  14777. };
  14778. }
  14779. function traverseElement(el, cb) {
  14780. var stopped;
  14781. // TODO
  14782. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14783. if (el.isGroup) {
  14784. stopped = cb(el);
  14785. }
  14786. if (!stopped) {
  14787. el.traverse(cb);
  14788. }
  14789. }
  14790. function traverseElements(els, cb) {
  14791. if (els) {
  14792. if (isArray(els)) {
  14793. for (var i = 0; i < els.length; i++) {
  14794. traverseElement(els[i], cb);
  14795. }
  14796. } else {
  14797. traverseElement(els, cb);
  14798. }
  14799. }
  14800. }
  14801. // Register built-in shapes. These shapes might be overwritten
  14802. // by users, although we do not recommend that.
  14803. registerShape('circle', Circle);
  14804. registerShape('ellipse', Ellipse);
  14805. registerShape('sector', Sector);
  14806. registerShape('ring', Ring);
  14807. registerShape('polygon', Polygon);
  14808. registerShape('polyline', Polyline);
  14809. registerShape('rect', Rect);
  14810. registerShape('line', Line);
  14811. registerShape('bezierCurve', BezierCurve);
  14812. registerShape('arc', Arc);
  14813. var graphic = /*#__PURE__*/Object.freeze({
  14814. __proto__: null,
  14815. updateProps: updateProps,
  14816. initProps: initProps,
  14817. removeElement: removeElement,
  14818. removeElementWithFadeOut: removeElementWithFadeOut,
  14819. isElementRemoved: isElementRemoved,
  14820. extendShape: extendShape,
  14821. extendPath: extendPath,
  14822. registerShape: registerShape,
  14823. getShapeClass: getShapeClass,
  14824. makePath: makePath,
  14825. makeImage: makeImage,
  14826. mergePath: mergePath$1,
  14827. resizePath: resizePath,
  14828. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14829. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14830. subPixelOptimize: subPixelOptimize$1,
  14831. getTransform: getTransform,
  14832. applyTransform: applyTransform$1,
  14833. transformDirection: transformDirection,
  14834. groupTransition: groupTransition,
  14835. clipPointsByRect: clipPointsByRect,
  14836. clipRectByRect: clipRectByRect,
  14837. createIcon: createIcon,
  14838. linePolygonIntersect: linePolygonIntersect,
  14839. lineLineIntersect: lineLineIntersect,
  14840. setTooltipConfig: setTooltipConfig,
  14841. traverseElements: traverseElements,
  14842. Group: Group,
  14843. Image: ZRImage,
  14844. Text: ZRText,
  14845. Circle: Circle,
  14846. Ellipse: Ellipse,
  14847. Sector: Sector,
  14848. Ring: Ring,
  14849. Polygon: Polygon,
  14850. Polyline: Polyline,
  14851. Rect: Rect,
  14852. Line: Line,
  14853. BezierCurve: BezierCurve,
  14854. Arc: Arc,
  14855. IncrementalDisplayable: IncrementalDisplayable,
  14856. CompoundPath: CompoundPath,
  14857. LinearGradient: LinearGradient,
  14858. RadialGradient: RadialGradient,
  14859. BoundingRect: BoundingRect,
  14860. OrientedBoundingRect: OrientedBoundingRect,
  14861. Point: Point,
  14862. Path: Path
  14863. });
  14864. var EMPTY_OBJ = {};
  14865. function setLabelText(label, labelTexts) {
  14866. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14867. var stateName = SPECIAL_STATES[i];
  14868. var text = labelTexts[stateName];
  14869. var state = label.ensureState(stateName);
  14870. state.style = state.style || {};
  14871. state.style.text = text;
  14872. }
  14873. var oldStates = label.currentStates.slice();
  14874. label.clearStates(true);
  14875. label.setStyle({
  14876. text: labelTexts.normal
  14877. });
  14878. label.useStates(oldStates, true);
  14879. }
  14880. function getLabelText(opt, stateModels, interpolatedValue) {
  14881. var labelFetcher = opt.labelFetcher;
  14882. var labelDataIndex = opt.labelDataIndex;
  14883. var labelDimIndex = opt.labelDimIndex;
  14884. var normalModel = stateModels.normal;
  14885. var baseText;
  14886. if (labelFetcher) {
  14887. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14888. interpolatedValue: interpolatedValue
  14889. } : null);
  14890. }
  14891. if (baseText == null) {
  14892. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14893. }
  14894. var statesText = {
  14895. normal: baseText
  14896. };
  14897. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14898. var stateName = SPECIAL_STATES[i];
  14899. var stateModel = stateModels[stateName];
  14900. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14901. }
  14902. return statesText;
  14903. }
  14904. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified
  14905. // TODO specified position?
  14906. ) {
  14907. opt = opt || EMPTY_OBJ;
  14908. var isSetOnText = targetEl instanceof ZRText;
  14909. var needsCreateText = false;
  14910. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14911. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14912. if (stateModel && stateModel.getShallow('show')) {
  14913. needsCreateText = true;
  14914. break;
  14915. }
  14916. }
  14917. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14918. if (needsCreateText) {
  14919. if (!isSetOnText) {
  14920. // Reuse the previous
  14921. if (!textContent) {
  14922. textContent = new ZRText();
  14923. targetEl.setTextContent(textContent);
  14924. }
  14925. // Use same state proxy
  14926. if (targetEl.stateProxy) {
  14927. textContent.stateProxy = targetEl.stateProxy;
  14928. }
  14929. }
  14930. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14931. var normalModel = labelStatesModels.normal;
  14932. var showNormal = !!normalModel.getShallow('show');
  14933. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14934. normalStyle.text = labelStatesTexts.normal;
  14935. if (!isSetOnText) {
  14936. // Always create new
  14937. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14938. }
  14939. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14940. var stateName = SPECIAL_STATES[i];
  14941. var stateModel = labelStatesModels[stateName];
  14942. if (stateModel) {
  14943. var stateObj = textContent.ensureState(stateName);
  14944. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14945. if (stateShow !== showNormal) {
  14946. stateObj.ignore = !stateShow;
  14947. }
  14948. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14949. stateObj.style.text = labelStatesTexts[stateName];
  14950. if (!isSetOnText) {
  14951. var targetElEmphasisState = targetEl.ensureState(stateName);
  14952. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14953. }
  14954. }
  14955. }
  14956. // PENDING: if there is many requirements that emphasis position
  14957. // need to be different from normal position, we might consider
  14958. // auto silent is those cases.
  14959. textContent.silent = !!normalModel.getShallow('silent');
  14960. // Keep x and y
  14961. if (textContent.style.x != null) {
  14962. normalStyle.x = textContent.style.x;
  14963. }
  14964. if (textContent.style.y != null) {
  14965. normalStyle.y = textContent.style.y;
  14966. }
  14967. textContent.ignore = !showNormal;
  14968. // Always create new style.
  14969. textContent.useStyle(normalStyle);
  14970. textContent.dirty();
  14971. if (opt.enableTextSetter) {
  14972. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14973. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14974. setLabelText(textContent, labelStatesTexts);
  14975. };
  14976. }
  14977. } else if (textContent) {
  14978. // Not display rich text.
  14979. textContent.ignore = true;
  14980. }
  14981. targetEl.dirty();
  14982. }
  14983. function getLabelStatesModels(itemModel, labelName) {
  14984. labelName = labelName || 'label';
  14985. var statesModels = {
  14986. normal: itemModel.getModel(labelName)
  14987. };
  14988. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14989. var stateName = SPECIAL_STATES[i];
  14990. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14991. }
  14992. return statesModels;
  14993. }
  14994. /**
  14995. * Set basic textStyle properties.
  14996. */
  14997. function createTextStyle(textStyleModel, specifiedTextStyle,
  14998. // Fixed style in the code. Can't be set by model.
  14999. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  15000. ) {
  15001. var textStyle = {};
  15002. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  15003. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15004. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15005. return textStyle;
  15006. }
  15007. function createTextConfig(textStyleModel, opt, isNotNormal) {
  15008. opt = opt || {};
  15009. var textConfig = {};
  15010. var labelPosition;
  15011. var labelRotate = textStyleModel.getShallow('rotate');
  15012. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  15013. var labelOffset = textStyleModel.getShallow('offset');
  15014. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside');
  15015. // 'outside' is not a valid zr textPostion value, but used
  15016. // in bar series, and magric type should be considered.
  15017. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  15018. if (labelPosition != null) {
  15019. textConfig.position = labelPosition;
  15020. }
  15021. if (labelOffset != null) {
  15022. textConfig.offset = labelOffset;
  15023. }
  15024. if (labelRotate != null) {
  15025. labelRotate *= Math.PI / 180;
  15026. textConfig.rotation = labelRotate;
  15027. }
  15028. if (labelDistance != null) {
  15029. textConfig.distance = labelDistance;
  15030. }
  15031. // fill and auto is determined by the color of path fill if it's not specified by developers.
  15032. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  15033. return textConfig;
  15034. }
  15035. /**
  15036. * The uniform entry of set text style, that is, retrieve style definitions
  15037. * from `model` and set to `textStyle` object.
  15038. *
  15039. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15040. * properties will be set. (Consider the states of normal and emphasis and
  15041. * default value can be adopted, merge would make the logic too complicated
  15042. * to manage.)
  15043. */
  15044. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  15045. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15046. opt = opt || EMPTY_OBJ;
  15047. var ecModel = textStyleModel.ecModel;
  15048. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15049. // Consider case:
  15050. // {
  15051. // data: [{
  15052. // value: 12,
  15053. // label: {
  15054. // rich: {
  15055. // // no 'a' here but using parent 'a'.
  15056. // }
  15057. // }
  15058. // }],
  15059. // rich: {
  15060. // a: { ... }
  15061. // }
  15062. // }
  15063. var richItemNames = getRichItemNames(textStyleModel);
  15064. var richResult;
  15065. if (richItemNames) {
  15066. richResult = {};
  15067. for (var name_1 in richItemNames) {
  15068. if (richItemNames.hasOwnProperty(name_1)) {
  15069. // Cascade is supported in rich.
  15070. var richTextStyle = textStyleModel.getModel(['rich', name_1]);
  15071. // In rich, never `disableBox`.
  15072. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15073. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15074. // That might confuses users. So probably we should put `textStyleModel` as the
  15075. // root ancestor of the `richTextStyle`. But that would be a break change.
  15076. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  15077. }
  15078. }
  15079. }
  15080. if (richResult) {
  15081. textStyle.rich = richResult;
  15082. }
  15083. var overflow = textStyleModel.get('overflow');
  15084. if (overflow) {
  15085. textStyle.overflow = overflow;
  15086. }
  15087. var margin = textStyleModel.get('minMargin');
  15088. if (margin != null) {
  15089. textStyle.margin = margin;
  15090. }
  15091. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  15092. }
  15093. // Consider case:
  15094. // {
  15095. // data: [{
  15096. // value: 12,
  15097. // label: {
  15098. // rich: {
  15099. // // no 'a' here but using parent 'a'.
  15100. // }
  15101. // }
  15102. // }],
  15103. // rich: {
  15104. // a: { ... }
  15105. // }
  15106. // }
  15107. // TODO TextStyleModel
  15108. function getRichItemNames(textStyleModel) {
  15109. // Use object to remove duplicated names.
  15110. var richItemNameMap;
  15111. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15112. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15113. if (rich) {
  15114. richItemNameMap = richItemNameMap || {};
  15115. var richKeys = keys(rich);
  15116. for (var i = 0; i < richKeys.length; i++) {
  15117. var richKey = richKeys[i];
  15118. richItemNameMap[richKey] = 1;
  15119. }
  15120. }
  15121. textStyleModel = textStyleModel.parentModel;
  15122. }
  15123. return richItemNameMap;
  15124. }
  15125. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15126. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign', 'ellipsis'];
  15127. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15128. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  15129. // In merge mode, default value should not be given.
  15130. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15131. var inheritColor = opt && opt.inheritColor;
  15132. var fillColor = textStyleModel.getShallow('color');
  15133. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15134. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15135. if (fillColor === 'inherit' || fillColor === 'auto') {
  15136. if ("development" !== 'production') {
  15137. if (fillColor === 'auto') {
  15138. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15139. }
  15140. }
  15141. if (inheritColor) {
  15142. fillColor = inheritColor;
  15143. } else {
  15144. fillColor = null;
  15145. }
  15146. }
  15147. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15148. if ("development" !== 'production') {
  15149. if (strokeColor === 'auto') {
  15150. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15151. }
  15152. }
  15153. if (inheritColor) {
  15154. strokeColor = inheritColor;
  15155. } else {
  15156. strokeColor = null;
  15157. }
  15158. }
  15159. if (!isAttached) {
  15160. // Only use default global textStyle.color if text is individual.
  15161. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15162. fillColor = fillColor || globalTextStyle.color;
  15163. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15164. }
  15165. if (fillColor != null) {
  15166. textStyle.fill = fillColor;
  15167. }
  15168. if (strokeColor != null) {
  15169. textStyle.stroke = strokeColor;
  15170. }
  15171. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15172. if (textBorderWidth != null) {
  15173. textStyle.lineWidth = textBorderWidth;
  15174. }
  15175. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15176. if (textBorderType != null) {
  15177. textStyle.lineDash = textBorderType;
  15178. }
  15179. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15180. if (textBorderDashOffset != null) {
  15181. textStyle.lineDashOffset = textBorderDashOffset;
  15182. }
  15183. if (!isNotNormal && opacity == null && !inRich) {
  15184. opacity = opt && opt.defaultOpacity;
  15185. }
  15186. if (opacity != null) {
  15187. textStyle.opacity = opacity;
  15188. }
  15189. // TODO
  15190. if (!isNotNormal && !isAttached) {
  15191. // Set default finally.
  15192. if (textStyle.fill == null && opt.inheritColor) {
  15193. textStyle.fill = opt.inheritColor;
  15194. }
  15195. }
  15196. // Do not use `getFont` here, because merge should be supported, where
  15197. // part of these properties may be changed in emphasis style, and the
  15198. // others should remain their original value got from normal style.
  15199. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15200. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15201. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15202. if (val != null) {
  15203. textStyle[key] = val;
  15204. }
  15205. }
  15206. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15207. var key = TEXT_PROPS_SELF[i];
  15208. var val = textStyleModel.getShallow(key);
  15209. if (val != null) {
  15210. textStyle[key] = val;
  15211. }
  15212. }
  15213. if (textStyle.verticalAlign == null) {
  15214. var baseline = textStyleModel.getShallow('baseline');
  15215. if (baseline != null) {
  15216. textStyle.verticalAlign = baseline;
  15217. }
  15218. }
  15219. if (!isBlock || !opt.disableBox) {
  15220. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15221. var key = TEXT_PROPS_BOX[i];
  15222. var val = textStyleModel.getShallow(key);
  15223. if (val != null) {
  15224. textStyle[key] = val;
  15225. }
  15226. }
  15227. var borderType = textStyleModel.getShallow('borderType');
  15228. if (borderType != null) {
  15229. textStyle.borderDash = borderType;
  15230. }
  15231. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15232. if ("development" !== 'production') {
  15233. if (textStyle.backgroundColor === 'auto') {
  15234. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15235. }
  15236. }
  15237. textStyle.backgroundColor = inheritColor;
  15238. }
  15239. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15240. if ("development" !== 'production') {
  15241. if (textStyle.borderColor === 'auto') {
  15242. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15243. }
  15244. }
  15245. textStyle.borderColor = inheritColor;
  15246. }
  15247. }
  15248. }
  15249. function getFont(opt, ecModel) {
  15250. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15251. return trim([
  15252. // FIXME in node-canvas fontWeight is before fontStyle
  15253. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'].join(' '));
  15254. }
  15255. var labelInner = makeInner();
  15256. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15257. if (!label) {
  15258. return;
  15259. }
  15260. var obj = labelInner(label);
  15261. obj.prevValue = obj.value;
  15262. obj.value = value;
  15263. var normalLabelModel = labelStatesModels.normal;
  15264. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15265. if (obj.valueAnimation) {
  15266. obj.precision = normalLabelModel.get('precision');
  15267. obj.defaultInterpolatedText = getDefaultText;
  15268. obj.statesModels = labelStatesModels;
  15269. }
  15270. }
  15271. var PATH_COLOR = ['textStyle', 'color'];
  15272. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow'];
  15273. // TODO Performance improvement?
  15274. var tmpText = new ZRText();
  15275. var TextStyleMixin = /** @class */function () {
  15276. function TextStyleMixin() {}
  15277. /**
  15278. * Get color property or get color from option.textStyle.color
  15279. */
  15280. // TODO Callback
  15281. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15282. var ecModel = this.ecModel;
  15283. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15284. };
  15285. /**
  15286. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15287. * @return {string}
  15288. */
  15289. TextStyleMixin.prototype.getFont = function () {
  15290. return getFont({
  15291. fontStyle: this.getShallow('fontStyle'),
  15292. fontWeight: this.getShallow('fontWeight'),
  15293. fontSize: this.getShallow('fontSize'),
  15294. fontFamily: this.getShallow('fontFamily')
  15295. }, this.ecModel);
  15296. };
  15297. TextStyleMixin.prototype.getTextRect = function (text) {
  15298. var style = {
  15299. text: text,
  15300. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15301. };
  15302. for (var i = 0; i < textStyleParams.length; i++) {
  15303. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15304. }
  15305. tmpText.useStyle(style);
  15306. tmpText.update();
  15307. return tmpText.getBoundingRect();
  15308. };
  15309. return TextStyleMixin;
  15310. }();
  15311. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit']
  15312. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15313. // So do not transfer decal directly.
  15314. ];
  15315. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15316. var LineStyleMixin = /** @class */function () {
  15317. function LineStyleMixin() {}
  15318. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15319. return getLineStyle(this, excludes);
  15320. };
  15321. return LineStyleMixin;
  15322. }();
  15323. var ITEM_STYLE_KEY_MAP = [['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'borderType'], ['lineDashOffset', 'borderDashOffset'], ['lineCap', 'borderCap'], ['lineJoin', 'borderJoin'], ['miterLimit', 'borderMiterLimit']
  15324. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15325. // So do not transfer decal directly.
  15326. ];
  15327. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15328. var ItemStyleMixin = /** @class */function () {
  15329. function ItemStyleMixin() {}
  15330. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15331. return getItemStyle(this, excludes, includes);
  15332. };
  15333. return ItemStyleMixin;
  15334. }();
  15335. var Model = /** @class */function () {
  15336. function Model(option, parentModel, ecModel) {
  15337. this.parentModel = parentModel;
  15338. this.ecModel = ecModel;
  15339. this.option = option;
  15340. // Simple optimization
  15341. // if (this.init) {
  15342. // if (arguments.length <= 4) {
  15343. // this.init(option, parentModel, ecModel, extraOpt);
  15344. // }
  15345. // else {
  15346. // this.init.apply(this, arguments);
  15347. // }
  15348. // }
  15349. }
  15350. Model.prototype.init = function (option, parentModel, ecModel) {
  15351. var rest = [];
  15352. for (var _i = 3; _i < arguments.length; _i++) {
  15353. rest[_i - 3] = arguments[_i];
  15354. }
  15355. };
  15356. /**
  15357. * Merge the input option to me.
  15358. */
  15359. Model.prototype.mergeOption = function (option, ecModel) {
  15360. merge(this.option, option, true);
  15361. };
  15362. // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15363. // TODO: TYPE strict key check?
  15364. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15365. Model.prototype.get = function (path, ignoreParent) {
  15366. if (path == null) {
  15367. return this.option;
  15368. }
  15369. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15370. };
  15371. Model.prototype.getShallow = function (key, ignoreParent) {
  15372. var option = this.option;
  15373. var val = option == null ? option : option[key];
  15374. if (val == null && !ignoreParent) {
  15375. var parentModel = this.parentModel;
  15376. if (parentModel) {
  15377. // FIXME:TS do not know how to make it works
  15378. val = parentModel.getShallow(key);
  15379. }
  15380. }
  15381. return val;
  15382. };
  15383. // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15384. // getModel(path: string | string[], parentModel?: Model): Model;
  15385. // TODO 'a.b.c' is deprecated
  15386. Model.prototype.getModel = function (path, parentModel) {
  15387. var hasPath = path != null;
  15388. var pathFinal = hasPath ? this.parsePath(path) : null;
  15389. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15390. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15391. return new Model(obj, parentModel, this.ecModel);
  15392. };
  15393. /**
  15394. * If model has option
  15395. */
  15396. Model.prototype.isEmpty = function () {
  15397. return this.option == null;
  15398. };
  15399. Model.prototype.restoreData = function () {};
  15400. // Pending
  15401. Model.prototype.clone = function () {
  15402. var Ctor = this.constructor;
  15403. return new Ctor(clone(this.option));
  15404. };
  15405. // setReadOnly(properties): void {
  15406. // clazzUtil.setReadOnly(this, properties);
  15407. // }
  15408. // If path is null/undefined, return null/undefined.
  15409. Model.prototype.parsePath = function (path) {
  15410. if (typeof path === 'string') {
  15411. return path.split('.');
  15412. }
  15413. return path;
  15414. };
  15415. // Resolve path for parent. Perhaps useful when parent use a different property.
  15416. // Default to be a identity resolver.
  15417. // Can be modified to a different resolver.
  15418. Model.prototype.resolveParentPath = function (path) {
  15419. return path;
  15420. };
  15421. // FIXME:TS check whether put this method here
  15422. Model.prototype.isAnimationEnabled = function () {
  15423. if (!env.node && this.option) {
  15424. if (this.option.animation != null) {
  15425. return !!this.option.animation;
  15426. } else if (this.parentModel) {
  15427. return this.parentModel.isAnimationEnabled();
  15428. }
  15429. }
  15430. };
  15431. Model.prototype._doGet = function (pathArr, parentModel) {
  15432. var obj = this.option;
  15433. if (!pathArr) {
  15434. return obj;
  15435. }
  15436. for (var i = 0; i < pathArr.length; i++) {
  15437. // Ignore empty
  15438. if (!pathArr[i]) {
  15439. continue;
  15440. }
  15441. // obj could be number/string/... (like 0)
  15442. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15443. if (obj == null) {
  15444. break;
  15445. }
  15446. }
  15447. if (obj == null && parentModel) {
  15448. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15449. }
  15450. return obj;
  15451. };
  15452. return Model;
  15453. }();
  15454. // Enable Model.extend.
  15455. enableClassExtend(Model);
  15456. enableClassCheck(Model);
  15457. mixin(Model, LineStyleMixin);
  15458. mixin(Model, ItemStyleMixin);
  15459. mixin(Model, AreaStyleMixin);
  15460. mixin(Model, TextStyleMixin);
  15461. // A random offset
  15462. var base = Math.round(Math.random() * 10);
  15463. /**
  15464. * @public
  15465. * @param {string} type
  15466. * @return {string}
  15467. */
  15468. function getUID(type) {
  15469. // Considering the case of crossing js context,
  15470. // use Math.random to make id as unique as possible.
  15471. return [type || '', base++].join('_');
  15472. }
  15473. /**
  15474. * Implements `SubTypeDefaulterManager` for `target`.
  15475. */
  15476. function enableSubTypeDefaulter(target) {
  15477. var subTypeDefaulters = {};
  15478. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15479. var componentTypeInfo = parseClassType(componentType);
  15480. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15481. };
  15482. target.determineSubType = function (componentType, option) {
  15483. var type = option.type;
  15484. if (!type) {
  15485. var componentTypeMain = parseClassType(componentType).main;
  15486. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15487. type = subTypeDefaulters[componentTypeMain](option);
  15488. }
  15489. }
  15490. return type;
  15491. };
  15492. }
  15493. /**
  15494. * Implements `TopologicalTravelable<any>` for `entity`.
  15495. *
  15496. * Topological travel on Activity Network (Activity On Vertices).
  15497. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15498. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15499. * If there is circular dependencey, Error will be thrown.
  15500. */
  15501. function enableTopologicalTravel(entity, dependencyGetter) {
  15502. /**
  15503. * @param targetNameList Target Component type list.
  15504. * Can be ['aa', 'bb', 'aa.xx']
  15505. * @param fullNameList By which we can build dependency graph.
  15506. * @param callback Params: componentType, dependencies.
  15507. * @param context Scope of callback.
  15508. */
  15509. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15510. if (!targetNameList.length) {
  15511. return;
  15512. }
  15513. var result = makeDepndencyGraph(fullNameList);
  15514. var graph = result.graph;
  15515. var noEntryList = result.noEntryList;
  15516. var targetNameSet = {};
  15517. each(targetNameList, function (name) {
  15518. targetNameSet[name] = true;
  15519. });
  15520. while (noEntryList.length) {
  15521. var currComponentType = noEntryList.pop();
  15522. var currVertex = graph[currComponentType];
  15523. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15524. if (isInTargetNameSet) {
  15525. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15526. delete targetNameSet[currComponentType];
  15527. }
  15528. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15529. }
  15530. each(targetNameSet, function () {
  15531. var errMsg = '';
  15532. if ("development" !== 'production') {
  15533. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15534. }
  15535. throw new Error(errMsg);
  15536. });
  15537. function removeEdge(succComponentType) {
  15538. graph[succComponentType].entryCount--;
  15539. if (graph[succComponentType].entryCount === 0) {
  15540. noEntryList.push(succComponentType);
  15541. }
  15542. }
  15543. // Consider this case: legend depends on series, and we call
  15544. // chart.setOption({series: [...]}), where only series is in option.
  15545. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15546. // not be called, but only sereis.mergeOption is called. Thus legend
  15547. // have no chance to update its local record about series (like which
  15548. // name of series is available in legend).
  15549. function removeEdgeAndAdd(succComponentType) {
  15550. targetNameSet[succComponentType] = true;
  15551. removeEdge(succComponentType);
  15552. }
  15553. };
  15554. function makeDepndencyGraph(fullNameList) {
  15555. var graph = {};
  15556. var noEntryList = [];
  15557. each(fullNameList, function (name) {
  15558. var thisItem = createDependencyGraphItem(graph, name);
  15559. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15560. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15561. thisItem.entryCount = availableDeps.length;
  15562. if (thisItem.entryCount === 0) {
  15563. noEntryList.push(name);
  15564. }
  15565. each(availableDeps, function (dependentName) {
  15566. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15567. thisItem.predecessor.push(dependentName);
  15568. }
  15569. var thatItem = createDependencyGraphItem(graph, dependentName);
  15570. if (indexOf(thatItem.successor, dependentName) < 0) {
  15571. thatItem.successor.push(name);
  15572. }
  15573. });
  15574. });
  15575. return {
  15576. graph: graph,
  15577. noEntryList: noEntryList
  15578. };
  15579. }
  15580. function createDependencyGraphItem(graph, name) {
  15581. if (!graph[name]) {
  15582. graph[name] = {
  15583. predecessor: [],
  15584. successor: []
  15585. };
  15586. }
  15587. return graph[name];
  15588. }
  15589. function getAvailableDependencies(originalDeps, fullNameList) {
  15590. var availableDeps = [];
  15591. each(originalDeps, function (dep) {
  15592. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15593. });
  15594. return availableDeps;
  15595. }
  15596. }
  15597. function inheritDefaultOption(superOption, subOption) {
  15598. // See also `model/Component.ts#getDefaultOption`
  15599. return merge(merge({}, superOption, true), subOption, true);
  15600. }
  15601. /*
  15602. * Licensed to the Apache Software Foundation (ASF) under one
  15603. * or more contributor license agreements. See the NOTICE file
  15604. * distributed with this work for additional information
  15605. * regarding copyright ownership. The ASF licenses this file
  15606. * to you under the Apache License, Version 2.0 (the
  15607. * "License"); you may not use this file except in compliance
  15608. * with the License. You may obtain a copy of the License at
  15609. *
  15610. * http://www.apache.org/licenses/LICENSE-2.0
  15611. *
  15612. * Unless required by applicable law or agreed to in writing,
  15613. * software distributed under the License is distributed on an
  15614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15615. * KIND, either express or implied. See the License for the
  15616. * specific language governing permissions and limitations
  15617. * under the License.
  15618. */
  15619. /**
  15620. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15621. */
  15622. /*
  15623. * Licensed to the Apache Software Foundation (ASF) under one
  15624. * or more contributor license agreements. See the NOTICE file
  15625. * distributed with this work for additional information
  15626. * regarding copyright ownership. The ASF licenses this file
  15627. * to you under the Apache License, Version 2.0 (the
  15628. * "License"); you may not use this file except in compliance
  15629. * with the License. You may obtain a copy of the License at
  15630. *
  15631. * http://www.apache.org/licenses/LICENSE-2.0
  15632. *
  15633. * Unless required by applicable law or agreed to in writing,
  15634. * software distributed under the License is distributed on an
  15635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15636. * KIND, either express or implied. See the License for the
  15637. * specific language governing permissions and limitations
  15638. * under the License.
  15639. */
  15640. /**
  15641. * Language: English.
  15642. */
  15643. var langEN = {
  15644. time: {
  15645. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15646. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15647. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15648. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15649. },
  15650. legend: {
  15651. selector: {
  15652. all: 'All',
  15653. inverse: 'Inv'
  15654. }
  15655. },
  15656. toolbox: {
  15657. brush: {
  15658. title: {
  15659. rect: 'Box Select',
  15660. polygon: 'Lasso Select',
  15661. lineX: 'Horizontally Select',
  15662. lineY: 'Vertically Select',
  15663. keep: 'Keep Selections',
  15664. clear: 'Clear Selections'
  15665. }
  15666. },
  15667. dataView: {
  15668. title: 'Data View',
  15669. lang: ['Data View', 'Close', 'Refresh']
  15670. },
  15671. dataZoom: {
  15672. title: {
  15673. zoom: 'Zoom',
  15674. back: 'Zoom Reset'
  15675. }
  15676. },
  15677. magicType: {
  15678. title: {
  15679. line: 'Switch to Line Chart',
  15680. bar: 'Switch to Bar Chart',
  15681. stack: 'Stack',
  15682. tiled: 'Tile'
  15683. }
  15684. },
  15685. restore: {
  15686. title: 'Restore'
  15687. },
  15688. saveAsImage: {
  15689. title: 'Save as Image',
  15690. lang: ['Right Click to Save Image']
  15691. }
  15692. },
  15693. series: {
  15694. typeNames: {
  15695. pie: 'Pie chart',
  15696. bar: 'Bar chart',
  15697. line: 'Line chart',
  15698. scatter: 'Scatter plot',
  15699. effectScatter: 'Ripple scatter plot',
  15700. radar: 'Radar chart',
  15701. tree: 'Tree',
  15702. treemap: 'Treemap',
  15703. boxplot: 'Boxplot',
  15704. candlestick: 'Candlestick',
  15705. k: 'K line chart',
  15706. heatmap: 'Heat map',
  15707. map: 'Map',
  15708. parallel: 'Parallel coordinate map',
  15709. lines: 'Line graph',
  15710. graph: 'Relationship graph',
  15711. sankey: 'Sankey diagram',
  15712. funnel: 'Funnel chart',
  15713. gauge: 'Gauge',
  15714. pictorialBar: 'Pictorial bar',
  15715. themeRiver: 'Theme River Map',
  15716. sunburst: 'Sunburst',
  15717. custom: 'Custom chart',
  15718. chart: 'Chart'
  15719. }
  15720. },
  15721. aria: {
  15722. general: {
  15723. withTitle: 'This is a chart about "{title}"',
  15724. withoutTitle: 'This is a chart'
  15725. },
  15726. series: {
  15727. single: {
  15728. prefix: '',
  15729. withName: ' with type {seriesType} named {seriesName}.',
  15730. withoutName: ' with type {seriesType}.'
  15731. },
  15732. multiple: {
  15733. prefix: '. It consists of {seriesCount} series count.',
  15734. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15735. withoutName: ' The {seriesId} series is a {seriesType}.',
  15736. separator: {
  15737. middle: '',
  15738. end: ''
  15739. }
  15740. }
  15741. },
  15742. data: {
  15743. allData: 'The data is as follows: ',
  15744. partialData: 'The first {displayCnt} items are: ',
  15745. withName: 'the data for {name} is {value}',
  15746. withoutName: '{value}',
  15747. separator: {
  15748. middle: ', ',
  15749. end: '. '
  15750. }
  15751. }
  15752. }
  15753. };
  15754. /*
  15755. * Licensed to the Apache Software Foundation (ASF) under one
  15756. * or more contributor license agreements. See the NOTICE file
  15757. * distributed with this work for additional information
  15758. * regarding copyright ownership. The ASF licenses this file
  15759. * to you under the Apache License, Version 2.0 (the
  15760. * "License"); you may not use this file except in compliance
  15761. * with the License. You may obtain a copy of the License at
  15762. *
  15763. * http://www.apache.org/licenses/LICENSE-2.0
  15764. *
  15765. * Unless required by applicable law or agreed to in writing,
  15766. * software distributed under the License is distributed on an
  15767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15768. * KIND, either express or implied. See the License for the
  15769. * specific language governing permissions and limitations
  15770. * under the License.
  15771. */
  15772. /**
  15773. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15774. */
  15775. /*
  15776. * Licensed to the Apache Software Foundation (ASF) under one
  15777. * or more contributor license agreements. See the NOTICE file
  15778. * distributed with this work for additional information
  15779. * regarding copyright ownership. The ASF licenses this file
  15780. * to you under the Apache License, Version 2.0 (the
  15781. * "License"); you may not use this file except in compliance
  15782. * with the License. You may obtain a copy of the License at
  15783. *
  15784. * http://www.apache.org/licenses/LICENSE-2.0
  15785. *
  15786. * Unless required by applicable law or agreed to in writing,
  15787. * software distributed under the License is distributed on an
  15788. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15789. * KIND, either express or implied. See the License for the
  15790. * specific language governing permissions and limitations
  15791. * under the License.
  15792. */
  15793. var langZH = {
  15794. time: {
  15795. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15796. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15797. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15798. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15799. },
  15800. legend: {
  15801. selector: {
  15802. all: '全选',
  15803. inverse: '反选'
  15804. }
  15805. },
  15806. toolbox: {
  15807. brush: {
  15808. title: {
  15809. rect: '矩形选择',
  15810. polygon: '圈选',
  15811. lineX: '横向选择',
  15812. lineY: '纵向选择',
  15813. keep: '保持选择',
  15814. clear: '清除选择'
  15815. }
  15816. },
  15817. dataView: {
  15818. title: '数据视图',
  15819. lang: ['数据视图', '关闭', '刷新']
  15820. },
  15821. dataZoom: {
  15822. title: {
  15823. zoom: '区域缩放',
  15824. back: '区域缩放还原'
  15825. }
  15826. },
  15827. magicType: {
  15828. title: {
  15829. line: '切换为折线图',
  15830. bar: '切换为柱状图',
  15831. stack: '切换为堆叠',
  15832. tiled: '切换为平铺'
  15833. }
  15834. },
  15835. restore: {
  15836. title: '还原'
  15837. },
  15838. saveAsImage: {
  15839. title: '保存为图片',
  15840. lang: ['右键另存为图片']
  15841. }
  15842. },
  15843. series: {
  15844. typeNames: {
  15845. pie: '饼图',
  15846. bar: '柱状图',
  15847. line: '折线图',
  15848. scatter: '散点图',
  15849. effectScatter: '涟漪散点图',
  15850. radar: '雷达图',
  15851. tree: '树图',
  15852. treemap: '矩形树图',
  15853. boxplot: '箱型图',
  15854. candlestick: 'K线图',
  15855. k: 'K线图',
  15856. heatmap: '热力图',
  15857. map: '地图',
  15858. parallel: '平行坐标图',
  15859. lines: '线图',
  15860. graph: '关系图',
  15861. sankey: '桑基图',
  15862. funnel: '漏斗图',
  15863. gauge: '仪表盘图',
  15864. pictorialBar: '象形柱图',
  15865. themeRiver: '主题河流图',
  15866. sunburst: '旭日图',
  15867. custom: '自定义图表',
  15868. chart: '图表'
  15869. }
  15870. },
  15871. aria: {
  15872. general: {
  15873. withTitle: '这是一个关于“{title}”的图表。',
  15874. withoutTitle: '这是一个图表,'
  15875. },
  15876. series: {
  15877. single: {
  15878. prefix: '',
  15879. withName: '图表类型是{seriesType},表示{seriesName}。',
  15880. withoutName: '图表类型是{seriesType}。'
  15881. },
  15882. multiple: {
  15883. prefix: '它由{seriesCount}个图表系列组成。',
  15884. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15885. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15886. separator: {
  15887. middle: ';',
  15888. end: '。'
  15889. }
  15890. }
  15891. },
  15892. data: {
  15893. allData: '其数据是——',
  15894. partialData: '其中,前{displayCnt}项是——',
  15895. withName: '{name}的数据是{value}',
  15896. withoutName: '{value}',
  15897. separator: {
  15898. middle: ',',
  15899. end: ''
  15900. }
  15901. }
  15902. }
  15903. };
  15904. var LOCALE_ZH = 'ZH';
  15905. var LOCALE_EN = 'EN';
  15906. var DEFAULT_LOCALE = LOCALE_EN;
  15907. var localeStorage = {};
  15908. var localeModels = {};
  15909. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15910. var langStr = (/* eslint-disable-next-line */
  15911. document.documentElement.lang || navigator.language || navigator.browserLanguage || DEFAULT_LOCALE).toUpperCase();
  15912. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15913. }();
  15914. function registerLocale(locale, localeObj) {
  15915. locale = locale.toUpperCase();
  15916. localeModels[locale] = new Model(localeObj);
  15917. localeStorage[locale] = localeObj;
  15918. }
  15919. // export function getLocale(locale: string) {
  15920. // return localeStorage[locale];
  15921. // }
  15922. function createLocaleObject(locale) {
  15923. if (isString(locale)) {
  15924. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15925. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15926. return clone(localeObj);
  15927. } else {
  15928. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15929. }
  15930. } else {
  15931. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15932. }
  15933. }
  15934. function getLocaleModel(lang) {
  15935. return localeModels[lang];
  15936. }
  15937. function getDefaultLocaleModel() {
  15938. return localeModels[DEFAULT_LOCALE];
  15939. }
  15940. // Default locale
  15941. registerLocale(LOCALE_EN, langEN);
  15942. registerLocale(LOCALE_ZH, langZH);
  15943. var ONE_SECOND = 1000;
  15944. var ONE_MINUTE = ONE_SECOND * 60;
  15945. var ONE_HOUR = ONE_MINUTE * 60;
  15946. var ONE_DAY = ONE_HOUR * 24;
  15947. var ONE_YEAR = ONE_DAY * 365;
  15948. var defaultLeveledFormatter = {
  15949. year: '{yyyy}',
  15950. month: '{MMM}',
  15951. day: '{d}',
  15952. hour: '{HH}:{mm}',
  15953. minute: '{HH}:{mm}',
  15954. second: '{HH}:{mm}:{ss}',
  15955. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15956. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15957. };
  15958. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15959. var fullLeveledFormatter = {
  15960. year: '{yyyy}',
  15961. month: '{yyyy}-{MM}',
  15962. day: fullDayFormatter,
  15963. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15964. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15965. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15966. millisecond: defaultLeveledFormatter.none
  15967. };
  15968. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15969. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15970. function pad(str, len) {
  15971. str += '';
  15972. return '0000'.substr(0, len - str.length) + str;
  15973. }
  15974. function getPrimaryTimeUnit(timeUnit) {
  15975. switch (timeUnit) {
  15976. case 'half-year':
  15977. case 'quarter':
  15978. return 'month';
  15979. case 'week':
  15980. case 'half-week':
  15981. return 'day';
  15982. case 'half-day':
  15983. case 'quarter-day':
  15984. return 'hour';
  15985. default:
  15986. // year, minutes, second, milliseconds
  15987. return timeUnit;
  15988. }
  15989. }
  15990. function isPrimaryTimeUnit(timeUnit) {
  15991. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15992. }
  15993. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15994. switch (timeUnit) {
  15995. case 'year':
  15996. case 'month':
  15997. return 'day';
  15998. case 'millisecond':
  15999. return 'millisecond';
  16000. default:
  16001. // Also for day, hour, minute, second
  16002. return 'second';
  16003. }
  16004. }
  16005. function format(
  16006. // Note: The result based on `isUTC` are totally different, which can not be just simply
  16007. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  16008. time, template, isUTC, lang) {
  16009. var date = parseDate(time);
  16010. var y = date[fullYearGetterName(isUTC)]();
  16011. var M = date[monthGetterName(isUTC)]() + 1;
  16012. var q = Math.floor((M - 1) / 3) + 1;
  16013. var d = date[dateGetterName(isUTC)]();
  16014. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  16015. var H = date[hoursGetterName(isUTC)]();
  16016. var h = (H - 1) % 12 + 1;
  16017. var m = date[minutesGetterName(isUTC)]();
  16018. var s = date[secondsGetterName(isUTC)]();
  16019. var S = date[millisecondsGetterName(isUTC)]();
  16020. var a = H >= 12 ? 'pm' : 'am';
  16021. var A = a.toUpperCase();
  16022. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  16023. var timeModel = localeModel.getModel('time');
  16024. var month = timeModel.get('month');
  16025. var monthAbbr = timeModel.get('monthAbbr');
  16026. var dayOfWeek = timeModel.get('dayOfWeek');
  16027. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  16028. return (template || '').replace(/{a}/g, a + '').replace(/{A}/g, A + '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, pad(y % 100 + '', 2)).replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  16029. }
  16030. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  16031. var template = null;
  16032. if (isString(formatter)) {
  16033. // Single formatter for all units at all levels
  16034. template = formatter;
  16035. } else if (isFunction(formatter)) {
  16036. // Callback formatter
  16037. template = formatter(tick.value, idx, {
  16038. level: tick.level
  16039. });
  16040. } else {
  16041. var defaults$1 = extend({}, defaultLeveledFormatter);
  16042. if (tick.level > 0) {
  16043. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  16044. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  16045. }
  16046. }
  16047. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  16048. : defaults(formatter, defaults$1) : defaults$1;
  16049. var unit = getUnitFromValue(tick.value, isUTC);
  16050. if (mergedFormatter[unit]) {
  16051. template = mergedFormatter[unit];
  16052. } else if (mergedFormatter.inherit) {
  16053. // Unit formatter is not defined and should inherit from bigger units
  16054. var targetId = timeUnits.indexOf(unit);
  16055. for (var i = targetId - 1; i >= 0; --i) {
  16056. if (mergedFormatter[unit]) {
  16057. template = mergedFormatter[unit];
  16058. break;
  16059. }
  16060. }
  16061. template = template || defaults$1.none;
  16062. }
  16063. if (isArray(template)) {
  16064. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  16065. levelId = Math.min(levelId, template.length - 1);
  16066. template = template[levelId];
  16067. }
  16068. }
  16069. return format(new Date(tick.value), template, isUTC, lang);
  16070. }
  16071. function getUnitFromValue(value, isUTC) {
  16072. var date = parseDate(value);
  16073. var M = date[monthGetterName(isUTC)]() + 1;
  16074. var d = date[dateGetterName(isUTC)]();
  16075. var h = date[hoursGetterName(isUTC)]();
  16076. var m = date[minutesGetterName(isUTC)]();
  16077. var s = date[secondsGetterName(isUTC)]();
  16078. var S = date[millisecondsGetterName(isUTC)]();
  16079. var isSecond = S === 0;
  16080. var isMinute = isSecond && s === 0;
  16081. var isHour = isMinute && m === 0;
  16082. var isDay = isHour && h === 0;
  16083. var isMonth = isDay && d === 1;
  16084. var isYear = isMonth && M === 1;
  16085. if (isYear) {
  16086. return 'year';
  16087. } else if (isMonth) {
  16088. return 'month';
  16089. } else if (isDay) {
  16090. return 'day';
  16091. } else if (isHour) {
  16092. return 'hour';
  16093. } else if (isMinute) {
  16094. return 'minute';
  16095. } else if (isSecond) {
  16096. return 'second';
  16097. } else {
  16098. return 'millisecond';
  16099. }
  16100. }
  16101. function getUnitValue(value, unit, isUTC) {
  16102. var date = isNumber(value) ? parseDate(value) : value;
  16103. unit = unit || getUnitFromValue(value, isUTC);
  16104. switch (unit) {
  16105. case 'year':
  16106. return date[fullYearGetterName(isUTC)]();
  16107. case 'half-year':
  16108. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16109. case 'quarter':
  16110. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16111. case 'month':
  16112. return date[monthGetterName(isUTC)]();
  16113. case 'day':
  16114. return date[dateGetterName(isUTC)]();
  16115. case 'half-day':
  16116. return date[hoursGetterName(isUTC)]() / 24;
  16117. case 'hour':
  16118. return date[hoursGetterName(isUTC)]();
  16119. case 'minute':
  16120. return date[minutesGetterName(isUTC)]();
  16121. case 'second':
  16122. return date[secondsGetterName(isUTC)]();
  16123. case 'millisecond':
  16124. return date[millisecondsGetterName(isUTC)]();
  16125. }
  16126. }
  16127. function fullYearGetterName(isUTC) {
  16128. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16129. }
  16130. function monthGetterName(isUTC) {
  16131. return isUTC ? 'getUTCMonth' : 'getMonth';
  16132. }
  16133. function dateGetterName(isUTC) {
  16134. return isUTC ? 'getUTCDate' : 'getDate';
  16135. }
  16136. function hoursGetterName(isUTC) {
  16137. return isUTC ? 'getUTCHours' : 'getHours';
  16138. }
  16139. function minutesGetterName(isUTC) {
  16140. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16141. }
  16142. function secondsGetterName(isUTC) {
  16143. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16144. }
  16145. function millisecondsGetterName(isUTC) {
  16146. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16147. }
  16148. function fullYearSetterName(isUTC) {
  16149. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16150. }
  16151. function monthSetterName(isUTC) {
  16152. return isUTC ? 'setUTCMonth' : 'setMonth';
  16153. }
  16154. function dateSetterName(isUTC) {
  16155. return isUTC ? 'setUTCDate' : 'setDate';
  16156. }
  16157. function hoursSetterName(isUTC) {
  16158. return isUTC ? 'setUTCHours' : 'setHours';
  16159. }
  16160. function minutesSetterName(isUTC) {
  16161. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16162. }
  16163. function secondsSetterName(isUTC) {
  16164. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16165. }
  16166. function millisecondsSetterName(isUTC) {
  16167. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16168. }
  16169. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16170. var textEl = new ZRText({
  16171. style: {
  16172. text: text,
  16173. font: font,
  16174. align: align,
  16175. verticalAlign: verticalAlign,
  16176. padding: padding,
  16177. rich: rich,
  16178. overflow: truncate ? 'truncate' : null,
  16179. lineHeight: lineHeight
  16180. }
  16181. });
  16182. return textEl.getBoundingRect();
  16183. }
  16184. /**
  16185. * Add a comma each three digit.
  16186. */
  16187. function addCommas(x) {
  16188. if (!isNumeric(x)) {
  16189. return isString(x) ? x : '-';
  16190. }
  16191. var parts = (x + '').split('.');
  16192. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16193. }
  16194. function toCamelCase(str, upperCaseFirst) {
  16195. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16196. return group1.toUpperCase();
  16197. });
  16198. if (upperCaseFirst && str) {
  16199. str = str.charAt(0).toUpperCase() + str.slice(1);
  16200. }
  16201. return str;
  16202. }
  16203. var normalizeCssArray$1 = normalizeCssArray;
  16204. /**
  16205. * Make value user readable for tooltip and label.
  16206. * "User readable":
  16207. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16208. * Avoid to display an empty string, which users can not recognize there is
  16209. * a value and it might look like a bug.
  16210. */
  16211. function makeValueReadable(value, valueType, useUTC) {
  16212. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16213. function stringToUserReadable(str) {
  16214. return str && trim(str) ? str : '-';
  16215. }
  16216. function isNumberUserReadable(num) {
  16217. return !!(num != null && !isNaN(num) && isFinite(num));
  16218. }
  16219. var isTypeTime = valueType === 'time';
  16220. var isValueDate = value instanceof Date;
  16221. if (isTypeTime || isValueDate) {
  16222. var date = isTypeTime ? parseDate(value) : value;
  16223. if (!isNaN(+date)) {
  16224. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16225. } else if (isValueDate) {
  16226. return '-';
  16227. }
  16228. // In other cases, continue to try to display the value in the following code.
  16229. }
  16230. if (valueType === 'ordinal') {
  16231. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16232. }
  16233. // By default.
  16234. var numericResult = numericToNumber(value);
  16235. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16236. }
  16237. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16238. var wrapVar = function (varName, seriesIdx) {
  16239. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16240. };
  16241. /**
  16242. * Template formatter
  16243. * @param {Array.<Object>|Object} paramsList
  16244. */
  16245. function formatTpl(tpl, paramsList, encode) {
  16246. if (!isArray(paramsList)) {
  16247. paramsList = [paramsList];
  16248. }
  16249. var seriesLen = paramsList.length;
  16250. if (!seriesLen) {
  16251. return '';
  16252. }
  16253. var $vars = paramsList[0].$vars || [];
  16254. for (var i = 0; i < $vars.length; i++) {
  16255. var alias = TPL_VAR_ALIAS[i];
  16256. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16257. }
  16258. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16259. for (var k = 0; k < $vars.length; k++) {
  16260. var val = paramsList[seriesIdx][$vars[k]];
  16261. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16262. }
  16263. }
  16264. return tpl;
  16265. }
  16266. function getTooltipMarker(inOpt, extraCssText) {
  16267. var opt = isString(inOpt) ? {
  16268. color: inOpt,
  16269. extraCssText: extraCssText
  16270. } : inOpt || {};
  16271. var color = opt.color;
  16272. var type = opt.type;
  16273. extraCssText = opt.extraCssText;
  16274. var renderMode = opt.renderMode || 'html';
  16275. if (!color) {
  16276. return '';
  16277. }
  16278. if (renderMode === 'html') {
  16279. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:'
  16280. // Only support string
  16281. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:4px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16282. } else {
  16283. // Should better not to auto generate style name by auto-increment number here.
  16284. // Because this util is usually called in tooltip formatter, which is probably
  16285. // called repeatedly when mouse move and the auto-increment number increases fast.
  16286. // Users can make their own style name by theirselves, make it unique and readable.
  16287. var markerId = opt.markerId || 'markerX';
  16288. return {
  16289. renderMode: renderMode,
  16290. content: '{' + markerId + '|} ',
  16291. style: type === 'subItem' ? {
  16292. width: 4,
  16293. height: 4,
  16294. borderRadius: 2,
  16295. backgroundColor: color
  16296. } : {
  16297. width: 10,
  16298. height: 10,
  16299. borderRadius: 5,
  16300. backgroundColor: color
  16301. }
  16302. };
  16303. }
  16304. }
  16305. /**
  16306. * @deprecated Use `time/format` instead.
  16307. * ISO Date format
  16308. * @param {string} tpl
  16309. * @param {number} value
  16310. * @param {boolean} [isUTC=false] Default in local time.
  16311. * see `module:echarts/scale/Time`
  16312. * and `module:echarts/util/number#parseDate`.
  16313. * @inner
  16314. */
  16315. function formatTime(tpl, value, isUTC) {
  16316. if ("development" !== 'production') {
  16317. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16318. }
  16319. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16320. tpl = 'MM-dd\nyyyy';
  16321. }
  16322. var date = parseDate(value);
  16323. var getUTC = isUTC ? 'getUTC' : 'get';
  16324. var y = date[getUTC + 'FullYear']();
  16325. var M = date[getUTC + 'Month']() + 1;
  16326. var d = date[getUTC + 'Date']();
  16327. var h = date[getUTC + 'Hours']();
  16328. var m = date[getUTC + 'Minutes']();
  16329. var s = date[getUTC + 'Seconds']();
  16330. var S = date[getUTC + 'Milliseconds']();
  16331. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', pad(y % 100 + '', 2)).replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  16332. return tpl;
  16333. }
  16334. /**
  16335. * Capital first
  16336. * @param {string} str
  16337. * @return {string}
  16338. */
  16339. function capitalFirst(str) {
  16340. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16341. }
  16342. /**
  16343. * @return Never be null/undefined.
  16344. */
  16345. function convertToColorString(color, defaultColor) {
  16346. defaultColor = defaultColor || 'transparent';
  16347. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16348. }
  16349. /**
  16350. * open new tab
  16351. * @param link url
  16352. * @param target blank or self
  16353. */
  16354. function windowOpen(link, target) {
  16355. /* global window */
  16356. if (target === '_blank' || target === 'blank') {
  16357. var blank = window.open();
  16358. blank.opener = null;
  16359. blank.location.href = link;
  16360. } else {
  16361. window.open(link, target);
  16362. }
  16363. }
  16364. var each$1 = each;
  16365. /**
  16366. * @public
  16367. */
  16368. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16369. /**
  16370. * @public
  16371. */
  16372. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16373. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16374. var x = 0;
  16375. var y = 0;
  16376. if (maxWidth == null) {
  16377. maxWidth = Infinity;
  16378. }
  16379. if (maxHeight == null) {
  16380. maxHeight = Infinity;
  16381. }
  16382. var currentLineMaxSize = 0;
  16383. group.eachChild(function (child, idx) {
  16384. var rect = child.getBoundingRect();
  16385. var nextChild = group.childAt(idx + 1);
  16386. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16387. var nextX;
  16388. var nextY;
  16389. if (orient === 'horizontal') {
  16390. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16391. nextX = x + moveX;
  16392. // Wrap when width exceeds maxWidth or meet a `newline` group
  16393. // FIXME compare before adding gap?
  16394. if (nextX > maxWidth || child.newline) {
  16395. x = 0;
  16396. nextX = moveX;
  16397. y += currentLineMaxSize + gap;
  16398. currentLineMaxSize = rect.height;
  16399. } else {
  16400. // FIXME: consider rect.y is not `0`?
  16401. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16402. }
  16403. } else {
  16404. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16405. nextY = y + moveY;
  16406. // Wrap when width exceeds maxHeight or meet a `newline` group
  16407. if (nextY > maxHeight || child.newline) {
  16408. x += currentLineMaxSize + gap;
  16409. y = 0;
  16410. nextY = moveY;
  16411. currentLineMaxSize = rect.width;
  16412. } else {
  16413. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16414. }
  16415. }
  16416. if (child.newline) {
  16417. return;
  16418. }
  16419. child.x = x;
  16420. child.y = y;
  16421. child.markRedraw();
  16422. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16423. });
  16424. }
  16425. /**
  16426. * VBox or HBox layouting
  16427. * @param {string} orient
  16428. * @param {module:zrender/graphic/Group} group
  16429. * @param {number} gap
  16430. * @param {number} [width=Infinity]
  16431. * @param {number} [height=Infinity]
  16432. */
  16433. var box = boxLayout;
  16434. /**
  16435. * VBox layouting
  16436. * @param {module:zrender/graphic/Group} group
  16437. * @param {number} gap
  16438. * @param {number} [width=Infinity]
  16439. * @param {number} [height=Infinity]
  16440. */
  16441. var vbox = curry(boxLayout, 'vertical');
  16442. /**
  16443. * HBox layouting
  16444. * @param {module:zrender/graphic/Group} group
  16445. * @param {number} gap
  16446. * @param {number} [width=Infinity]
  16447. * @param {number} [height=Infinity]
  16448. */
  16449. var hbox = curry(boxLayout, 'horizontal');
  16450. /**
  16451. * Parse position info.
  16452. */
  16453. function getLayoutRect(positionInfo, containerRect, margin) {
  16454. margin = normalizeCssArray$1(margin || 0);
  16455. var containerWidth = containerRect.width;
  16456. var containerHeight = containerRect.height;
  16457. var left = parsePercent$1(positionInfo.left, containerWidth);
  16458. var top = parsePercent$1(positionInfo.top, containerHeight);
  16459. var right = parsePercent$1(positionInfo.right, containerWidth);
  16460. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16461. var width = parsePercent$1(positionInfo.width, containerWidth);
  16462. var height = parsePercent$1(positionInfo.height, containerHeight);
  16463. var verticalMargin = margin[2] + margin[0];
  16464. var horizontalMargin = margin[1] + margin[3];
  16465. var aspect = positionInfo.aspect;
  16466. // If width is not specified, calculate width from left and right
  16467. if (isNaN(width)) {
  16468. width = containerWidth - right - horizontalMargin - left;
  16469. }
  16470. if (isNaN(height)) {
  16471. height = containerHeight - bottom - verticalMargin - top;
  16472. }
  16473. if (aspect != null) {
  16474. // If width and height are not given
  16475. // 1. Graph should not exceeds the container
  16476. // 2. Aspect must be keeped
  16477. // 3. Graph should take the space as more as possible
  16478. // FIXME
  16479. // Margin is not considered, because there is no case that both
  16480. // using margin and aspect so far.
  16481. if (isNaN(width) && isNaN(height)) {
  16482. if (aspect > containerWidth / containerHeight) {
  16483. width = containerWidth * 0.8;
  16484. } else {
  16485. height = containerHeight * 0.8;
  16486. }
  16487. }
  16488. // Calculate width or height with given aspect
  16489. if (isNaN(width)) {
  16490. width = aspect * height;
  16491. }
  16492. if (isNaN(height)) {
  16493. height = width / aspect;
  16494. }
  16495. }
  16496. // If left is not specified, calculate left from right and width
  16497. if (isNaN(left)) {
  16498. left = containerWidth - right - width - horizontalMargin;
  16499. }
  16500. if (isNaN(top)) {
  16501. top = containerHeight - bottom - height - verticalMargin;
  16502. }
  16503. // Align left and top
  16504. switch (positionInfo.left || positionInfo.right) {
  16505. case 'center':
  16506. left = containerWidth / 2 - width / 2 - margin[3];
  16507. break;
  16508. case 'right':
  16509. left = containerWidth - width - horizontalMargin;
  16510. break;
  16511. }
  16512. switch (positionInfo.top || positionInfo.bottom) {
  16513. case 'middle':
  16514. case 'center':
  16515. top = containerHeight / 2 - height / 2 - margin[0];
  16516. break;
  16517. case 'bottom':
  16518. top = containerHeight - height - verticalMargin;
  16519. break;
  16520. }
  16521. // If something is wrong and left, top, width, height are calculated as NaN
  16522. left = left || 0;
  16523. top = top || 0;
  16524. if (isNaN(width)) {
  16525. // Width may be NaN if only one value is given except width
  16526. width = containerWidth - horizontalMargin - left - (right || 0);
  16527. }
  16528. if (isNaN(height)) {
  16529. // Height may be NaN if only one value is given except height
  16530. height = containerHeight - verticalMargin - top - (bottom || 0);
  16531. }
  16532. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16533. rect.margin = margin;
  16534. return rect;
  16535. }
  16536. /**
  16537. * Position a zr element in viewport
  16538. * Group position is specified by either
  16539. * {left, top}, {right, bottom}
  16540. * If all properties exists, right and bottom will be igonred.
  16541. *
  16542. * Logic:
  16543. * 1. Scale (against origin point in parent coord)
  16544. * 2. Rotate (against origin point in parent coord)
  16545. * 3. Translate (with el.position by this method)
  16546. * So this method only fixes the last step 'Translate', which does not affect
  16547. * scaling and rotating.
  16548. *
  16549. * If be called repeatedly with the same input el, the same result will be gotten.
  16550. *
  16551. * Return true if the layout happened.
  16552. *
  16553. * @param el Should have `getBoundingRect` method.
  16554. * @param positionInfo
  16555. * @param positionInfo.left
  16556. * @param positionInfo.top
  16557. * @param positionInfo.right
  16558. * @param positionInfo.bottom
  16559. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16560. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16561. * @param containerRect
  16562. * @param margin
  16563. * @param opt
  16564. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16565. * @param opt.boundingMode
  16566. * Specify how to calculate boundingRect when locating.
  16567. * 'all': Position the boundingRect that is transformed and uioned
  16568. * both itself and its descendants.
  16569. * This mode simplies confine the elements in the bounding
  16570. * of their container (e.g., using 'right: 0').
  16571. * 'raw': Position the boundingRect that is not transformed and only itself.
  16572. * This mode is useful when you want a element can overflow its
  16573. * container. (Consider a rotated circle needs to be located in a corner.)
  16574. * In this mode positionInfo.width/height can only be number.
  16575. */
  16576. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16577. var h = !opt || !opt.hv || opt.hv[0];
  16578. var v = !opt || !opt.hv || opt.hv[1];
  16579. var boundingMode = opt && opt.boundingMode || 'all';
  16580. out = out || el;
  16581. out.x = el.x;
  16582. out.y = el.y;
  16583. if (!h && !v) {
  16584. return false;
  16585. }
  16586. var rect;
  16587. if (boundingMode === 'raw') {
  16588. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16589. } else {
  16590. rect = el.getBoundingRect();
  16591. if (el.needLocalTransform()) {
  16592. var transform = el.getLocalTransform();
  16593. // Notice: raw rect may be inner object of el,
  16594. // which should not be modified.
  16595. rect = rect.clone();
  16596. rect.applyTransform(transform);
  16597. }
  16598. }
  16599. // The real width and height can not be specified but calculated by the given el.
  16600. var layoutRect = getLayoutRect(defaults({
  16601. width: rect.width,
  16602. height: rect.height
  16603. }, positionInfo), containerRect, margin);
  16604. // Because 'tranlate' is the last step in transform
  16605. // (see zrender/core/Transformable#getLocalTransform),
  16606. // we can just only modify el.position to get final result.
  16607. var dx = h ? layoutRect.x - rect.x : 0;
  16608. var dy = v ? layoutRect.y - rect.y : 0;
  16609. if (boundingMode === 'raw') {
  16610. out.x = dx;
  16611. out.y = dy;
  16612. } else {
  16613. out.x += dx;
  16614. out.y += dy;
  16615. }
  16616. if (out === el) {
  16617. el.markRedraw();
  16618. }
  16619. return true;
  16620. }
  16621. function fetchLayoutMode(ins) {
  16622. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16623. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16624. type: layoutMode
  16625. } : null;
  16626. }
  16627. /**
  16628. * Consider Case:
  16629. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16630. * through setOption or media query, using normal zrUtil.merge will cause
  16631. * {right: 0} does not take effect.
  16632. *
  16633. * @example
  16634. * ComponentModel.extend({
  16635. * init: function () {
  16636. * ...
  16637. * let inputPositionParams = layout.getLayoutParams(option);
  16638. * this.mergeOption(inputPositionParams);
  16639. * },
  16640. * mergeOption: function (newOption) {
  16641. * newOption && zrUtil.merge(thisOption, newOption, true);
  16642. * layout.mergeLayoutParam(thisOption, newOption);
  16643. * }
  16644. * });
  16645. *
  16646. * @param targetOption
  16647. * @param newOption
  16648. * @param opt
  16649. */
  16650. function mergeLayoutParam(targetOption, newOption, opt) {
  16651. var ignoreSize = opt && opt.ignoreSize;
  16652. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16653. var hResult = merge(HV_NAMES[0], 0);
  16654. var vResult = merge(HV_NAMES[1], 1);
  16655. copy(HV_NAMES[0], targetOption, hResult);
  16656. copy(HV_NAMES[1], targetOption, vResult);
  16657. function merge(names, hvIdx) {
  16658. var newParams = {};
  16659. var newValueCount = 0;
  16660. var merged = {};
  16661. var mergedValueCount = 0;
  16662. var enoughParamNumber = 2;
  16663. each$1(names, function (name) {
  16664. merged[name] = targetOption[name];
  16665. });
  16666. each$1(names, function (name) {
  16667. // Consider case: newOption.width is null, which is
  16668. // set by user for removing width setting.
  16669. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16670. hasValue(newParams, name) && newValueCount++;
  16671. hasValue(merged, name) && mergedValueCount++;
  16672. });
  16673. if (ignoreSize[hvIdx]) {
  16674. // Only one of left/right is premitted to exist.
  16675. if (hasValue(newOption, names[1])) {
  16676. merged[names[2]] = null;
  16677. } else if (hasValue(newOption, names[2])) {
  16678. merged[names[1]] = null;
  16679. }
  16680. return merged;
  16681. }
  16682. // Case: newOption: {width: ..., right: ...},
  16683. // or targetOption: {right: ...} and newOption: {width: ...},
  16684. // There is no conflict when merged only has params count
  16685. // little than enoughParamNumber.
  16686. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16687. return merged;
  16688. }
  16689. // Case: newOption: {width: ..., right: ...},
  16690. // Than we can make sure user only want those two, and ignore
  16691. // all origin params in targetOption.
  16692. else if (newValueCount >= enoughParamNumber) {
  16693. return newParams;
  16694. } else {
  16695. // Chose another param from targetOption by priority.
  16696. for (var i = 0; i < names.length; i++) {
  16697. var name_1 = names[i];
  16698. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16699. newParams[name_1] = targetOption[name_1];
  16700. break;
  16701. }
  16702. }
  16703. return newParams;
  16704. }
  16705. }
  16706. function hasProp(obj, name) {
  16707. return obj.hasOwnProperty(name);
  16708. }
  16709. function hasValue(obj, name) {
  16710. return obj[name] != null && obj[name] !== 'auto';
  16711. }
  16712. function copy(names, target, source) {
  16713. each$1(names, function (name) {
  16714. target[name] = source[name];
  16715. });
  16716. }
  16717. }
  16718. /**
  16719. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16720. */
  16721. function getLayoutParams(source) {
  16722. return copyLayoutParams({}, source);
  16723. }
  16724. /**
  16725. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16726. * @param {Object} source
  16727. * @return {Object} Result contains those props.
  16728. */
  16729. function copyLayoutParams(target, source) {
  16730. source && target && each$1(LOCATION_PARAMS, function (name) {
  16731. source.hasOwnProperty(name) && (target[name] = source[name]);
  16732. });
  16733. return target;
  16734. }
  16735. var inner = makeInner();
  16736. var ComponentModel = /** @class */function (_super) {
  16737. __extends(ComponentModel, _super);
  16738. function ComponentModel(option, parentModel, ecModel) {
  16739. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16740. _this.uid = getUID('ec_cpt_model');
  16741. return _this;
  16742. }
  16743. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16744. this.mergeDefaultAndTheme(option, ecModel);
  16745. };
  16746. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16747. var layoutMode = fetchLayoutMode(this);
  16748. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16749. var themeModel = ecModel.getTheme();
  16750. merge(option, themeModel.get(this.mainType));
  16751. merge(option, this.getDefaultOption());
  16752. if (layoutMode) {
  16753. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16754. }
  16755. };
  16756. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16757. merge(this.option, option, true);
  16758. var layoutMode = fetchLayoutMode(this);
  16759. if (layoutMode) {
  16760. mergeLayoutParam(this.option, option, layoutMode);
  16761. }
  16762. };
  16763. /**
  16764. * Called immediately after `init` or `mergeOption` of this instance called.
  16765. */
  16766. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16767. /**
  16768. * [How to declare defaultOption]:
  16769. *
  16770. * (A) If using class declaration in typescript (since echarts 5):
  16771. * ```ts
  16772. * import {ComponentOption} from '../model/option.js';
  16773. * export interface XxxOption extends ComponentOption {
  16774. * aaa: number
  16775. * }
  16776. * export class XxxModel extends Component {
  16777. * static type = 'xxx';
  16778. * static defaultOption: XxxOption = {
  16779. * aaa: 123
  16780. * }
  16781. * }
  16782. * Component.registerClass(XxxModel);
  16783. * ```
  16784. * ```ts
  16785. * import {inheritDefaultOption} from '../util/component.js';
  16786. * import {XxxModel, XxxOption} from './XxxModel.js';
  16787. * export interface XxxSubOption extends XxxOption {
  16788. * bbb: number
  16789. * }
  16790. * class XxxSubModel extends XxxModel {
  16791. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16792. * bbb: 456
  16793. * })
  16794. * fn() {
  16795. * let opt = this.getDefaultOption();
  16796. * // opt is {aaa: 123, bbb: 456}
  16797. * }
  16798. * }
  16799. * ```
  16800. *
  16801. * (B) If using class extend (previous approach in echarts 3 & 4):
  16802. * ```js
  16803. * let XxxComponent = Component.extend({
  16804. * defaultOption: {
  16805. * xx: 123
  16806. * }
  16807. * })
  16808. * ```
  16809. * ```js
  16810. * let XxxSubComponent = XxxComponent.extend({
  16811. * defaultOption: {
  16812. * yy: 456
  16813. * },
  16814. * fn: function () {
  16815. * let opt = this.getDefaultOption();
  16816. * // opt is {xx: 123, yy: 456}
  16817. * }
  16818. * })
  16819. * ```
  16820. */
  16821. ComponentModel.prototype.getDefaultOption = function () {
  16822. var ctor = this.constructor;
  16823. // If using class declaration, it is different to travel super class
  16824. // in legacy env and auto merge defaultOption. So if using class
  16825. // declaration, defaultOption should be merged manually.
  16826. if (!isExtendedClass(ctor)) {
  16827. // When using ts class, defaultOption must be declared as static.
  16828. return ctor.defaultOption;
  16829. }
  16830. // FIXME: remove this approach?
  16831. var fields = inner(this);
  16832. if (!fields.defaultOption) {
  16833. var optList = [];
  16834. var clz = ctor;
  16835. while (clz) {
  16836. var opt = clz.prototype.defaultOption;
  16837. opt && optList.push(opt);
  16838. clz = clz.superClass;
  16839. }
  16840. var defaultOption = {};
  16841. for (var i = optList.length - 1; i >= 0; i--) {
  16842. defaultOption = merge(defaultOption, optList[i], true);
  16843. }
  16844. fields.defaultOption = defaultOption;
  16845. }
  16846. return fields.defaultOption;
  16847. };
  16848. /**
  16849. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16850. * The same behavior as `modelUtil.parseFinder`.
  16851. *
  16852. * @param useDefault In many cases like series refer axis and axis refer grid,
  16853. * If axis index / axis id not specified, use the first target as default.
  16854. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16855. */
  16856. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16857. var indexKey = mainType + 'Index';
  16858. var idKey = mainType + 'Id';
  16859. return queryReferringComponents(this.ecModel, mainType, {
  16860. index: this.get(indexKey, true),
  16861. id: this.get(idKey, true)
  16862. }, opt);
  16863. };
  16864. ComponentModel.prototype.getBoxLayoutParams = function () {
  16865. // Consider itself having box layout configs.
  16866. var boxLayoutModel = this;
  16867. return {
  16868. left: boxLayoutModel.get('left'),
  16869. top: boxLayoutModel.get('top'),
  16870. right: boxLayoutModel.get('right'),
  16871. bottom: boxLayoutModel.get('bottom'),
  16872. width: boxLayoutModel.get('width'),
  16873. height: boxLayoutModel.get('height')
  16874. };
  16875. };
  16876. /**
  16877. * Get key for zlevel.
  16878. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16879. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16880. */
  16881. ComponentModel.prototype.getZLevelKey = function () {
  16882. return '';
  16883. };
  16884. ComponentModel.prototype.setZLevel = function (zlevel) {
  16885. this.option.zlevel = zlevel;
  16886. };
  16887. ComponentModel.protoInitialize = function () {
  16888. var proto = ComponentModel.prototype;
  16889. proto.type = 'component';
  16890. proto.id = '';
  16891. proto.name = '';
  16892. proto.mainType = '';
  16893. proto.subType = '';
  16894. proto.componentIndex = 0;
  16895. }();
  16896. return ComponentModel;
  16897. }(Model);
  16898. mountExtend(ComponentModel, Model);
  16899. enableClassManagement(ComponentModel);
  16900. enableSubTypeDefaulter(ComponentModel);
  16901. enableTopologicalTravel(ComponentModel, getDependencies);
  16902. function getDependencies(componentType) {
  16903. var deps = [];
  16904. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16905. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16906. });
  16907. // Ensure main type.
  16908. deps = map(deps, function (type) {
  16909. return parseClassType(type).main;
  16910. });
  16911. // Hack dataset for convenience.
  16912. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16913. deps.unshift('dataset');
  16914. }
  16915. return deps;
  16916. }
  16917. /*
  16918. * Licensed to the Apache Software Foundation (ASF) under one
  16919. * or more contributor license agreements. See the NOTICE file
  16920. * distributed with this work for additional information
  16921. * regarding copyright ownership. The ASF licenses this file
  16922. * to you under the Apache License, Version 2.0 (the
  16923. * "License"); you may not use this file except in compliance
  16924. * with the License. You may obtain a copy of the License at
  16925. *
  16926. * http://www.apache.org/licenses/LICENSE-2.0
  16927. *
  16928. * Unless required by applicable law or agreed to in writing,
  16929. * software distributed under the License is distributed on an
  16930. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16931. * KIND, either express or implied. See the License for the
  16932. * specific language governing permissions and limitations
  16933. * under the License.
  16934. */
  16935. /**
  16936. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16937. */
  16938. /*
  16939. * Licensed to the Apache Software Foundation (ASF) under one
  16940. * or more contributor license agreements. See the NOTICE file
  16941. * distributed with this work for additional information
  16942. * regarding copyright ownership. The ASF licenses this file
  16943. * to you under the Apache License, Version 2.0 (the
  16944. * "License"); you may not use this file except in compliance
  16945. * with the License. You may obtain a copy of the License at
  16946. *
  16947. * http://www.apache.org/licenses/LICENSE-2.0
  16948. *
  16949. * Unless required by applicable law or agreed to in writing,
  16950. * software distributed under the License is distributed on an
  16951. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16952. * KIND, either express or implied. See the License for the
  16953. * specific language governing permissions and limitations
  16954. * under the License.
  16955. */
  16956. var platform = '';
  16957. // Navigator not exists in node
  16958. if (typeof navigator !== 'undefined') {
  16959. /* global navigator */
  16960. platform = navigator.platform || '';
  16961. }
  16962. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16963. var globalDefault = {
  16964. darkMode: 'auto',
  16965. // backgroundColor: 'rgba(0,0,0,0)',
  16966. colorBy: 'series',
  16967. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16968. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16969. aria: {
  16970. decal: {
  16971. decals: [{
  16972. color: decalColor,
  16973. dashArrayX: [1, 0],
  16974. dashArrayY: [2, 5],
  16975. symbolSize: 1,
  16976. rotation: Math.PI / 6
  16977. }, {
  16978. color: decalColor,
  16979. symbol: 'circle',
  16980. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16981. dashArrayY: [6, 0],
  16982. symbolSize: 0.8
  16983. }, {
  16984. color: decalColor,
  16985. dashArrayX: [1, 0],
  16986. dashArrayY: [4, 3],
  16987. rotation: -Math.PI / 4
  16988. }, {
  16989. color: decalColor,
  16990. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16991. dashArrayY: [6, 0]
  16992. }, {
  16993. color: decalColor,
  16994. dashArrayX: [[1, 0], [1, 6]],
  16995. dashArrayY: [1, 0, 6, 0],
  16996. rotation: Math.PI / 4
  16997. }, {
  16998. color: decalColor,
  16999. symbol: 'triangle',
  17000. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  17001. dashArrayY: [7, 2],
  17002. symbolSize: 0.75
  17003. }]
  17004. }
  17005. },
  17006. // If xAxis and yAxis declared, grid is created by default.
  17007. // grid: {},
  17008. textStyle: {
  17009. // color: '#000',
  17010. // decoration: 'none',
  17011. // PENDING
  17012. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17013. // fontFamily: 'Arial, Verdana, sans-serif',
  17014. fontSize: 12,
  17015. fontStyle: 'normal',
  17016. fontWeight: 'normal'
  17017. },
  17018. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17019. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17020. // Default is source-over
  17021. blendMode: null,
  17022. stateAnimation: {
  17023. duration: 300,
  17024. easing: 'cubicOut'
  17025. },
  17026. animation: 'auto',
  17027. animationDuration: 1000,
  17028. animationDurationUpdate: 500,
  17029. animationEasing: 'cubicInOut',
  17030. animationEasingUpdate: 'cubicInOut',
  17031. animationThreshold: 2000,
  17032. // Configuration for progressive/incremental rendering
  17033. progressiveThreshold: 3000,
  17034. progressive: 400,
  17035. // Threshold of if use single hover layer to optimize.
  17036. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17037. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17038. // which is unexpected.
  17039. // see example <echarts/test/heatmap-large.html>.
  17040. hoverLayerThreshold: 3000,
  17041. // See: module:echarts/scale/Time
  17042. useUTC: false
  17043. };
  17044. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'itemChildGroupId', 'seriesName']);
  17045. var SOURCE_FORMAT_ORIGINAL = 'original';
  17046. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17047. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17048. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17049. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17050. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17051. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17052. var SERIES_LAYOUT_BY_ROW = 'row';
  17053. // The result of `guessOrdinal`.
  17054. var BE_ORDINAL = {
  17055. Must: 1,
  17056. Might: 2,
  17057. Not: 3 // Other cases
  17058. };
  17059. var innerGlobalModel = makeInner();
  17060. /**
  17061. * MUST be called before mergeOption of all series.
  17062. */
  17063. function resetSourceDefaulter(ecModel) {
  17064. // `datasetMap` is used to make default encode.
  17065. innerGlobalModel(ecModel).datasetMap = createHashMap();
  17066. }
  17067. /**
  17068. * [The strategy of the arrengment of data dimensions for dataset]:
  17069. * "value way": all axes are non-category axes. So series one by one take
  17070. * several (the number is coordSysDims.length) dimensions from dataset.
  17071. * The result of data arrengment of data dimensions like:
  17072. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17073. * "category way": at least one axis is category axis. So the the first data
  17074. * dimension is always mapped to the first category axis and shared by
  17075. * all of the series. The other data dimensions are taken by series like
  17076. * "value way" does.
  17077. * The result of data arrengment of data dimensions like:
  17078. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17079. *
  17080. * @return encode Never be `null/undefined`.
  17081. */
  17082. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17083. var encode = {};
  17084. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  17085. // Currently only make default when using dataset, util more reqirements occur.
  17086. if (!datasetModel || !coordDimensions) {
  17087. return encode;
  17088. }
  17089. var encodeItemName = [];
  17090. var encodeSeriesName = [];
  17091. var ecModel = seriesModel.ecModel;
  17092. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  17093. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17094. var baseCategoryDimIndex;
  17095. var categoryWayValueDimStart;
  17096. coordDimensions = coordDimensions.slice();
  17097. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  17098. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  17099. name: coordDimInfoLoose
  17100. };
  17101. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17102. baseCategoryDimIndex = coordDimIdx;
  17103. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  17104. }
  17105. encode[coordDimInfo.name] = [];
  17106. });
  17107. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17108. categoryWayDim: categoryWayValueDimStart,
  17109. valueWayDim: 0
  17110. });
  17111. // TODO
  17112. // Auto detect first time axis and do arrangement.
  17113. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17114. var coordDimName = coordDimInfo.name;
  17115. var count = getDataDimCountOnCoordDim(coordDimInfo);
  17116. // In value way.
  17117. if (baseCategoryDimIndex == null) {
  17118. var start = datasetRecord.valueWayDim;
  17119. pushDim(encode[coordDimName], start, count);
  17120. pushDim(encodeSeriesName, start, count);
  17121. datasetRecord.valueWayDim += count;
  17122. // ??? TODO give a better default series name rule?
  17123. // especially when encode x y specified.
  17124. // consider: when multiple series share one dimension
  17125. // category axis, series name should better use
  17126. // the other dimension name. On the other hand, use
  17127. // both dimensions name.
  17128. }
  17129. // In category way, the first category axis.
  17130. else if (baseCategoryDimIndex === coordDimIdx) {
  17131. pushDim(encode[coordDimName], 0, count);
  17132. pushDim(encodeItemName, 0, count);
  17133. }
  17134. // In category way, the other axis.
  17135. else {
  17136. var start = datasetRecord.categoryWayDim;
  17137. pushDim(encode[coordDimName], start, count);
  17138. pushDim(encodeSeriesName, start, count);
  17139. datasetRecord.categoryWayDim += count;
  17140. }
  17141. });
  17142. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17143. for (var i = 0; i < idxCount; i++) {
  17144. dimIdxArr.push(idxFrom + i);
  17145. }
  17146. }
  17147. function getDataDimCountOnCoordDim(coordDimInfo) {
  17148. var dimsDef = coordDimInfo.dimsDef;
  17149. return dimsDef ? dimsDef.length : 1;
  17150. }
  17151. encodeItemName.length && (encode.itemName = encodeItemName);
  17152. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17153. return encode;
  17154. }
  17155. /**
  17156. * Work for data like [{name: ..., value: ...}, ...].
  17157. *
  17158. * @return encode Never be `null/undefined`.
  17159. */
  17160. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17161. var encode = {};
  17162. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  17163. // Currently only make default when using dataset, util more reqirements occur.
  17164. if (!datasetModel) {
  17165. return encode;
  17166. }
  17167. var sourceFormat = source.sourceFormat;
  17168. var dimensionsDefine = source.dimensionsDefine;
  17169. var potentialNameDimIndex;
  17170. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17171. each(dimensionsDefine, function (dim, idx) {
  17172. if ((isObject(dim) ? dim.name : dim) === 'name') {
  17173. potentialNameDimIndex = idx;
  17174. }
  17175. });
  17176. }
  17177. var idxResult = function () {
  17178. var idxRes0 = {};
  17179. var idxRes1 = {};
  17180. var guessRecords = [];
  17181. // 5 is an experience value.
  17182. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17183. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17184. guessRecords.push(guessResult);
  17185. var isPureNumber = guessResult === BE_ORDINAL.Not;
  17186. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17187. // and then find a name dim with the priority:
  17188. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17189. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17190. idxRes0.v = i;
  17191. }
  17192. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17193. idxRes0.n = i;
  17194. }
  17195. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17196. return idxRes0;
  17197. }
  17198. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17199. // find the first BE_ORDINAL.Might as the value dim,
  17200. // and then find a name dim with the priority:
  17201. // "other dim" > "the value dim itself".
  17202. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17203. // treated as number.
  17204. if (!isPureNumber) {
  17205. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17206. idxRes1.v = i;
  17207. }
  17208. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17209. idxRes1.n = i;
  17210. }
  17211. }
  17212. }
  17213. function fulfilled(idxResult) {
  17214. return idxResult.v != null && idxResult.n != null;
  17215. }
  17216. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17217. }();
  17218. if (idxResult) {
  17219. encode.value = [idxResult.v];
  17220. // `potentialNameDimIndex` has highest priority.
  17221. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  17222. // By default, label uses itemName in charts.
  17223. // So we don't set encodeLabel here.
  17224. encode.itemName = [nameDimIndex];
  17225. encode.seriesName = [nameDimIndex];
  17226. }
  17227. return encode;
  17228. }
  17229. /**
  17230. * @return If return null/undefined, indicate that should not use datasetModel.
  17231. */
  17232. function querySeriesUpstreamDatasetModel(seriesModel) {
  17233. // Caution: consider the scenario:
  17234. // A dataset is declared and a series is not expected to use the dataset,
  17235. // and at the beginning `setOption({series: { noData })` (just prepare other
  17236. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17237. // the user should set an empty array to avoid that dataset is used by default.
  17238. var thisData = seriesModel.get('data', true);
  17239. if (!thisData) {
  17240. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  17241. index: seriesModel.get('datasetIndex', true),
  17242. id: seriesModel.get('datasetId', true)
  17243. }, SINGLE_REFERRING).models[0];
  17244. }
  17245. }
  17246. /**
  17247. * @return Always return an array event empty.
  17248. */
  17249. function queryDatasetUpstreamDatasetModels(datasetModel) {
  17250. // Only these attributes declared, we by default reference to `datasetIndex: 0`.
  17251. // Otherwise, no reference.
  17252. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  17253. return [];
  17254. }
  17255. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  17256. index: datasetModel.get('fromDatasetIndex', true),
  17257. id: datasetModel.get('fromDatasetId', true)
  17258. }, SINGLE_REFERRING).models;
  17259. }
  17260. /**
  17261. * The rule should not be complex, otherwise user might not
  17262. * be able to known where the data is wrong.
  17263. * The code is ugly, but how to make it neat?
  17264. */
  17265. function guessOrdinal(source, dimIndex) {
  17266. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17267. }
  17268. // dimIndex may be overflow source data.
  17269. // return {BE_ORDINAL}
  17270. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17271. var result;
  17272. // Experience value.
  17273. var maxLoop = 5;
  17274. if (isTypedArray(data)) {
  17275. return BE_ORDINAL.Not;
  17276. }
  17277. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17278. // always exists in source.
  17279. var dimName;
  17280. var dimType;
  17281. if (dimensionsDefine) {
  17282. var dimDefItem = dimensionsDefine[dimIndex];
  17283. if (isObject(dimDefItem)) {
  17284. dimName = dimDefItem.name;
  17285. dimType = dimDefItem.type;
  17286. } else if (isString(dimDefItem)) {
  17287. dimName = dimDefItem;
  17288. }
  17289. }
  17290. if (dimType != null) {
  17291. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17292. }
  17293. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17294. var dataArrayRows = data;
  17295. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17296. var sample = dataArrayRows[dimIndex];
  17297. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17298. if ((result = detectValue(sample[startIndex + i])) != null) {
  17299. return result;
  17300. }
  17301. }
  17302. } else {
  17303. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17304. var row = dataArrayRows[startIndex + i];
  17305. if (row && (result = detectValue(row[dimIndex])) != null) {
  17306. return result;
  17307. }
  17308. }
  17309. }
  17310. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17311. var dataObjectRows = data;
  17312. if (!dimName) {
  17313. return BE_ORDINAL.Not;
  17314. }
  17315. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17316. var item = dataObjectRows[i];
  17317. if (item && (result = detectValue(item[dimName])) != null) {
  17318. return result;
  17319. }
  17320. }
  17321. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17322. var dataKeyedColumns = data;
  17323. if (!dimName) {
  17324. return BE_ORDINAL.Not;
  17325. }
  17326. var sample = dataKeyedColumns[dimName];
  17327. if (!sample || isTypedArray(sample)) {
  17328. return BE_ORDINAL.Not;
  17329. }
  17330. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17331. if ((result = detectValue(sample[i])) != null) {
  17332. return result;
  17333. }
  17334. }
  17335. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17336. var dataOriginal = data;
  17337. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17338. var item = dataOriginal[i];
  17339. var val = getDataItemValue(item);
  17340. if (!isArray(val)) {
  17341. return BE_ORDINAL.Not;
  17342. }
  17343. if ((result = detectValue(val[dimIndex])) != null) {
  17344. return result;
  17345. }
  17346. }
  17347. }
  17348. function detectValue(val) {
  17349. var beStr = isString(val);
  17350. // Consider usage convenience, '1', '2' will be treated as "number".
  17351. // `Number('')` (or any whitespace) is `0`.
  17352. if (val != null && Number.isFinite(Number(val)) && val !== '') {
  17353. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17354. } else if (beStr && val !== '-') {
  17355. return BE_ORDINAL.Must;
  17356. }
  17357. }
  17358. return BE_ORDINAL.Not;
  17359. }
  17360. var internalOptionCreatorMap = createHashMap();
  17361. function registerInternalOptionCreator(mainType, creator) {
  17362. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17363. internalOptionCreatorMap.set(mainType, creator);
  17364. }
  17365. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17366. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17367. if (!internalOptionCreator) {
  17368. return newCmptOptionList;
  17369. }
  17370. var internalOptions = internalOptionCreator(ecModel);
  17371. if (!internalOptions) {
  17372. return newCmptOptionList;
  17373. }
  17374. if ("development" !== 'production') {
  17375. for (var i = 0; i < internalOptions.length; i++) {
  17376. assert(isComponentIdInternal(internalOptions[i]));
  17377. }
  17378. }
  17379. return newCmptOptionList.concat(internalOptions);
  17380. }
  17381. var innerColor = makeInner();
  17382. var innerDecal = makeInner();
  17383. var PaletteMixin = /** @class */function () {
  17384. function PaletteMixin() {}
  17385. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17386. var defaultPalette = normalizeToArray(this.get('color', true));
  17387. var layeredPalette = this.get('colorLayer', true);
  17388. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17389. };
  17390. PaletteMixin.prototype.clearColorPalette = function () {
  17391. clearPalette(this, innerColor);
  17392. };
  17393. return PaletteMixin;
  17394. }();
  17395. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17396. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17397. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17398. }
  17399. function getNearestPalette(palettes, requestColorNum) {
  17400. var paletteNum = palettes.length;
  17401. // TODO palettes must be in order
  17402. for (var i = 0; i < paletteNum; i++) {
  17403. if (palettes[i].length > requestColorNum) {
  17404. return palettes[i];
  17405. }
  17406. }
  17407. return palettes[paletteNum - 1];
  17408. }
  17409. /**
  17410. * @param name MUST NOT be null/undefined. Otherwise call this function
  17411. * twise with the same parameters will get different result.
  17412. * @param scope default this.
  17413. * @return Can be null/undefined
  17414. */
  17415. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17416. scope = scope || that;
  17417. var scopeFields = inner(scope);
  17418. var paletteIdx = scopeFields.paletteIdx || 0;
  17419. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {};
  17420. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17421. if (paletteNameMap.hasOwnProperty(name)) {
  17422. return paletteNameMap[name];
  17423. }
  17424. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum);
  17425. // In case can't find in layered color palette.
  17426. palette = palette || defaultPalette;
  17427. if (!palette || !palette.length) {
  17428. return;
  17429. }
  17430. var pickedPaletteItem = palette[paletteIdx];
  17431. if (name) {
  17432. paletteNameMap[name] = pickedPaletteItem;
  17433. }
  17434. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17435. return pickedPaletteItem;
  17436. }
  17437. function clearPalette(that, inner) {
  17438. inner(that).paletteIdx = 0;
  17439. inner(that).paletteNameMap = {};
  17440. }
  17441. // -----------------------
  17442. // Internal method names:
  17443. // -----------------------
  17444. var reCreateSeriesIndices;
  17445. var assertSeriesInitialized;
  17446. var initBase;
  17447. var OPTION_INNER_KEY = '\0_ec_inner';
  17448. var OPTION_INNER_VALUE = 1;
  17449. var BUITIN_COMPONENTS_MAP = {
  17450. grid: 'GridComponent',
  17451. polar: 'PolarComponent',
  17452. geo: 'GeoComponent',
  17453. singleAxis: 'SingleAxisComponent',
  17454. parallel: 'ParallelComponent',
  17455. calendar: 'CalendarComponent',
  17456. graphic: 'GraphicComponent',
  17457. toolbox: 'ToolboxComponent',
  17458. tooltip: 'TooltipComponent',
  17459. axisPointer: 'AxisPointerComponent',
  17460. brush: 'BrushComponent',
  17461. title: 'TitleComponent',
  17462. timeline: 'TimelineComponent',
  17463. markPoint: 'MarkPointComponent',
  17464. markLine: 'MarkLineComponent',
  17465. markArea: 'MarkAreaComponent',
  17466. legend: 'LegendComponent',
  17467. dataZoom: 'DataZoomComponent',
  17468. visualMap: 'VisualMapComponent',
  17469. // aria: 'AriaComponent',
  17470. // dataset: 'DatasetComponent',
  17471. // Dependencies
  17472. xAxis: 'GridComponent',
  17473. yAxis: 'GridComponent',
  17474. angleAxis: 'PolarComponent',
  17475. radiusAxis: 'PolarComponent'
  17476. };
  17477. var BUILTIN_CHARTS_MAP = {
  17478. line: 'LineChart',
  17479. bar: 'BarChart',
  17480. pie: 'PieChart',
  17481. scatter: 'ScatterChart',
  17482. radar: 'RadarChart',
  17483. map: 'MapChart',
  17484. tree: 'TreeChart',
  17485. treemap: 'TreemapChart',
  17486. graph: 'GraphChart',
  17487. gauge: 'GaugeChart',
  17488. funnel: 'FunnelChart',
  17489. parallel: 'ParallelChart',
  17490. sankey: 'SankeyChart',
  17491. boxplot: 'BoxplotChart',
  17492. candlestick: 'CandlestickChart',
  17493. effectScatter: 'EffectScatterChart',
  17494. lines: 'LinesChart',
  17495. heatmap: 'HeatmapChart',
  17496. pictorialBar: 'PictorialBarChart',
  17497. themeRiver: 'ThemeRiverChart',
  17498. sunburst: 'SunburstChart',
  17499. custom: 'CustomChart'
  17500. };
  17501. var componetsMissingLogPrinted = {};
  17502. function checkMissingComponents(option) {
  17503. each(option, function (componentOption, mainType) {
  17504. if (!ComponentModel.hasClass(mainType)) {
  17505. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17506. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17507. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17508. componetsMissingLogPrinted[componentImportName] = true;
  17509. }
  17510. }
  17511. });
  17512. }
  17513. var GlobalModel = /** @class */function (_super) {
  17514. __extends(GlobalModel, _super);
  17515. function GlobalModel() {
  17516. return _super !== null && _super.apply(this, arguments) || this;
  17517. }
  17518. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17519. theme = theme || {};
  17520. this.option = null; // Mark as not initialized.
  17521. this._theme = new Model(theme);
  17522. this._locale = new Model(locale);
  17523. this._optionManager = optionManager;
  17524. };
  17525. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17526. if ("development" !== 'production') {
  17527. assert(option != null, 'option is null/undefined');
  17528. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17529. }
  17530. var innerOpt = normalizeSetOptionInput(opts);
  17531. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17532. this._resetOption(null, innerOpt);
  17533. };
  17534. /**
  17535. * @param type null/undefined: reset all.
  17536. * 'recreate': force recreate all.
  17537. * 'timeline': only reset timeline option
  17538. * 'media': only reset media query option
  17539. * @return Whether option changed.
  17540. */
  17541. GlobalModel.prototype.resetOption = function (type, opt) {
  17542. return this._resetOption(type, normalizeSetOptionInput(opt));
  17543. };
  17544. GlobalModel.prototype._resetOption = function (type, opt) {
  17545. var optionChanged = false;
  17546. var optionManager = this._optionManager;
  17547. if (!type || type === 'recreate') {
  17548. var baseOption = optionManager.mountOption(type === 'recreate');
  17549. if ("development" !== 'production') {
  17550. checkMissingComponents(baseOption);
  17551. }
  17552. if (!this.option || type === 'recreate') {
  17553. initBase(this, baseOption);
  17554. } else {
  17555. this.restoreData();
  17556. this._mergeOption(baseOption, opt);
  17557. }
  17558. optionChanged = true;
  17559. }
  17560. if (type === 'timeline' || type === 'media') {
  17561. this.restoreData();
  17562. }
  17563. // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17564. // it should better not have the same props with `MediaUnit['option']`.
  17565. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17566. // rather than original "baseOption". If they both override a prop, the result might be
  17567. // unexpected when media state changed after `setOption` called.
  17568. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17569. // (`{baseOption, media}`) in `setOption`.
  17570. // For `timeline`, the case is the same.
  17571. if (!type || type === 'recreate' || type === 'timeline') {
  17572. var timelineOption = optionManager.getTimelineOption(this);
  17573. if (timelineOption) {
  17574. optionChanged = true;
  17575. this._mergeOption(timelineOption, opt);
  17576. }
  17577. }
  17578. if (!type || type === 'recreate' || type === 'media') {
  17579. var mediaOptions = optionManager.getMediaOption(this);
  17580. if (mediaOptions.length) {
  17581. each(mediaOptions, function (mediaOption) {
  17582. optionChanged = true;
  17583. this._mergeOption(mediaOption, opt);
  17584. }, this);
  17585. }
  17586. }
  17587. return optionChanged;
  17588. };
  17589. GlobalModel.prototype.mergeOption = function (option) {
  17590. this._mergeOption(option, null);
  17591. };
  17592. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17593. var option = this.option;
  17594. var componentsMap = this._componentsMap;
  17595. var componentsCount = this._componentsCount;
  17596. var newCmptTypes = [];
  17597. var newCmptTypeMap = createHashMap();
  17598. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17599. resetSourceDefaulter(this);
  17600. // If no component class, merge directly.
  17601. // For example: color, animaiton options, etc.
  17602. each(newOption, function (componentOption, mainType) {
  17603. if (componentOption == null) {
  17604. return;
  17605. }
  17606. if (!ComponentModel.hasClass(mainType)) {
  17607. // globalSettingTask.dirty();
  17608. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17609. } else if (mainType) {
  17610. newCmptTypes.push(mainType);
  17611. newCmptTypeMap.set(mainType, true);
  17612. }
  17613. });
  17614. if (replaceMergeMainTypeMap) {
  17615. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17616. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17617. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17618. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17619. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17620. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17621. newCmptTypes.push(mainTypeInReplaceMerge);
  17622. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17623. }
  17624. });
  17625. }
  17626. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17627. function visitComponent(mainType) {
  17628. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17629. var oldCmptList = componentsMap.get(mainType);
  17630. var mergeMode =
  17631. // `!oldCmptList` means init. See the comment in `mappingToExists`
  17632. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17633. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode);
  17634. // Set mainType and complete subType.
  17635. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel);
  17636. // Empty it before the travel, in order to prevent `this._componentsMap`
  17637. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17638. // components, which is probably incorrect logic.
  17639. option[mainType] = null;
  17640. componentsMap.set(mainType, null);
  17641. componentsCount.set(mainType, 0);
  17642. var optionsByMainType = [];
  17643. var cmptsByMainType = [];
  17644. var cmptsCountByMainType = 0;
  17645. var tooltipExists;
  17646. var tooltipWarningLogged;
  17647. each(mappingResult, function (resultItem, index) {
  17648. var componentModel = resultItem.existing;
  17649. var newCmptOption = resultItem.newOption;
  17650. if (!newCmptOption) {
  17651. if (componentModel) {
  17652. // Consider where is no new option and should be merged using {},
  17653. // see removeEdgeAndAdd in topologicalTravel and
  17654. // ComponentModel.getAllClassMainTypes.
  17655. componentModel.mergeOption({}, this);
  17656. componentModel.optionUpdated({}, false);
  17657. }
  17658. // If no both `resultItem.exist` and `resultItem.option`,
  17659. // either it is in `replaceMerge` and not matched by any id,
  17660. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17661. } else {
  17662. var isSeriesType = mainType === 'series';
  17663. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17664. );
  17665. if (!ComponentModelClass) {
  17666. if ("development" !== 'production') {
  17667. var subType = resultItem.keyInfo.subType;
  17668. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17669. if (!componetsMissingLogPrinted[subType]) {
  17670. componetsMissingLogPrinted[subType] = true;
  17671. if (seriesImportName) {
  17672. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17673. } else {
  17674. error("Unknown series " + subType);
  17675. }
  17676. }
  17677. }
  17678. return;
  17679. }
  17680. // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17681. if (mainType === 'tooltip') {
  17682. if (tooltipExists) {
  17683. if ("development" !== 'production') {
  17684. if (!tooltipWarningLogged) {
  17685. warn('Currently only one tooltip component is allowed.');
  17686. tooltipWarningLogged = true;
  17687. }
  17688. }
  17689. return;
  17690. }
  17691. tooltipExists = true;
  17692. }
  17693. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17694. componentModel.name = resultItem.keyInfo.name;
  17695. // componentModel.settingTask && componentModel.settingTask.dirty();
  17696. componentModel.mergeOption(newCmptOption, this);
  17697. componentModel.optionUpdated(newCmptOption, false);
  17698. } else {
  17699. // PENDING Global as parent ?
  17700. var extraOpt = extend({
  17701. componentIndex: index
  17702. }, resultItem.keyInfo);
  17703. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt);
  17704. // Assign `keyInfo`
  17705. extend(componentModel, extraOpt);
  17706. if (resultItem.brandNew) {
  17707. componentModel.__requireNewView = true;
  17708. }
  17709. componentModel.init(newCmptOption, this, this);
  17710. // Call optionUpdated after init.
  17711. // newCmptOption has been used as componentModel.option
  17712. // and may be merged with theme and default, so pass null
  17713. // to avoid confusion.
  17714. componentModel.optionUpdated(null, true);
  17715. }
  17716. }
  17717. if (componentModel) {
  17718. optionsByMainType.push(componentModel.option);
  17719. cmptsByMainType.push(componentModel);
  17720. cmptsCountByMainType++;
  17721. } else {
  17722. // Always do assign to avoid elided item in array.
  17723. optionsByMainType.push(void 0);
  17724. cmptsByMainType.push(void 0);
  17725. }
  17726. }, this);
  17727. option[mainType] = optionsByMainType;
  17728. componentsMap.set(mainType, cmptsByMainType);
  17729. componentsCount.set(mainType, cmptsCountByMainType);
  17730. // Backup series for filtering.
  17731. if (mainType === 'series') {
  17732. reCreateSeriesIndices(this);
  17733. }
  17734. }
  17735. // If no series declared, ensure `_seriesIndices` initialized.
  17736. if (!this._seriesIndices) {
  17737. reCreateSeriesIndices(this);
  17738. }
  17739. };
  17740. /**
  17741. * Get option for output (cloned option and inner info removed)
  17742. */
  17743. GlobalModel.prototype.getOption = function () {
  17744. var option = clone(this.option);
  17745. each(option, function (optInMainType, mainType) {
  17746. if (ComponentModel.hasClass(mainType)) {
  17747. var opts = normalizeToArray(optInMainType);
  17748. // Inner cmpts need to be removed.
  17749. // Inner cmpts might not be at last since ec5.0, but still
  17750. // compatible for users: if inner cmpt at last, splice the returned array.
  17751. var realLen = opts.length;
  17752. var metNonInner = false;
  17753. for (var i = realLen - 1; i >= 0; i--) {
  17754. // Remove options with inner id.
  17755. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17756. metNonInner = true;
  17757. } else {
  17758. opts[i] = null;
  17759. !metNonInner && realLen--;
  17760. }
  17761. }
  17762. opts.length = realLen;
  17763. option[mainType] = opts;
  17764. }
  17765. });
  17766. delete option[OPTION_INNER_KEY];
  17767. return option;
  17768. };
  17769. GlobalModel.prototype.getTheme = function () {
  17770. return this._theme;
  17771. };
  17772. GlobalModel.prototype.getLocaleModel = function () {
  17773. return this._locale;
  17774. };
  17775. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17776. this._payload = payload;
  17777. };
  17778. GlobalModel.prototype.getUpdatePayload = function () {
  17779. return this._payload;
  17780. };
  17781. /**
  17782. * @param idx If not specified, return the first one.
  17783. */
  17784. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17785. var list = this._componentsMap.get(mainType);
  17786. if (list) {
  17787. var cmpt = list[idx || 0];
  17788. if (cmpt) {
  17789. return cmpt;
  17790. } else if (idx == null) {
  17791. for (var i = 0; i < list.length; i++) {
  17792. if (list[i]) {
  17793. return list[i];
  17794. }
  17795. }
  17796. }
  17797. }
  17798. };
  17799. /**
  17800. * @return Never be null/undefined.
  17801. */
  17802. GlobalModel.prototype.queryComponents = function (condition) {
  17803. var mainType = condition.mainType;
  17804. if (!mainType) {
  17805. return [];
  17806. }
  17807. var index = condition.index;
  17808. var id = condition.id;
  17809. var name = condition.name;
  17810. var cmpts = this._componentsMap.get(mainType);
  17811. if (!cmpts || !cmpts.length) {
  17812. return [];
  17813. }
  17814. var result;
  17815. if (index != null) {
  17816. result = [];
  17817. each(normalizeToArray(index), function (idx) {
  17818. cmpts[idx] && result.push(cmpts[idx]);
  17819. });
  17820. } else if (id != null) {
  17821. result = queryByIdOrName('id', id, cmpts);
  17822. } else if (name != null) {
  17823. result = queryByIdOrName('name', name, cmpts);
  17824. } else {
  17825. // Return all non-empty components in that mainType
  17826. result = filter(cmpts, function (cmpt) {
  17827. return !!cmpt;
  17828. });
  17829. }
  17830. return filterBySubType(result, condition);
  17831. };
  17832. /**
  17833. * The interface is different from queryComponents,
  17834. * which is convenient for inner usage.
  17835. *
  17836. * @usage
  17837. * let result = findComponents(
  17838. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17839. * );
  17840. * let result = findComponents(
  17841. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17842. * );
  17843. * let result = findComponents(
  17844. * {mainType: 'series',
  17845. * filter: function (model, index) {...}}
  17846. * );
  17847. * // result like [component0, componnet1, ...]
  17848. */
  17849. GlobalModel.prototype.findComponents = function (condition) {
  17850. var query = condition.query;
  17851. var mainType = condition.mainType;
  17852. var queryCond = getQueryCond(query);
  17853. var result = queryCond ? this.queryComponents(queryCond)
  17854. // Retrieve all non-empty components.
  17855. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17856. return !!cmpt;
  17857. });
  17858. return doFilter(filterBySubType(result, condition));
  17859. function getQueryCond(q) {
  17860. var indexAttr = mainType + 'Index';
  17861. var idAttr = mainType + 'Id';
  17862. var nameAttr = mainType + 'Name';
  17863. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17864. mainType: mainType,
  17865. // subType will be filtered finally.
  17866. index: q[indexAttr],
  17867. id: q[idAttr],
  17868. name: q[nameAttr]
  17869. } : null;
  17870. }
  17871. function doFilter(res) {
  17872. return condition.filter ? filter(res, condition.filter) : res;
  17873. }
  17874. };
  17875. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17876. var componentsMap = this._componentsMap;
  17877. if (isFunction(mainType)) {
  17878. var ctxForAll_1 = cb;
  17879. var cbForAll_1 = mainType;
  17880. componentsMap.each(function (cmpts, componentType) {
  17881. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17882. var cmpt = cmpts[i];
  17883. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17884. }
  17885. });
  17886. } else {
  17887. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17888. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17889. var cmpt = cmpts[i];
  17890. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17891. }
  17892. }
  17893. };
  17894. /**
  17895. * Get series list before filtered by name.
  17896. */
  17897. GlobalModel.prototype.getSeriesByName = function (name) {
  17898. var nameStr = convertOptionIdName(name, null);
  17899. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17900. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17901. });
  17902. };
  17903. /**
  17904. * Get series list before filtered by index.
  17905. */
  17906. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17907. return this._componentsMap.get('series')[seriesIndex];
  17908. };
  17909. /**
  17910. * Get series list before filtered by type.
  17911. * FIXME: rename to getRawSeriesByType?
  17912. */
  17913. GlobalModel.prototype.getSeriesByType = function (subType) {
  17914. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17915. return !!oneSeries && oneSeries.subType === subType;
  17916. });
  17917. };
  17918. /**
  17919. * Get all series before filtered.
  17920. */
  17921. GlobalModel.prototype.getSeries = function () {
  17922. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17923. return !!oneSeries;
  17924. });
  17925. };
  17926. /**
  17927. * Count series before filtered.
  17928. */
  17929. GlobalModel.prototype.getSeriesCount = function () {
  17930. return this._componentsCount.get('series');
  17931. };
  17932. /**
  17933. * After filtering, series may be different
  17934. * from raw series.
  17935. */
  17936. GlobalModel.prototype.eachSeries = function (cb, context) {
  17937. assertSeriesInitialized(this);
  17938. each(this._seriesIndices, function (rawSeriesIndex) {
  17939. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17940. cb.call(context, series, rawSeriesIndex);
  17941. }, this);
  17942. };
  17943. /**
  17944. * Iterate raw series before filtered.
  17945. *
  17946. * @param {Function} cb
  17947. * @param {*} context
  17948. */
  17949. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17950. each(this._componentsMap.get('series'), function (series) {
  17951. series && cb.call(context, series, series.componentIndex);
  17952. });
  17953. };
  17954. /**
  17955. * After filtering, series may be different.
  17956. * from raw series.
  17957. */
  17958. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17959. assertSeriesInitialized(this);
  17960. each(this._seriesIndices, function (rawSeriesIndex) {
  17961. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17962. if (series.subType === subType) {
  17963. cb.call(context, series, rawSeriesIndex);
  17964. }
  17965. }, this);
  17966. };
  17967. /**
  17968. * Iterate raw series before filtered of given type.
  17969. */
  17970. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17971. return each(this.getSeriesByType(subType), cb, context);
  17972. };
  17973. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17974. assertSeriesInitialized(this);
  17975. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17976. };
  17977. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17978. return (this._seriesIndices || []).slice();
  17979. };
  17980. GlobalModel.prototype.filterSeries = function (cb, context) {
  17981. assertSeriesInitialized(this);
  17982. var newSeriesIndices = [];
  17983. each(this._seriesIndices, function (seriesRawIdx) {
  17984. var series = this._componentsMap.get('series')[seriesRawIdx];
  17985. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17986. }, this);
  17987. this._seriesIndices = newSeriesIndices;
  17988. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17989. };
  17990. GlobalModel.prototype.restoreData = function (payload) {
  17991. reCreateSeriesIndices(this);
  17992. var componentsMap = this._componentsMap;
  17993. var componentTypes = [];
  17994. componentsMap.each(function (components, componentType) {
  17995. if (ComponentModel.hasClass(componentType)) {
  17996. componentTypes.push(componentType);
  17997. }
  17998. });
  17999. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  18000. each(componentsMap.get(componentType), function (component) {
  18001. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  18002. component.restoreData();
  18003. }
  18004. });
  18005. });
  18006. };
  18007. GlobalModel.internalField = function () {
  18008. reCreateSeriesIndices = function (ecModel) {
  18009. var seriesIndices = ecModel._seriesIndices = [];
  18010. each(ecModel._componentsMap.get('series'), function (series) {
  18011. // series may have been removed by `replaceMerge`.
  18012. series && seriesIndices.push(series.componentIndex);
  18013. });
  18014. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  18015. };
  18016. assertSeriesInitialized = function (ecModel) {
  18017. // Components that use _seriesIndices should depends on series component,
  18018. // which make sure that their initialization is after series.
  18019. if ("development" !== 'production') {
  18020. if (!ecModel._seriesIndices) {
  18021. throw new Error('Option should contains series.');
  18022. }
  18023. }
  18024. };
  18025. initBase = function (ecModel, baseOption) {
  18026. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  18027. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  18028. ecModel.option = {};
  18029. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE;
  18030. // Init with series: [], in case of calling findSeries method
  18031. // before series initialized.
  18032. ecModel._componentsMap = createHashMap({
  18033. series: []
  18034. });
  18035. ecModel._componentsCount = createHashMap();
  18036. // If user spefied `option.aria`, aria will be enable. This detection should be
  18037. // performed before theme and globalDefault merge.
  18038. var airaOption = baseOption.aria;
  18039. if (isObject(airaOption) && airaOption.enabled == null) {
  18040. airaOption.enabled = true;
  18041. }
  18042. mergeTheme(baseOption, ecModel._theme.option);
  18043. // TODO Needs clone when merging to the unexisted property
  18044. merge(baseOption, globalDefault, false);
  18045. ecModel._mergeOption(baseOption, null);
  18046. };
  18047. }();
  18048. return GlobalModel;
  18049. }(Model);
  18050. function isNotTargetSeries(seriesModel, payload) {
  18051. if (payload) {
  18052. var index = payload.seriesIndex;
  18053. var id = payload.seriesId;
  18054. var name_1 = payload.seriesName;
  18055. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  18056. }
  18057. }
  18058. function mergeTheme(option, theme) {
  18059. // PENDING
  18060. // NOT use `colorLayer` in theme if option has `color`
  18061. var notMergeColorLayer = option.color && !option.colorLayer;
  18062. each(theme, function (themeItem, name) {
  18063. if (name === 'colorLayer' && notMergeColorLayer) {
  18064. return;
  18065. }
  18066. // If it is component model mainType, the model handles that merge later.
  18067. // otherwise, merge them here.
  18068. if (!ComponentModel.hasClass(name)) {
  18069. if (typeof themeItem === 'object') {
  18070. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  18071. } else {
  18072. if (option[name] == null) {
  18073. option[name] = themeItem;
  18074. }
  18075. }
  18076. }
  18077. });
  18078. }
  18079. function queryByIdOrName(attr, idOrName, cmpts) {
  18080. // Here is a break from echarts4: string and number are
  18081. // treated as equal.
  18082. if (isArray(idOrName)) {
  18083. var keyMap_1 = createHashMap();
  18084. each(idOrName, function (idOrNameItem) {
  18085. if (idOrNameItem != null) {
  18086. var idName = convertOptionIdName(idOrNameItem, null);
  18087. idName != null && keyMap_1.set(idOrNameItem, true);
  18088. }
  18089. });
  18090. return filter(cmpts, function (cmpt) {
  18091. return cmpt && keyMap_1.get(cmpt[attr]);
  18092. });
  18093. } else {
  18094. var idName_1 = convertOptionIdName(idOrName, null);
  18095. return filter(cmpts, function (cmpt) {
  18096. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  18097. });
  18098. }
  18099. }
  18100. function filterBySubType(components, condition) {
  18101. // Using hasOwnProperty for restrict. Consider
  18102. // subType is undefined in user payload.
  18103. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  18104. return cmpt && cmpt.subType === condition.subType;
  18105. }) : components;
  18106. }
  18107. function normalizeSetOptionInput(opts) {
  18108. var replaceMergeMainTypeMap = createHashMap();
  18109. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  18110. if ("development" !== 'production') {
  18111. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  18112. }
  18113. replaceMergeMainTypeMap.set(mainType, true);
  18114. });
  18115. return {
  18116. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  18117. };
  18118. }
  18119. mixin(GlobalModel, PaletteMixin);
  18120. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL',
  18121. // 'getModel',
  18122. 'getOption',
  18123. // 'getViewOfComponentModel',
  18124. // 'getViewOfSeriesModel',
  18125. 'getId', 'updateLabelLayout'];
  18126. var ExtensionAPI = /** @class */function () {
  18127. function ExtensionAPI(ecInstance) {
  18128. each(availableMethods, function (methodName) {
  18129. this[methodName] = bind(ecInstance[methodName], ecInstance);
  18130. }, this);
  18131. }
  18132. return ExtensionAPI;
  18133. }();
  18134. var coordinateSystemCreators = {};
  18135. var CoordinateSystemManager = /** @class */function () {
  18136. function CoordinateSystemManager() {
  18137. this._coordinateSystems = [];
  18138. }
  18139. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  18140. var coordinateSystems = [];
  18141. each(coordinateSystemCreators, function (creator, type) {
  18142. var list = creator.create(ecModel, api);
  18143. coordinateSystems = coordinateSystems.concat(list || []);
  18144. });
  18145. this._coordinateSystems = coordinateSystems;
  18146. };
  18147. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  18148. each(this._coordinateSystems, function (coordSys) {
  18149. coordSys.update && coordSys.update(ecModel, api);
  18150. });
  18151. };
  18152. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  18153. return this._coordinateSystems.slice();
  18154. };
  18155. CoordinateSystemManager.register = function (type, creator) {
  18156. coordinateSystemCreators[type] = creator;
  18157. };
  18158. CoordinateSystemManager.get = function (type) {
  18159. return coordinateSystemCreators[type];
  18160. };
  18161. return CoordinateSystemManager;
  18162. }();
  18163. var QUERY_REG = /^(min|max)?(.+)$/;
  18164. // Key: mainType
  18165. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  18166. /**
  18167. * TERM EXPLANATIONS:
  18168. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  18169. */
  18170. var OptionManager = /** @class */function () {
  18171. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18172. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18173. // rawOption cloned and backuped when timeline changed, which does no
  18174. // good to performance. What's more, that both timeline and setOption
  18175. // method supply 'notMerge' brings complex and some problems.
  18176. // Consider this case:
  18177. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18178. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18179. function OptionManager(api) {
  18180. this._timelineOptions = [];
  18181. this._mediaList = [];
  18182. /**
  18183. * -1, means default.
  18184. * empty means no media.
  18185. */
  18186. this._currentMediaIndices = [];
  18187. this._api = api;
  18188. }
  18189. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  18190. if (rawOption) {
  18191. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18192. each(normalizeToArray(rawOption.series), function (series) {
  18193. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18194. });
  18195. each(normalizeToArray(rawOption.dataset), function (dataset) {
  18196. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  18197. });
  18198. }
  18199. // Caution: some series modify option data, if do not clone,
  18200. // it should ensure that the repeat modify correctly
  18201. // (create a new object when modify itself).
  18202. rawOption = clone(rawOption);
  18203. // FIXME
  18204. // If some property is set in timeline options or media option but
  18205. // not set in baseOption, a warning should be given.
  18206. var optionBackup = this._optionBackup;
  18207. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  18208. this._newBaseOption = newParsedOption.baseOption;
  18209. // For setOption at second time (using merge mode);
  18210. if (optionBackup) {
  18211. // FIXME
  18212. // the restore merge solution is essentially incorrect.
  18213. // the mapping can not be 100% consistent with ecModel, which probably brings
  18214. // potential bug!
  18215. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  18216. // let fakeCmptsMap = this._fakeCmptsMap;
  18217. // if (!fakeCmptsMap) {
  18218. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  18219. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  18220. // }
  18221. // mergeToBackupOption(
  18222. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  18223. // );
  18224. // For simplicity, timeline options and media options do not support merge,
  18225. // that is, if you `setOption` twice and both has timeline options, the latter
  18226. // timeline options will not be merged to the former, but just substitute them.
  18227. if (newParsedOption.timelineOptions.length) {
  18228. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  18229. }
  18230. if (newParsedOption.mediaList.length) {
  18231. optionBackup.mediaList = newParsedOption.mediaList;
  18232. }
  18233. if (newParsedOption.mediaDefault) {
  18234. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  18235. }
  18236. } else {
  18237. this._optionBackup = newParsedOption;
  18238. }
  18239. };
  18240. OptionManager.prototype.mountOption = function (isRecreate) {
  18241. var optionBackup = this._optionBackup;
  18242. this._timelineOptions = optionBackup.timelineOptions;
  18243. this._mediaList = optionBackup.mediaList;
  18244. this._mediaDefault = optionBackup.mediaDefault;
  18245. this._currentMediaIndices = [];
  18246. return clone(isRecreate
  18247. // this._optionBackup.baseOption, which is created at the first `setOption`
  18248. // called, and is merged into every new option by inner method `mergeToBackupOption`
  18249. // each time `setOption` called, can be only used in `isRecreate`, because
  18250. // its reliability is under suspicion. In other cases option merge is
  18251. // performed by `model.mergeOption`.
  18252. ? optionBackup.baseOption : this._newBaseOption);
  18253. };
  18254. OptionManager.prototype.getTimelineOption = function (ecModel) {
  18255. var option;
  18256. var timelineOptions = this._timelineOptions;
  18257. if (timelineOptions.length) {
  18258. // getTimelineOption can only be called after ecModel inited,
  18259. // so we can get currentIndex from timelineModel.
  18260. var timelineModel = ecModel.getComponent('timeline');
  18261. if (timelineModel) {
  18262. option = clone(
  18263. // FIXME:TS as TimelineModel or quivlant interface
  18264. timelineOptions[timelineModel.getCurrentIndex()]);
  18265. }
  18266. }
  18267. return option;
  18268. };
  18269. OptionManager.prototype.getMediaOption = function (ecModel) {
  18270. var ecWidth = this._api.getWidth();
  18271. var ecHeight = this._api.getHeight();
  18272. var mediaList = this._mediaList;
  18273. var mediaDefault = this._mediaDefault;
  18274. var indices = [];
  18275. var result = [];
  18276. // No media defined.
  18277. if (!mediaList.length && !mediaDefault) {
  18278. return result;
  18279. }
  18280. // Multi media may be applied, the latter defined media has higher priority.
  18281. for (var i = 0, len = mediaList.length; i < len; i++) {
  18282. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18283. indices.push(i);
  18284. }
  18285. }
  18286. // FIXME
  18287. // Whether mediaDefault should force users to provide? Otherwise
  18288. // the change by media query can not be recorvered.
  18289. if (!indices.length && mediaDefault) {
  18290. indices = [-1];
  18291. }
  18292. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18293. result = map(indices, function (index) {
  18294. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18295. });
  18296. }
  18297. // Otherwise return nothing.
  18298. this._currentMediaIndices = indices;
  18299. return result;
  18300. };
  18301. return OptionManager;
  18302. }();
  18303. /**
  18304. * [RAW_OPTION_PATTERNS]
  18305. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18306. *
  18307. * (1) No prop "baseOption" declared:
  18308. * Root option is used as "baseOption" (except prop "options" and "media").
  18309. * ```js
  18310. * option = {
  18311. * series: [],
  18312. * timeline: {},
  18313. * options: [],
  18314. * };
  18315. * option = {
  18316. * series: [],
  18317. * media: {},
  18318. * };
  18319. * option = {
  18320. * series: [],
  18321. * timeline: {},
  18322. * options: [],
  18323. * media: {},
  18324. * }
  18325. * ```
  18326. *
  18327. * (2) Prop "baseOption" declared:
  18328. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18329. * inside "baseOption" except prop "timeline" (compat ec2).
  18330. * ```js
  18331. * option = {
  18332. * baseOption: {
  18333. * timeline: {},
  18334. * series: [],
  18335. * },
  18336. * options: []
  18337. * };
  18338. * option = {
  18339. * baseOption: {
  18340. * series: [],
  18341. * },
  18342. * media: []
  18343. * };
  18344. * option = {
  18345. * baseOption: {
  18346. * timeline: {},
  18347. * series: [],
  18348. * },
  18349. * options: []
  18350. * media: []
  18351. * };
  18352. * option = {
  18353. * // ec3 compat ec2: allow (only) `timeline` declared
  18354. * // outside baseOption. Keep this setting for compat.
  18355. * timeline: {},
  18356. * baseOption: {
  18357. * series: [],
  18358. * },
  18359. * options: [],
  18360. * media: []
  18361. * };
  18362. * ```
  18363. */
  18364. function parseRawOption(
  18365. // `rawOption` May be modified
  18366. rawOption, optionPreprocessorFuncs, isNew) {
  18367. var mediaList = [];
  18368. var mediaDefault;
  18369. var baseOption;
  18370. var declaredBaseOption = rawOption.baseOption;
  18371. // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18372. var timelineOnRoot = rawOption.timeline;
  18373. var timelineOptionsOnRoot = rawOption.options;
  18374. var mediaOnRoot = rawOption.media;
  18375. var hasMedia = !!rawOption.media;
  18376. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18377. if (declaredBaseOption) {
  18378. baseOption = declaredBaseOption;
  18379. // For merge option.
  18380. if (!baseOption.timeline) {
  18381. baseOption.timeline = timelineOnRoot;
  18382. }
  18383. }
  18384. // For convenience, enable to use the root option as the `baseOption`:
  18385. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18386. else {
  18387. if (hasTimeline || hasMedia) {
  18388. rawOption.options = rawOption.media = null;
  18389. }
  18390. baseOption = rawOption;
  18391. }
  18392. if (hasMedia) {
  18393. if (isArray(mediaOnRoot)) {
  18394. each(mediaOnRoot, function (singleMedia) {
  18395. if ("development" !== 'production') {
  18396. // Real case of wrong config.
  18397. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18398. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18399. }
  18400. }
  18401. if (singleMedia && singleMedia.option) {
  18402. if (singleMedia.query) {
  18403. mediaList.push(singleMedia);
  18404. } else if (!mediaDefault) {
  18405. // Use the first media default.
  18406. mediaDefault = singleMedia;
  18407. }
  18408. }
  18409. });
  18410. } else {
  18411. if ("development" !== 'production') {
  18412. // Real case of wrong config.
  18413. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18414. }
  18415. }
  18416. }
  18417. doPreprocess(baseOption);
  18418. each(timelineOptionsOnRoot, function (option) {
  18419. return doPreprocess(option);
  18420. });
  18421. each(mediaList, function (media) {
  18422. return doPreprocess(media.option);
  18423. });
  18424. function doPreprocess(option) {
  18425. each(optionPreprocessorFuncs, function (preProcess) {
  18426. preProcess(option, isNew);
  18427. });
  18428. }
  18429. return {
  18430. baseOption: baseOption,
  18431. timelineOptions: timelineOptionsOnRoot || [],
  18432. mediaDefault: mediaDefault,
  18433. mediaList: mediaList
  18434. };
  18435. }
  18436. /**
  18437. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18438. * Support: width, height, aspectRatio
  18439. * Can use max or min as prefix.
  18440. */
  18441. function applyMediaQuery(query, ecWidth, ecHeight) {
  18442. var realMap = {
  18443. width: ecWidth,
  18444. height: ecHeight,
  18445. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18446. };
  18447. var applicable = true;
  18448. each(query, function (value, attr) {
  18449. var matched = attr.match(QUERY_REG);
  18450. if (!matched || !matched[1] || !matched[2]) {
  18451. return;
  18452. }
  18453. var operator = matched[1];
  18454. var realAttr = matched[2].toLowerCase();
  18455. if (!compare(realMap[realAttr], value, operator)) {
  18456. applicable = false;
  18457. }
  18458. });
  18459. return applicable;
  18460. }
  18461. function compare(real, expect, operator) {
  18462. if (operator === 'min') {
  18463. return real >= expect;
  18464. } else if (operator === 'max') {
  18465. return real <= expect;
  18466. } else {
  18467. // Equals
  18468. return real === expect;
  18469. }
  18470. }
  18471. function indicesEquals(indices1, indices2) {
  18472. // indices is always order by asc and has only finite number.
  18473. return indices1.join(',') === indices2.join(',');
  18474. }
  18475. var each$2 = each;
  18476. var isObject$1 = isObject;
  18477. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18478. function compatEC2ItemStyle(opt) {
  18479. var itemStyleOpt = opt && opt.itemStyle;
  18480. if (!itemStyleOpt) {
  18481. return;
  18482. }
  18483. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18484. var styleName = POSSIBLE_STYLES[i];
  18485. var normalItemStyleOpt = itemStyleOpt.normal;
  18486. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18487. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18488. if ("development" !== 'production') {
  18489. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18490. }
  18491. opt[styleName] = opt[styleName] || {};
  18492. if (!opt[styleName].normal) {
  18493. opt[styleName].normal = normalItemStyleOpt[styleName];
  18494. } else {
  18495. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18496. }
  18497. normalItemStyleOpt[styleName] = null;
  18498. }
  18499. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18500. if ("development" !== 'production') {
  18501. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18502. }
  18503. opt[styleName] = opt[styleName] || {};
  18504. if (!opt[styleName].emphasis) {
  18505. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18506. } else {
  18507. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18508. }
  18509. emphasisItemStyleOpt[styleName] = null;
  18510. }
  18511. }
  18512. }
  18513. function convertNormalEmphasis(opt, optType, useExtend) {
  18514. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18515. var normalOpt = opt[optType].normal;
  18516. var emphasisOpt = opt[optType].emphasis;
  18517. if (normalOpt) {
  18518. if ("development" !== 'production') {
  18519. // eslint-disable-next-line max-len
  18520. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18521. }
  18522. // Timeline controlStyle has other properties besides normal and emphasis
  18523. if (useExtend) {
  18524. opt[optType].normal = opt[optType].emphasis = null;
  18525. defaults(opt[optType], normalOpt);
  18526. } else {
  18527. opt[optType] = normalOpt;
  18528. }
  18529. }
  18530. if (emphasisOpt) {
  18531. if ("development" !== 'production') {
  18532. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18533. }
  18534. opt.emphasis = opt.emphasis || {};
  18535. opt.emphasis[optType] = emphasisOpt;
  18536. // Also compat the case user mix the style and focus together in ec3 style
  18537. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18538. if (emphasisOpt.focus) {
  18539. opt.emphasis.focus = emphasisOpt.focus;
  18540. }
  18541. if (emphasisOpt.blurScope) {
  18542. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18543. }
  18544. }
  18545. }
  18546. }
  18547. function removeEC3NormalStatus(opt) {
  18548. convertNormalEmphasis(opt, 'itemStyle');
  18549. convertNormalEmphasis(opt, 'lineStyle');
  18550. convertNormalEmphasis(opt, 'areaStyle');
  18551. convertNormalEmphasis(opt, 'label');
  18552. convertNormalEmphasis(opt, 'labelLine');
  18553. // treemap
  18554. convertNormalEmphasis(opt, 'upperLabel');
  18555. // graph
  18556. convertNormalEmphasis(opt, 'edgeLabel');
  18557. }
  18558. function compatTextStyle(opt, propName) {
  18559. // Check whether is not object (string\null\undefined ...)
  18560. var labelOptSingle = isObject$1(opt) && opt[propName];
  18561. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18562. if (textStyle) {
  18563. if ("development" !== 'production') {
  18564. // eslint-disable-next-line max-len
  18565. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18566. }
  18567. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18568. var textPropName = TEXT_STYLE_OPTIONS[i];
  18569. if (textStyle.hasOwnProperty(textPropName)) {
  18570. labelOptSingle[textPropName] = textStyle[textPropName];
  18571. }
  18572. }
  18573. }
  18574. }
  18575. function compatEC3CommonStyles(opt) {
  18576. if (opt) {
  18577. removeEC3NormalStatus(opt);
  18578. compatTextStyle(opt, 'label');
  18579. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18580. }
  18581. }
  18582. function processSeries(seriesOpt) {
  18583. if (!isObject$1(seriesOpt)) {
  18584. return;
  18585. }
  18586. compatEC2ItemStyle(seriesOpt);
  18587. removeEC3NormalStatus(seriesOpt);
  18588. compatTextStyle(seriesOpt, 'label');
  18589. // treemap
  18590. compatTextStyle(seriesOpt, 'upperLabel');
  18591. // graph
  18592. compatTextStyle(seriesOpt, 'edgeLabel');
  18593. if (seriesOpt.emphasis) {
  18594. compatTextStyle(seriesOpt.emphasis, 'label');
  18595. // treemap
  18596. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18597. // graph
  18598. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18599. }
  18600. var markPoint = seriesOpt.markPoint;
  18601. if (markPoint) {
  18602. compatEC2ItemStyle(markPoint);
  18603. compatEC3CommonStyles(markPoint);
  18604. }
  18605. var markLine = seriesOpt.markLine;
  18606. if (markLine) {
  18607. compatEC2ItemStyle(markLine);
  18608. compatEC3CommonStyles(markLine);
  18609. }
  18610. var markArea = seriesOpt.markArea;
  18611. if (markArea) {
  18612. compatEC3CommonStyles(markArea);
  18613. }
  18614. var data = seriesOpt.data;
  18615. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18616. // then the backward compat based on option type will not be performed.
  18617. if (seriesOpt.type === 'graph') {
  18618. data = data || seriesOpt.nodes;
  18619. var edgeData = seriesOpt.links || seriesOpt.edges;
  18620. if (edgeData && !isTypedArray(edgeData)) {
  18621. for (var i = 0; i < edgeData.length; i++) {
  18622. compatEC3CommonStyles(edgeData[i]);
  18623. }
  18624. }
  18625. each(seriesOpt.categories, function (opt) {
  18626. removeEC3NormalStatus(opt);
  18627. });
  18628. }
  18629. if (data && !isTypedArray(data)) {
  18630. for (var i = 0; i < data.length; i++) {
  18631. compatEC3CommonStyles(data[i]);
  18632. }
  18633. }
  18634. // mark point data
  18635. markPoint = seriesOpt.markPoint;
  18636. if (markPoint && markPoint.data) {
  18637. var mpData = markPoint.data;
  18638. for (var i = 0; i < mpData.length; i++) {
  18639. compatEC3CommonStyles(mpData[i]);
  18640. }
  18641. }
  18642. // mark line data
  18643. markLine = seriesOpt.markLine;
  18644. if (markLine && markLine.data) {
  18645. var mlData = markLine.data;
  18646. for (var i = 0; i < mlData.length; i++) {
  18647. if (isArray(mlData[i])) {
  18648. compatEC3CommonStyles(mlData[i][0]);
  18649. compatEC3CommonStyles(mlData[i][1]);
  18650. } else {
  18651. compatEC3CommonStyles(mlData[i]);
  18652. }
  18653. }
  18654. }
  18655. // Series
  18656. if (seriesOpt.type === 'gauge') {
  18657. compatTextStyle(seriesOpt, 'axisLabel');
  18658. compatTextStyle(seriesOpt, 'title');
  18659. compatTextStyle(seriesOpt, 'detail');
  18660. } else if (seriesOpt.type === 'treemap') {
  18661. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18662. each(seriesOpt.levels, function (opt) {
  18663. removeEC3NormalStatus(opt);
  18664. });
  18665. } else if (seriesOpt.type === 'tree') {
  18666. removeEC3NormalStatus(seriesOpt.leaves);
  18667. }
  18668. // sunburst starts from ec4, so it does not need to compat levels.
  18669. }
  18670. function toArr(o) {
  18671. return isArray(o) ? o : o ? [o] : [];
  18672. }
  18673. function toObj(o) {
  18674. return (isArray(o) ? o[0] : o) || {};
  18675. }
  18676. function globalCompatStyle(option, isTheme) {
  18677. each$2(toArr(option.series), function (seriesOpt) {
  18678. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18679. });
  18680. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18681. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18682. each$2(axes, function (axisName) {
  18683. each$2(toArr(option[axisName]), function (axisOpt) {
  18684. if (axisOpt) {
  18685. compatTextStyle(axisOpt, 'axisLabel');
  18686. compatTextStyle(axisOpt.axisPointer, 'label');
  18687. }
  18688. });
  18689. });
  18690. each$2(toArr(option.parallel), function (parallelOpt) {
  18691. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18692. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18693. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18694. });
  18695. each$2(toArr(option.calendar), function (calendarOpt) {
  18696. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18697. compatTextStyle(calendarOpt, 'dayLabel');
  18698. compatTextStyle(calendarOpt, 'monthLabel');
  18699. compatTextStyle(calendarOpt, 'yearLabel');
  18700. });
  18701. // radar.name.textStyle
  18702. each$2(toArr(option.radar), function (radarOpt) {
  18703. compatTextStyle(radarOpt, 'name');
  18704. // Use axisName instead of name because component has name property
  18705. if (radarOpt.name && radarOpt.axisName == null) {
  18706. radarOpt.axisName = radarOpt.name;
  18707. delete radarOpt.name;
  18708. if ("development" !== 'production') {
  18709. deprecateLog('name property in radar component has been changed to axisName');
  18710. }
  18711. }
  18712. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18713. radarOpt.axisNameGap = radarOpt.nameGap;
  18714. delete radarOpt.nameGap;
  18715. if ("development" !== 'production') {
  18716. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18717. }
  18718. }
  18719. if ("development" !== 'production') {
  18720. each$2(radarOpt.indicator, function (indicatorOpt) {
  18721. if (indicatorOpt.text) {
  18722. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18723. }
  18724. });
  18725. }
  18726. });
  18727. each$2(toArr(option.geo), function (geoOpt) {
  18728. if (isObject$1(geoOpt)) {
  18729. compatEC3CommonStyles(geoOpt);
  18730. each$2(toArr(geoOpt.regions), function (regionObj) {
  18731. compatEC3CommonStyles(regionObj);
  18732. });
  18733. }
  18734. });
  18735. each$2(toArr(option.timeline), function (timelineOpt) {
  18736. compatEC3CommonStyles(timelineOpt);
  18737. convertNormalEmphasis(timelineOpt, 'label');
  18738. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18739. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18740. var data = timelineOpt.data;
  18741. isArray(data) && each(data, function (item) {
  18742. if (isObject(item)) {
  18743. convertNormalEmphasis(item, 'label');
  18744. convertNormalEmphasis(item, 'itemStyle');
  18745. }
  18746. });
  18747. });
  18748. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18749. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18750. each$2(toolboxOpt.feature, function (featureOpt) {
  18751. convertNormalEmphasis(featureOpt, 'iconStyle');
  18752. });
  18753. });
  18754. compatTextStyle(toObj(option.axisPointer), 'label');
  18755. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18756. // Clean logs
  18757. // storedLogs = {};
  18758. }
  18759. function get(opt, path) {
  18760. var pathArr = path.split(',');
  18761. var obj = opt;
  18762. for (var i = 0; i < pathArr.length; i++) {
  18763. obj = obj && obj[pathArr[i]];
  18764. if (obj == null) {
  18765. break;
  18766. }
  18767. }
  18768. return obj;
  18769. }
  18770. function set$1(opt, path, val, overwrite) {
  18771. var pathArr = path.split(',');
  18772. var obj = opt;
  18773. var key;
  18774. var i = 0;
  18775. for (; i < pathArr.length - 1; i++) {
  18776. key = pathArr[i];
  18777. if (obj[key] == null) {
  18778. obj[key] = {};
  18779. }
  18780. obj = obj[key];
  18781. }
  18782. if (overwrite || obj[pathArr[i]] == null) {
  18783. obj[pathArr[i]] = val;
  18784. }
  18785. }
  18786. function compatLayoutProperties(option) {
  18787. option && each(LAYOUT_PROPERTIES, function (prop) {
  18788. if (prop[0] in option && !(prop[1] in option)) {
  18789. option[prop[1]] = option[prop[0]];
  18790. }
  18791. });
  18792. }
  18793. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18794. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18795. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18796. function compatBarItemStyle(option) {
  18797. var itemStyle = option && option.itemStyle;
  18798. if (itemStyle) {
  18799. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18800. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18801. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18802. if (itemStyle[oldName] != null) {
  18803. itemStyle[newName] = itemStyle[oldName];
  18804. if ("development" !== 'production') {
  18805. deprecateReplaceLog(oldName, newName);
  18806. }
  18807. }
  18808. }
  18809. }
  18810. }
  18811. function compatPieLabel(option) {
  18812. if (!option) {
  18813. return;
  18814. }
  18815. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18816. if ("development" !== 'production') {
  18817. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18818. }
  18819. option.edgeDistance = option.margin;
  18820. }
  18821. }
  18822. function compatSunburstState(option) {
  18823. if (!option) {
  18824. return;
  18825. }
  18826. if (option.downplay && !option.blur) {
  18827. option.blur = option.downplay;
  18828. if ("development" !== 'production') {
  18829. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18830. }
  18831. }
  18832. }
  18833. function compatGraphFocus(option) {
  18834. if (!option) {
  18835. return;
  18836. }
  18837. if (option.focusNodeAdjacency != null) {
  18838. option.emphasis = option.emphasis || {};
  18839. if (option.emphasis.focus == null) {
  18840. if ("development" !== 'production') {
  18841. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18842. }
  18843. option.emphasis.focus = 'adjacency';
  18844. }
  18845. }
  18846. }
  18847. function traverseTree(data, cb) {
  18848. if (data) {
  18849. for (var i = 0; i < data.length; i++) {
  18850. cb(data[i]);
  18851. data[i] && traverseTree(data[i].children, cb);
  18852. }
  18853. }
  18854. }
  18855. function globalBackwardCompat(option, isTheme) {
  18856. globalCompatStyle(option, isTheme);
  18857. // Make sure series array for model initialization.
  18858. option.series = normalizeToArray(option.series);
  18859. each(option.series, function (seriesOpt) {
  18860. if (!isObject(seriesOpt)) {
  18861. return;
  18862. }
  18863. var seriesType = seriesOpt.type;
  18864. if (seriesType === 'line') {
  18865. if (seriesOpt.clipOverflow != null) {
  18866. seriesOpt.clip = seriesOpt.clipOverflow;
  18867. if ("development" !== 'production') {
  18868. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18869. }
  18870. }
  18871. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18872. if (seriesOpt.clockWise != null) {
  18873. seriesOpt.clockwise = seriesOpt.clockWise;
  18874. if ("development" !== 'production') {
  18875. deprecateReplaceLog('clockWise', 'clockwise');
  18876. }
  18877. }
  18878. compatPieLabel(seriesOpt.label);
  18879. var data = seriesOpt.data;
  18880. if (data && !isTypedArray(data)) {
  18881. for (var i = 0; i < data.length; i++) {
  18882. compatPieLabel(data[i]);
  18883. }
  18884. }
  18885. if (seriesOpt.hoverOffset != null) {
  18886. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18887. if (seriesOpt.emphasis.scaleSize = null) {
  18888. if ("development" !== 'production') {
  18889. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18890. }
  18891. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18892. }
  18893. }
  18894. } else if (seriesType === 'gauge') {
  18895. var pointerColor = get(seriesOpt, 'pointer.color');
  18896. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18897. } else if (seriesType === 'bar') {
  18898. compatBarItemStyle(seriesOpt);
  18899. compatBarItemStyle(seriesOpt.backgroundStyle);
  18900. compatBarItemStyle(seriesOpt.emphasis);
  18901. var data = seriesOpt.data;
  18902. if (data && !isTypedArray(data)) {
  18903. for (var i = 0; i < data.length; i++) {
  18904. if (typeof data[i] === 'object') {
  18905. compatBarItemStyle(data[i]);
  18906. compatBarItemStyle(data[i] && data[i].emphasis);
  18907. }
  18908. }
  18909. }
  18910. } else if (seriesType === 'sunburst') {
  18911. var highlightPolicy = seriesOpt.highlightPolicy;
  18912. if (highlightPolicy) {
  18913. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18914. if (!seriesOpt.emphasis.focus) {
  18915. seriesOpt.emphasis.focus = highlightPolicy;
  18916. if ("development" !== 'production') {
  18917. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18918. }
  18919. }
  18920. }
  18921. compatSunburstState(seriesOpt);
  18922. traverseTree(seriesOpt.data, compatSunburstState);
  18923. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18924. compatGraphFocus(seriesOpt);
  18925. // TODO nodes, edges?
  18926. } else if (seriesType === 'map') {
  18927. if (seriesOpt.mapType && !seriesOpt.map) {
  18928. if ("development" !== 'production') {
  18929. deprecateReplaceLog('mapType', 'map', 'map');
  18930. }
  18931. seriesOpt.map = seriesOpt.mapType;
  18932. }
  18933. if (seriesOpt.mapLocation) {
  18934. if ("development" !== 'production') {
  18935. deprecateLog('`mapLocation` is not used anymore.');
  18936. }
  18937. defaults(seriesOpt, seriesOpt.mapLocation);
  18938. }
  18939. }
  18940. if (seriesOpt.hoverAnimation != null) {
  18941. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18942. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18943. if ("development" !== 'production') {
  18944. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18945. }
  18946. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18947. }
  18948. }
  18949. compatLayoutProperties(seriesOpt);
  18950. });
  18951. // dataRange has changed to visualMap
  18952. if (option.dataRange) {
  18953. option.visualMap = option.dataRange;
  18954. }
  18955. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18956. var options = option[componentName];
  18957. if (options) {
  18958. if (!isArray(options)) {
  18959. options = [options];
  18960. }
  18961. each(options, function (option) {
  18962. compatLayoutProperties(option);
  18963. });
  18964. }
  18965. });
  18966. }
  18967. // (1) [Caution]: the logic is correct based on the premises:
  18968. // data processing stage is blocked in stream.
  18969. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18970. // (2) Only register once when import repeatedly.
  18971. // Should be executed after series is filtered and before stack calculation.
  18972. function dataStack(ecModel) {
  18973. var stackInfoMap = createHashMap();
  18974. ecModel.eachSeries(function (seriesModel) {
  18975. var stack = seriesModel.get('stack');
  18976. // Compatible: when `stack` is set as '', do not stack.
  18977. if (stack) {
  18978. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18979. var data = seriesModel.getData();
  18980. var stackInfo = {
  18981. // Used for calculate axis extent automatically.
  18982. // TODO: Type getCalculationInfo return more specific type?
  18983. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18984. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18985. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18986. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18987. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18988. data: data,
  18989. seriesModel: seriesModel
  18990. };
  18991. // If stacked on axis that do not support data stack.
  18992. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18993. return;
  18994. }
  18995. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18996. stackInfoList.push(stackInfo);
  18997. }
  18998. });
  18999. stackInfoMap.each(calculateStack);
  19000. }
  19001. function calculateStack(stackInfoList) {
  19002. each(stackInfoList, function (targetStackInfo, idxInStack) {
  19003. var resultVal = [];
  19004. var resultNaN = [NaN, NaN];
  19005. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19006. var targetData = targetStackInfo.data;
  19007. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19008. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign';
  19009. // Should not write on raw data, because stack series model list changes
  19010. // depending on legend selection.
  19011. targetData.modify(dims, function (v0, v1, dataIndex) {
  19012. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19013. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19014. // should also be NaN, to draw a appropriate belt area.
  19015. if (isNaN(sum)) {
  19016. return resultNaN;
  19017. }
  19018. var byValue;
  19019. var stackedDataRawIndex;
  19020. if (isStackedByIndex) {
  19021. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19022. } else {
  19023. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19024. }
  19025. // If stackOver is NaN, chart view will render point on value start.
  19026. var stackedOver = NaN;
  19027. for (var j = idxInStack - 1; j >= 0; j--) {
  19028. var stackInfo = stackInfoList[j];
  19029. // Has been optimized by inverted indices on `stackedByDimension`.
  19030. if (!isStackedByIndex) {
  19031. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19032. }
  19033. if (stackedDataRawIndex >= 0) {
  19034. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19035. // Considering positive stack, negative stack and empty data
  19036. if (stackStrategy === 'all' // single stack group
  19037. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  19038. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  19039. ) {
  19040. // The sum has to be very small to be affected by the
  19041. // floating arithmetic problem. An incorrect result will probably
  19042. // cause axis min/max to be filtered incorrectly.
  19043. sum = addSafe(sum, val);
  19044. stackedOver = val;
  19045. break;
  19046. }
  19047. }
  19048. }
  19049. resultVal[0] = sum;
  19050. resultVal[1] = stackedOver;
  19051. return resultVal;
  19052. });
  19053. });
  19054. }
  19055. // @inner
  19056. var SourceImpl = /** @class */function () {
  19057. function SourceImpl(fields) {
  19058. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  19059. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  19060. // Visit config
  19061. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  19062. this.startIndex = fields.startIndex || 0;
  19063. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  19064. this.metaRawOption = fields.metaRawOption;
  19065. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  19066. if (dimensionsDefine) {
  19067. for (var i = 0; i < dimensionsDefine.length; i++) {
  19068. var dim = dimensionsDefine[i];
  19069. if (dim.type == null) {
  19070. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  19071. dim.type = 'ordinal';
  19072. }
  19073. }
  19074. }
  19075. }
  19076. }
  19077. return SourceImpl;
  19078. }();
  19079. function isSourceInstance(val) {
  19080. return val instanceof SourceImpl;
  19081. }
  19082. /**
  19083. * Create a source from option.
  19084. * NOTE: Created source is immutable. Don't change any properties in it.
  19085. */
  19086. function createSource(sourceData, thisMetaRawOption,
  19087. // can be null. If not provided, auto detect it from `sourceData`.
  19088. sourceFormat) {
  19089. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  19090. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  19091. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  19092. var source = new SourceImpl({
  19093. data: sourceData,
  19094. sourceFormat: sourceFormat,
  19095. seriesLayoutBy: seriesLayoutBy,
  19096. dimensionsDefine: determined.dimensionsDefine,
  19097. startIndex: determined.startIndex,
  19098. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  19099. metaRawOption: clone(thisMetaRawOption)
  19100. });
  19101. return source;
  19102. }
  19103. /**
  19104. * Wrap original series data for some compatibility cases.
  19105. */
  19106. function createSourceFromSeriesDataOption(data) {
  19107. return new SourceImpl({
  19108. data: data,
  19109. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  19110. });
  19111. }
  19112. /**
  19113. * Clone source but excludes source data.
  19114. */
  19115. function cloneSourceShallow(source) {
  19116. return new SourceImpl({
  19117. data: source.data,
  19118. sourceFormat: source.sourceFormat,
  19119. seriesLayoutBy: source.seriesLayoutBy,
  19120. dimensionsDefine: clone(source.dimensionsDefine),
  19121. startIndex: source.startIndex,
  19122. dimensionsDetectedCount: source.dimensionsDetectedCount
  19123. });
  19124. }
  19125. /**
  19126. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  19127. */
  19128. function detectSourceFormat(data) {
  19129. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  19130. if (isTypedArray(data)) {
  19131. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  19132. } else if (isArray(data)) {
  19133. // FIXME Whether tolerate null in top level array?
  19134. if (data.length === 0) {
  19135. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19136. }
  19137. for (var i = 0, len = data.length; i < len; i++) {
  19138. var item = data[i];
  19139. if (item == null) {
  19140. continue;
  19141. } else if (isArray(item) || isTypedArray(item)) {
  19142. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19143. break;
  19144. } else if (isObject(item)) {
  19145. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  19146. break;
  19147. }
  19148. }
  19149. } else if (isObject(data)) {
  19150. for (var key in data) {
  19151. if (hasOwn(data, key) && isArrayLike(data[key])) {
  19152. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  19153. break;
  19154. }
  19155. }
  19156. }
  19157. return sourceFormat;
  19158. }
  19159. /**
  19160. * Determine the source definitions from data standalone dimensions definitions
  19161. * are not specified.
  19162. */
  19163. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader,
  19164. // standalone raw dimensions definition, like:
  19165. // {
  19166. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  19167. // }
  19168. // in `dataset` or `series`
  19169. dimensionsDefine) {
  19170. var dimensionsDetectedCount;
  19171. var startIndex;
  19172. // PENDING: Could data be null/undefined here?
  19173. // currently, if `dataset.source` not specified, error thrown.
  19174. // if `series.data` not specified, nothing rendered without error thrown.
  19175. // Should test these cases.
  19176. if (!data) {
  19177. return {
  19178. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19179. startIndex: startIndex,
  19180. dimensionsDetectedCount: dimensionsDetectedCount
  19181. };
  19182. }
  19183. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19184. var dataArrayRows = data;
  19185. // Rule: Most of the first line are string: it is header.
  19186. // Caution: consider a line with 5 string and 1 number,
  19187. // it still can not be sure it is a head, because the
  19188. // 5 string may be 5 values of category columns.
  19189. if (sourceHeader === 'auto' || sourceHeader == null) {
  19190. arrayRowsTravelFirst(function (val) {
  19191. // '-' is regarded as null/undefined.
  19192. if (val != null && val !== '-') {
  19193. if (isString(val)) {
  19194. startIndex == null && (startIndex = 1);
  19195. } else {
  19196. startIndex = 0;
  19197. }
  19198. }
  19199. // 10 is an experience number, avoid long loop.
  19200. }, seriesLayoutBy, dataArrayRows, 10);
  19201. } else {
  19202. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  19203. }
  19204. if (!dimensionsDefine && startIndex === 1) {
  19205. dimensionsDefine = [];
  19206. arrayRowsTravelFirst(function (val, index) {
  19207. dimensionsDefine[index] = val != null ? val + '' : '';
  19208. }, seriesLayoutBy, dataArrayRows, Infinity);
  19209. }
  19210. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  19211. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19212. if (!dimensionsDefine) {
  19213. dimensionsDefine = objectRowsCollectDimensions(data);
  19214. }
  19215. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19216. if (!dimensionsDefine) {
  19217. dimensionsDefine = [];
  19218. each(data, function (colArr, key) {
  19219. dimensionsDefine.push(key);
  19220. });
  19221. }
  19222. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19223. var value0 = getDataItemValue(data[0]);
  19224. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  19225. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19226. if ("development" !== 'production') {
  19227. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  19228. }
  19229. }
  19230. return {
  19231. startIndex: startIndex,
  19232. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19233. dimensionsDetectedCount: dimensionsDetectedCount
  19234. };
  19235. }
  19236. function objectRowsCollectDimensions(data) {
  19237. var firstIndex = 0;
  19238. var obj;
  19239. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  19240. if (obj) {
  19241. return keys(obj);
  19242. }
  19243. }
  19244. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  19245. // which is reasonable. But dimension name is duplicated.
  19246. // Returns undefined or an array contains only object without null/undefined or string.
  19247. function normalizeDimensionsOption(dimensionsDefine) {
  19248. if (!dimensionsDefine) {
  19249. // The meaning of null/undefined is different from empty array.
  19250. return;
  19251. }
  19252. var nameMap = createHashMap();
  19253. return map(dimensionsDefine, function (rawItem, index) {
  19254. rawItem = isObject(rawItem) ? rawItem : {
  19255. name: rawItem
  19256. };
  19257. // Other fields will be discarded.
  19258. var item = {
  19259. name: rawItem.name,
  19260. displayName: rawItem.displayName,
  19261. type: rawItem.type
  19262. };
  19263. // User can set null in dimensions.
  19264. // We don't auto specify name, otherwise a given name may
  19265. // cause it to be referred unexpectedly.
  19266. if (item.name == null) {
  19267. return item;
  19268. }
  19269. // Also consider number form like 2012.
  19270. item.name += '';
  19271. // User may also specify displayName.
  19272. // displayName will always exists except user not
  19273. // specified or dim name is not specified or detected.
  19274. // (A auto generated dim name will not be used as
  19275. // displayName).
  19276. if (item.displayName == null) {
  19277. item.displayName = item.name;
  19278. }
  19279. var exist = nameMap.get(item.name);
  19280. if (!exist) {
  19281. nameMap.set(item.name, {
  19282. count: 1
  19283. });
  19284. } else {
  19285. item.name += '-' + exist.count++;
  19286. }
  19287. return item;
  19288. });
  19289. }
  19290. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  19291. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19292. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19293. cb(data[i] ? data[i][0] : null, i);
  19294. }
  19295. } else {
  19296. var value0 = data[0] || [];
  19297. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  19298. cb(value0[i], i);
  19299. }
  19300. }
  19301. }
  19302. function shouldRetrieveDataByName(source) {
  19303. var sourceFormat = source.sourceFormat;
  19304. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  19305. }
  19306. /*
  19307. * Licensed to the Apache Software Foundation (ASF) under one
  19308. * or more contributor license agreements. See the NOTICE file
  19309. * distributed with this work for additional information
  19310. * regarding copyright ownership. The ASF licenses this file
  19311. * to you under the Apache License, Version 2.0 (the
  19312. * "License"); you may not use this file except in compliance
  19313. * with the License. You may obtain a copy of the License at
  19314. *
  19315. * http://www.apache.org/licenses/LICENSE-2.0
  19316. *
  19317. * Unless required by applicable law or agreed to in writing,
  19318. * software distributed under the License is distributed on an
  19319. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19320. * KIND, either express or implied. See the License for the
  19321. * specific language governing permissions and limitations
  19322. * under the License.
  19323. */
  19324. /**
  19325. * AUTO-GENERATED FILE. DO NOT MODIFY.
  19326. */
  19327. /*
  19328. * Licensed to the Apache Software Foundation (ASF) under one
  19329. * or more contributor license agreements. See the NOTICE file
  19330. * distributed with this work for additional information
  19331. * regarding copyright ownership. The ASF licenses this file
  19332. * to you under the Apache License, Version 2.0 (the
  19333. * "License"); you may not use this file except in compliance
  19334. * with the License. You may obtain a copy of the License at
  19335. *
  19336. * http://www.apache.org/licenses/LICENSE-2.0
  19337. *
  19338. * Unless required by applicable law or agreed to in writing,
  19339. * software distributed under the License is distributed on an
  19340. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19341. * KIND, either express or implied. See the License for the
  19342. * specific language governing permissions and limitations
  19343. * under the License.
  19344. */
  19345. var _a, _b, _c;
  19346. var providerMethods;
  19347. var mountMethods;
  19348. /**
  19349. * If normal array used, mutable chunk size is supported.
  19350. * If typed array used, chunk size must be fixed.
  19351. */
  19352. var DefaultDataProvider = /** @class */function () {
  19353. function DefaultDataProvider(sourceParam, dimSize) {
  19354. // let source: Source;
  19355. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam;
  19356. // declare source is Source;
  19357. this._source = source;
  19358. var data = this._data = source.data;
  19359. // Typed array. TODO IE10+?
  19360. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19361. if ("development" !== 'production') {
  19362. if (dimSize == null) {
  19363. throw new Error('Typed array data must specify dimension size');
  19364. }
  19365. }
  19366. this._offset = 0;
  19367. this._dimSize = dimSize;
  19368. this._data = data;
  19369. }
  19370. mountMethods(this, data, source);
  19371. }
  19372. DefaultDataProvider.prototype.getSource = function () {
  19373. return this._source;
  19374. };
  19375. DefaultDataProvider.prototype.count = function () {
  19376. return 0;
  19377. };
  19378. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19379. return;
  19380. };
  19381. DefaultDataProvider.prototype.appendData = function (newData) {};
  19382. DefaultDataProvider.prototype.clean = function () {};
  19383. DefaultDataProvider.protoInitialize = function () {
  19384. // PENDING: To avoid potential incompat (e.g., prototype
  19385. // is visited somewhere), still init them on prototype.
  19386. var proto = DefaultDataProvider.prototype;
  19387. proto.pure = false;
  19388. proto.persistent = true;
  19389. }();
  19390. DefaultDataProvider.internalField = function () {
  19391. var _a;
  19392. mountMethods = function (provider, data, source) {
  19393. var sourceFormat = source.sourceFormat;
  19394. var seriesLayoutBy = source.seriesLayoutBy;
  19395. var startIndex = source.startIndex;
  19396. var dimsDef = source.dimensionsDefine;
  19397. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19398. if ("development" !== 'production') {
  19399. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19400. }
  19401. extend(provider, methods);
  19402. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19403. provider.getItem = getItemForTypedArray;
  19404. provider.count = countForTypedArray;
  19405. provider.fillStorage = fillStorageForTypedArray;
  19406. } else {
  19407. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19408. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19409. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19410. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19411. }
  19412. };
  19413. var getItemForTypedArray = function (idx, out) {
  19414. idx = idx - this._offset;
  19415. out = out || [];
  19416. var data = this._data;
  19417. var dimSize = this._dimSize;
  19418. var offset = dimSize * idx;
  19419. for (var i = 0; i < dimSize; i++) {
  19420. out[i] = data[offset + i];
  19421. }
  19422. return out;
  19423. };
  19424. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19425. var data = this._data;
  19426. var dimSize = this._dimSize;
  19427. for (var dim = 0; dim < dimSize; dim++) {
  19428. var dimExtent = extent[dim];
  19429. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19430. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19431. var count = end - start;
  19432. var arr = storage[dim];
  19433. for (var i = 0; i < count; i++) {
  19434. // appendData with TypedArray will always do replace in provider.
  19435. var val = data[i * dimSize + dim];
  19436. arr[start + i] = val;
  19437. val < min && (min = val);
  19438. val > max && (max = val);
  19439. }
  19440. dimExtent[0] = min;
  19441. dimExtent[1] = max;
  19442. }
  19443. };
  19444. var countForTypedArray = function () {
  19445. return this._data ? this._data.length / this._dimSize : 0;
  19446. };
  19447. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19448. pure: true,
  19449. appendData: appendDataSimply
  19450. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19451. pure: true,
  19452. appendData: function () {
  19453. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19454. }
  19455. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19456. pure: true,
  19457. appendData: appendDataSimply
  19458. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19459. pure: true,
  19460. appendData: function (newData) {
  19461. var data = this._data;
  19462. each(newData, function (newCol, key) {
  19463. var oldCol = data[key] || (data[key] = []);
  19464. for (var i = 0; i < (newCol || []).length; i++) {
  19465. oldCol.push(newCol[i]);
  19466. }
  19467. });
  19468. }
  19469. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19470. appendData: appendDataSimply
  19471. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19472. persistent: false,
  19473. pure: true,
  19474. appendData: function (newData) {
  19475. if ("development" !== 'production') {
  19476. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19477. }
  19478. this._data = newData;
  19479. },
  19480. // Clean self if data is already used.
  19481. clean: function () {
  19482. // PENDING
  19483. this._offset += this.count();
  19484. this._data = null;
  19485. }
  19486. }, _a);
  19487. function appendDataSimply(newData) {
  19488. for (var i = 0; i < newData.length; i++) {
  19489. this._data.push(newData[i]);
  19490. }
  19491. }
  19492. }();
  19493. return DefaultDataProvider;
  19494. }();
  19495. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19496. return rawData[idx];
  19497. };
  19498. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19499. return rawData[idx + startIndex];
  19500. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19501. idx += startIndex;
  19502. var item = out || [];
  19503. var data = rawData;
  19504. for (var i = 0; i < data.length; i++) {
  19505. var row = data[i];
  19506. item[i] = row ? row[idx] : null;
  19507. }
  19508. return item;
  19509. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19510. var item = out || [];
  19511. for (var i = 0; i < dimsDef.length; i++) {
  19512. var dimName = dimsDef[i].name;
  19513. if ("development" !== 'production') {
  19514. if (dimName == null) {
  19515. throw new Error();
  19516. }
  19517. }
  19518. var col = rawData[dimName];
  19519. item[i] = col ? col[idx] : null;
  19520. }
  19521. return item;
  19522. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19523. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19524. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19525. if ("development" !== 'production') {
  19526. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19527. }
  19528. return method;
  19529. }
  19530. var countSimply = function (rawData, startIndex, dimsDef) {
  19531. return rawData.length;
  19532. };
  19533. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19534. return Math.max(0, rawData.length - startIndex);
  19535. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19536. var row = rawData[0];
  19537. return row ? Math.max(0, row.length - startIndex) : 0;
  19538. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19539. var dimName = dimsDef[0].name;
  19540. if ("development" !== 'production') {
  19541. if (dimName == null) {
  19542. throw new Error();
  19543. }
  19544. }
  19545. var col = rawData[dimName];
  19546. return col ? col.length : 0;
  19547. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19548. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19549. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19550. if ("development" !== 'production') {
  19551. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19552. }
  19553. return method;
  19554. }
  19555. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19556. return dataItem[dimIndex];
  19557. };
  19558. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19559. return dataItem[property];
  19560. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19561. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19562. // dataItem is {coord: [...]}
  19563. var value = getDataItemValue(dataItem);
  19564. return !(value instanceof Array) ? value : value[dimIndex];
  19565. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19566. function getRawSourceValueGetter(sourceFormat) {
  19567. var method = rawSourceValueGetterMap[sourceFormat];
  19568. if ("development" !== 'production') {
  19569. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19570. }
  19571. return method;
  19572. }
  19573. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19574. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19575. }
  19576. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19577. // Consider persistent.
  19578. // Caution: why use raw value to display on label or tooltip?
  19579. // A reason is to avoid format. For example time value we do not know
  19580. // how to format is expected. More over, if stack is used, calculated
  19581. // value may be 0.91000000001, which have brings trouble to display.
  19582. // TODO: consider how to treat null/undefined/NaN when display?
  19583. function retrieveRawValue(data, dataIndex,
  19584. // If dimIndex is null/undefined, return OptionDataItem.
  19585. // Otherwise, return OptionDataValue.
  19586. dim) {
  19587. if (!data) {
  19588. return;
  19589. }
  19590. // Consider data may be not persistent.
  19591. var dataItem = data.getRawDataItem(dataIndex);
  19592. if (dataItem == null) {
  19593. return;
  19594. }
  19595. var store = data.getStore();
  19596. var sourceFormat = store.getSource().sourceFormat;
  19597. if (dim != null) {
  19598. var dimIndex = data.getDimensionIndex(dim);
  19599. var property = store.getDimensionProperty(dimIndex);
  19600. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19601. } else {
  19602. var result = dataItem;
  19603. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19604. result = getDataItemValue(dataItem);
  19605. }
  19606. return result;
  19607. }
  19608. }
  19609. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19610. var DataFormatMixin = /** @class */function () {
  19611. function DataFormatMixin() {}
  19612. /**
  19613. * Get params for formatter
  19614. */
  19615. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19616. var data = this.getData(dataType);
  19617. var rawValue = this.getRawValue(dataIndex, dataType);
  19618. var rawDataIndex = data.getRawIndex(dataIndex);
  19619. var name = data.getName(dataIndex);
  19620. var itemOpt = data.getRawDataItem(dataIndex);
  19621. var style = data.getItemVisual(dataIndex, 'style');
  19622. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19623. var borderColor = style && style.stroke;
  19624. var mainType = this.mainType;
  19625. var isSeries = mainType === 'series';
  19626. var userOutput = data.userOutput && data.userOutput.get();
  19627. return {
  19628. componentType: mainType,
  19629. componentSubType: this.subType,
  19630. componentIndex: this.componentIndex,
  19631. seriesType: isSeries ? this.subType : null,
  19632. seriesIndex: this.seriesIndex,
  19633. seriesId: isSeries ? this.id : null,
  19634. seriesName: isSeries ? this.name : null,
  19635. name: name,
  19636. dataIndex: rawDataIndex,
  19637. data: itemOpt,
  19638. dataType: dataType,
  19639. value: rawValue,
  19640. color: color,
  19641. borderColor: borderColor,
  19642. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19643. encode: userOutput ? userOutput.encode : null,
  19644. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19645. $vars: ['seriesName', 'name', 'value']
  19646. };
  19647. };
  19648. /**
  19649. * Format label
  19650. * @param dataIndex
  19651. * @param status 'normal' by default
  19652. * @param dataType
  19653. * @param labelDimIndex Only used in some chart that
  19654. * use formatter in different dimensions, like radar.
  19655. * @param formatter Formatter given outside.
  19656. * @return return null/undefined if no formatter
  19657. */
  19658. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19659. status = status || 'normal';
  19660. var data = this.getData(dataType);
  19661. var params = this.getDataParams(dataIndex, dataType);
  19662. if (extendParams) {
  19663. params.value = extendParams.interpolatedValue;
  19664. }
  19665. if (labelDimIndex != null && isArray(params.value)) {
  19666. params.value = params.value[labelDimIndex];
  19667. }
  19668. if (!formatter) {
  19669. var itemModel = data.getItemModel(dataIndex);
  19670. // @ts-ignore
  19671. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19672. }
  19673. if (isFunction(formatter)) {
  19674. params.status = status;
  19675. params.dimensionIndex = labelDimIndex;
  19676. return formatter(params);
  19677. } else if (isString(formatter)) {
  19678. var str = formatTpl(formatter, params);
  19679. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19680. // Do not support '}' in dim name util have to.
  19681. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19682. var len = dimStr.length;
  19683. var dimLoose = dimStr;
  19684. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19685. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19686. if ("development" !== 'production') {
  19687. if (isNaN(dimLoose)) {
  19688. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19689. }
  19690. }
  19691. }
  19692. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19693. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19694. var dimIndex = data.getDimensionIndex(dimLoose);
  19695. if (dimIndex >= 0) {
  19696. val = extendParams.interpolatedValue[dimIndex];
  19697. }
  19698. }
  19699. return val != null ? val + '' : '';
  19700. });
  19701. }
  19702. };
  19703. /**
  19704. * Get raw value in option
  19705. */
  19706. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19707. return retrieveRawValue(this.getData(dataType), idx);
  19708. };
  19709. /**
  19710. * Should be implemented.
  19711. * @param {number} dataIndex
  19712. * @param {boolean} [multipleSeries=false]
  19713. * @param {string} [dataType]
  19714. */
  19715. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19716. // Empty function
  19717. return;
  19718. };
  19719. return DataFormatMixin;
  19720. }();
  19721. // PENDING: previously we accept this type when calling `formatTooltip`,
  19722. // but guess little chance has been used outside. Do we need to backward
  19723. // compat it?
  19724. // type TooltipFormatResultLegacyObject = {
  19725. // // `html` means the markup language text, either in 'html' or 'richText'.
  19726. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19727. // // string. But still support it for backward compatibility.
  19728. // html: string;
  19729. // markers: Dictionary<ColorString>;
  19730. // };
  19731. /**
  19732. * For backward compat, normalize the return from `formatTooltip`.
  19733. */
  19734. function normalizeTooltipFormatResult(result) {
  19735. var markupText;
  19736. // let markers: Dictionary<ColorString>;
  19737. var markupFragment;
  19738. if (isObject(result)) {
  19739. if (result.type) {
  19740. markupFragment = result;
  19741. } else {
  19742. if ("development" !== 'production') {
  19743. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19744. }
  19745. }
  19746. // else {
  19747. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19748. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19749. // if (markersExisting) {
  19750. // markers = zrUtil.merge(markersExisting, markers);
  19751. // }
  19752. // }
  19753. } else {
  19754. markupText = result;
  19755. }
  19756. return {
  19757. text: markupText,
  19758. // markers: markers || markersExisting,
  19759. frag: markupFragment
  19760. };
  19761. }
  19762. /**
  19763. * @param {Object} define
  19764. * @return See the return of `createTask`.
  19765. */
  19766. function createTask(define) {
  19767. return new Task(define);
  19768. }
  19769. var Task = /** @class */function () {
  19770. function Task(define) {
  19771. define = define || {};
  19772. this._reset = define.reset;
  19773. this._plan = define.plan;
  19774. this._count = define.count;
  19775. this._onDirty = define.onDirty;
  19776. this._dirty = true;
  19777. }
  19778. /**
  19779. * @param step Specified step.
  19780. * @param skip Skip customer perform call.
  19781. * @param modBy Sampling window size.
  19782. * @param modDataCount Sampling count.
  19783. * @return whether unfinished.
  19784. */
  19785. Task.prototype.perform = function (performArgs) {
  19786. var upTask = this._upstream;
  19787. var skip = performArgs && performArgs.skip;
  19788. // TODO some refactor.
  19789. // Pull data. Must pull data each time, because context.data
  19790. // may be updated by Series.setData.
  19791. if (this._dirty && upTask) {
  19792. var context = this.context;
  19793. context.data = context.outputData = upTask.context.outputData;
  19794. }
  19795. if (this.__pipeline) {
  19796. this.__pipeline.currentTask = this;
  19797. }
  19798. var planResult;
  19799. if (this._plan && !skip) {
  19800. planResult = this._plan(this.context);
  19801. }
  19802. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19803. // elements uniformed distributed when progress, especially when moving or zooming.
  19804. var lastModBy = normalizeModBy(this._modBy);
  19805. var lastModDataCount = this._modDataCount || 0;
  19806. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19807. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19808. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19809. planResult = 'reset';
  19810. }
  19811. function normalizeModBy(val) {
  19812. !(val >= 1) && (val = 1); // jshint ignore:line
  19813. return val;
  19814. }
  19815. var forceFirstProgress;
  19816. if (this._dirty || planResult === 'reset') {
  19817. this._dirty = false;
  19818. forceFirstProgress = this._doReset(skip);
  19819. }
  19820. this._modBy = modBy;
  19821. this._modDataCount = modDataCount;
  19822. var step = performArgs && performArgs.step;
  19823. if (upTask) {
  19824. if ("development" !== 'production') {
  19825. assert(upTask._outputDueEnd != null);
  19826. }
  19827. this._dueEnd = upTask._outputDueEnd;
  19828. }
  19829. // DataTask or overallTask
  19830. else {
  19831. if ("development" !== 'production') {
  19832. assert(!this._progress || this._count);
  19833. }
  19834. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19835. }
  19836. // Note: Stubs, that its host overall task let it has progress, has progress.
  19837. // If no progress, pass index from upstream to downstream each time plan called.
  19838. if (this._progress) {
  19839. var start = this._dueIndex;
  19840. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19841. if (!skip && (forceFirstProgress || start < end)) {
  19842. var progress = this._progress;
  19843. if (isArray(progress)) {
  19844. for (var i = 0; i < progress.length; i++) {
  19845. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19846. }
  19847. } else {
  19848. this._doProgress(progress, start, end, modBy, modDataCount);
  19849. }
  19850. }
  19851. this._dueIndex = end;
  19852. // If no `outputDueEnd`, assume that output data and
  19853. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19854. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19855. if ("development" !== 'production') {
  19856. // ??? Can not rollback.
  19857. assert(outputDueEnd >= this._outputDueEnd);
  19858. }
  19859. this._outputDueEnd = outputDueEnd;
  19860. } else {
  19861. // (1) Some overall task has no progress.
  19862. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19863. // This should always be performed so it can be passed to downstream.
  19864. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19865. }
  19866. return this.unfinished();
  19867. };
  19868. Task.prototype.dirty = function () {
  19869. this._dirty = true;
  19870. this._onDirty && this._onDirty(this.context);
  19871. };
  19872. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19873. iterator.reset(start, end, modBy, modDataCount);
  19874. this._callingProgress = progress;
  19875. this._callingProgress({
  19876. start: start,
  19877. end: end,
  19878. count: end - start,
  19879. next: iterator.next
  19880. }, this.context);
  19881. };
  19882. Task.prototype._doReset = function (skip) {
  19883. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19884. this._settedOutputEnd = null;
  19885. var progress;
  19886. var forceFirstProgress;
  19887. if (!skip && this._reset) {
  19888. progress = this._reset(this.context);
  19889. if (progress && progress.progress) {
  19890. forceFirstProgress = progress.forceFirstProgress;
  19891. progress = progress.progress;
  19892. }
  19893. // To simplify no progress checking, array must has item.
  19894. if (isArray(progress) && !progress.length) {
  19895. progress = null;
  19896. }
  19897. }
  19898. this._progress = progress;
  19899. this._modBy = this._modDataCount = null;
  19900. var downstream = this._downstream;
  19901. downstream && downstream.dirty();
  19902. return forceFirstProgress;
  19903. };
  19904. Task.prototype.unfinished = function () {
  19905. return this._progress && this._dueIndex < this._dueEnd;
  19906. };
  19907. /**
  19908. * @param downTask The downstream task.
  19909. * @return The downstream task.
  19910. */
  19911. Task.prototype.pipe = function (downTask) {
  19912. if ("development" !== 'production') {
  19913. assert(downTask && !downTask._disposed && downTask !== this);
  19914. }
  19915. // If already downstream, do not dirty downTask.
  19916. if (this._downstream !== downTask || this._dirty) {
  19917. this._downstream = downTask;
  19918. downTask._upstream = this;
  19919. downTask.dirty();
  19920. }
  19921. };
  19922. Task.prototype.dispose = function () {
  19923. if (this._disposed) {
  19924. return;
  19925. }
  19926. this._upstream && (this._upstream._downstream = null);
  19927. this._downstream && (this._downstream._upstream = null);
  19928. this._dirty = false;
  19929. this._disposed = true;
  19930. };
  19931. Task.prototype.getUpstream = function () {
  19932. return this._upstream;
  19933. };
  19934. Task.prototype.getDownstream = function () {
  19935. return this._downstream;
  19936. };
  19937. Task.prototype.setOutputEnd = function (end) {
  19938. // This only happens in dataTask, dataZoom, map, currently.
  19939. // where dataZoom do not set end each time, but only set
  19940. // when reset. So we should record the set end, in case
  19941. // that the stub of dataZoom perform again and earse the
  19942. // set end by upstream.
  19943. this._outputDueEnd = this._settedOutputEnd = end;
  19944. };
  19945. return Task;
  19946. }();
  19947. var iterator = function () {
  19948. var end;
  19949. var current;
  19950. var modBy;
  19951. var modDataCount;
  19952. var winCount;
  19953. var it = {
  19954. reset: function (s, e, sStep, sCount) {
  19955. current = s;
  19956. end = e;
  19957. modBy = sStep;
  19958. modDataCount = sCount;
  19959. winCount = Math.ceil(modDataCount / modBy);
  19960. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19961. }
  19962. };
  19963. return it;
  19964. function sequentialNext() {
  19965. return current < end ? current++ : null;
  19966. }
  19967. function modNext() {
  19968. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19969. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex
  19970. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19971. // Use normal linear rendering mode.
  19972. : current;
  19973. current++;
  19974. return result;
  19975. }
  19976. }();
  19977. // -----------------------------------------------------------------------------
  19978. // For stream debug (Should be commented out after used!)
  19979. // @usage: printTask(this, 'begin');
  19980. // @usage: printTask(this, null, {someExtraProp});
  19981. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19982. //
  19983. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19984. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19985. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19986. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19987. // let props = [];
  19988. // if (task.__pipeline) {
  19989. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19990. // props.push({text: '__idxInPipeline/total', value: val});
  19991. // } else {
  19992. // let stubCount = 0;
  19993. // task.agentStubMap.each(() => stubCount++);
  19994. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19995. // }
  19996. // props.push({text: 'uid', value: task.uidDebug});
  19997. // if (task.__pipeline) {
  19998. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19999. // task.agent && props.push(
  20000. // {text: 'stubFor', value: task.agent.uidDebug}
  20001. // );
  20002. // }
  20003. // props.push(
  20004. // {text: 'dirty', value: task._dirty},
  20005. // {text: 'dueIndex', value: task._dueIndex},
  20006. // {text: 'dueEnd', value: task._dueEnd},
  20007. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20008. // );
  20009. // if (extra) {
  20010. // Object.keys(extra).forEach(key => {
  20011. // props.push({text: key, value: extra[key]});
  20012. // });
  20013. // }
  20014. // let args = ['color: blue'];
  20015. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20016. // args.push('color: green', 'color: red'),
  20017. // `${item.text}: %c${item.value}`
  20018. // )).join('%c, ');
  20019. // console.log.apply(console, [msg].concat(args));
  20020. // // console.log(this);
  20021. // };
  20022. // window.printPipeline = function (task: any, prefix: string) {
  20023. // const pipeline = task.__pipeline;
  20024. // let currTask = pipeline.head;
  20025. // while (currTask) {
  20026. // window.printTask(currTask, prefix);
  20027. // currTask = currTask._downstream;
  20028. // }
  20029. // };
  20030. // window.showChain = function (chainHeadTask) {
  20031. // var chain = [];
  20032. // var task = chainHeadTask;
  20033. // while (task) {
  20034. // chain.push({
  20035. // task: task,
  20036. // up: task._upstream,
  20037. // down: task._downstream,
  20038. // idxInPipeline: task.__idxInPipeline
  20039. // });
  20040. // task = task._downstream;
  20041. // }
  20042. // return chain;
  20043. // };
  20044. // window.findTaskInChain = function (task, chainHeadTask) {
  20045. // let chain = window.showChain(chainHeadTask);
  20046. // let result = [];
  20047. // for (let i = 0; i < chain.length; i++) {
  20048. // let chainItem = chain[i];
  20049. // if (chainItem.task === task) {
  20050. // result.push(i);
  20051. // }
  20052. // }
  20053. // return result;
  20054. // };
  20055. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  20056. // let chainA = window.showChain(chainHeadTaskA);
  20057. // for (let i = 0; i < chainA.length; i++) {
  20058. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  20059. // }
  20060. // };
  20061. /**
  20062. * Convert raw the value in to inner value in List.
  20063. *
  20064. * [Performance sensitive]
  20065. *
  20066. * [Caution]: this is the key logic of user value parser.
  20067. * For backward compatibility, do not modify it until you have to!
  20068. */
  20069. function parseDataValue(value,
  20070. // For high performance, do not omit the second param.
  20071. opt) {
  20072. // Performance sensitive.
  20073. var dimType = opt && opt.type;
  20074. if (dimType === 'ordinal') {
  20075. // If given value is a category string
  20076. return value;
  20077. }
  20078. if (dimType === 'time'
  20079. // spead up when using timestamp
  20080. && !isNumber(value) && value != null && value !== '-') {
  20081. value = +parseDate(value);
  20082. }
  20083. // dimType defaults 'number'.
  20084. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20085. // parse to NaN.
  20086. // number-like string (like ' 123 ') can be converted to a number.
  20087. // where null/undefined or other string will be converted to NaN.
  20088. return value == null || value === '' ? NaN
  20089. // If string (like '-'), using '+' parse to NaN
  20090. // If object, also parse to NaN
  20091. : Number(value);
  20092. }
  20093. var valueParserMap = createHashMap({
  20094. 'number': function (val) {
  20095. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  20096. // Here the number parser can have loose rule:
  20097. // enable to cut suffix: "120px" => 120, "14%" => 14.
  20098. return parseFloat(val);
  20099. },
  20100. 'time': function (val) {
  20101. // return timestamp.
  20102. return +parseDate(val);
  20103. },
  20104. 'trim': function (val) {
  20105. return isString(val) ? trim(val) : val;
  20106. }
  20107. });
  20108. var SortOrderComparator = /** @class */function () {
  20109. /**
  20110. * @param order by default: 'asc'
  20111. * @param incomparable by default: Always on the tail.
  20112. * That is, if 'asc' => 'max', if 'desc' => 'min'
  20113. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  20114. */
  20115. function SortOrderComparator(order, incomparable) {
  20116. var isDesc = order === 'desc';
  20117. this._resultLT = isDesc ? 1 : -1;
  20118. if (incomparable == null) {
  20119. incomparable = isDesc ? 'min' : 'max';
  20120. }
  20121. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  20122. }
  20123. // See [SORT_COMPARISON_RULE].
  20124. // Performance sensitive.
  20125. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  20126. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  20127. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  20128. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  20129. var lvalNotNumeric = isNaN(lvalFloat);
  20130. var rvalNotNumeric = isNaN(rvalFloat);
  20131. if (lvalNotNumeric) {
  20132. lvalFloat = this._incomparable;
  20133. }
  20134. if (rvalNotNumeric) {
  20135. rvalFloat = this._incomparable;
  20136. }
  20137. if (lvalNotNumeric && rvalNotNumeric) {
  20138. var lvalIsStr = isString(lval);
  20139. var rvalIsStr = isString(rval);
  20140. if (lvalIsStr) {
  20141. lvalFloat = rvalIsStr ? lval : 0;
  20142. }
  20143. if (rvalIsStr) {
  20144. rvalFloat = lvalIsStr ? rval : 0;
  20145. }
  20146. }
  20147. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  20148. };
  20149. return SortOrderComparator;
  20150. }();
  20151. /**
  20152. * TODO: disable writable.
  20153. * This structure will be exposed to users.
  20154. */
  20155. var ExternalSource = /** @class */function () {
  20156. function ExternalSource() {}
  20157. ExternalSource.prototype.getRawData = function () {
  20158. // Only built-in transform available.
  20159. throw new Error('not supported');
  20160. };
  20161. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  20162. // Only built-in transform available.
  20163. throw new Error('not supported');
  20164. };
  20165. ExternalSource.prototype.cloneRawData = function () {
  20166. return;
  20167. };
  20168. /**
  20169. * @return If dimension not found, return null/undefined.
  20170. */
  20171. ExternalSource.prototype.getDimensionInfo = function (dim) {
  20172. return;
  20173. };
  20174. /**
  20175. * dimensions defined if and only if either:
  20176. * (a) dataset.dimensions are declared.
  20177. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  20178. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  20179. * the defined dimensions.
  20180. * Otherwise, `dimensionInfoAll` is determined by data columns.
  20181. * @return Always return an array (even empty array).
  20182. */
  20183. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  20184. return;
  20185. };
  20186. ExternalSource.prototype.count = function () {
  20187. return;
  20188. };
  20189. /**
  20190. * Only support by dimension index.
  20191. * No need to support by dimension name in transform function,
  20192. * because transform function is not case-specific, no need to use name literally.
  20193. */
  20194. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  20195. return;
  20196. };
  20197. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  20198. return;
  20199. };
  20200. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  20201. return parseDataValue(rawVal, dimInfo);
  20202. };
  20203. return ExternalSource;
  20204. }();
  20205. function createExternalSource(internalSource, externalTransform) {
  20206. var extSource = new ExternalSource();
  20207. var data = internalSource.data;
  20208. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  20209. var sourceHeaderCount = internalSource.startIndex;
  20210. var errMsg = '';
  20211. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  20212. // For the logic simplicity in transformer, only 'culumn' is
  20213. // supported in data transform. Otherwise, the `dimensionsDefine`
  20214. // might be detected by 'row', which probably confuses users.
  20215. if ("development" !== 'production') {
  20216. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  20217. }
  20218. throwError(errMsg);
  20219. }
  20220. // [MEMO]
  20221. // Create a new dimensions structure for exposing.
  20222. // Do not expose all dimension info to users directly.
  20223. // Because the dimension is probably auto detected from data and not might reliable.
  20224. // Should not lead the transformers to think that is reliable and return it.
  20225. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20226. var dimensions = [];
  20227. var dimsByName = {};
  20228. var dimsDef = internalSource.dimensionsDefine;
  20229. if (dimsDef) {
  20230. each(dimsDef, function (dimDef, idx) {
  20231. var name = dimDef.name;
  20232. var dimDefExt = {
  20233. index: idx,
  20234. name: name,
  20235. displayName: dimDef.displayName
  20236. };
  20237. dimensions.push(dimDefExt);
  20238. // Users probably do not specify dimension name. For simplicity, data transform
  20239. // does not generate dimension name.
  20240. if (name != null) {
  20241. // Dimension name should not be duplicated.
  20242. // For simplicity, data transform forbids name duplication, do not generate
  20243. // new name like module `completeDimensions.ts` did, but just tell users.
  20244. var errMsg_1 = '';
  20245. if (hasOwn(dimsByName, name)) {
  20246. if ("development" !== 'production') {
  20247. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  20248. }
  20249. throwError(errMsg_1);
  20250. }
  20251. dimsByName[name] = dimDefExt;
  20252. }
  20253. });
  20254. }
  20255. // If dimension definitions are not defined and can not be detected.
  20256. // e.g., pure data `[[11, 22], ...]`.
  20257. else {
  20258. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  20259. // Do not generete name or anything others. The consequence process in
  20260. // `transform` or `series` probably have there own name generation strategry.
  20261. dimensions.push({
  20262. index: i
  20263. });
  20264. }
  20265. }
  20266. // Implement public methods:
  20267. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20268. if (externalTransform.__isBuiltIn) {
  20269. extSource.getRawDataItem = function (dataIndex) {
  20270. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20271. };
  20272. extSource.getRawData = bind(getRawData, null, internalSource);
  20273. }
  20274. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  20275. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20276. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  20277. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  20278. extSource.retrieveValue = function (dataIndex, dimIndex) {
  20279. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20280. return retrieveValueFromItem(rawItem, dimIndex);
  20281. };
  20282. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  20283. if (dataItem == null) {
  20284. return;
  20285. }
  20286. var dimDef = dimensions[dimIndex];
  20287. // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  20288. if (dimDef) {
  20289. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  20290. }
  20291. };
  20292. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  20293. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  20294. return extSource;
  20295. }
  20296. function getRawData(upstream) {
  20297. var sourceFormat = upstream.sourceFormat;
  20298. if (!isSupportedSourceFormat(sourceFormat)) {
  20299. var errMsg = '';
  20300. if ("development" !== 'production') {
  20301. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  20302. }
  20303. throwError(errMsg);
  20304. }
  20305. return upstream.data;
  20306. }
  20307. function cloneRawData(upstream) {
  20308. var sourceFormat = upstream.sourceFormat;
  20309. var data = upstream.data;
  20310. if (!isSupportedSourceFormat(sourceFormat)) {
  20311. var errMsg = '';
  20312. if ("development" !== 'production') {
  20313. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  20314. }
  20315. throwError(errMsg);
  20316. }
  20317. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20318. var result = [];
  20319. for (var i = 0, len = data.length; i < len; i++) {
  20320. // Not strictly clone for performance
  20321. result.push(data[i].slice());
  20322. }
  20323. return result;
  20324. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20325. var result = [];
  20326. for (var i = 0, len = data.length; i < len; i++) {
  20327. // Not strictly clone for performance
  20328. result.push(extend({}, data[i]));
  20329. }
  20330. return result;
  20331. }
  20332. }
  20333. function getDimensionInfo(dimensions, dimsByName, dim) {
  20334. if (dim == null) {
  20335. return;
  20336. }
  20337. // Keep the same logic as `List::getDimension` did.
  20338. if (isNumber(dim)
  20339. // If being a number-like string but not being defined a dimension name.
  20340. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20341. return dimensions[dim];
  20342. } else if (hasOwn(dimsByName, dim)) {
  20343. return dimsByName[dim];
  20344. }
  20345. }
  20346. function cloneAllDimensionInfo(dimensions) {
  20347. return clone(dimensions);
  20348. }
  20349. var externalTransformMap = createHashMap();
  20350. function registerExternalTransform(externalTransform) {
  20351. externalTransform = clone(externalTransform);
  20352. var type = externalTransform.type;
  20353. var errMsg = '';
  20354. if (!type) {
  20355. if ("development" !== 'production') {
  20356. errMsg = 'Must have a `type` when `registerTransform`.';
  20357. }
  20358. throwError(errMsg);
  20359. }
  20360. var typeParsed = type.split(':');
  20361. if (typeParsed.length !== 2) {
  20362. if ("development" !== 'production') {
  20363. errMsg = 'Name must include namespace like "ns:regression".';
  20364. }
  20365. throwError(errMsg);
  20366. }
  20367. // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20368. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20369. var isBuiltIn = false;
  20370. if (typeParsed[0] === 'echarts') {
  20371. type = typeParsed[1];
  20372. isBuiltIn = true;
  20373. }
  20374. externalTransform.__isBuiltIn = isBuiltIn;
  20375. externalTransformMap.set(type, externalTransform);
  20376. }
  20377. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20378. var pipedTransOption = normalizeToArray(rawTransOption);
  20379. var pipeLen = pipedTransOption.length;
  20380. var errMsg = '';
  20381. if (!pipeLen) {
  20382. if ("development" !== 'production') {
  20383. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20384. }
  20385. throwError(errMsg);
  20386. }
  20387. for (var i = 0, len = pipeLen; i < len; i++) {
  20388. var transOption = pipedTransOption[i];
  20389. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i);
  20390. // piped transform only support single input, except the fist one.
  20391. // piped transform only support single output, except the last one.
  20392. if (i !== len - 1) {
  20393. sourceList.length = Math.max(sourceList.length, 1);
  20394. }
  20395. }
  20396. return sourceList;
  20397. }
  20398. function applySingleDataTransform(transOption, upSourceList, infoForPrint,
  20399. // If `pipeIndex` is null/undefined, no piped transform.
  20400. pipeIndex) {
  20401. var errMsg = '';
  20402. if (!upSourceList.length) {
  20403. if ("development" !== 'production') {
  20404. errMsg = 'Must have at least one upstream dataset.';
  20405. }
  20406. throwError(errMsg);
  20407. }
  20408. if (!isObject(transOption)) {
  20409. if ("development" !== 'production') {
  20410. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20411. }
  20412. throwError(errMsg);
  20413. }
  20414. var transType = transOption.type;
  20415. var externalTransform = externalTransformMap.get(transType);
  20416. if (!externalTransform) {
  20417. if ("development" !== 'production') {
  20418. errMsg = 'Can not find transform on type "' + transType + '".';
  20419. }
  20420. throwError(errMsg);
  20421. }
  20422. // Prepare source
  20423. var extUpSourceList = map(upSourceList, function (upSource) {
  20424. return createExternalSource(upSource, externalTransform);
  20425. });
  20426. var resultList = normalizeToArray(externalTransform.transform({
  20427. upstream: extUpSourceList[0],
  20428. upstreamList: extUpSourceList,
  20429. config: clone(transOption.config)
  20430. }));
  20431. if ("development" !== 'production') {
  20432. if (transOption.print) {
  20433. var printStrArr = map(resultList, function (extSource) {
  20434. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20435. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20436. }).join('\n');
  20437. log(printStrArr);
  20438. }
  20439. }
  20440. return map(resultList, function (result, resultIndex) {
  20441. var errMsg = '';
  20442. if (!isObject(result)) {
  20443. if ("development" !== 'production') {
  20444. errMsg = 'A transform should not return some empty results.';
  20445. }
  20446. throwError(errMsg);
  20447. }
  20448. if (!result.data) {
  20449. if ("development" !== 'production') {
  20450. errMsg = 'Transform result data should be not be null or undefined';
  20451. }
  20452. throwError(errMsg);
  20453. }
  20454. var sourceFormat = detectSourceFormat(result.data);
  20455. if (!isSupportedSourceFormat(sourceFormat)) {
  20456. if ("development" !== 'production') {
  20457. errMsg = 'Transform result data should be array rows or object rows.';
  20458. }
  20459. throwError(errMsg);
  20460. }
  20461. var resultMetaRawOption;
  20462. var firstUpSource = upSourceList[0];
  20463. /**
  20464. * Intuitively, the end users known the content of the original `dataset.source`,
  20465. * calucating the transform result in mind.
  20466. * Suppose the original `dataset.source` is:
  20467. * ```js
  20468. * [
  20469. * ['product', '2012', '2013', '2014', '2015'],
  20470. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20471. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20472. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20473. * ]
  20474. * ```
  20475. * The dimension info have to be detected from the source data.
  20476. * Some of the transformers (like filter, sort) will follow the dimension info
  20477. * of upstream, while others use new dimensions (like aggregate).
  20478. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20479. * We also allow transformers to ignore the output `dimensions` field, and
  20480. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20481. * dimensions in transformers.
  20482. *
  20483. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20484. */
  20485. if (firstUpSource && resultIndex === 0
  20486. // If transformer returns `dimensions`, it means that the transformer has different
  20487. // dimensions definitions. We do not inherit anything from upstream.
  20488. && !result.dimensions) {
  20489. var startIndex = firstUpSource.startIndex;
  20490. // We copy the header of upstream to the result, because:
  20491. // (1) The returned data always does not contain header line and can not be used
  20492. // as dimension-detection. In this case we can not use "detected dimensions" of
  20493. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20494. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20495. // So the original detected header should be add to the result, otherwise they can not be read.
  20496. if (startIndex) {
  20497. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20498. }
  20499. resultMetaRawOption = {
  20500. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20501. sourceHeader: startIndex,
  20502. dimensions: firstUpSource.metaRawOption.dimensions
  20503. };
  20504. } else {
  20505. resultMetaRawOption = {
  20506. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20507. sourceHeader: 0,
  20508. dimensions: result.dimensions
  20509. };
  20510. }
  20511. return createSource(result.data, resultMetaRawOption, null);
  20512. });
  20513. }
  20514. function isSupportedSourceFormat(sourceFormat) {
  20515. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20516. }
  20517. var UNDEFINED = 'undefined';
  20518. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20519. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20520. // different from the Ctor of typed array.
  20521. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20522. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20523. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20524. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20525. /**
  20526. * Multi dimensional data store
  20527. */
  20528. var dataCtors = {
  20529. 'float': CtorFloat64Array,
  20530. 'int': CtorInt32Array,
  20531. // Ordinal data type can be string or int
  20532. 'ordinal': Array,
  20533. 'number': Array,
  20534. 'time': CtorFloat64Array
  20535. };
  20536. var defaultDimValueGetters;
  20537. function getIndicesCtor(rawCount) {
  20538. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20539. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20540. }
  20541. function getInitialExtent() {
  20542. return [Infinity, -Infinity];
  20543. }
  20544. function cloneChunk(originalChunk) {
  20545. var Ctor = originalChunk.constructor;
  20546. // Only shallow clone is enough when Array.
  20547. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20548. }
  20549. function prepareStore(store, dimIdx, dimType, end, append) {
  20550. var DataCtor = dataCtors[dimType || 'float'];
  20551. if (append) {
  20552. var oldStore = store[dimIdx];
  20553. var oldLen = oldStore && oldStore.length;
  20554. if (!(oldLen === end)) {
  20555. var newStore = new DataCtor(end);
  20556. // The cost of the copy is probably inconsiderable
  20557. // within the initial chunkSize.
  20558. for (var j = 0; j < oldLen; j++) {
  20559. newStore[j] = oldStore[j];
  20560. }
  20561. store[dimIdx] = newStore;
  20562. }
  20563. } else {
  20564. store[dimIdx] = new DataCtor(end);
  20565. }
  20566. }
  20567. /**
  20568. * Basically, DataStore API keep immutable.
  20569. */
  20570. var DataStore = /** @class */function () {
  20571. function DataStore() {
  20572. this._chunks = [];
  20573. // It will not be calculated until needed.
  20574. this._rawExtent = [];
  20575. this._extent = [];
  20576. this._count = 0;
  20577. this._rawCount = 0;
  20578. this._calcDimNameToIdx = createHashMap();
  20579. }
  20580. /**
  20581. * Initialize from data
  20582. */
  20583. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20584. if ("development" !== 'production') {
  20585. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20586. }
  20587. this._provider = provider;
  20588. // Clear
  20589. this._chunks = [];
  20590. this._indices = null;
  20591. this.getRawIndex = this._getRawIdxIdentity;
  20592. var source = provider.getSource();
  20593. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat];
  20594. // Default dim value getter
  20595. this._dimValueGetter = dimValueGetter || defaultGetter;
  20596. // Reset raw extent.
  20597. this._rawExtent = [];
  20598. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20599. this._dimensions = map(inputDimensions, function (dim) {
  20600. if ("development" !== 'production') {
  20601. if (willRetrieveDataByName) {
  20602. assert(dim.property != null);
  20603. }
  20604. }
  20605. return {
  20606. // Only pick these two props. Not leak other properties like orderMeta.
  20607. type: dim.type,
  20608. property: dim.property
  20609. };
  20610. });
  20611. this._initDataFromProvider(0, provider.count());
  20612. };
  20613. DataStore.prototype.getProvider = function () {
  20614. return this._provider;
  20615. };
  20616. /**
  20617. * Caution: even when a `source` instance owned by a series, the created data store
  20618. * may still be shared by different sereis (the source hash does not use all `source`
  20619. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20620. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20621. * thus should not be fetch here.
  20622. */
  20623. DataStore.prototype.getSource = function () {
  20624. return this._provider.getSource();
  20625. };
  20626. /**
  20627. * @caution Only used in dataStack.
  20628. */
  20629. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20630. var calcDimNameToIdx = this._calcDimNameToIdx;
  20631. var dimensions = this._dimensions;
  20632. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20633. if (calcDimIdx != null) {
  20634. if (dimensions[calcDimIdx].type === type) {
  20635. return calcDimIdx;
  20636. }
  20637. } else {
  20638. calcDimIdx = dimensions.length;
  20639. }
  20640. dimensions[calcDimIdx] = {
  20641. type: type
  20642. };
  20643. calcDimNameToIdx.set(dimName, calcDimIdx);
  20644. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20645. this._rawExtent[calcDimIdx] = getInitialExtent();
  20646. return calcDimIdx;
  20647. };
  20648. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20649. var chunk = this._chunks[dimIdx];
  20650. var dim = this._dimensions[dimIdx];
  20651. var rawExtents = this._rawExtent;
  20652. var offset = dim.ordinalOffset || 0;
  20653. var len = chunk.length;
  20654. if (offset === 0) {
  20655. // We need to reset the rawExtent if collect is from start.
  20656. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20657. rawExtents[dimIdx] = getInitialExtent();
  20658. }
  20659. var dimRawExtent = rawExtents[dimIdx];
  20660. // Parse from previous data offset. len may be changed after appendData
  20661. for (var i = offset; i < len; i++) {
  20662. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20663. if (!isNaN(val)) {
  20664. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20665. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20666. }
  20667. }
  20668. dim.ordinalMeta = ordinalMeta;
  20669. dim.ordinalOffset = len;
  20670. dim.type = 'ordinal'; // Force to be ordinal
  20671. };
  20672. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20673. var dimInfo = this._dimensions[dimIdx];
  20674. var ordinalMeta = dimInfo.ordinalMeta;
  20675. return ordinalMeta;
  20676. };
  20677. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20678. var item = this._dimensions[dimIndex];
  20679. return item && item.property;
  20680. };
  20681. /**
  20682. * Caution: Can be only called on raw data (before `this._indices` created).
  20683. */
  20684. DataStore.prototype.appendData = function (data) {
  20685. if ("development" !== 'production') {
  20686. assert(!this._indices, 'appendData can only be called on raw data.');
  20687. }
  20688. var provider = this._provider;
  20689. var start = this.count();
  20690. provider.appendData(data);
  20691. var end = provider.count();
  20692. if (!provider.persistent) {
  20693. end += start;
  20694. }
  20695. if (start < end) {
  20696. this._initDataFromProvider(start, end, true);
  20697. }
  20698. return [start, end];
  20699. };
  20700. DataStore.prototype.appendValues = function (values, minFillLen) {
  20701. var chunks = this._chunks;
  20702. var dimensions = this._dimensions;
  20703. var dimLen = dimensions.length;
  20704. var rawExtent = this._rawExtent;
  20705. var start = this.count();
  20706. var end = start + Math.max(values.length, minFillLen || 0);
  20707. for (var i = 0; i < dimLen; i++) {
  20708. var dim = dimensions[i];
  20709. prepareStore(chunks, i, dim.type, end, true);
  20710. }
  20711. var emptyDataItem = [];
  20712. for (var idx = start; idx < end; idx++) {
  20713. var sourceIdx = idx - start;
  20714. // Store the data by dimensions
  20715. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20716. var dim = dimensions[dimIdx];
  20717. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20718. chunks[dimIdx][idx] = val;
  20719. var dimRawExtent = rawExtent[dimIdx];
  20720. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20721. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20722. }
  20723. }
  20724. this._rawCount = this._count = end;
  20725. return {
  20726. start: start,
  20727. end: end
  20728. };
  20729. };
  20730. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20731. var provider = this._provider;
  20732. var chunks = this._chunks;
  20733. var dimensions = this._dimensions;
  20734. var dimLen = dimensions.length;
  20735. var rawExtent = this._rawExtent;
  20736. var dimNames = map(dimensions, function (dim) {
  20737. return dim.property;
  20738. });
  20739. for (var i = 0; i < dimLen; i++) {
  20740. var dim = dimensions[i];
  20741. if (!rawExtent[i]) {
  20742. rawExtent[i] = getInitialExtent();
  20743. }
  20744. prepareStore(chunks, i, dim.type, end, append);
  20745. }
  20746. if (provider.fillStorage) {
  20747. provider.fillStorage(start, end, chunks, rawExtent);
  20748. } else {
  20749. var dataItem = [];
  20750. for (var idx = start; idx < end; idx++) {
  20751. // NOTICE: Try not to write things into dataItem
  20752. dataItem = provider.getItem(idx, dataItem);
  20753. // Each data item is value
  20754. // [1, 2]
  20755. // 2
  20756. // Bar chart, line chart which uses category axis
  20757. // only gives the 'y' value. 'x' value is the indices of category
  20758. // Use a tempValue to normalize the value to be a (x, y) value
  20759. // Store the data by dimensions
  20760. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20761. var dimStorage = chunks[dimIdx];
  20762. // PENDING NULL is empty or zero
  20763. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20764. dimStorage[idx] = val;
  20765. var dimRawExtent = rawExtent[dimIdx];
  20766. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20767. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20768. }
  20769. }
  20770. }
  20771. if (!provider.persistent && provider.clean) {
  20772. // Clean unused data if data source is typed array.
  20773. provider.clean();
  20774. }
  20775. this._rawCount = this._count = end;
  20776. // Reset data extent
  20777. this._extent = [];
  20778. };
  20779. DataStore.prototype.count = function () {
  20780. return this._count;
  20781. };
  20782. /**
  20783. * Get value. Return NaN if idx is out of range.
  20784. */
  20785. DataStore.prototype.get = function (dim, idx) {
  20786. if (!(idx >= 0 && idx < this._count)) {
  20787. return NaN;
  20788. }
  20789. var dimStore = this._chunks[dim];
  20790. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20791. };
  20792. DataStore.prototype.getValues = function (dimensions, idx) {
  20793. var values = [];
  20794. var dimArr = [];
  20795. if (idx == null) {
  20796. idx = dimensions;
  20797. // TODO get all from store?
  20798. dimensions = [];
  20799. // All dimensions
  20800. for (var i = 0; i < this._dimensions.length; i++) {
  20801. dimArr.push(i);
  20802. }
  20803. } else {
  20804. dimArr = dimensions;
  20805. }
  20806. for (var i = 0, len = dimArr.length; i < len; i++) {
  20807. values.push(this.get(dimArr[i], idx));
  20808. }
  20809. return values;
  20810. };
  20811. /**
  20812. * @param dim concrete dim
  20813. */
  20814. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20815. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20816. return NaN;
  20817. }
  20818. var dimStore = this._chunks[dim];
  20819. return dimStore ? dimStore[rawIdx] : NaN;
  20820. };
  20821. /**
  20822. * Get sum of data in one dimension
  20823. */
  20824. DataStore.prototype.getSum = function (dim) {
  20825. var dimData = this._chunks[dim];
  20826. var sum = 0;
  20827. if (dimData) {
  20828. for (var i = 0, len = this.count(); i < len; i++) {
  20829. var value = this.get(dim, i);
  20830. if (!isNaN(value)) {
  20831. sum += value;
  20832. }
  20833. }
  20834. }
  20835. return sum;
  20836. };
  20837. /**
  20838. * Get median of data in one dimension
  20839. */
  20840. DataStore.prototype.getMedian = function (dim) {
  20841. var dimDataArray = [];
  20842. // map all data of one dimension
  20843. this.each([dim], function (val) {
  20844. if (!isNaN(val)) {
  20845. dimDataArray.push(val);
  20846. }
  20847. });
  20848. // TODO
  20849. // Use quick select?
  20850. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20851. return a - b;
  20852. });
  20853. var len = this.count();
  20854. // calculate median
  20855. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20856. };
  20857. /**
  20858. * Retrieve the index with given raw data index.
  20859. */
  20860. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20861. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20862. return -1;
  20863. }
  20864. if (!this._indices) {
  20865. return rawIndex;
  20866. }
  20867. // Indices are ascending
  20868. var indices = this._indices;
  20869. // If rawIndex === dataIndex
  20870. var rawDataIndex = indices[rawIndex];
  20871. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20872. return rawIndex;
  20873. }
  20874. var left = 0;
  20875. var right = this._count - 1;
  20876. while (left <= right) {
  20877. var mid = (left + right) / 2 | 0;
  20878. if (indices[mid] < rawIndex) {
  20879. left = mid + 1;
  20880. } else if (indices[mid] > rawIndex) {
  20881. right = mid - 1;
  20882. } else {
  20883. return mid;
  20884. }
  20885. }
  20886. return -1;
  20887. };
  20888. /**
  20889. * Retrieve the index of nearest value.
  20890. * @param dim
  20891. * @param value
  20892. * @param [maxDistance=Infinity]
  20893. * @return If and only if multiple indices have
  20894. * the same value, they are put to the result.
  20895. */
  20896. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20897. var chunks = this._chunks;
  20898. var dimData = chunks[dim];
  20899. var nearestIndices = [];
  20900. if (!dimData) {
  20901. return nearestIndices;
  20902. }
  20903. if (maxDistance == null) {
  20904. maxDistance = Infinity;
  20905. }
  20906. var minDist = Infinity;
  20907. var minDiff = -1;
  20908. var nearestIndicesLen = 0;
  20909. // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20910. for (var i = 0, len = this.count(); i < len; i++) {
  20911. var dataIndex = this.getRawIndex(i);
  20912. var diff = value - dimData[dataIndex];
  20913. var dist = Math.abs(diff);
  20914. if (dist <= maxDistance) {
  20915. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20916. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20917. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20918. // So we choose the one that `diff >= 0` in this case.
  20919. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20920. // should be push to `nearestIndices`.
  20921. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20922. minDist = dist;
  20923. minDiff = diff;
  20924. nearestIndicesLen = 0;
  20925. }
  20926. if (diff === minDiff) {
  20927. nearestIndices[nearestIndicesLen++] = i;
  20928. }
  20929. }
  20930. }
  20931. nearestIndices.length = nearestIndicesLen;
  20932. return nearestIndices;
  20933. };
  20934. DataStore.prototype.getIndices = function () {
  20935. var newIndices;
  20936. var indices = this._indices;
  20937. if (indices) {
  20938. var Ctor = indices.constructor;
  20939. var thisCount = this._count;
  20940. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20941. if (Ctor === Array) {
  20942. newIndices = new Ctor(thisCount);
  20943. for (var i = 0; i < thisCount; i++) {
  20944. newIndices[i] = indices[i];
  20945. }
  20946. } else {
  20947. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20948. }
  20949. } else {
  20950. var Ctor = getIndicesCtor(this._rawCount);
  20951. newIndices = new Ctor(this.count());
  20952. for (var i = 0; i < newIndices.length; i++) {
  20953. newIndices[i] = i;
  20954. }
  20955. }
  20956. return newIndices;
  20957. };
  20958. /**
  20959. * Data filter.
  20960. */
  20961. DataStore.prototype.filter = function (dims, cb) {
  20962. if (!this._count) {
  20963. return this;
  20964. }
  20965. var newStore = this.clone();
  20966. var count = newStore.count();
  20967. var Ctor = getIndicesCtor(newStore._rawCount);
  20968. var newIndices = new Ctor(count);
  20969. var value = [];
  20970. var dimSize = dims.length;
  20971. var offset = 0;
  20972. var dim0 = dims[0];
  20973. var chunks = newStore._chunks;
  20974. for (var i = 0; i < count; i++) {
  20975. var keep = void 0;
  20976. var rawIdx = newStore.getRawIndex(i);
  20977. // Simple optimization
  20978. if (dimSize === 0) {
  20979. keep = cb(i);
  20980. } else if (dimSize === 1) {
  20981. var val = chunks[dim0][rawIdx];
  20982. keep = cb(val, i);
  20983. } else {
  20984. var k = 0;
  20985. for (; k < dimSize; k++) {
  20986. value[k] = chunks[dims[k]][rawIdx];
  20987. }
  20988. value[k] = i;
  20989. keep = cb.apply(null, value);
  20990. }
  20991. if (keep) {
  20992. newIndices[offset++] = rawIdx;
  20993. }
  20994. }
  20995. // Set indices after filtered.
  20996. if (offset < count) {
  20997. newStore._indices = newIndices;
  20998. }
  20999. newStore._count = offset;
  21000. // Reset data extent
  21001. newStore._extent = [];
  21002. newStore._updateGetRawIdx();
  21003. return newStore;
  21004. };
  21005. /**
  21006. * Select data in range. (For optimization of filter)
  21007. * (Manually inline code, support 5 million data filtering in data zoom.)
  21008. */
  21009. DataStore.prototype.selectRange = function (range) {
  21010. var newStore = this.clone();
  21011. var len = newStore._count;
  21012. if (!len) {
  21013. return this;
  21014. }
  21015. var dims = keys(range);
  21016. var dimSize = dims.length;
  21017. if (!dimSize) {
  21018. return this;
  21019. }
  21020. var originalCount = newStore.count();
  21021. var Ctor = getIndicesCtor(newStore._rawCount);
  21022. var newIndices = new Ctor(originalCount);
  21023. var offset = 0;
  21024. var dim0 = dims[0];
  21025. var min = range[dim0][0];
  21026. var max = range[dim0][1];
  21027. var storeArr = newStore._chunks;
  21028. var quickFinished = false;
  21029. if (!newStore._indices) {
  21030. // Extreme optimization for common case. About 2x faster in chrome.
  21031. var idx = 0;
  21032. if (dimSize === 1) {
  21033. var dimStorage = storeArr[dims[0]];
  21034. for (var i = 0; i < len; i++) {
  21035. var val = dimStorage[i];
  21036. // NaN will not be filtered. Consider the case, in line chart, empty
  21037. // value indicates the line should be broken. But for the case like
  21038. // scatter plot, a data item with empty value will not be rendered,
  21039. // but the axis extent may be effected if some other dim of the data
  21040. // item has value. Fortunately it is not a significant negative effect.
  21041. if (val >= min && val <= max || isNaN(val)) {
  21042. newIndices[offset++] = idx;
  21043. }
  21044. idx++;
  21045. }
  21046. quickFinished = true;
  21047. } else if (dimSize === 2) {
  21048. var dimStorage = storeArr[dims[0]];
  21049. var dimStorage2 = storeArr[dims[1]];
  21050. var min2 = range[dims[1]][0];
  21051. var max2 = range[dims[1]][1];
  21052. for (var i = 0; i < len; i++) {
  21053. var val = dimStorage[i];
  21054. var val2 = dimStorage2[i];
  21055. // Do not filter NaN, see comment above.
  21056. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  21057. newIndices[offset++] = idx;
  21058. }
  21059. idx++;
  21060. }
  21061. quickFinished = true;
  21062. }
  21063. }
  21064. if (!quickFinished) {
  21065. if (dimSize === 1) {
  21066. for (var i = 0; i < originalCount; i++) {
  21067. var rawIndex = newStore.getRawIndex(i);
  21068. var val = storeArr[dims[0]][rawIndex];
  21069. // Do not filter NaN, see comment above.
  21070. if (val >= min && val <= max || isNaN(val)) {
  21071. newIndices[offset++] = rawIndex;
  21072. }
  21073. }
  21074. } else {
  21075. for (var i = 0; i < originalCount; i++) {
  21076. var keep = true;
  21077. var rawIndex = newStore.getRawIndex(i);
  21078. for (var k = 0; k < dimSize; k++) {
  21079. var dimk = dims[k];
  21080. var val = storeArr[dimk][rawIndex];
  21081. // Do not filter NaN, see comment above.
  21082. if (val < range[dimk][0] || val > range[dimk][1]) {
  21083. keep = false;
  21084. }
  21085. }
  21086. if (keep) {
  21087. newIndices[offset++] = newStore.getRawIndex(i);
  21088. }
  21089. }
  21090. }
  21091. }
  21092. // Set indices after filtered.
  21093. if (offset < originalCount) {
  21094. newStore._indices = newIndices;
  21095. }
  21096. newStore._count = offset;
  21097. // Reset data extent
  21098. newStore._extent = [];
  21099. newStore._updateGetRawIdx();
  21100. return newStore;
  21101. };
  21102. // /**
  21103. // * Data mapping to a plain array
  21104. // */
  21105. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  21106. // const result: any[] = [];
  21107. // this.each(dims, function () {
  21108. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  21109. // });
  21110. // return result;
  21111. // }
  21112. /**
  21113. * Data mapping to a new List with given dimensions
  21114. */
  21115. DataStore.prototype.map = function (dims, cb) {
  21116. // TODO only clone picked chunks.
  21117. var target = this.clone(dims);
  21118. this._updateDims(target, dims, cb);
  21119. return target;
  21120. };
  21121. /**
  21122. * @caution Danger!! Only used in dataStack.
  21123. */
  21124. DataStore.prototype.modify = function (dims, cb) {
  21125. this._updateDims(this, dims, cb);
  21126. };
  21127. DataStore.prototype._updateDims = function (target, dims, cb) {
  21128. var targetChunks = target._chunks;
  21129. var tmpRetValue = [];
  21130. var dimSize = dims.length;
  21131. var dataCount = target.count();
  21132. var values = [];
  21133. var rawExtent = target._rawExtent;
  21134. for (var i = 0; i < dims.length; i++) {
  21135. rawExtent[dims[i]] = getInitialExtent();
  21136. }
  21137. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  21138. var rawIndex = target.getRawIndex(dataIndex);
  21139. for (var k = 0; k < dimSize; k++) {
  21140. values[k] = targetChunks[dims[k]][rawIndex];
  21141. }
  21142. values[dimSize] = dataIndex;
  21143. var retValue = cb && cb.apply(null, values);
  21144. if (retValue != null) {
  21145. // a number or string (in oridinal dimension)?
  21146. if (typeof retValue !== 'object') {
  21147. tmpRetValue[0] = retValue;
  21148. retValue = tmpRetValue;
  21149. }
  21150. for (var i = 0; i < retValue.length; i++) {
  21151. var dim = dims[i];
  21152. var val = retValue[i];
  21153. var rawExtentOnDim = rawExtent[dim];
  21154. var dimStore = targetChunks[dim];
  21155. if (dimStore) {
  21156. dimStore[rawIndex] = val;
  21157. }
  21158. if (val < rawExtentOnDim[0]) {
  21159. rawExtentOnDim[0] = val;
  21160. }
  21161. if (val > rawExtentOnDim[1]) {
  21162. rawExtentOnDim[1] = val;
  21163. }
  21164. }
  21165. }
  21166. }
  21167. };
  21168. /**
  21169. * Large data down sampling using largest-triangle-three-buckets
  21170. * @param {string} valueDimension
  21171. * @param {number} targetCount
  21172. */
  21173. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  21174. var target = this.clone([valueDimension], true);
  21175. var targetStorage = target._chunks;
  21176. var dimStore = targetStorage[valueDimension];
  21177. var len = this.count();
  21178. var sampledIndex = 0;
  21179. var frameSize = Math.floor(1 / rate);
  21180. var currentRawIndex = this.getRawIndex(0);
  21181. var maxArea;
  21182. var area;
  21183. var nextRawIndex;
  21184. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len));
  21185. // First frame use the first data.
  21186. newIndices[sampledIndex++] = currentRawIndex;
  21187. for (var i = 1; i < len - 1; i += frameSize) {
  21188. var nextFrameStart = Math.min(i + frameSize, len - 1);
  21189. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  21190. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  21191. var avgY = 0;
  21192. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  21193. var rawIndex = this.getRawIndex(idx);
  21194. var y = dimStore[rawIndex];
  21195. if (isNaN(y)) {
  21196. continue;
  21197. }
  21198. avgY += y;
  21199. }
  21200. avgY /= nextFrameEnd - nextFrameStart;
  21201. var frameStart = i;
  21202. var frameEnd = Math.min(i + frameSize, len);
  21203. var pointAX = i - 1;
  21204. var pointAY = dimStore[currentRawIndex];
  21205. maxArea = -1;
  21206. nextRawIndex = frameStart;
  21207. var firstNaNIndex = -1;
  21208. var countNaN = 0;
  21209. // Find a point from current frame that construct a triangle with largest area with previous selected point
  21210. // And the average of next frame.
  21211. for (var idx = frameStart; idx < frameEnd; idx++) {
  21212. var rawIndex = this.getRawIndex(idx);
  21213. var y = dimStore[rawIndex];
  21214. if (isNaN(y)) {
  21215. countNaN++;
  21216. if (firstNaNIndex < 0) {
  21217. firstNaNIndex = rawIndex;
  21218. }
  21219. continue;
  21220. }
  21221. // Calculate triangle area over three buckets
  21222. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  21223. if (area > maxArea) {
  21224. maxArea = area;
  21225. nextRawIndex = rawIndex; // Next a is this b
  21226. }
  21227. }
  21228. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  21229. // Append first NaN point in every bucket.
  21230. // It is necessary to ensure the correct order of indices.
  21231. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  21232. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  21233. }
  21234. newIndices[sampledIndex++] = nextRawIndex;
  21235. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  21236. }
  21237. // First frame use the last data.
  21238. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  21239. target._count = sampledIndex;
  21240. target._indices = newIndices;
  21241. target.getRawIndex = this._getRawIdx;
  21242. return target;
  21243. };
  21244. /**
  21245. * Large data down sampling using min-max
  21246. * @param {string} valueDimension
  21247. * @param {number} rate
  21248. */
  21249. DataStore.prototype.minmaxDownSample = function (valueDimension, rate) {
  21250. var target = this.clone([valueDimension], true);
  21251. var targetStorage = target._chunks;
  21252. var frameSize = Math.floor(1 / rate);
  21253. var dimStore = targetStorage[valueDimension];
  21254. var len = this.count();
  21255. // Each frame results in 2 data points, one for min and one for max
  21256. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize) * 2);
  21257. var offset = 0;
  21258. for (var i = 0; i < len; i += frameSize) {
  21259. var minIndex = i;
  21260. var minValue = dimStore[this.getRawIndex(minIndex)];
  21261. var maxIndex = i;
  21262. var maxValue = dimStore[this.getRawIndex(maxIndex)];
  21263. var thisFrameSize = frameSize;
  21264. // Handle final smaller frame
  21265. if (i + frameSize > len) {
  21266. thisFrameSize = len - i;
  21267. }
  21268. // Determine min and max within the current frame
  21269. for (var k = 0; k < thisFrameSize; k++) {
  21270. var rawIndex = this.getRawIndex(i + k);
  21271. var value = dimStore[rawIndex];
  21272. if (value < minValue) {
  21273. minValue = value;
  21274. minIndex = i + k;
  21275. }
  21276. if (value > maxValue) {
  21277. maxValue = value;
  21278. maxIndex = i + k;
  21279. }
  21280. }
  21281. var rawMinIndex = this.getRawIndex(minIndex);
  21282. var rawMaxIndex = this.getRawIndex(maxIndex);
  21283. // Set the order of the min and max values, based on their ordering in the frame
  21284. if (minIndex < maxIndex) {
  21285. newIndices[offset++] = rawMinIndex;
  21286. newIndices[offset++] = rawMaxIndex;
  21287. } else {
  21288. newIndices[offset++] = rawMaxIndex;
  21289. newIndices[offset++] = rawMinIndex;
  21290. }
  21291. }
  21292. target._count = offset;
  21293. target._indices = newIndices;
  21294. target._updateGetRawIdx();
  21295. return target;
  21296. };
  21297. /**
  21298. * Large data down sampling on given dimension
  21299. * @param sampleIndex Sample index for name and id
  21300. */
  21301. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  21302. var target = this.clone([dimension], true);
  21303. var targetStorage = target._chunks;
  21304. var frameValues = [];
  21305. var frameSize = Math.floor(1 / rate);
  21306. var dimStore = targetStorage[dimension];
  21307. var len = this.count();
  21308. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  21309. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  21310. var offset = 0;
  21311. for (var i = 0; i < len; i += frameSize) {
  21312. // Last frame
  21313. if (frameSize > len - i) {
  21314. frameSize = len - i;
  21315. frameValues.length = frameSize;
  21316. }
  21317. for (var k = 0; k < frameSize; k++) {
  21318. var dataIdx = this.getRawIndex(i + k);
  21319. frameValues[k] = dimStore[dataIdx];
  21320. }
  21321. var value = sampleValue(frameValues);
  21322. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  21323. // Only write value on the filtered data
  21324. dimStore[sampleFrameIdx] = value;
  21325. if (value < rawExtentOnDim[0]) {
  21326. rawExtentOnDim[0] = value;
  21327. }
  21328. if (value > rawExtentOnDim[1]) {
  21329. rawExtentOnDim[1] = value;
  21330. }
  21331. newIndices[offset++] = sampleFrameIdx;
  21332. }
  21333. target._count = offset;
  21334. target._indices = newIndices;
  21335. target._updateGetRawIdx();
  21336. return target;
  21337. };
  21338. /**
  21339. * Data iteration
  21340. * @param ctx default this
  21341. * @example
  21342. * list.each('x', function (x, idx) {});
  21343. * list.each(['x', 'y'], function (x, y, idx) {});
  21344. * list.each(function (idx) {})
  21345. */
  21346. DataStore.prototype.each = function (dims, cb) {
  21347. if (!this._count) {
  21348. return;
  21349. }
  21350. var dimSize = dims.length;
  21351. var chunks = this._chunks;
  21352. for (var i = 0, len = this.count(); i < len; i++) {
  21353. var rawIdx = this.getRawIndex(i);
  21354. // Simple optimization
  21355. switch (dimSize) {
  21356. case 0:
  21357. cb(i);
  21358. break;
  21359. case 1:
  21360. cb(chunks[dims[0]][rawIdx], i);
  21361. break;
  21362. case 2:
  21363. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  21364. break;
  21365. default:
  21366. var k = 0;
  21367. var value = [];
  21368. for (; k < dimSize; k++) {
  21369. value[k] = chunks[dims[k]][rawIdx];
  21370. }
  21371. // Index
  21372. value[k] = i;
  21373. cb.apply(null, value);
  21374. }
  21375. }
  21376. };
  21377. /**
  21378. * Get extent of data in one dimension
  21379. */
  21380. DataStore.prototype.getDataExtent = function (dim) {
  21381. // Make sure use concrete dim as cache name.
  21382. var dimData = this._chunks[dim];
  21383. var initialExtent = getInitialExtent();
  21384. if (!dimData) {
  21385. return initialExtent;
  21386. }
  21387. // Make more strict checkings to ensure hitting cache.
  21388. var currEnd = this.count();
  21389. // Consider the most cases when using data zoom, `getDataExtent`
  21390. // happened before filtering. We cache raw extent, which is not
  21391. // necessary to be cleared and recalculated when restore data.
  21392. var useRaw = !this._indices;
  21393. var dimExtent;
  21394. if (useRaw) {
  21395. return this._rawExtent[dim].slice();
  21396. }
  21397. dimExtent = this._extent[dim];
  21398. if (dimExtent) {
  21399. return dimExtent.slice();
  21400. }
  21401. dimExtent = initialExtent;
  21402. var min = dimExtent[0];
  21403. var max = dimExtent[1];
  21404. for (var i = 0; i < currEnd; i++) {
  21405. var rawIdx = this.getRawIndex(i);
  21406. var value = dimData[rawIdx];
  21407. value < min && (min = value);
  21408. value > max && (max = value);
  21409. }
  21410. dimExtent = [min, max];
  21411. this._extent[dim] = dimExtent;
  21412. return dimExtent;
  21413. };
  21414. /**
  21415. * Get raw data item
  21416. */
  21417. DataStore.prototype.getRawDataItem = function (idx) {
  21418. var rawIdx = this.getRawIndex(idx);
  21419. if (!this._provider.persistent) {
  21420. var val = [];
  21421. var chunks = this._chunks;
  21422. for (var i = 0; i < chunks.length; i++) {
  21423. val.push(chunks[i][rawIdx]);
  21424. }
  21425. return val;
  21426. } else {
  21427. return this._provider.getItem(rawIdx);
  21428. }
  21429. };
  21430. /**
  21431. * Clone shallow.
  21432. *
  21433. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  21434. */
  21435. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  21436. var target = new DataStore();
  21437. var chunks = this._chunks;
  21438. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  21439. obj[dimIdx] = true;
  21440. return obj;
  21441. }, {});
  21442. if (clonedDimsMap) {
  21443. for (var i = 0; i < chunks.length; i++) {
  21444. // Not clone if dim is not picked.
  21445. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21446. }
  21447. } else {
  21448. target._chunks = chunks;
  21449. }
  21450. this._copyCommonProps(target);
  21451. if (!ignoreIndices) {
  21452. target._indices = this._cloneIndices();
  21453. }
  21454. target._updateGetRawIdx();
  21455. return target;
  21456. };
  21457. DataStore.prototype._copyCommonProps = function (target) {
  21458. target._count = this._count;
  21459. target._rawCount = this._rawCount;
  21460. target._provider = this._provider;
  21461. target._dimensions = this._dimensions;
  21462. target._extent = clone(this._extent);
  21463. target._rawExtent = clone(this._rawExtent);
  21464. };
  21465. DataStore.prototype._cloneIndices = function () {
  21466. if (this._indices) {
  21467. var Ctor = this._indices.constructor;
  21468. var indices = void 0;
  21469. if (Ctor === Array) {
  21470. var thisCount = this._indices.length;
  21471. indices = new Ctor(thisCount);
  21472. for (var i = 0; i < thisCount; i++) {
  21473. indices[i] = this._indices[i];
  21474. }
  21475. } else {
  21476. indices = new Ctor(this._indices);
  21477. }
  21478. return indices;
  21479. }
  21480. return null;
  21481. };
  21482. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21483. return idx;
  21484. };
  21485. DataStore.prototype._getRawIdx = function (idx) {
  21486. if (idx < this._count && idx >= 0) {
  21487. return this._indices[idx];
  21488. }
  21489. return -1;
  21490. };
  21491. DataStore.prototype._updateGetRawIdx = function () {
  21492. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21493. };
  21494. DataStore.internalField = function () {
  21495. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21496. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21497. }
  21498. defaultDimValueGetters = {
  21499. arrayRows: getDimValueSimply,
  21500. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21501. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21502. },
  21503. keyedColumns: getDimValueSimply,
  21504. original: function (dataItem, property, dataIndex, dimIndex) {
  21505. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21506. // If dataItem is an plain object with no value field, the let `value`
  21507. // will be assigned with the object, but it will be tread correctly
  21508. // in the `convertValue`.
  21509. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21510. return parseDataValue(value instanceof Array ? value[dimIndex]
  21511. // If value is a single number or something else not array.
  21512. : value, this._dimensions[dimIndex]);
  21513. },
  21514. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21515. return dataItem[dimIndex];
  21516. }
  21517. };
  21518. }();
  21519. return DataStore;
  21520. }();
  21521. /**
  21522. * [REQUIREMENT_MEMO]:
  21523. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21524. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21525. * `root-dataset`. Them on `series` has higher priority.
  21526. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21527. * confuse users: whether those props indicate how to visit the upstream source or visit
  21528. * the transform result source, and some transforms has nothing to do with these props,
  21529. * and some transforms might have multiple upstream.
  21530. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21531. * declared in `root-dataset`.
  21532. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21533. * That is for reducing complexity in transforms.
  21534. * PENDING: Whether to provide transposition transform?
  21535. *
  21536. * [IMPLEMENTAION_MEMO]:
  21537. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21538. * They will not be calculated until `source` is about to be visited (to prevent from
  21539. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21540. *
  21541. * [DIMENSION_INHERIT_RULE]:
  21542. * By default the dimensions are inherited from ancestors, unless a transform return
  21543. * a new dimensions definition.
  21544. * Consider the case:
  21545. * ```js
  21546. * dataset: [{
  21547. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21548. * }, {
  21549. * transform: { type: 'filter', ... }
  21550. * }]
  21551. * dataset: [{
  21552. * dimension: ['Product', 'Sales', 'Prise'],
  21553. * source: [ ['Cookies', 321, 44.21], ...]
  21554. * }, {
  21555. * transform: { type: 'filter', ... }
  21556. * }]
  21557. * ```
  21558. * The two types of option should have the same behavior after transform.
  21559. *
  21560. *
  21561. * [SCENARIO]:
  21562. * (1) Provide source data directly:
  21563. * ```js
  21564. * series: {
  21565. * encode: {...},
  21566. * dimensions: [...]
  21567. * seriesLayoutBy: 'row',
  21568. * data: [[...]]
  21569. * }
  21570. * ```
  21571. * (2) Series refer to dataset.
  21572. * ```js
  21573. * series: [{
  21574. * encode: {...}
  21575. * // Ignore datasetIndex means `datasetIndex: 0`
  21576. * // and the dimensions defination in dataset is used
  21577. * }, {
  21578. * encode: {...},
  21579. * seriesLayoutBy: 'column',
  21580. * datasetIndex: 1
  21581. * }]
  21582. * ```
  21583. * (3) dataset transform
  21584. * ```js
  21585. * dataset: [{
  21586. * source: [...]
  21587. * }, {
  21588. * source: [...]
  21589. * }, {
  21590. * // By default from 0.
  21591. * transform: { type: 'filter', config: {...} }
  21592. * }, {
  21593. * // Piped.
  21594. * transform: [
  21595. * { type: 'filter', config: {...} },
  21596. * { type: 'sort', config: {...} }
  21597. * ]
  21598. * }, {
  21599. * id: 'regressionData',
  21600. * fromDatasetIndex: 1,
  21601. * // Third-party transform
  21602. * transform: { type: 'ecStat:regression', config: {...} }
  21603. * }, {
  21604. * // retrieve the extra result.
  21605. * id: 'regressionFormula',
  21606. * fromDatasetId: 'regressionData',
  21607. * fromTransformResult: 1
  21608. * }]
  21609. * ```
  21610. */
  21611. var SourceManager = /** @class */function () {
  21612. function SourceManager(sourceHost) {
  21613. // Cached source. Do not repeat calculating if not dirty.
  21614. this._sourceList = [];
  21615. this._storeList = [];
  21616. // version sign of each upstream source manager.
  21617. this._upstreamSignList = [];
  21618. this._versionSignBase = 0;
  21619. this._dirty = true;
  21620. this._sourceHost = sourceHost;
  21621. }
  21622. /**
  21623. * Mark dirty.
  21624. */
  21625. SourceManager.prototype.dirty = function () {
  21626. this._setLocalSource([], []);
  21627. this._storeList = [];
  21628. this._dirty = true;
  21629. };
  21630. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21631. this._sourceList = sourceList;
  21632. this._upstreamSignList = upstreamSignList;
  21633. this._versionSignBase++;
  21634. if (this._versionSignBase > 9e10) {
  21635. this._versionSignBase = 0;
  21636. }
  21637. };
  21638. /**
  21639. * For detecting whether the upstream source is dirty, so that
  21640. * the local cached source (in `_sourceList`) should be discarded.
  21641. */
  21642. SourceManager.prototype._getVersionSign = function () {
  21643. return this._sourceHost.uid + '_' + this._versionSignBase;
  21644. };
  21645. /**
  21646. * Always return a source instance. Otherwise throw error.
  21647. */
  21648. SourceManager.prototype.prepareSource = function () {
  21649. // For the case that call `setOption` multiple time but no data changed,
  21650. // cache the result source to prevent from repeating transform.
  21651. if (this._isDirty()) {
  21652. this._createSource();
  21653. this._dirty = false;
  21654. }
  21655. };
  21656. SourceManager.prototype._createSource = function () {
  21657. this._setLocalSource([], []);
  21658. var sourceHost = this._sourceHost;
  21659. var upSourceMgrList = this._getUpstreamSourceManagers();
  21660. var hasUpstream = !!upSourceMgrList.length;
  21661. var resultSourceList;
  21662. var upstreamSignList;
  21663. if (isSeries(sourceHost)) {
  21664. var seriesModel = sourceHost;
  21665. var data = void 0;
  21666. var sourceFormat = void 0;
  21667. var upSource = void 0;
  21668. // Has upstream dataset
  21669. if (hasUpstream) {
  21670. var upSourceMgr = upSourceMgrList[0];
  21671. upSourceMgr.prepareSource();
  21672. upSource = upSourceMgr.getSource();
  21673. data = upSource.data;
  21674. sourceFormat = upSource.sourceFormat;
  21675. upstreamSignList = [upSourceMgr._getVersionSign()];
  21676. }
  21677. // Series data is from own.
  21678. else {
  21679. data = seriesModel.get('data', true);
  21680. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21681. upstreamSignList = [];
  21682. }
  21683. // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21684. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21685. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21686. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21687. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader);
  21688. // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21689. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21690. // but series need `seriesLayoutBy: 'row'`.
  21691. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions);
  21692. // We share source with dataset as much as possible
  21693. // to avoid extra memory cost of high dimensional data.
  21694. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21695. resultSourceList = needsCreateSource ? [createSource(data, {
  21696. seriesLayoutBy: seriesLayoutBy,
  21697. sourceHeader: sourceHeader,
  21698. dimensions: dimensions
  21699. }, sourceFormat)] : [];
  21700. } else {
  21701. var datasetModel = sourceHost;
  21702. // Has upstream dataset.
  21703. if (hasUpstream) {
  21704. var result = this._applyTransform(upSourceMgrList);
  21705. resultSourceList = result.sourceList;
  21706. upstreamSignList = result.upstreamSignList;
  21707. }
  21708. // Is root dataset.
  21709. else {
  21710. var sourceData = datasetModel.get('source', true);
  21711. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21712. upstreamSignList = [];
  21713. }
  21714. }
  21715. if ("development" !== 'production') {
  21716. assert(resultSourceList && upstreamSignList);
  21717. }
  21718. this._setLocalSource(resultSourceList, upstreamSignList);
  21719. };
  21720. SourceManager.prototype._applyTransform = function (upMgrList) {
  21721. var datasetModel = this._sourceHost;
  21722. var transformOption = datasetModel.get('transform', true);
  21723. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21724. if ("development" !== 'production') {
  21725. assert(fromTransformResult != null || transformOption != null);
  21726. }
  21727. if (fromTransformResult != null) {
  21728. var errMsg = '';
  21729. if (upMgrList.length !== 1) {
  21730. if ("development" !== 'production') {
  21731. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21732. }
  21733. doThrow(errMsg);
  21734. }
  21735. }
  21736. var sourceList;
  21737. var upSourceList = [];
  21738. var upstreamSignList = [];
  21739. each(upMgrList, function (upMgr) {
  21740. upMgr.prepareSource();
  21741. var upSource = upMgr.getSource(fromTransformResult || 0);
  21742. var errMsg = '';
  21743. if (fromTransformResult != null && !upSource) {
  21744. if ("development" !== 'production') {
  21745. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21746. }
  21747. doThrow(errMsg);
  21748. }
  21749. upSourceList.push(upSource);
  21750. upstreamSignList.push(upMgr._getVersionSign());
  21751. });
  21752. if (transformOption) {
  21753. sourceList = applyDataTransform(transformOption, upSourceList, {
  21754. datasetIndex: datasetModel.componentIndex
  21755. });
  21756. } else if (fromTransformResult != null) {
  21757. sourceList = [cloneSourceShallow(upSourceList[0])];
  21758. }
  21759. return {
  21760. sourceList: sourceList,
  21761. upstreamSignList: upstreamSignList
  21762. };
  21763. };
  21764. SourceManager.prototype._isDirty = function () {
  21765. if (this._dirty) {
  21766. return true;
  21767. }
  21768. // All sourceList is from the some upstream.
  21769. var upSourceMgrList = this._getUpstreamSourceManagers();
  21770. for (var i = 0; i < upSourceMgrList.length; i++) {
  21771. var upSrcMgr = upSourceMgrList[i];
  21772. if (
  21773. // Consider the case that there is ancestor diry, call it recursively.
  21774. // The performance is probably not an issue because usually the chain is not long.
  21775. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21776. return true;
  21777. }
  21778. }
  21779. };
  21780. /**
  21781. * @param sourceIndex By default 0, means "main source".
  21782. * In most cases there is only one source.
  21783. */
  21784. SourceManager.prototype.getSource = function (sourceIndex) {
  21785. sourceIndex = sourceIndex || 0;
  21786. var source = this._sourceList[sourceIndex];
  21787. if (!source) {
  21788. // Series may share source instance with dataset.
  21789. var upSourceMgrList = this._getUpstreamSourceManagers();
  21790. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21791. }
  21792. return source;
  21793. };
  21794. /**
  21795. *
  21796. * Get a data store which can be shared across series.
  21797. * Only available for series.
  21798. *
  21799. * @param seriesDimRequest Dimensions that are generated in series.
  21800. * Should have been sorted by `storeDimIndex` asc.
  21801. */
  21802. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21803. if ("development" !== 'production') {
  21804. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21805. }
  21806. var schema = seriesDimRequest.makeStoreSchema();
  21807. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21808. };
  21809. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21810. // TODO Can use other sourceIndex?
  21811. var sourceIndex = 0;
  21812. var storeList = this._storeList;
  21813. var cachedStoreMap = storeList[sourceIndex];
  21814. if (!cachedStoreMap) {
  21815. cachedStoreMap = storeList[sourceIndex] = {};
  21816. }
  21817. var cachedStore = cachedStoreMap[sourceReadKey];
  21818. if (!cachedStore) {
  21819. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21820. if (isSeries(this._sourceHost) && upSourceMgr) {
  21821. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21822. } else {
  21823. cachedStore = new DataStore();
  21824. // Always create store from source of series.
  21825. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21826. }
  21827. cachedStoreMap[sourceReadKey] = cachedStore;
  21828. }
  21829. return cachedStore;
  21830. };
  21831. /**
  21832. * PENDING: Is it fast enough?
  21833. * If no upstream, return empty array.
  21834. */
  21835. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21836. // Always get the relationship from the raw option.
  21837. // Do not cache the link of the dependency graph, so that
  21838. // there is no need to update them when change happens.
  21839. var sourceHost = this._sourceHost;
  21840. if (isSeries(sourceHost)) {
  21841. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21842. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21843. } else {
  21844. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21845. return datasetModel.getSourceManager();
  21846. });
  21847. }
  21848. };
  21849. SourceManager.prototype._getSourceMetaRawOption = function () {
  21850. var sourceHost = this._sourceHost;
  21851. var seriesLayoutBy;
  21852. var sourceHeader;
  21853. var dimensions;
  21854. if (isSeries(sourceHost)) {
  21855. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21856. sourceHeader = sourceHost.get('sourceHeader', true);
  21857. dimensions = sourceHost.get('dimensions', true);
  21858. }
  21859. // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21860. else if (!this._getUpstreamSourceManagers().length) {
  21861. var model = sourceHost;
  21862. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21863. sourceHeader = model.get('sourceHeader', true);
  21864. dimensions = model.get('dimensions', true);
  21865. }
  21866. return {
  21867. seriesLayoutBy: seriesLayoutBy,
  21868. sourceHeader: sourceHeader,
  21869. dimensions: dimensions
  21870. };
  21871. };
  21872. return SourceManager;
  21873. }();
  21874. // Call this method after `super.init` and `super.mergeOption` to
  21875. // disable the transform merge, but do not disable transform clone from rawOption.
  21876. function disableTransformOptionMerge(datasetModel) {
  21877. var transformOption = datasetModel.option.transform;
  21878. transformOption && setAsPrimitive(datasetModel.option.transform);
  21879. }
  21880. function isSeries(sourceHost) {
  21881. // Avoid circular dependency with Series.ts
  21882. return sourceHost.mainType === 'series';
  21883. }
  21884. function doThrow(errMsg) {
  21885. throw new Error(errMsg);
  21886. }
  21887. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1';
  21888. function getTooltipLineHeight(textStyle) {
  21889. var lineHeight = textStyle.lineHeight;
  21890. if (lineHeight == null) {
  21891. return TOOLTIP_LINE_HEIGHT_CSS;
  21892. } else {
  21893. return "line-height:" + encodeHTML(lineHeight + '') + "px";
  21894. }
  21895. }
  21896. // TODO: more textStyle option
  21897. function getTooltipTextStyle(textStyle, renderMode) {
  21898. var nameFontColor = textStyle.color || '#6e7079';
  21899. var nameFontSize = textStyle.fontSize || 12;
  21900. var nameFontWeight = textStyle.fontWeight || '400';
  21901. var valueFontColor = textStyle.color || '#464646';
  21902. var valueFontSize = textStyle.fontSize || 14;
  21903. var valueFontWeight = textStyle.fontWeight || '900';
  21904. if (renderMode === 'html') {
  21905. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21906. return {
  21907. // eslint-disable-next-line max-len
  21908. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21909. // eslint-disable-next-line max-len
  21910. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21911. };
  21912. } else {
  21913. return {
  21914. nameStyle: {
  21915. fontSize: nameFontSize,
  21916. fill: nameFontColor,
  21917. fontWeight: nameFontWeight
  21918. },
  21919. valueStyle: {
  21920. fontSize: valueFontSize,
  21921. fill: valueFontColor,
  21922. fontWeight: valueFontWeight
  21923. }
  21924. };
  21925. }
  21926. }
  21927. // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21928. // (value from UI design)
  21929. var HTML_GAPS = [0, 10, 20, 30];
  21930. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n'];
  21931. // eslint-disable-next-line max-len
  21932. function createTooltipMarkup(type, option) {
  21933. option.type = type;
  21934. return option;
  21935. }
  21936. function isSectionFragment(frag) {
  21937. return frag.type === 'section';
  21938. }
  21939. function getBuilder(frag) {
  21940. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21941. }
  21942. function getBlockGapLevel(frag) {
  21943. if (isSectionFragment(frag)) {
  21944. var gapLevel_1 = 0;
  21945. var subBlockLen = frag.blocks.length;
  21946. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21947. each(frag.blocks, function (subBlock) {
  21948. var subGapLevel = getBlockGapLevel(subBlock);
  21949. // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21950. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21951. if (subGapLevel >= gapLevel_1) {
  21952. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && (
  21953. // 0 always can not be readable gap level.
  21954. !subGapLevel
  21955. // If no header, always keep the sub gap level. Otherwise
  21956. // look weird in case `multipleSeries`.
  21957. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21958. }
  21959. });
  21960. return gapLevel_1;
  21961. }
  21962. return 0;
  21963. }
  21964. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21965. var noHeader = fragment.noHeader;
  21966. var gaps = getGap(getBlockGapLevel(fragment));
  21967. var subMarkupTextList = [];
  21968. var subBlocks = fragment.blocks || [];
  21969. assert(!subBlocks || isArray(subBlocks));
  21970. subBlocks = subBlocks || [];
  21971. var orderMode = ctx.orderMode;
  21972. if (fragment.sortBlocks && orderMode) {
  21973. subBlocks = subBlocks.slice();
  21974. var orderMap = {
  21975. valueAsc: 'asc',
  21976. valueDesc: 'desc'
  21977. };
  21978. if (hasOwn(orderMap, orderMode)) {
  21979. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21980. subBlocks.sort(function (a, b) {
  21981. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21982. });
  21983. }
  21984. // FIXME 'seriesDesc' necessary?
  21985. else if (orderMode === 'seriesDesc') {
  21986. subBlocks.reverse();
  21987. }
  21988. }
  21989. each(subBlocks, function (subBlock, idx) {
  21990. var valueFormatter = fragment.valueFormatter;
  21991. var subMarkupText = getBuilder(subBlock)(
  21992. // Inherit valueFormatter
  21993. valueFormatter ? extend(extend({}, ctx), {
  21994. valueFormatter: valueFormatter
  21995. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21996. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21997. });
  21998. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(toolTipTextStyle, subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21999. if (noHeader) {
  22000. return subMarkupText;
  22001. }
  22002. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  22003. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  22004. var tooltipLineHeight = getTooltipLineHeight(toolTipTextStyle);
  22005. if (ctx.renderMode === 'richText') {
  22006. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  22007. } else {
  22008. return wrapBlockHTML(toolTipTextStyle, "<div style=\"" + nameStyle + ";" + tooltipLineHeight + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  22009. }
  22010. }
  22011. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  22012. var renderMode = ctx.renderMode;
  22013. var noName = fragment.noName;
  22014. var noValue = fragment.noValue;
  22015. var noMarker = !fragment.markerType;
  22016. var name = fragment.name;
  22017. var useUTC = ctx.useUTC;
  22018. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  22019. value = isArray(value) ? value : [value];
  22020. return map(value, function (val, idx) {
  22021. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  22022. });
  22023. };
  22024. if (noName && noValue) {
  22025. return;
  22026. }
  22027. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  22028. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  22029. var valueTypeOption = fragment.valueType;
  22030. var readableValueList = noValue ? [] : valueFormatter(fragment.value, fragment.dataIndex);
  22031. var valueAlignRight = !noMarker || !noName;
  22032. // It little weird if only value next to marker but far from marker.
  22033. var valueCloseToMarker = !noMarker && noName;
  22034. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  22035. nameStyle = _a.nameStyle,
  22036. valueStyle = _a.valueStyle;
  22037. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle))
  22038. // Value has commas inside, so use ' ' as delimiter for multiple values.
  22039. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML(toolTipTextStyle, (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  22040. }
  22041. /**
  22042. * @return markupText. null/undefined means no content.
  22043. */
  22044. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  22045. if (!fragment) {
  22046. return;
  22047. }
  22048. var builder = getBuilder(fragment);
  22049. var ctx = {
  22050. useUTC: useUTC,
  22051. renderMode: renderMode,
  22052. orderMode: orderMode,
  22053. markupStyleCreator: markupStyleCreator,
  22054. valueFormatter: fragment.valueFormatter
  22055. };
  22056. return builder(ctx, fragment, 0, toolTipTextStyle);
  22057. }
  22058. function getGap(gapLevel) {
  22059. return {
  22060. html: HTML_GAPS[gapLevel],
  22061. richText: RICH_TEXT_GAPS[gapLevel]
  22062. };
  22063. }
  22064. function wrapBlockHTML(textStyle, encodedContent, topGap) {
  22065. var clearfix = '<div style="clear:both"></div>';
  22066. var marginCSS = "margin: " + topGap + "px 0 0";
  22067. var tooltipLineHeight = getTooltipLineHeight(textStyle);
  22068. return "<div style=\"" + marginCSS + ";" + tooltipLineHeight + ";\">" + encodedContent + clearfix + '</div>';
  22069. }
  22070. function wrapInlineNameHTML(name, leftHasMarker, style) {
  22071. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  22072. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  22073. }
  22074. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  22075. // Do not too close to marker, considering there are multiple values separated by spaces.
  22076. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  22077. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  22078. valueList = isArray(valueList) ? valueList : [valueList];
  22079. return "<span style=\"" + alignCSS + ";" + style + "\">"
  22080. // Value has commas inside, so use ' ' as delimiter for multiple values.
  22081. + map(valueList, function (value) {
  22082. return encodeHTML(value);
  22083. }).join('&nbsp;&nbsp;') + '</span>';
  22084. }
  22085. function wrapInlineNameRichText(ctx, name, style) {
  22086. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  22087. }
  22088. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  22089. var styles = [style];
  22090. var paddingLeft = valueCloseToMarker ? 10 : 20;
  22091. alignRight && styles.push({
  22092. padding: [0, 0, 0, paddingLeft],
  22093. align: 'right'
  22094. });
  22095. // Value has commas inside, so use ' ' as delimiter for multiple values.
  22096. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  22097. }
  22098. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  22099. var style = series.getData().getItemVisual(dataIndex, 'style');
  22100. var color = style[series.visualDrawType];
  22101. return convertToColorString(color);
  22102. }
  22103. function getPaddingFromTooltipModel(model, renderMode) {
  22104. var padding = model.get('padding');
  22105. return padding != null ? padding
  22106. // We give slightly different to look pretty.
  22107. : renderMode === 'richText' ? [8, 10] : 10;
  22108. }
  22109. /**
  22110. * The major feature is generate styles for `renderMode: 'richText'`.
  22111. * But it also serves `renderMode: 'html'` to provide
  22112. * "renderMode-independent" API.
  22113. */
  22114. var TooltipMarkupStyleCreator = /** @class */function () {
  22115. function TooltipMarkupStyleCreator() {
  22116. this.richTextStyles = {};
  22117. // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  22118. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  22119. // rather than static shared by all creators (which will cause it increase to fast).
  22120. this._nextStyleNameId = getRandomIdBase();
  22121. }
  22122. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  22123. return '__EC_aUTo_' + this._nextStyleNameId++;
  22124. };
  22125. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  22126. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  22127. var marker = getTooltipMarker({
  22128. color: colorStr,
  22129. type: markerType,
  22130. renderMode: renderMode,
  22131. markerId: markerId
  22132. });
  22133. if (isString(marker)) {
  22134. return marker;
  22135. } else {
  22136. if ("development" !== 'production') {
  22137. assert(markerId);
  22138. }
  22139. this.richTextStyles[markerId] = marker.style;
  22140. return marker.content;
  22141. }
  22142. };
  22143. /**
  22144. * @usage
  22145. * ```ts
  22146. * const styledText = markupStyleCreator.wrapRichTextStyle([
  22147. * // The styles will be auto merged.
  22148. * {
  22149. * fontSize: 12,
  22150. * color: 'blue'
  22151. * },
  22152. * {
  22153. * padding: 20
  22154. * }
  22155. * ]);
  22156. * ```
  22157. */
  22158. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  22159. var finalStl = {};
  22160. if (isArray(styles)) {
  22161. each(styles, function (stl) {
  22162. return extend(finalStl, stl);
  22163. });
  22164. } else {
  22165. extend(finalStl, styles);
  22166. }
  22167. var styleName = this._generateStyleName();
  22168. this.richTextStyles[styleName] = finalStl;
  22169. return "{" + styleName + "|" + text + "}";
  22170. };
  22171. return TooltipMarkupStyleCreator;
  22172. }();
  22173. function defaultSeriesFormatTooltip(opt) {
  22174. var series = opt.series;
  22175. var dataIndex = opt.dataIndex;
  22176. var multipleSeries = opt.multipleSeries;
  22177. var data = series.getData();
  22178. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  22179. var tooltipDimLen = tooltipDims.length;
  22180. var value = series.getRawValue(dataIndex);
  22181. var isValueArr = isArray(value);
  22182. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex);
  22183. // Complicated rule for pretty tooltip.
  22184. var inlineValue;
  22185. var inlineValueType;
  22186. var subBlocks;
  22187. var sortParam;
  22188. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  22189. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  22190. inlineValue = formatArrResult.inlineValues;
  22191. inlineValueType = formatArrResult.inlineValueTypes;
  22192. subBlocks = formatArrResult.blocks;
  22193. // Only support tooltip sort by the first inline value. It's enough in most cases.
  22194. sortParam = formatArrResult.inlineValues[0];
  22195. } else if (tooltipDimLen) {
  22196. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  22197. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  22198. inlineValueType = dimInfo.type;
  22199. } else {
  22200. sortParam = inlineValue = isValueArr ? value[0] : value;
  22201. }
  22202. // Do not show generated series name. It might not be readable.
  22203. var seriesNameSpecified = isNameSpecified(series);
  22204. var seriesName = seriesNameSpecified && series.name || '';
  22205. var itemName = data.getName(dataIndex);
  22206. var inlineName = multipleSeries ? seriesName : itemName;
  22207. return createTooltipMarkup('section', {
  22208. header: seriesName,
  22209. // When series name is not specified, do not show a header line with only '-'.
  22210. // This case always happens in tooltip.trigger: 'item'.
  22211. noHeader: multipleSeries || !seriesNameSpecified,
  22212. sortParam: sortParam,
  22213. blocks: [createTooltipMarkup('nameValue', {
  22214. markerType: 'item',
  22215. markerColor: markerColor,
  22216. // Do not mix display seriesName and itemName in one tooltip,
  22217. // which might confuses users.
  22218. name: inlineName,
  22219. // name dimension might be auto assigned, where the name might
  22220. // be not readable. So we check trim here.
  22221. noName: !trim(inlineName),
  22222. value: inlineValue,
  22223. valueType: inlineValueType,
  22224. dataIndex: dataIndex
  22225. })].concat(subBlocks || [])
  22226. });
  22227. }
  22228. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  22229. // check: category-no-encode-has-axis-data in dataset.html
  22230. var data = series.getData();
  22231. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  22232. var dimItem = data.getDimensionInfo(idx);
  22233. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  22234. }, false);
  22235. var inlineValues = [];
  22236. var inlineValueTypes = [];
  22237. var blocks = [];
  22238. tooltipDims.length ? each(tooltipDims, function (dim) {
  22239. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  22240. })
  22241. // By default, all dims is used on tooltip.
  22242. : each(value, setEachItem);
  22243. function setEachItem(val, dim) {
  22244. var dimInfo = data.getDimensionInfo(dim);
  22245. // If `dimInfo.tooltip` is not set, show tooltip.
  22246. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  22247. return;
  22248. }
  22249. if (isValueMultipleLine) {
  22250. blocks.push(createTooltipMarkup('nameValue', {
  22251. markerType: 'subItem',
  22252. markerColor: colorStr,
  22253. name: dimInfo.displayName,
  22254. value: val,
  22255. valueType: dimInfo.type
  22256. }));
  22257. } else {
  22258. inlineValues.push(val);
  22259. inlineValueTypes.push(dimInfo.type);
  22260. }
  22261. }
  22262. return {
  22263. inlineValues: inlineValues,
  22264. inlineValueTypes: inlineValueTypes,
  22265. blocks: blocks
  22266. };
  22267. }
  22268. var inner$1 = makeInner();
  22269. function getSelectionKey(data, dataIndex) {
  22270. return data.getName(dataIndex) || data.getId(dataIndex);
  22271. }
  22272. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  22273. var SeriesModel = /** @class */function (_super) {
  22274. __extends(SeriesModel, _super);
  22275. function SeriesModel() {
  22276. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  22277. // the class members must not be initialized in constructor or declaration place.
  22278. // Otherwise there is bad case:
  22279. // class A {xxx = 1;}
  22280. // enableClassExtend(A);
  22281. // class B extends A {}
  22282. // var C = B.extend({xxx: 5});
  22283. // var c = new C();
  22284. // console.log(c.xxx); // expect 5 but always 1.
  22285. var _this = _super !== null && _super.apply(this, arguments) || this;
  22286. // ---------------------------------------
  22287. // Props about data selection
  22288. // ---------------------------------------
  22289. _this._selectedDataIndicesMap = {};
  22290. return _this;
  22291. }
  22292. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  22293. this.seriesIndex = this.componentIndex;
  22294. this.dataTask = createTask({
  22295. count: dataTaskCount,
  22296. reset: dataTaskReset
  22297. });
  22298. this.dataTask.context = {
  22299. model: this
  22300. };
  22301. this.mergeDefaultAndTheme(option, ecModel);
  22302. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  22303. sourceManager.prepareSource();
  22304. var data = this.getInitialData(option, ecModel);
  22305. wrapData(data, this);
  22306. this.dataTask.context.data = data;
  22307. if ("development" !== 'production') {
  22308. assert(data, 'getInitialData returned invalid data.');
  22309. }
  22310. inner$1(this).dataBeforeProcessed = data;
  22311. // If we reverse the order (make data firstly, and then make
  22312. // dataBeforeProcessed by cloneShallow), cloneShallow will
  22313. // cause data.graph.data !== data when using
  22314. // module:echarts/data/Graph or module:echarts/data/Tree.
  22315. // See module:echarts/data/helper/linkSeriesData
  22316. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  22317. // init or merge stage, because the data can be restored. So we do not `restoreData`
  22318. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  22319. // Call `seriesModel.getRawData()` instead.
  22320. // this.restoreData();
  22321. autoSeriesName(this);
  22322. this._initSelectedMapFromData(data);
  22323. };
  22324. /**
  22325. * Util for merge default and theme to option
  22326. */
  22327. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  22328. var layoutMode = fetchLayoutMode(this);
  22329. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  22330. // Backward compat: using subType on theme.
  22331. // But if name duplicate between series subType
  22332. // (for example: parallel) add component mainType,
  22333. // add suffix 'Series'.
  22334. var themeSubType = this.subType;
  22335. if (ComponentModel.hasClass(themeSubType)) {
  22336. themeSubType += 'Series';
  22337. }
  22338. merge(option, ecModel.getTheme().get(this.subType));
  22339. merge(option, this.getDefaultOption());
  22340. // Default label emphasis `show`
  22341. defaultEmphasis(option, 'label', ['show']);
  22342. this.fillDataTextStyle(option.data);
  22343. if (layoutMode) {
  22344. mergeLayoutParam(option, inputPositionParams, layoutMode);
  22345. }
  22346. };
  22347. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  22348. // this.settingTask.dirty();
  22349. newSeriesOption = merge(this.option, newSeriesOption, true);
  22350. this.fillDataTextStyle(newSeriesOption.data);
  22351. var layoutMode = fetchLayoutMode(this);
  22352. if (layoutMode) {
  22353. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  22354. }
  22355. var sourceManager = inner$1(this).sourceManager;
  22356. sourceManager.dirty();
  22357. sourceManager.prepareSource();
  22358. var data = this.getInitialData(newSeriesOption, ecModel);
  22359. wrapData(data, this);
  22360. this.dataTask.dirty();
  22361. this.dataTask.context.data = data;
  22362. inner$1(this).dataBeforeProcessed = data;
  22363. autoSeriesName(this);
  22364. this._initSelectedMapFromData(data);
  22365. };
  22366. SeriesModel.prototype.fillDataTextStyle = function (data) {
  22367. // Default data label emphasis `show`
  22368. // FIXME Tree structure data ?
  22369. // FIXME Performance ?
  22370. if (data && !isTypedArray(data)) {
  22371. var props = ['show'];
  22372. for (var i = 0; i < data.length; i++) {
  22373. if (data[i] && data[i].label) {
  22374. defaultEmphasis(data[i], 'label', props);
  22375. }
  22376. }
  22377. }
  22378. };
  22379. /**
  22380. * Init a data structure from data related option in series
  22381. * Must be overridden.
  22382. */
  22383. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  22384. return;
  22385. };
  22386. /**
  22387. * Append data to list
  22388. */
  22389. SeriesModel.prototype.appendData = function (params) {
  22390. // FIXME ???
  22391. // (1) If data from dataset, forbidden append.
  22392. // (2) support append data of dataset.
  22393. var data = this.getRawData();
  22394. data.appendData(params.data);
  22395. };
  22396. /**
  22397. * Consider some method like `filter`, `map` need make new data,
  22398. * We should make sure that `seriesModel.getData()` get correct
  22399. * data in the stream procedure. So we fetch data from upstream
  22400. * each time `task.perform` called.
  22401. */
  22402. SeriesModel.prototype.getData = function (dataType) {
  22403. var task = getCurrentTask(this);
  22404. if (task) {
  22405. var data = task.context.data;
  22406. return dataType == null || !data.getLinkedData ? data : data.getLinkedData(dataType);
  22407. } else {
  22408. // When series is not alive (that may happen when click toolbox
  22409. // restore or setOption with not merge mode), series data may
  22410. // be still need to judge animation or something when graphic
  22411. // elements want to know whether fade out.
  22412. return inner$1(this).data;
  22413. }
  22414. };
  22415. SeriesModel.prototype.getAllData = function () {
  22416. var mainData = this.getData();
  22417. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  22418. data: mainData
  22419. }];
  22420. };
  22421. SeriesModel.prototype.setData = function (data) {
  22422. var task = getCurrentTask(this);
  22423. if (task) {
  22424. var context = task.context;
  22425. // Consider case: filter, data sample.
  22426. // FIXME:TS never used, so comment it
  22427. // if (context.data !== data && task.modifyOutputEnd) {
  22428. // task.setOutputEnd(data.count());
  22429. // }
  22430. context.outputData = data;
  22431. // Caution: setData should update context.data,
  22432. // Because getData may be called multiply in a
  22433. // single stage and expect to get the data just
  22434. // set. (For example, AxisProxy, x y both call
  22435. // getData and setDate sequentially).
  22436. // So the context.data should be fetched from
  22437. // upstream each time when a stage starts to be
  22438. // performed.
  22439. if (task !== this.dataTask) {
  22440. context.data = data;
  22441. }
  22442. }
  22443. inner$1(this).data = data;
  22444. };
  22445. SeriesModel.prototype.getEncode = function () {
  22446. var encode = this.get('encode', true);
  22447. if (encode) {
  22448. return createHashMap(encode);
  22449. }
  22450. };
  22451. SeriesModel.prototype.getSourceManager = function () {
  22452. return inner$1(this).sourceManager;
  22453. };
  22454. SeriesModel.prototype.getSource = function () {
  22455. return this.getSourceManager().getSource();
  22456. };
  22457. /**
  22458. * Get data before processed
  22459. */
  22460. SeriesModel.prototype.getRawData = function () {
  22461. return inner$1(this).dataBeforeProcessed;
  22462. };
  22463. SeriesModel.prototype.getColorBy = function () {
  22464. var colorBy = this.get('colorBy');
  22465. return colorBy || 'series';
  22466. };
  22467. SeriesModel.prototype.isColorBySeries = function () {
  22468. return this.getColorBy() === 'series';
  22469. };
  22470. /**
  22471. * Get base axis if has coordinate system and has axis.
  22472. * By default use coordSys.getBaseAxis();
  22473. * Can be overridden for some chart.
  22474. * @return {type} description
  22475. */
  22476. SeriesModel.prototype.getBaseAxis = function () {
  22477. var coordSys = this.coordinateSystem;
  22478. // @ts-ignore
  22479. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22480. };
  22481. /**
  22482. * Default tooltip formatter
  22483. *
  22484. * @param dataIndex
  22485. * @param multipleSeries
  22486. * @param dataType
  22487. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22488. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22489. * string is used as DOM HTML content.
  22490. * 'richText' is used for rendering tooltip in rich text form, for those where
  22491. * DOM operation is not supported.
  22492. * @return formatted tooltip with `html` and `markers`
  22493. * Notice: The override method can also return string
  22494. */
  22495. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22496. return defaultSeriesFormatTooltip({
  22497. series: this,
  22498. dataIndex: dataIndex,
  22499. multipleSeries: multipleSeries
  22500. });
  22501. };
  22502. SeriesModel.prototype.isAnimationEnabled = function () {
  22503. var ecModel = this.ecModel;
  22504. // Disable animation if using echarts in node but not give ssr flag.
  22505. // In ssr mode, renderToString will generate svg with css animation.
  22506. if (env.node && !(ecModel && ecModel.ssr)) {
  22507. return false;
  22508. }
  22509. var animationEnabled = this.getShallow('animation');
  22510. if (animationEnabled) {
  22511. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22512. animationEnabled = false;
  22513. }
  22514. }
  22515. return !!animationEnabled;
  22516. };
  22517. SeriesModel.prototype.restoreData = function () {
  22518. this.dataTask.dirty();
  22519. };
  22520. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22521. var ecModel = this.ecModel;
  22522. // PENDING
  22523. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22524. if (!color) {
  22525. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22526. }
  22527. return color;
  22528. };
  22529. /**
  22530. * Use `data.mapDimensionsAll(coordDim)` instead.
  22531. * @deprecated
  22532. */
  22533. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22534. return this.getRawData().mapDimensionsAll(coordDim);
  22535. };
  22536. /**
  22537. * Get progressive rendering count each step
  22538. */
  22539. SeriesModel.prototype.getProgressive = function () {
  22540. return this.get('progressive');
  22541. };
  22542. /**
  22543. * Get progressive rendering count each step
  22544. */
  22545. SeriesModel.prototype.getProgressiveThreshold = function () {
  22546. return this.get('progressiveThreshold');
  22547. };
  22548. // PENGING If selectedMode is null ?
  22549. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22550. this._innerSelect(this.getData(dataType), innerDataIndices);
  22551. };
  22552. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22553. var selectedMap = this.option.selectedMap;
  22554. if (!selectedMap) {
  22555. return;
  22556. }
  22557. var selectedMode = this.option.selectedMode;
  22558. var data = this.getData(dataType);
  22559. if (selectedMode === 'series' || selectedMap === 'all') {
  22560. this.option.selectedMap = {};
  22561. this._selectedDataIndicesMap = {};
  22562. return;
  22563. }
  22564. for (var i = 0; i < innerDataIndices.length; i++) {
  22565. var dataIndex = innerDataIndices[i];
  22566. var nameOrId = getSelectionKey(data, dataIndex);
  22567. selectedMap[nameOrId] = false;
  22568. this._selectedDataIndicesMap[nameOrId] = -1;
  22569. }
  22570. };
  22571. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22572. var tmpArr = [];
  22573. for (var i = 0; i < innerDataIndices.length; i++) {
  22574. tmpArr[0] = innerDataIndices[i];
  22575. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22576. }
  22577. };
  22578. SeriesModel.prototype.getSelectedDataIndices = function () {
  22579. if (this.option.selectedMap === 'all') {
  22580. return [].slice.call(this.getData().getIndices());
  22581. }
  22582. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22583. var nameOrIds = keys(selectedDataIndicesMap);
  22584. var dataIndices = [];
  22585. for (var i = 0; i < nameOrIds.length; i++) {
  22586. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22587. if (dataIndex >= 0) {
  22588. dataIndices.push(dataIndex);
  22589. }
  22590. }
  22591. return dataIndices;
  22592. };
  22593. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22594. var selectedMap = this.option.selectedMap;
  22595. if (!selectedMap) {
  22596. return false;
  22597. }
  22598. var data = this.getData(dataType);
  22599. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22600. };
  22601. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22602. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22603. return true;
  22604. }
  22605. var universalTransitionOpt = this.option.universalTransition;
  22606. // Quick reject
  22607. if (!universalTransitionOpt) {
  22608. return false;
  22609. }
  22610. if (universalTransitionOpt === true) {
  22611. return true;
  22612. }
  22613. // Can be simply 'universalTransition: true'
  22614. return universalTransitionOpt && universalTransitionOpt.enabled;
  22615. };
  22616. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22617. var _a, _b;
  22618. var option = this.option;
  22619. var selectedMode = option.selectedMode;
  22620. var len = innerDataIndices.length;
  22621. if (!selectedMode || !len) {
  22622. return;
  22623. }
  22624. if (selectedMode === 'series') {
  22625. option.selectedMap = 'all';
  22626. } else if (selectedMode === 'multiple') {
  22627. if (!isObject(option.selectedMap)) {
  22628. option.selectedMap = {};
  22629. }
  22630. var selectedMap = option.selectedMap;
  22631. for (var i = 0; i < len; i++) {
  22632. var dataIndex = innerDataIndices[i];
  22633. // TODO different types of data share same object.
  22634. var nameOrId = getSelectionKey(data, dataIndex);
  22635. selectedMap[nameOrId] = true;
  22636. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22637. }
  22638. } else if (selectedMode === 'single' || selectedMode === true) {
  22639. var lastDataIndex = innerDataIndices[len - 1];
  22640. var nameOrId = getSelectionKey(data, lastDataIndex);
  22641. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22642. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22643. }
  22644. };
  22645. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22646. // Ignore select info in data if selectedMap exists.
  22647. // NOTE It's only for legacy usage. edge data is not supported.
  22648. if (this.option.selectedMap) {
  22649. return;
  22650. }
  22651. var dataIndices = [];
  22652. if (data.hasItemOption) {
  22653. data.each(function (idx) {
  22654. var rawItem = data.getRawDataItem(idx);
  22655. if (rawItem && rawItem.selected) {
  22656. dataIndices.push(idx);
  22657. }
  22658. });
  22659. }
  22660. if (dataIndices.length > 0) {
  22661. this._innerSelect(data, dataIndices);
  22662. }
  22663. };
  22664. // /**
  22665. // * @see {module:echarts/stream/Scheduler}
  22666. // */
  22667. // abstract pipeTask: null
  22668. SeriesModel.registerClass = function (clz) {
  22669. return ComponentModel.registerClass(clz);
  22670. };
  22671. SeriesModel.protoInitialize = function () {
  22672. var proto = SeriesModel.prototype;
  22673. proto.type = 'series.__base__';
  22674. proto.seriesIndex = 0;
  22675. proto.ignoreStyleOnData = false;
  22676. proto.hasSymbolVisual = false;
  22677. proto.defaultSymbol = 'circle';
  22678. // Make sure the values can be accessed!
  22679. proto.visualStyleAccessPath = 'itemStyle';
  22680. proto.visualDrawType = 'fill';
  22681. }();
  22682. return SeriesModel;
  22683. }(ComponentModel);
  22684. mixin(SeriesModel, DataFormatMixin);
  22685. mixin(SeriesModel, PaletteMixin);
  22686. mountExtend(SeriesModel, ComponentModel);
  22687. /**
  22688. * MUST be called after `prepareSource` called
  22689. * Here we need to make auto series, especially for auto legend. But we
  22690. * do not modify series.name in option to avoid side effects.
  22691. */
  22692. function autoSeriesName(seriesModel) {
  22693. // User specified name has higher priority, otherwise it may cause
  22694. // series can not be queried unexpectedly.
  22695. var name = seriesModel.name;
  22696. if (!isNameSpecified(seriesModel)) {
  22697. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22698. }
  22699. }
  22700. function getSeriesAutoName(seriesModel) {
  22701. var data = seriesModel.getRawData();
  22702. var dataDims = data.mapDimensionsAll('seriesName');
  22703. var nameArr = [];
  22704. each(dataDims, function (dataDim) {
  22705. var dimInfo = data.getDimensionInfo(dataDim);
  22706. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22707. });
  22708. return nameArr.join(' ');
  22709. }
  22710. function dataTaskCount(context) {
  22711. return context.model.getRawData().count();
  22712. }
  22713. function dataTaskReset(context) {
  22714. var seriesModel = context.model;
  22715. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22716. return dataTaskProgress;
  22717. }
  22718. function dataTaskProgress(param, context) {
  22719. // Avoid repeat cloneShallow when data just created in reset.
  22720. if (context.outputData && param.end > context.outputData.count()) {
  22721. context.model.getRawData().cloneShallow(context.outputData);
  22722. }
  22723. }
  22724. // TODO refactor
  22725. function wrapData(data, seriesModel) {
  22726. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22727. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22728. });
  22729. }
  22730. function onDataChange(seriesModel, newList) {
  22731. var task = getCurrentTask(seriesModel);
  22732. if (task) {
  22733. // Consider case: filter, selectRange
  22734. task.setOutputEnd((newList || this).count());
  22735. }
  22736. return newList;
  22737. }
  22738. function getCurrentTask(seriesModel) {
  22739. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22740. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22741. if (pipeline) {
  22742. // When pipline finished, the currrentTask keep the last
  22743. // task (renderTask).
  22744. var task = pipeline.currentTask;
  22745. if (task) {
  22746. var agentStubMap = task.agentStubMap;
  22747. if (agentStubMap) {
  22748. task = agentStubMap.get(seriesModel.uid);
  22749. }
  22750. }
  22751. return task;
  22752. }
  22753. }
  22754. var ComponentView = /** @class */function () {
  22755. function ComponentView() {
  22756. this.group = new Group();
  22757. this.uid = getUID('viewComponent');
  22758. }
  22759. ComponentView.prototype.init = function (ecModel, api) {};
  22760. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22761. ComponentView.prototype.dispose = function (ecModel, api) {};
  22762. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {
  22763. // Do nothing;
  22764. };
  22765. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {
  22766. // Do nothing;
  22767. };
  22768. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {
  22769. // Do nothing;
  22770. };
  22771. /**
  22772. * Hook for toggle blur target series.
  22773. * Can be used in marker for blur or leave blur the markers
  22774. */
  22775. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {
  22776. // Do nothing;
  22777. };
  22778. /**
  22779. * Traverse the new rendered elements.
  22780. *
  22781. * It will traverse the new added element in progressive rendering.
  22782. * And traverse all in normal rendering.
  22783. */
  22784. ComponentView.prototype.eachRendered = function (cb) {
  22785. var group = this.group;
  22786. if (group) {
  22787. group.traverse(cb);
  22788. }
  22789. };
  22790. return ComponentView;
  22791. }();
  22792. enableClassExtend(ComponentView);
  22793. enableClassManagement(ComponentView);
  22794. /**
  22795. * @return {string} If large mode changed, return string 'reset';
  22796. */
  22797. function createRenderPlanner() {
  22798. var inner = makeInner();
  22799. return function (seriesModel) {
  22800. var fields = inner(seriesModel);
  22801. var pipelineContext = seriesModel.pipelineContext;
  22802. var originalLarge = !!fields.large;
  22803. var originalProgressive = !!fields.progressiveRender;
  22804. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22805. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22806. // on `performRawSeries` in `Schedular.js`.
  22807. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22808. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22809. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22810. };
  22811. }
  22812. var inner$2 = makeInner();
  22813. var renderPlanner = createRenderPlanner();
  22814. var ChartView = /** @class */function () {
  22815. function ChartView() {
  22816. this.group = new Group();
  22817. this.uid = getUID('viewChart');
  22818. this.renderTask = createTask({
  22819. plan: renderTaskPlan,
  22820. reset: renderTaskReset
  22821. });
  22822. this.renderTask.context = {
  22823. view: this
  22824. };
  22825. }
  22826. ChartView.prototype.init = function (ecModel, api) {};
  22827. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22828. if ("development" !== 'production') {
  22829. throw new Error('render method must been implemented');
  22830. }
  22831. };
  22832. /**
  22833. * Highlight series or specified data item.
  22834. */
  22835. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22836. var data = seriesModel.getData(payload && payload.dataType);
  22837. if (!data) {
  22838. if ("development" !== 'production') {
  22839. error("Unknown dataType " + payload.dataType);
  22840. }
  22841. return;
  22842. }
  22843. toggleHighlight(data, payload, 'emphasis');
  22844. };
  22845. /**
  22846. * Downplay series or specified data item.
  22847. */
  22848. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22849. var data = seriesModel.getData(payload && payload.dataType);
  22850. if (!data) {
  22851. if ("development" !== 'production') {
  22852. error("Unknown dataType " + payload.dataType);
  22853. }
  22854. return;
  22855. }
  22856. toggleHighlight(data, payload, 'normal');
  22857. };
  22858. /**
  22859. * Remove self.
  22860. */
  22861. ChartView.prototype.remove = function (ecModel, api) {
  22862. this.group.removeAll();
  22863. };
  22864. /**
  22865. * Dispose self.
  22866. */
  22867. ChartView.prototype.dispose = function (ecModel, api) {};
  22868. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22869. this.render(seriesModel, ecModel, api, payload);
  22870. };
  22871. // FIXME never used?
  22872. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22873. this.render(seriesModel, ecModel, api, payload);
  22874. };
  22875. // FIXME never used?
  22876. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22877. this.render(seriesModel, ecModel, api, payload);
  22878. };
  22879. /**
  22880. * Traverse the new rendered elements.
  22881. *
  22882. * It will traverse the new added element in progressive rendering.
  22883. * And traverse all in normal rendering.
  22884. */
  22885. ChartView.prototype.eachRendered = function (cb) {
  22886. traverseElements(this.group, cb);
  22887. };
  22888. ChartView.markUpdateMethod = function (payload, methodName) {
  22889. inner$2(payload).updateMethod = methodName;
  22890. };
  22891. ChartView.protoInitialize = function () {
  22892. var proto = ChartView.prototype;
  22893. proto.type = 'chart';
  22894. }();
  22895. return ChartView;
  22896. }();
  22897. /**
  22898. * Set state of single element
  22899. */
  22900. function elSetState(el, state, highlightDigit) {
  22901. if (el && isHighDownDispatcher(el)) {
  22902. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22903. }
  22904. }
  22905. function toggleHighlight(data, payload, state) {
  22906. var dataIndex = queryDataIndex(data, payload);
  22907. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22908. if (dataIndex != null) {
  22909. each(normalizeToArray(dataIndex), function (dataIdx) {
  22910. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22911. });
  22912. } else {
  22913. data.eachItemGraphicEl(function (el) {
  22914. elSetState(el, state, highlightDigit);
  22915. });
  22916. }
  22917. }
  22918. enableClassExtend(ChartView, ['dispose']);
  22919. enableClassManagement(ChartView);
  22920. function renderTaskPlan(context) {
  22921. return renderPlanner(context.model);
  22922. }
  22923. function renderTaskReset(context) {
  22924. var seriesModel = context.model;
  22925. var ecModel = context.ecModel;
  22926. var api = context.api;
  22927. var payload = context.payload;
  22928. // FIXME: remove updateView updateVisual
  22929. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22930. var view = context.view;
  22931. var updateMethod = payload && inner$2(payload).updateMethod;
  22932. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod
  22933. // `appendData` is also supported when data amount
  22934. // is less than progressive threshold.
  22935. : 'render';
  22936. if (methodName !== 'render') {
  22937. view[methodName](seriesModel, ecModel, api, payload);
  22938. }
  22939. return progressMethodMap[methodName];
  22940. }
  22941. var progressMethodMap = {
  22942. incrementalPrepareRender: {
  22943. progress: function (params, context) {
  22944. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22945. }
  22946. },
  22947. render: {
  22948. // Put view.render in `progress` to support appendData. But in this case
  22949. // view.render should not be called in reset, otherwise it will be called
  22950. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22951. // in any cases.
  22952. forceFirstProgress: true,
  22953. progress: function (params, context) {
  22954. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22955. }
  22956. }
  22957. };
  22958. /*
  22959. * Licensed to the Apache Software Foundation (ASF) under one
  22960. * or more contributor license agreements. See the NOTICE file
  22961. * distributed with this work for additional information
  22962. * regarding copyright ownership. The ASF licenses this file
  22963. * to you under the Apache License, Version 2.0 (the
  22964. * "License"); you may not use this file except in compliance
  22965. * with the License. You may obtain a copy of the License at
  22966. *
  22967. * http://www.apache.org/licenses/LICENSE-2.0
  22968. *
  22969. * Unless required by applicable law or agreed to in writing,
  22970. * software distributed under the License is distributed on an
  22971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22972. * KIND, either express or implied. See the License for the
  22973. * specific language governing permissions and limitations
  22974. * under the License.
  22975. */
  22976. /**
  22977. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22978. */
  22979. /*
  22980. * Licensed to the Apache Software Foundation (ASF) under one
  22981. * or more contributor license agreements. See the NOTICE file
  22982. * distributed with this work for additional information
  22983. * regarding copyright ownership. The ASF licenses this file
  22984. * to you under the Apache License, Version 2.0 (the
  22985. * "License"); you may not use this file except in compliance
  22986. * with the License. You may obtain a copy of the License at
  22987. *
  22988. * http://www.apache.org/licenses/LICENSE-2.0
  22989. *
  22990. * Unless required by applicable law or agreed to in writing,
  22991. * software distributed under the License is distributed on an
  22992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22993. * KIND, either express or implied. See the License for the
  22994. * specific language governing permissions and limitations
  22995. * under the License.
  22996. */
  22997. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22998. var RATE = '\0__throttleRate';
  22999. var THROTTLE_TYPE = '\0__throttleType';
  23000. /**
  23001. * @public
  23002. * @param {(Function)} fn
  23003. * @param {number} [delay=0] Unit: ms.
  23004. * @param {boolean} [debounce=false]
  23005. * true: If call interval less than `delay`, only the last call works.
  23006. * false: If call interval less than `delay, call works on fixed rate.
  23007. * @return {(Function)} throttled fn.
  23008. */
  23009. function throttle(fn, delay, debounce) {
  23010. var currCall;
  23011. var lastCall = 0;
  23012. var lastExec = 0;
  23013. var timer = null;
  23014. var diff;
  23015. var scope;
  23016. var args;
  23017. var debounceNextCall;
  23018. delay = delay || 0;
  23019. function exec() {
  23020. lastExec = new Date().getTime();
  23021. timer = null;
  23022. fn.apply(scope, args || []);
  23023. }
  23024. var cb = function () {
  23025. var cbArgs = [];
  23026. for (var _i = 0; _i < arguments.length; _i++) {
  23027. cbArgs[_i] = arguments[_i];
  23028. }
  23029. currCall = new Date().getTime();
  23030. scope = this;
  23031. args = cbArgs;
  23032. var thisDelay = debounceNextCall || delay;
  23033. var thisDebounce = debounceNextCall || debounce;
  23034. debounceNextCall = null;
  23035. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  23036. clearTimeout(timer);
  23037. // Here we should make sure that: the `exec` SHOULD NOT be called later
  23038. // than a new call of `cb`, that is, preserving the command order. Consider
  23039. // calculating "scale rate" when roaming as an example. When a call of `cb`
  23040. // happens, either the `exec` is called dierectly, or the call is delayed.
  23041. // But the delayed call should never be later than next call of `cb`. Under
  23042. // this assurance, we can simply update view state each time `dispatchAction`
  23043. // triggered by user roaming, but not need to add extra code to avoid the
  23044. // state being "rolled-back".
  23045. if (thisDebounce) {
  23046. timer = setTimeout(exec, thisDelay);
  23047. } else {
  23048. if (diff >= 0) {
  23049. exec();
  23050. } else {
  23051. timer = setTimeout(exec, -diff);
  23052. }
  23053. }
  23054. lastCall = currCall;
  23055. };
  23056. /**
  23057. * Clear throttle.
  23058. * @public
  23059. */
  23060. cb.clear = function () {
  23061. if (timer) {
  23062. clearTimeout(timer);
  23063. timer = null;
  23064. }
  23065. };
  23066. /**
  23067. * Enable debounce once.
  23068. */
  23069. cb.debounceNextCall = function (debounceDelay) {
  23070. debounceNextCall = debounceDelay;
  23071. };
  23072. return cb;
  23073. }
  23074. /**
  23075. * Create throttle method or update throttle rate.
  23076. *
  23077. * @example
  23078. * ComponentView.prototype.render = function () {
  23079. * ...
  23080. * throttle.createOrUpdate(
  23081. * this,
  23082. * '_dispatchAction',
  23083. * this.model.get('throttle'),
  23084. * 'fixRate'
  23085. * );
  23086. * };
  23087. * ComponentView.prototype.remove = function () {
  23088. * throttle.clear(this, '_dispatchAction');
  23089. * };
  23090. * ComponentView.prototype.dispose = function () {
  23091. * throttle.clear(this, '_dispatchAction');
  23092. * };
  23093. *
  23094. */
  23095. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  23096. var fn = obj[fnAttr];
  23097. if (!fn) {
  23098. return;
  23099. }
  23100. var originFn = fn[ORIGIN_METHOD] || fn;
  23101. var lastThrottleType = fn[THROTTLE_TYPE];
  23102. var lastRate = fn[RATE];
  23103. if (lastRate !== rate || lastThrottleType !== throttleType) {
  23104. if (rate == null || !throttleType) {
  23105. return obj[fnAttr] = originFn;
  23106. }
  23107. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  23108. fn[ORIGIN_METHOD] = originFn;
  23109. fn[THROTTLE_TYPE] = throttleType;
  23110. fn[RATE] = rate;
  23111. }
  23112. return fn;
  23113. }
  23114. /**
  23115. * Clear throttle. Example see throttle.createOrUpdate.
  23116. */
  23117. function clear(obj, fnAttr) {
  23118. var fn = obj[fnAttr];
  23119. if (fn && fn[ORIGIN_METHOD]) {
  23120. // Clear throttle
  23121. fn.clear && fn.clear();
  23122. obj[fnAttr] = fn[ORIGIN_METHOD];
  23123. }
  23124. }
  23125. var inner$3 = makeInner();
  23126. var defaultStyleMappers = {
  23127. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  23128. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  23129. };
  23130. var defaultColorKey = {
  23131. lineStyle: 'stroke',
  23132. itemStyle: 'fill'
  23133. };
  23134. function getStyleMapper(seriesModel, stylePath) {
  23135. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  23136. if (!styleMapper) {
  23137. console.warn("Unknown style type '" + stylePath + "'.");
  23138. return defaultStyleMappers.itemStyle;
  23139. }
  23140. return styleMapper;
  23141. }
  23142. function getDefaultColorKey(seriesModel, stylePath) {
  23143. // return defaultColorKey[stylePath] ||
  23144. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  23145. if (!colorKey) {
  23146. console.warn("Unknown style type '" + stylePath + "'.");
  23147. return 'fill';
  23148. }
  23149. return colorKey;
  23150. }
  23151. var seriesStyleTask = {
  23152. createOnAllSeries: true,
  23153. performRawSeries: true,
  23154. reset: function (seriesModel, ecModel) {
  23155. var data = seriesModel.getData();
  23156. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23157. // Set in itemStyle
  23158. var styleModel = seriesModel.getModel(stylePath);
  23159. var getStyle = getStyleMapper(seriesModel, stylePath);
  23160. var globalStyle = getStyle(styleModel);
  23161. var decalOption = styleModel.getShallow('decal');
  23162. if (decalOption) {
  23163. data.setVisual('decal', decalOption);
  23164. decalOption.dirty = true;
  23165. }
  23166. // TODO
  23167. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23168. var color = globalStyle[colorKey];
  23169. // TODO style callback
  23170. var colorCallback = isFunction(color) ? color : null;
  23171. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto';
  23172. // Get from color palette by default.
  23173. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  23174. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  23175. // make it effect palette. Because some scenarios users need to make some series
  23176. // transparent or as background, which should better not effect the palette.
  23177. var colorPalette = seriesModel.getColorFromPalette(
  23178. // TODO series count changed.
  23179. seriesModel.name, null, ecModel.getSeriesCount());
  23180. if (!globalStyle[colorKey]) {
  23181. globalStyle[colorKey] = colorPalette;
  23182. data.setVisual('colorFromPalette', true);
  23183. }
  23184. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  23185. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  23186. }
  23187. data.setVisual('style', globalStyle);
  23188. data.setVisual('drawType', colorKey);
  23189. // Only visible series has each data be visual encoded
  23190. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  23191. data.setVisual('colorFromPalette', false);
  23192. return {
  23193. dataEach: function (data, idx) {
  23194. var dataParams = seriesModel.getDataParams(idx);
  23195. var itemStyle = extend({}, globalStyle);
  23196. itemStyle[colorKey] = colorCallback(dataParams);
  23197. data.setItemVisual(idx, 'style', itemStyle);
  23198. }
  23199. };
  23200. }
  23201. }
  23202. };
  23203. var sharedModel = new Model();
  23204. var dataStyleTask = {
  23205. createOnAllSeries: true,
  23206. performRawSeries: true,
  23207. reset: function (seriesModel, ecModel) {
  23208. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  23209. return;
  23210. }
  23211. var data = seriesModel.getData();
  23212. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23213. // Set in itemStyle
  23214. var getStyle = getStyleMapper(seriesModel, stylePath);
  23215. var colorKey = data.getVisual('drawType');
  23216. return {
  23217. dataEach: data.hasItemOption ? function (data, idx) {
  23218. // Not use getItemModel for performance considuration
  23219. var rawItem = data.getRawDataItem(idx);
  23220. if (rawItem && rawItem[stylePath]) {
  23221. sharedModel.option = rawItem[stylePath];
  23222. var style = getStyle(sharedModel);
  23223. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  23224. extend(existsStyle, style);
  23225. if (sharedModel.option.decal) {
  23226. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  23227. sharedModel.option.decal.dirty = true;
  23228. }
  23229. if (colorKey in style) {
  23230. data.setItemVisual(idx, 'colorFromPalette', false);
  23231. }
  23232. }
  23233. } : null
  23234. };
  23235. }
  23236. };
  23237. // Pick color from palette for the data which has not been set with color yet.
  23238. // Note: do not support stream rendering. No such cases yet.
  23239. var dataColorPaletteTask = {
  23240. performRawSeries: true,
  23241. overallReset: function (ecModel) {
  23242. // Each type of series uses one scope.
  23243. // Pie and funnel are using different scopes.
  23244. var paletteScopeGroupByType = createHashMap();
  23245. ecModel.eachSeries(function (seriesModel) {
  23246. var colorBy = seriesModel.getColorBy();
  23247. if (seriesModel.isColorBySeries()) {
  23248. return;
  23249. }
  23250. var key = seriesModel.type + '-' + colorBy;
  23251. var colorScope = paletteScopeGroupByType.get(key);
  23252. if (!colorScope) {
  23253. colorScope = {};
  23254. paletteScopeGroupByType.set(key, colorScope);
  23255. }
  23256. inner$3(seriesModel).scope = colorScope;
  23257. });
  23258. ecModel.eachSeries(function (seriesModel) {
  23259. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  23260. return;
  23261. }
  23262. var dataAll = seriesModel.getRawData();
  23263. var idxMap = {};
  23264. var data = seriesModel.getData();
  23265. var colorScope = inner$3(seriesModel).scope;
  23266. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23267. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23268. data.each(function (idx) {
  23269. var rawIdx = data.getRawIndex(idx);
  23270. idxMap[rawIdx] = idx;
  23271. });
  23272. // Iterate on data before filtered. To make sure color from palette can be
  23273. // Consistent when toggling legend.
  23274. dataAll.each(function (rawIdx) {
  23275. var idx = idxMap[rawIdx];
  23276. var fromPalette = data.getItemVisual(idx, 'colorFromPalette');
  23277. // Get color from palette for each data only when the color is inherited from series color, which is
  23278. // also picked from color palette. So following situation is not in the case:
  23279. // 1. series.itemStyle.color is set
  23280. // 2. color is encoded by visualMap
  23281. if (fromPalette) {
  23282. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23283. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  23284. var dataCount = dataAll.count();
  23285. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  23286. }
  23287. });
  23288. });
  23289. }
  23290. };
  23291. var PI$3 = Math.PI;
  23292. /**
  23293. * @param {module:echarts/ExtensionAPI} api
  23294. * @param {Object} [opts]
  23295. * @param {string} [opts.text]
  23296. * @param {string} [opts.color]
  23297. * @param {string} [opts.textColor]
  23298. * @return {module:zrender/Element}
  23299. */
  23300. function defaultLoading(api, opts) {
  23301. opts = opts || {};
  23302. defaults(opts, {
  23303. text: 'loading',
  23304. textColor: '#000',
  23305. fontSize: 12,
  23306. fontWeight: 'normal',
  23307. fontStyle: 'normal',
  23308. fontFamily: 'sans-serif',
  23309. maskColor: 'rgba(255, 255, 255, 0.8)',
  23310. showSpinner: true,
  23311. color: '#5470c6',
  23312. spinnerRadius: 10,
  23313. lineWidth: 5,
  23314. zlevel: 0
  23315. });
  23316. var group = new Group();
  23317. var mask = new Rect({
  23318. style: {
  23319. fill: opts.maskColor
  23320. },
  23321. zlevel: opts.zlevel,
  23322. z: 10000
  23323. });
  23324. group.add(mask);
  23325. var textContent = new ZRText({
  23326. style: {
  23327. text: opts.text,
  23328. fill: opts.textColor,
  23329. fontSize: opts.fontSize,
  23330. fontWeight: opts.fontWeight,
  23331. fontStyle: opts.fontStyle,
  23332. fontFamily: opts.fontFamily
  23333. },
  23334. zlevel: opts.zlevel,
  23335. z: 10001
  23336. });
  23337. var labelRect = new Rect({
  23338. style: {
  23339. fill: 'none'
  23340. },
  23341. textContent: textContent,
  23342. textConfig: {
  23343. position: 'right',
  23344. distance: 10
  23345. },
  23346. zlevel: opts.zlevel,
  23347. z: 10001
  23348. });
  23349. group.add(labelRect);
  23350. var arc;
  23351. if (opts.showSpinner) {
  23352. arc = new Arc({
  23353. shape: {
  23354. startAngle: -PI$3 / 2,
  23355. endAngle: -PI$3 / 2 + 0.1,
  23356. r: opts.spinnerRadius
  23357. },
  23358. style: {
  23359. stroke: opts.color,
  23360. lineCap: 'round',
  23361. lineWidth: opts.lineWidth
  23362. },
  23363. zlevel: opts.zlevel,
  23364. z: 10001
  23365. });
  23366. arc.animateShape(true).when(1000, {
  23367. endAngle: PI$3 * 3 / 2
  23368. }).start('circularInOut');
  23369. arc.animateShape(true).when(1000, {
  23370. startAngle: PI$3 * 3 / 2
  23371. }).delay(300).start('circularInOut');
  23372. group.add(arc);
  23373. }
  23374. // Inject resize
  23375. group.resize = function () {
  23376. var textWidth = textContent.getBoundingRect().width;
  23377. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  23378. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  23379. // textDistance needs to be calculated when both animation and text exist
  23380. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2)
  23381. // only show the text
  23382. + (opts.showSpinner ? 0 : textWidth / 2)
  23383. // only show the spinner
  23384. + (textWidth ? 0 : r);
  23385. var cy = api.getHeight() / 2;
  23386. opts.showSpinner && arc.setShape({
  23387. cx: cx,
  23388. cy: cy
  23389. });
  23390. labelRect.setShape({
  23391. x: cx - r,
  23392. y: cy - r,
  23393. width: r * 2,
  23394. height: r * 2
  23395. });
  23396. mask.setShape({
  23397. x: 0,
  23398. y: 0,
  23399. width: api.getWidth(),
  23400. height: api.getHeight()
  23401. });
  23402. };
  23403. group.resize();
  23404. return group;
  23405. }
  23406. var Scheduler = /** @class */function () {
  23407. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  23408. // key: handlerUID
  23409. this._stageTaskMap = createHashMap();
  23410. this.ecInstance = ecInstance;
  23411. this.api = api;
  23412. // Fix current processors in case that in some rear cases that
  23413. // processors might be registered after echarts instance created.
  23414. // Register processors incrementally for a echarts instance is
  23415. // not supported by this stream architecture.
  23416. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  23417. visualHandlers = this._visualHandlers = visualHandlers.slice();
  23418. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  23419. }
  23420. Scheduler.prototype.restoreData = function (ecModel, payload) {
  23421. // TODO: Only restore needed series and components, but not all components.
  23422. // Currently `restoreData` of all of the series and component will be called.
  23423. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  23424. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  23425. // and some components like coordinate system, axes, dataZoom, visualMap only
  23426. // need their target series refresh.
  23427. // (1) If we are implementing this feature some day, we should consider these cases:
  23428. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  23429. // on the settings of `dataZoom`), it should be re-performed if the component
  23430. // is modified by `setOption`.
  23431. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  23432. // it should be re-performed when the result array of `getTargetSeries` changed.
  23433. // We use `dependencies` to cover these issues.
  23434. // (3) How to update target series when coordinate system related components modified.
  23435. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  23436. // and this case all of the tasks will be set as dirty.
  23437. ecModel.restoreData(payload);
  23438. // Theoretically an overall task not only depends on each of its target series, but also
  23439. // depends on all of the series.
  23440. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  23441. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  23442. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  23443. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  23444. // probably cause state chaos (consider `dataZoomProcessor`).
  23445. this._stageTaskMap.each(function (taskRecord) {
  23446. var overallTask = taskRecord.overallTask;
  23447. overallTask && overallTask.dirty();
  23448. });
  23449. };
  23450. // If seriesModel provided, incremental threshold is check by series data.
  23451. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  23452. // For overall task
  23453. if (!task.__pipeline) {
  23454. return;
  23455. }
  23456. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  23457. var pCtx = pipeline.context;
  23458. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  23459. var step = incremental ? pipeline.step : null;
  23460. var modDataCount = pCtx && pCtx.modDataCount;
  23461. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  23462. return {
  23463. step: step,
  23464. modBy: modBy,
  23465. modDataCount: modDataCount
  23466. };
  23467. };
  23468. Scheduler.prototype.getPipeline = function (pipelineId) {
  23469. return this._pipelineMap.get(pipelineId);
  23470. };
  23471. /**
  23472. * Current, progressive rendering starts from visual and layout.
  23473. * Always detect render mode in the same stage, avoiding that incorrect
  23474. * detection caused by data filtering.
  23475. * Caution:
  23476. * `updateStreamModes` use `seriesModel.getData()`.
  23477. */
  23478. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  23479. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23480. var data = seriesModel.getData();
  23481. var dataLen = data.count();
  23482. // `progressiveRender` means that can render progressively in each
  23483. // animation frame. Note that some types of series do not provide
  23484. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23485. // use the term `incremental` but not `progressive` to describe the
  23486. // case that `chart.appendData`.
  23487. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  23488. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  23489. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23490. // see `test/candlestick-large3.html`
  23491. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23492. seriesModel.pipelineContext = pipeline.context = {
  23493. progressiveRender: progressiveRender,
  23494. modDataCount: modDataCount,
  23495. large: large
  23496. };
  23497. };
  23498. Scheduler.prototype.restorePipelines = function (ecModel) {
  23499. var scheduler = this;
  23500. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23501. ecModel.eachSeries(function (seriesModel) {
  23502. var progressive = seriesModel.getProgressive();
  23503. var pipelineId = seriesModel.uid;
  23504. pipelineMap.set(pipelineId, {
  23505. id: pipelineId,
  23506. head: null,
  23507. tail: null,
  23508. threshold: seriesModel.getProgressiveThreshold(),
  23509. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23510. blockIndex: -1,
  23511. step: Math.round(progressive || 700),
  23512. count: 0
  23513. });
  23514. scheduler._pipe(seriesModel, seriesModel.dataTask);
  23515. });
  23516. };
  23517. Scheduler.prototype.prepareStageTasks = function () {
  23518. var stageTaskMap = this._stageTaskMap;
  23519. var ecModel = this.api.getModel();
  23520. var api = this.api;
  23521. each(this._allHandlers, function (handler) {
  23522. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  23523. var errMsg = '';
  23524. if ("development" !== 'production') {
  23525. // Currently do not need to support to sepecify them both.
  23526. errMsg = '"reset" and "overallReset" must not be both specified.';
  23527. }
  23528. assert(!(handler.reset && handler.overallReset), errMsg);
  23529. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23530. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23531. }, this);
  23532. };
  23533. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23534. var renderTask = view.renderTask;
  23535. var context = renderTask.context;
  23536. context.model = model;
  23537. context.ecModel = ecModel;
  23538. context.api = api;
  23539. renderTask.__block = !view.incrementalPrepareRender;
  23540. this._pipe(model, renderTask);
  23541. };
  23542. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23543. // If we do not use `block` here, it should be considered when to update modes.
  23544. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23545. block: true
  23546. });
  23547. };
  23548. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23549. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23550. };
  23551. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23552. opt = opt || {};
  23553. var unfinished = false;
  23554. var scheduler = this;
  23555. each(stageHandlers, function (stageHandler, idx) {
  23556. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23557. return;
  23558. }
  23559. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23560. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23561. var overallTask = stageHandlerRecord.overallTask;
  23562. if (overallTask) {
  23563. var overallNeedDirty_1;
  23564. var agentStubMap = overallTask.agentStubMap;
  23565. agentStubMap.each(function (stub) {
  23566. if (needSetDirty(opt, stub)) {
  23567. stub.dirty();
  23568. overallNeedDirty_1 = true;
  23569. }
  23570. });
  23571. overallNeedDirty_1 && overallTask.dirty();
  23572. scheduler.updatePayload(overallTask, payload);
  23573. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block);
  23574. // Execute stubs firstly, which may set the overall task dirty,
  23575. // then execute the overall task. And stub will call seriesModel.setData,
  23576. // which ensures that in the overallTask seriesModel.getData() will not
  23577. // return incorrect data.
  23578. agentStubMap.each(function (stub) {
  23579. stub.perform(performArgs_1);
  23580. });
  23581. if (overallTask.perform(performArgs_1)) {
  23582. unfinished = true;
  23583. }
  23584. } else if (seriesTaskMap) {
  23585. seriesTaskMap.each(function (task, pipelineId) {
  23586. if (needSetDirty(opt, task)) {
  23587. task.dirty();
  23588. }
  23589. var performArgs = scheduler.getPerformArgs(task, opt.block);
  23590. // FIXME
  23591. // if intending to declare `performRawSeries` in handlers, only
  23592. // stream-independent (specifically, data item independent) operations can be
  23593. // performed. Because if a series is filtered, most of the tasks will not
  23594. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23595. // Perhaps we should not provide a separate callback for this case instead
  23596. // of providing the config `performRawSeries`. The stream-dependent operations
  23597. // and stream-independent operations should better not be mixed.
  23598. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23599. scheduler.updatePayload(task, payload);
  23600. if (task.perform(performArgs)) {
  23601. unfinished = true;
  23602. }
  23603. });
  23604. }
  23605. });
  23606. function needSetDirty(opt, task) {
  23607. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23608. }
  23609. this.unfinished = unfinished || this.unfinished;
  23610. };
  23611. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23612. var unfinished;
  23613. ecModel.eachSeries(function (seriesModel) {
  23614. // Progress to the end for dataInit and dataRestore.
  23615. unfinished = seriesModel.dataTask.perform() || unfinished;
  23616. });
  23617. this.unfinished = unfinished || this.unfinished;
  23618. };
  23619. Scheduler.prototype.plan = function () {
  23620. // Travel pipelines, check block.
  23621. this._pipelineMap.each(function (pipeline) {
  23622. var task = pipeline.tail;
  23623. do {
  23624. if (task.__block) {
  23625. pipeline.blockIndex = task.__idxInPipeline;
  23626. break;
  23627. }
  23628. task = task.getUpstream();
  23629. } while (task);
  23630. });
  23631. };
  23632. Scheduler.prototype.updatePayload = function (task, payload) {
  23633. payload !== 'remain' && (task.context.payload = payload);
  23634. };
  23635. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23636. var scheduler = this;
  23637. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23638. // The count of stages are totally about only several dozen, so
  23639. // do not need to reuse the map.
  23640. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23641. var seriesType = stageHandler.seriesType;
  23642. var getTargetSeries = stageHandler.getTargetSeries;
  23643. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23644. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23645. // it works but it may cause other irrelevant charts blocked.
  23646. if (stageHandler.createOnAllSeries) {
  23647. ecModel.eachRawSeries(create);
  23648. } else if (seriesType) {
  23649. ecModel.eachRawSeriesByType(seriesType, create);
  23650. } else if (getTargetSeries) {
  23651. getTargetSeries(ecModel, api).each(create);
  23652. }
  23653. function create(seriesModel) {
  23654. var pipelineId = seriesModel.uid;
  23655. // Init tasks for each seriesModel only once.
  23656. // Reuse original task instance.
  23657. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23658. plan: seriesTaskPlan,
  23659. reset: seriesTaskReset,
  23660. count: seriesTaskCount
  23661. }));
  23662. task.context = {
  23663. model: seriesModel,
  23664. ecModel: ecModel,
  23665. api: api,
  23666. // PENDING: `useClearVisual` not used?
  23667. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23668. plan: stageHandler.plan,
  23669. reset: stageHandler.reset,
  23670. scheduler: scheduler
  23671. };
  23672. scheduler._pipe(seriesModel, task);
  23673. }
  23674. };
  23675. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23676. var scheduler = this;
  23677. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23678. // For overall task, the function only be called on reset stage.
  23679. || createTask({
  23680. reset: overallTaskReset
  23681. });
  23682. overallTask.context = {
  23683. ecModel: ecModel,
  23684. api: api,
  23685. overallReset: stageHandler.overallReset,
  23686. scheduler: scheduler
  23687. };
  23688. var oldAgentStubMap = overallTask.agentStubMap;
  23689. // The count of stages are totally about only several dozen, so
  23690. // do not need to reuse the map.
  23691. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23692. var seriesType = stageHandler.seriesType;
  23693. var getTargetSeries = stageHandler.getTargetSeries;
  23694. var overallProgress = true;
  23695. var shouldOverallTaskDirty = false;
  23696. // FIXME:TS never used, so comment it
  23697. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23698. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23699. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23700. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23701. // we set the pipeline block.
  23702. var errMsg = '';
  23703. if ("development" !== 'production') {
  23704. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23705. }
  23706. assert(!stageHandler.createOnAllSeries, errMsg);
  23707. if (seriesType) {
  23708. ecModel.eachRawSeriesByType(seriesType, createStub);
  23709. } else if (getTargetSeries) {
  23710. getTargetSeries(ecModel, api).each(createStub);
  23711. }
  23712. // Otherwise, (usually it is legacy case), the overall task will only be
  23713. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23714. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23715. // dirty info from upstream.
  23716. else {
  23717. overallProgress = false;
  23718. each(ecModel.getSeries(), createStub);
  23719. }
  23720. function createStub(seriesModel) {
  23721. var pipelineId = seriesModel.uid;
  23722. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || (
  23723. // When the result of `getTargetSeries` changed, the overallTask
  23724. // should be set as dirty and re-performed.
  23725. shouldOverallTaskDirty = true, createTask({
  23726. reset: stubReset,
  23727. onDirty: stubOnDirty
  23728. })));
  23729. stub.context = {
  23730. model: seriesModel,
  23731. overallProgress: overallProgress
  23732. // FIXME:TS never used, so comment it
  23733. // modifyOutputEnd: modifyOutputEnd
  23734. };
  23735. stub.agent = overallTask;
  23736. stub.__block = overallProgress;
  23737. scheduler._pipe(seriesModel, stub);
  23738. }
  23739. if (shouldOverallTaskDirty) {
  23740. overallTask.dirty();
  23741. }
  23742. };
  23743. Scheduler.prototype._pipe = function (seriesModel, task) {
  23744. var pipelineId = seriesModel.uid;
  23745. var pipeline = this._pipelineMap.get(pipelineId);
  23746. !pipeline.head && (pipeline.head = task);
  23747. pipeline.tail && pipeline.tail.pipe(task);
  23748. pipeline.tail = task;
  23749. task.__idxInPipeline = pipeline.count++;
  23750. task.__pipeline = pipeline;
  23751. };
  23752. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23753. if (isFunction(stageHandler)) {
  23754. stageHandler = {
  23755. overallReset: stageHandler,
  23756. seriesType: detectSeriseType(stageHandler)
  23757. };
  23758. }
  23759. stageHandler.uid = getUID('stageHandler');
  23760. visualType && (stageHandler.visualType = visualType);
  23761. return stageHandler;
  23762. };
  23763. return Scheduler;
  23764. }();
  23765. function overallTaskReset(context) {
  23766. context.overallReset(context.ecModel, context.api, context.payload);
  23767. }
  23768. function stubReset(context) {
  23769. return context.overallProgress && stubProgress;
  23770. }
  23771. function stubProgress() {
  23772. this.agent.dirty();
  23773. this.getDownstream().dirty();
  23774. }
  23775. function stubOnDirty() {
  23776. this.agent && this.agent.dirty();
  23777. }
  23778. function seriesTaskPlan(context) {
  23779. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23780. }
  23781. function seriesTaskReset(context) {
  23782. if (context.useClearVisual) {
  23783. context.data.clearAllVisual();
  23784. }
  23785. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23786. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23787. return makeSeriesTaskProgress(idx);
  23788. }) : singleSeriesTaskProgress;
  23789. }
  23790. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23791. function makeSeriesTaskProgress(resetDefineIdx) {
  23792. return function (params, context) {
  23793. var data = context.data;
  23794. var resetDefine = context.resetDefines[resetDefineIdx];
  23795. if (resetDefine && resetDefine.dataEach) {
  23796. for (var i = params.start; i < params.end; i++) {
  23797. resetDefine.dataEach(data, i);
  23798. }
  23799. } else if (resetDefine && resetDefine.progress) {
  23800. resetDefine.progress(params, data);
  23801. }
  23802. };
  23803. }
  23804. function seriesTaskCount(context) {
  23805. return context.data.count();
  23806. }
  23807. /**
  23808. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23809. * To ensure that they can work normally, they should work in block mode, that is,
  23810. * they should not be started util the previous tasks finished. So they cause the
  23811. * progressive rendering disabled. We try to detect the series type, to narrow down
  23812. * the block range to only the series type they concern, but not all series.
  23813. */
  23814. function detectSeriseType(legacyFunc) {
  23815. seriesType = null;
  23816. try {
  23817. // Assume there is no async when calling `eachSeriesByType`.
  23818. legacyFunc(ecModelMock, apiMock);
  23819. } catch (e) {}
  23820. return seriesType;
  23821. }
  23822. var ecModelMock = {};
  23823. var apiMock = {};
  23824. var seriesType;
  23825. mockMethods(ecModelMock, GlobalModel);
  23826. mockMethods(apiMock, ExtensionAPI);
  23827. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23828. seriesType = type;
  23829. };
  23830. ecModelMock.eachComponent = function (cond) {
  23831. if (cond.mainType === 'series' && cond.subType) {
  23832. seriesType = cond.subType;
  23833. }
  23834. };
  23835. function mockMethods(target, Clz) {
  23836. /* eslint-disable */
  23837. for (var name_1 in Clz.prototype) {
  23838. // Do not use hasOwnProperty
  23839. target[name_1] = noop;
  23840. }
  23841. /* eslint-enable */
  23842. }
  23843. /*
  23844. * Licensed to the Apache Software Foundation (ASF) under one
  23845. * or more contributor license agreements. See the NOTICE file
  23846. * distributed with this work for additional information
  23847. * regarding copyright ownership. The ASF licenses this file
  23848. * to you under the Apache License, Version 2.0 (the
  23849. * "License"); you may not use this file except in compliance
  23850. * with the License. You may obtain a copy of the License at
  23851. *
  23852. * http://www.apache.org/licenses/LICENSE-2.0
  23853. *
  23854. * Unless required by applicable law or agreed to in writing,
  23855. * software distributed under the License is distributed on an
  23856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23857. * KIND, either express or implied. See the License for the
  23858. * specific language governing permissions and limitations
  23859. * under the License.
  23860. */
  23861. /**
  23862. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23863. */
  23864. /*
  23865. * Licensed to the Apache Software Foundation (ASF) under one
  23866. * or more contributor license agreements. See the NOTICE file
  23867. * distributed with this work for additional information
  23868. * regarding copyright ownership. The ASF licenses this file
  23869. * to you under the Apache License, Version 2.0 (the
  23870. * "License"); you may not use this file except in compliance
  23871. * with the License. You may obtain a copy of the License at
  23872. *
  23873. * http://www.apache.org/licenses/LICENSE-2.0
  23874. *
  23875. * Unless required by applicable law or agreed to in writing,
  23876. * software distributed under the License is distributed on an
  23877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23878. * KIND, either express or implied. See the License for the
  23879. * specific language governing permissions and limitations
  23880. * under the License.
  23881. */
  23882. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23883. var lightTheme = {
  23884. color: colorAll,
  23885. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23886. };
  23887. /*
  23888. * Licensed to the Apache Software Foundation (ASF) under one
  23889. * or more contributor license agreements. See the NOTICE file
  23890. * distributed with this work for additional information
  23891. * regarding copyright ownership. The ASF licenses this file
  23892. * to you under the Apache License, Version 2.0 (the
  23893. * "License"); you may not use this file except in compliance
  23894. * with the License. You may obtain a copy of the License at
  23895. *
  23896. * http://www.apache.org/licenses/LICENSE-2.0
  23897. *
  23898. * Unless required by applicable law or agreed to in writing,
  23899. * software distributed under the License is distributed on an
  23900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23901. * KIND, either express or implied. See the License for the
  23902. * specific language governing permissions and limitations
  23903. * under the License.
  23904. */
  23905. /**
  23906. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23907. */
  23908. /*
  23909. * Licensed to the Apache Software Foundation (ASF) under one
  23910. * or more contributor license agreements. See the NOTICE file
  23911. * distributed with this work for additional information
  23912. * regarding copyright ownership. The ASF licenses this file
  23913. * to you under the Apache License, Version 2.0 (the
  23914. * "License"); you may not use this file except in compliance
  23915. * with the License. You may obtain a copy of the License at
  23916. *
  23917. * http://www.apache.org/licenses/LICENSE-2.0
  23918. *
  23919. * Unless required by applicable law or agreed to in writing,
  23920. * software distributed under the License is distributed on an
  23921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23922. * KIND, either express or implied. See the License for the
  23923. * specific language governing permissions and limitations
  23924. * under the License.
  23925. */
  23926. var contrastColor = '#B9B8CE';
  23927. var backgroundColor = '#100C2A';
  23928. var axisCommon = function () {
  23929. return {
  23930. axisLine: {
  23931. lineStyle: {
  23932. color: contrastColor
  23933. }
  23934. },
  23935. splitLine: {
  23936. lineStyle: {
  23937. color: '#484753'
  23938. }
  23939. },
  23940. splitArea: {
  23941. areaStyle: {
  23942. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23943. }
  23944. },
  23945. minorSplitLine: {
  23946. lineStyle: {
  23947. color: '#20203B'
  23948. }
  23949. }
  23950. };
  23951. };
  23952. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23953. var theme = {
  23954. darkMode: true,
  23955. color: colorPalette,
  23956. backgroundColor: backgroundColor,
  23957. axisPointer: {
  23958. lineStyle: {
  23959. color: '#817f91'
  23960. },
  23961. crossStyle: {
  23962. color: '#817f91'
  23963. },
  23964. label: {
  23965. // TODO Contrast of label backgorundColor
  23966. color: '#fff'
  23967. }
  23968. },
  23969. legend: {
  23970. textStyle: {
  23971. color: contrastColor
  23972. },
  23973. pageTextStyle: {
  23974. color: contrastColor
  23975. }
  23976. },
  23977. textStyle: {
  23978. color: contrastColor
  23979. },
  23980. title: {
  23981. textStyle: {
  23982. color: '#EEF1FA'
  23983. },
  23984. subtextStyle: {
  23985. color: '#B9B8CE'
  23986. }
  23987. },
  23988. toolbox: {
  23989. iconStyle: {
  23990. borderColor: contrastColor
  23991. }
  23992. },
  23993. dataZoom: {
  23994. borderColor: '#71708A',
  23995. textStyle: {
  23996. color: contrastColor
  23997. },
  23998. brushStyle: {
  23999. color: 'rgba(135,163,206,0.3)'
  24000. },
  24001. handleStyle: {
  24002. color: '#353450',
  24003. borderColor: '#C5CBE3'
  24004. },
  24005. moveHandleStyle: {
  24006. color: '#B0B6C3',
  24007. opacity: 0.3
  24008. },
  24009. fillerColor: 'rgba(135,163,206,0.2)',
  24010. emphasis: {
  24011. handleStyle: {
  24012. borderColor: '#91B7F2',
  24013. color: '#4D587D'
  24014. },
  24015. moveHandleStyle: {
  24016. color: '#636D9A',
  24017. opacity: 0.7
  24018. }
  24019. },
  24020. dataBackground: {
  24021. lineStyle: {
  24022. color: '#71708A',
  24023. width: 1
  24024. },
  24025. areaStyle: {
  24026. color: '#71708A'
  24027. }
  24028. },
  24029. selectedDataBackground: {
  24030. lineStyle: {
  24031. color: '#87A3CE'
  24032. },
  24033. areaStyle: {
  24034. color: '#87A3CE'
  24035. }
  24036. }
  24037. },
  24038. visualMap: {
  24039. textStyle: {
  24040. color: contrastColor
  24041. }
  24042. },
  24043. timeline: {
  24044. lineStyle: {
  24045. color: contrastColor
  24046. },
  24047. label: {
  24048. color: contrastColor
  24049. },
  24050. controlStyle: {
  24051. color: contrastColor,
  24052. borderColor: contrastColor
  24053. }
  24054. },
  24055. calendar: {
  24056. itemStyle: {
  24057. color: backgroundColor
  24058. },
  24059. dayLabel: {
  24060. color: contrastColor
  24061. },
  24062. monthLabel: {
  24063. color: contrastColor
  24064. },
  24065. yearLabel: {
  24066. color: contrastColor
  24067. }
  24068. },
  24069. timeAxis: axisCommon(),
  24070. logAxis: axisCommon(),
  24071. valueAxis: axisCommon(),
  24072. categoryAxis: axisCommon(),
  24073. line: {
  24074. symbol: 'circle'
  24075. },
  24076. graph: {
  24077. color: colorPalette
  24078. },
  24079. gauge: {
  24080. title: {
  24081. color: contrastColor
  24082. },
  24083. axisLine: {
  24084. lineStyle: {
  24085. color: [[1, 'rgba(207,212,219,0.2)']]
  24086. }
  24087. },
  24088. axisLabel: {
  24089. color: contrastColor
  24090. },
  24091. detail: {
  24092. color: '#EEF1FA'
  24093. }
  24094. },
  24095. candlestick: {
  24096. itemStyle: {
  24097. color: '#f64e56',
  24098. color0: '#54ea92',
  24099. borderColor: '#f64e56',
  24100. borderColor0: '#54ea92'
  24101. // borderColor: '#ca2824',
  24102. // borderColor0: '#09a443'
  24103. }
  24104. }
  24105. };
  24106. theme.categoryAxis.splitLine.show = false;
  24107. /**
  24108. * Usage of query:
  24109. * `chart.on('click', query, handler);`
  24110. * The `query` can be:
  24111. * + The component type query string, only `mainType` or `mainType.subType`,
  24112. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24113. * + The component query object, like:
  24114. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24115. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24116. * + The data query object, like:
  24117. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24118. * + The other query object (cmponent customized query), like:
  24119. * `{element: 'some'}` (only available in custom series).
  24120. *
  24121. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24122. * same as there is no such prop in the `query` object.
  24123. */
  24124. var ECEventProcessor = /** @class */function () {
  24125. function ECEventProcessor() {}
  24126. ECEventProcessor.prototype.normalizeQuery = function (query) {
  24127. var cptQuery = {};
  24128. var dataQuery = {};
  24129. var otherQuery = {};
  24130. // `query` is `mainType` or `mainType.subType` of component.
  24131. if (isString(query)) {
  24132. var condCptType = parseClassType(query);
  24133. // `.main` and `.sub` may be ''.
  24134. cptQuery.mainType = condCptType.main || null;
  24135. cptQuery.subType = condCptType.sub || null;
  24136. }
  24137. // `query` is an object, convert to {mainType, index, name, id}.
  24138. else {
  24139. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24140. // can not be used in `compomentModel.filterForExposedEvent`.
  24141. var suffixes_1 = ['Index', 'Name', 'Id'];
  24142. var dataKeys_1 = {
  24143. name: 1,
  24144. dataIndex: 1,
  24145. dataType: 1
  24146. };
  24147. each(query, function (val, key) {
  24148. var reserved = false;
  24149. for (var i = 0; i < suffixes_1.length; i++) {
  24150. var propSuffix = suffixes_1[i];
  24151. var suffixPos = key.lastIndexOf(propSuffix);
  24152. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24153. var mainType = key.slice(0, suffixPos);
  24154. // Consider `dataIndex`.
  24155. if (mainType !== 'data') {
  24156. cptQuery.mainType = mainType;
  24157. cptQuery[propSuffix.toLowerCase()] = val;
  24158. reserved = true;
  24159. }
  24160. }
  24161. }
  24162. if (dataKeys_1.hasOwnProperty(key)) {
  24163. dataQuery[key] = val;
  24164. reserved = true;
  24165. }
  24166. if (!reserved) {
  24167. otherQuery[key] = val;
  24168. }
  24169. });
  24170. }
  24171. return {
  24172. cptQuery: cptQuery,
  24173. dataQuery: dataQuery,
  24174. otherQuery: otherQuery
  24175. };
  24176. };
  24177. ECEventProcessor.prototype.filter = function (eventType, query) {
  24178. // They should be assigned before each trigger call.
  24179. var eventInfo = this.eventInfo;
  24180. if (!eventInfo) {
  24181. return true;
  24182. }
  24183. var targetEl = eventInfo.targetEl;
  24184. var packedEvent = eventInfo.packedEvent;
  24185. var model = eventInfo.model;
  24186. var view = eventInfo.view;
  24187. // For event like 'globalout'.
  24188. if (!model || !view) {
  24189. return true;
  24190. }
  24191. var cptQuery = query.cptQuery;
  24192. var dataQuery = query.dataQuery;
  24193. return check(cptQuery, model, 'mainType') && check(cptQuery, model, 'subType') && check(cptQuery, model, 'index', 'componentIndex') && check(cptQuery, model, 'name') && check(cptQuery, model, 'id') && check(dataQuery, packedEvent, 'name') && check(dataQuery, packedEvent, 'dataIndex') && check(dataQuery, packedEvent, 'dataType') && (!view.filterForExposedEvent || view.filterForExposedEvent(eventType, query.otherQuery, targetEl, packedEvent));
  24194. function check(query, host, prop, propOnHost) {
  24195. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24196. }
  24197. };
  24198. ECEventProcessor.prototype.afterTrigger = function () {
  24199. // Make sure the eventInfo won't be used in next trigger.
  24200. this.eventInfo = null;
  24201. };
  24202. return ECEventProcessor;
  24203. }();
  24204. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  24205. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']);
  24206. // Encoding visual for all series include which is filtered for legend drawing
  24207. var seriesSymbolTask = {
  24208. createOnAllSeries: true,
  24209. // For legend.
  24210. performRawSeries: true,
  24211. reset: function (seriesModel, ecModel) {
  24212. var data = seriesModel.getData();
  24213. if (seriesModel.legendIcon) {
  24214. data.setVisual('legendIcon', seriesModel.legendIcon);
  24215. }
  24216. if (!seriesModel.hasSymbolVisual) {
  24217. return;
  24218. }
  24219. var symbolOptions = {};
  24220. var symbolOptionsCb = {};
  24221. var hasCallback = false;
  24222. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  24223. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  24224. var val = seriesModel.get(symbolPropName);
  24225. if (isFunction(val)) {
  24226. hasCallback = true;
  24227. symbolOptionsCb[symbolPropName] = val;
  24228. } else {
  24229. symbolOptions[symbolPropName] = val;
  24230. }
  24231. }
  24232. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  24233. data.setVisual(extend({
  24234. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  24235. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  24236. }, symbolOptions));
  24237. // Only visible series has each data be visual encoded
  24238. if (ecModel.isSeriesFiltered(seriesModel)) {
  24239. return;
  24240. }
  24241. var symbolPropsCb = keys(symbolOptionsCb);
  24242. function dataEach(data, idx) {
  24243. var rawValue = seriesModel.getRawValue(idx);
  24244. var params = seriesModel.getDataParams(idx);
  24245. for (var i = 0; i < symbolPropsCb.length; i++) {
  24246. var symbolPropName = symbolPropsCb[i];
  24247. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  24248. }
  24249. }
  24250. return {
  24251. dataEach: hasCallback ? dataEach : null
  24252. };
  24253. }
  24254. };
  24255. var dataSymbolTask = {
  24256. createOnAllSeries: true,
  24257. // For legend.
  24258. performRawSeries: true,
  24259. reset: function (seriesModel, ecModel) {
  24260. if (!seriesModel.hasSymbolVisual) {
  24261. return;
  24262. }
  24263. // Only visible series has each data be visual encoded
  24264. if (ecModel.isSeriesFiltered(seriesModel)) {
  24265. return;
  24266. }
  24267. var data = seriesModel.getData();
  24268. function dataEach(data, idx) {
  24269. var itemModel = data.getItemModel(idx);
  24270. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  24271. var symbolPropName = SYMBOL_PROPS[i];
  24272. var val = itemModel.getShallow(symbolPropName, true);
  24273. if (val != null) {
  24274. data.setItemVisual(idx, symbolPropName, val);
  24275. }
  24276. }
  24277. }
  24278. return {
  24279. dataEach: data.hasItemOption ? dataEach : null
  24280. };
  24281. }
  24282. };
  24283. /*
  24284. * Licensed to the Apache Software Foundation (ASF) under one
  24285. * or more contributor license agreements. See the NOTICE file
  24286. * distributed with this work for additional information
  24287. * regarding copyright ownership. The ASF licenses this file
  24288. * to you under the Apache License, Version 2.0 (the
  24289. * "License"); you may not use this file except in compliance
  24290. * with the License. You may obtain a copy of the License at
  24291. *
  24292. * http://www.apache.org/licenses/LICENSE-2.0
  24293. *
  24294. * Unless required by applicable law or agreed to in writing,
  24295. * software distributed under the License is distributed on an
  24296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24297. * KIND, either express or implied. See the License for the
  24298. * specific language governing permissions and limitations
  24299. * under the License.
  24300. */
  24301. /**
  24302. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24303. */
  24304. /*
  24305. * Licensed to the Apache Software Foundation (ASF) under one
  24306. * or more contributor license agreements. See the NOTICE file
  24307. * distributed with this work for additional information
  24308. * regarding copyright ownership. The ASF licenses this file
  24309. * to you under the Apache License, Version 2.0 (the
  24310. * "License"); you may not use this file except in compliance
  24311. * with the License. You may obtain a copy of the License at
  24312. *
  24313. * http://www.apache.org/licenses/LICENSE-2.0
  24314. *
  24315. * Unless required by applicable law or agreed to in writing,
  24316. * software distributed under the License is distributed on an
  24317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24318. * KIND, either express or implied. See the License for the
  24319. * specific language governing permissions and limitations
  24320. * under the License.
  24321. */
  24322. function getItemVisualFromData(data, dataIndex, key) {
  24323. switch (key) {
  24324. case 'color':
  24325. var style = data.getItemVisual(dataIndex, 'style');
  24326. return style[data.getVisual('drawType')];
  24327. case 'opacity':
  24328. return data.getItemVisual(dataIndex, 'style').opacity;
  24329. case 'symbol':
  24330. case 'symbolSize':
  24331. case 'liftZ':
  24332. return data.getItemVisual(dataIndex, key);
  24333. default:
  24334. if ("development" !== 'production') {
  24335. console.warn("Unknown visual type " + key);
  24336. }
  24337. }
  24338. }
  24339. function getVisualFromData(data, key) {
  24340. switch (key) {
  24341. case 'color':
  24342. var style = data.getVisual('style');
  24343. return style[data.getVisual('drawType')];
  24344. case 'opacity':
  24345. return data.getVisual('style').opacity;
  24346. case 'symbol':
  24347. case 'symbolSize':
  24348. case 'liftZ':
  24349. return data.getVisual(key);
  24350. default:
  24351. if ("development" !== 'production') {
  24352. console.warn("Unknown visual type " + key);
  24353. }
  24354. }
  24355. }
  24356. // Legacy data selection action.
  24357. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  24358. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  24359. function getSeriesIndices(ecModel, payload) {
  24360. var seriesIndices = [];
  24361. ecModel.eachComponent({
  24362. mainType: 'series',
  24363. subType: seriesType,
  24364. query: payload
  24365. }, function (seriesModel) {
  24366. seriesIndices.push(seriesModel.seriesIndex);
  24367. });
  24368. return seriesIndices;
  24369. }
  24370. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  24371. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  24372. payload = extend({}, payload);
  24373. if ("development" !== 'production') {
  24374. deprecateReplaceLog(payload.type, eventsMap[1]);
  24375. }
  24376. api.dispatchAction(extend(payload, {
  24377. type: eventsMap[1],
  24378. seriesIndex: getSeriesIndices(ecModel, payload)
  24379. }));
  24380. });
  24381. });
  24382. }
  24383. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  24384. var legacyEventName = type + eventPostfix;
  24385. if (!ecIns.isSilent(legacyEventName)) {
  24386. if ("development" !== 'production') {
  24387. deprecateLog("event " + legacyEventName + " is deprecated.");
  24388. }
  24389. ecModel.eachComponent({
  24390. mainType: 'series',
  24391. subType: 'pie'
  24392. }, function (seriesModel) {
  24393. var seriesIndex = seriesModel.seriesIndex;
  24394. var selectedMap = seriesModel.option.selectedMap;
  24395. var selected = payload.selected;
  24396. for (var i = 0; i < selected.length; i++) {
  24397. if (selected[i].seriesIndex === seriesIndex) {
  24398. var data = seriesModel.getData();
  24399. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  24400. ecIns.trigger(legacyEventName, {
  24401. type: legacyEventName,
  24402. seriesId: seriesModel.id,
  24403. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  24404. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  24405. });
  24406. }
  24407. }
  24408. });
  24409. }
  24410. }
  24411. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  24412. messageCenter.on('selectchanged', function (params) {
  24413. var ecModel = api.getModel();
  24414. if (params.isFromClick) {
  24415. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  24416. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  24417. } else if (params.fromAction === 'select') {
  24418. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  24419. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  24420. } else if (params.fromAction === 'unselect') {
  24421. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  24422. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  24423. }
  24424. });
  24425. }
  24426. /*
  24427. * Licensed to the Apache Software Foundation (ASF) under one
  24428. * or more contributor license agreements. See the NOTICE file
  24429. * distributed with this work for additional information
  24430. * regarding copyright ownership. The ASF licenses this file
  24431. * to you under the Apache License, Version 2.0 (the
  24432. * "License"); you may not use this file except in compliance
  24433. * with the License. You may obtain a copy of the License at
  24434. *
  24435. * http://www.apache.org/licenses/LICENSE-2.0
  24436. *
  24437. * Unless required by applicable law or agreed to in writing,
  24438. * software distributed under the License is distributed on an
  24439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24440. * KIND, either express or implied. See the License for the
  24441. * specific language governing permissions and limitations
  24442. * under the License.
  24443. */
  24444. /**
  24445. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24446. */
  24447. /*
  24448. * Licensed to the Apache Software Foundation (ASF) under one
  24449. * or more contributor license agreements. See the NOTICE file
  24450. * distributed with this work for additional information
  24451. * regarding copyright ownership. The ASF licenses this file
  24452. * to you under the Apache License, Version 2.0 (the
  24453. * "License"); you may not use this file except in compliance
  24454. * with the License. You may obtain a copy of the License at
  24455. *
  24456. * http://www.apache.org/licenses/LICENSE-2.0
  24457. *
  24458. * Unless required by applicable law or agreed to in writing,
  24459. * software distributed under the License is distributed on an
  24460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24461. * KIND, either express or implied. See the License for the
  24462. * specific language governing permissions and limitations
  24463. * under the License.
  24464. */
  24465. function findEventDispatcher(target, det, returnFirstMatch) {
  24466. var found;
  24467. while (target) {
  24468. if (det(target)) {
  24469. found = target;
  24470. if (returnFirstMatch) {
  24471. break;
  24472. }
  24473. }
  24474. target = target.__hostTarget || target.parent;
  24475. }
  24476. return found;
  24477. }
  24478. var wmUniqueIndex = Math.round(Math.random() * 9);
  24479. var supportDefineProperty = typeof Object.defineProperty === 'function';
  24480. var WeakMap = (function () {
  24481. function WeakMap() {
  24482. this._id = '__ec_inner_' + wmUniqueIndex++;
  24483. }
  24484. WeakMap.prototype.get = function (key) {
  24485. return this._guard(key)[this._id];
  24486. };
  24487. WeakMap.prototype.set = function (key, value) {
  24488. var target = this._guard(key);
  24489. if (supportDefineProperty) {
  24490. Object.defineProperty(target, this._id, {
  24491. value: value,
  24492. enumerable: false,
  24493. configurable: true
  24494. });
  24495. }
  24496. else {
  24497. target[this._id] = value;
  24498. }
  24499. return this;
  24500. };
  24501. WeakMap.prototype["delete"] = function (key) {
  24502. if (this.has(key)) {
  24503. delete this._guard(key)[this._id];
  24504. return true;
  24505. }
  24506. return false;
  24507. };
  24508. WeakMap.prototype.has = function (key) {
  24509. return !!this._guard(key)[this._id];
  24510. };
  24511. WeakMap.prototype._guard = function (key) {
  24512. if (key !== Object(key)) {
  24513. throw TypeError('Value of WeakMap is not a non-null object.');
  24514. }
  24515. return key;
  24516. };
  24517. return WeakMap;
  24518. }());
  24519. /**
  24520. * Triangle shape
  24521. * @inner
  24522. */
  24523. var Triangle = Path.extend({
  24524. type: 'triangle',
  24525. shape: {
  24526. cx: 0,
  24527. cy: 0,
  24528. width: 0,
  24529. height: 0
  24530. },
  24531. buildPath: function (path, shape) {
  24532. var cx = shape.cx;
  24533. var cy = shape.cy;
  24534. var width = shape.width / 2;
  24535. var height = shape.height / 2;
  24536. path.moveTo(cx, cy - height);
  24537. path.lineTo(cx + width, cy + height);
  24538. path.lineTo(cx - width, cy + height);
  24539. path.closePath();
  24540. }
  24541. });
  24542. /**
  24543. * Diamond shape
  24544. * @inner
  24545. */
  24546. var Diamond = Path.extend({
  24547. type: 'diamond',
  24548. shape: {
  24549. cx: 0,
  24550. cy: 0,
  24551. width: 0,
  24552. height: 0
  24553. },
  24554. buildPath: function (path, shape) {
  24555. var cx = shape.cx;
  24556. var cy = shape.cy;
  24557. var width = shape.width / 2;
  24558. var height = shape.height / 2;
  24559. path.moveTo(cx, cy - height);
  24560. path.lineTo(cx + width, cy);
  24561. path.lineTo(cx, cy + height);
  24562. path.lineTo(cx - width, cy);
  24563. path.closePath();
  24564. }
  24565. });
  24566. /**
  24567. * Pin shape
  24568. * @inner
  24569. */
  24570. var Pin = Path.extend({
  24571. type: 'pin',
  24572. shape: {
  24573. // x, y on the cusp
  24574. x: 0,
  24575. y: 0,
  24576. width: 0,
  24577. height: 0
  24578. },
  24579. buildPath: function (path, shape) {
  24580. var x = shape.x;
  24581. var y = shape.y;
  24582. var w = shape.width / 5 * 3;
  24583. // Height must be larger than width
  24584. var h = Math.max(w, shape.height);
  24585. var r = w / 2;
  24586. // Dist on y with tangent point and circle center
  24587. var dy = r * r / (h - r);
  24588. var cy = y - h + r + dy;
  24589. var angle = Math.asin(dy / r);
  24590. // Dist on x with tangent point and circle center
  24591. var dx = Math.cos(angle) * r;
  24592. var tanX = Math.sin(angle);
  24593. var tanY = Math.cos(angle);
  24594. var cpLen = r * 0.6;
  24595. var cpLen2 = r * 0.7;
  24596. path.moveTo(x - dx, cy + dy);
  24597. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24598. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24599. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24600. path.closePath();
  24601. }
  24602. });
  24603. /**
  24604. * Arrow shape
  24605. * @inner
  24606. */
  24607. var Arrow = Path.extend({
  24608. type: 'arrow',
  24609. shape: {
  24610. x: 0,
  24611. y: 0,
  24612. width: 0,
  24613. height: 0
  24614. },
  24615. buildPath: function (ctx, shape) {
  24616. var height = shape.height;
  24617. var width = shape.width;
  24618. var x = shape.x;
  24619. var y = shape.y;
  24620. var dx = width / 3 * 2;
  24621. ctx.moveTo(x, y);
  24622. ctx.lineTo(x + dx, y + height);
  24623. ctx.lineTo(x, y + height / 4 * 3);
  24624. ctx.lineTo(x - dx, y + height);
  24625. ctx.lineTo(x, y);
  24626. ctx.closePath();
  24627. }
  24628. });
  24629. /**
  24630. * Map of path constructors
  24631. */
  24632. // TODO Use function to build symbol path.
  24633. var symbolCtors = {
  24634. line: Line,
  24635. rect: Rect,
  24636. roundRect: Rect,
  24637. square: Rect,
  24638. circle: Circle,
  24639. diamond: Diamond,
  24640. pin: Pin,
  24641. arrow: Arrow,
  24642. triangle: Triangle
  24643. };
  24644. var symbolShapeMakers = {
  24645. line: function (x, y, w, h, shape) {
  24646. shape.x1 = x;
  24647. shape.y1 = y + h / 2;
  24648. shape.x2 = x + w;
  24649. shape.y2 = y + h / 2;
  24650. },
  24651. rect: function (x, y, w, h, shape) {
  24652. shape.x = x;
  24653. shape.y = y;
  24654. shape.width = w;
  24655. shape.height = h;
  24656. },
  24657. roundRect: function (x, y, w, h, shape) {
  24658. shape.x = x;
  24659. shape.y = y;
  24660. shape.width = w;
  24661. shape.height = h;
  24662. shape.r = Math.min(w, h) / 4;
  24663. },
  24664. square: function (x, y, w, h, shape) {
  24665. var size = Math.min(w, h);
  24666. shape.x = x;
  24667. shape.y = y;
  24668. shape.width = size;
  24669. shape.height = size;
  24670. },
  24671. circle: function (x, y, w, h, shape) {
  24672. // Put circle in the center of square
  24673. shape.cx = x + w / 2;
  24674. shape.cy = y + h / 2;
  24675. shape.r = Math.min(w, h) / 2;
  24676. },
  24677. diamond: function (x, y, w, h, shape) {
  24678. shape.cx = x + w / 2;
  24679. shape.cy = y + h / 2;
  24680. shape.width = w;
  24681. shape.height = h;
  24682. },
  24683. pin: function (x, y, w, h, shape) {
  24684. shape.x = x + w / 2;
  24685. shape.y = y + h / 2;
  24686. shape.width = w;
  24687. shape.height = h;
  24688. },
  24689. arrow: function (x, y, w, h, shape) {
  24690. shape.x = x + w / 2;
  24691. shape.y = y + h / 2;
  24692. shape.width = w;
  24693. shape.height = h;
  24694. },
  24695. triangle: function (x, y, w, h, shape) {
  24696. shape.cx = x + w / 2;
  24697. shape.cy = y + h / 2;
  24698. shape.width = w;
  24699. shape.height = h;
  24700. }
  24701. };
  24702. var symbolBuildProxies = {};
  24703. each(symbolCtors, function (Ctor, name) {
  24704. symbolBuildProxies[name] = new Ctor();
  24705. });
  24706. var SymbolClz = Path.extend({
  24707. type: 'symbol',
  24708. shape: {
  24709. symbolType: '',
  24710. x: 0,
  24711. y: 0,
  24712. width: 0,
  24713. height: 0
  24714. },
  24715. calculateTextPosition: function (out, config, rect) {
  24716. var res = calculateTextPosition(out, config, rect);
  24717. var shape = this.shape;
  24718. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24719. res.y = rect.y + rect.height * 0.4;
  24720. }
  24721. return res;
  24722. },
  24723. buildPath: function (ctx, shape, inBundle) {
  24724. var symbolType = shape.symbolType;
  24725. if (symbolType !== 'none') {
  24726. var proxySymbol = symbolBuildProxies[symbolType];
  24727. if (!proxySymbol) {
  24728. // Default rect
  24729. symbolType = 'rect';
  24730. proxySymbol = symbolBuildProxies[symbolType];
  24731. }
  24732. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24733. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24734. }
  24735. }
  24736. });
  24737. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24738. function symbolPathSetColor(color, innerColor) {
  24739. if (this.type !== 'image') {
  24740. var symbolStyle = this.style;
  24741. if (this.__isEmptyBrush) {
  24742. symbolStyle.stroke = color;
  24743. symbolStyle.fill = innerColor || '#fff';
  24744. // TODO Same width with lineStyle in LineView
  24745. symbolStyle.lineWidth = 2;
  24746. } else if (this.shape.symbolType === 'line') {
  24747. symbolStyle.stroke = color;
  24748. } else {
  24749. symbolStyle.fill = color;
  24750. }
  24751. this.markRedraw();
  24752. }
  24753. }
  24754. /**
  24755. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24756. */
  24757. function createSymbol(symbolType, x, y, w, h, color,
  24758. // whether to keep the ratio of w/h,
  24759. keepAspect) {
  24760. // TODO Support image object, DynamicImage.
  24761. var isEmpty = symbolType.indexOf('empty') === 0;
  24762. if (isEmpty) {
  24763. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24764. }
  24765. var symbolPath;
  24766. if (symbolType.indexOf('image://') === 0) {
  24767. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24768. } else if (symbolType.indexOf('path://') === 0) {
  24769. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24770. } else {
  24771. symbolPath = new SymbolClz({
  24772. shape: {
  24773. symbolType: symbolType,
  24774. x: x,
  24775. y: y,
  24776. width: w,
  24777. height: h
  24778. }
  24779. });
  24780. }
  24781. symbolPath.__isEmptyBrush = isEmpty;
  24782. // TODO Should deprecate setColor
  24783. symbolPath.setColor = symbolPathSetColor;
  24784. if (color) {
  24785. symbolPath.setColor(color);
  24786. }
  24787. return symbolPath;
  24788. }
  24789. function normalizeSymbolSize(symbolSize) {
  24790. if (!isArray(symbolSize)) {
  24791. symbolSize = [+symbolSize, +symbolSize];
  24792. }
  24793. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24794. }
  24795. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24796. if (symbolOffset == null) {
  24797. return;
  24798. }
  24799. if (!isArray(symbolOffset)) {
  24800. symbolOffset = [symbolOffset, symbolOffset];
  24801. }
  24802. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24803. }
  24804. function isSafeNum(num) {
  24805. return isFinite(num);
  24806. }
  24807. function createLinearGradient(ctx, obj, rect) {
  24808. var x = obj.x == null ? 0 : obj.x;
  24809. var x2 = obj.x2 == null ? 1 : obj.x2;
  24810. var y = obj.y == null ? 0 : obj.y;
  24811. var y2 = obj.y2 == null ? 0 : obj.y2;
  24812. if (!obj.global) {
  24813. x = x * rect.width + rect.x;
  24814. x2 = x2 * rect.width + rect.x;
  24815. y = y * rect.height + rect.y;
  24816. y2 = y2 * rect.height + rect.y;
  24817. }
  24818. x = isSafeNum(x) ? x : 0;
  24819. x2 = isSafeNum(x2) ? x2 : 1;
  24820. y = isSafeNum(y) ? y : 0;
  24821. y2 = isSafeNum(y2) ? y2 : 0;
  24822. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24823. return canvasGradient;
  24824. }
  24825. function createRadialGradient(ctx, obj, rect) {
  24826. var width = rect.width;
  24827. var height = rect.height;
  24828. var min = Math.min(width, height);
  24829. var x = obj.x == null ? 0.5 : obj.x;
  24830. var y = obj.y == null ? 0.5 : obj.y;
  24831. var r = obj.r == null ? 0.5 : obj.r;
  24832. if (!obj.global) {
  24833. x = x * width + rect.x;
  24834. y = y * height + rect.y;
  24835. r = r * min;
  24836. }
  24837. x = isSafeNum(x) ? x : 0.5;
  24838. y = isSafeNum(y) ? y : 0.5;
  24839. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24840. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24841. return canvasGradient;
  24842. }
  24843. function getCanvasGradient(ctx, obj, rect) {
  24844. var canvasGradient = obj.type === 'radial'
  24845. ? createRadialGradient(ctx, obj, rect)
  24846. : createLinearGradient(ctx, obj, rect);
  24847. var colorStops = obj.colorStops;
  24848. for (var i = 0; i < colorStops.length; i++) {
  24849. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24850. }
  24851. return canvasGradient;
  24852. }
  24853. function isClipPathChanged(clipPaths, prevClipPaths) {
  24854. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24855. return false;
  24856. }
  24857. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24858. return true;
  24859. }
  24860. for (var i = 0; i < clipPaths.length; i++) {
  24861. if (clipPaths[i] !== prevClipPaths[i]) {
  24862. return true;
  24863. }
  24864. }
  24865. return false;
  24866. }
  24867. function parseInt10(val) {
  24868. return parseInt(val, 10);
  24869. }
  24870. function getSize(root, whIdx, opts) {
  24871. var wh = ['width', 'height'][whIdx];
  24872. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24873. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24874. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24875. if (opts[wh] != null && opts[wh] !== 'auto') {
  24876. return parseFloat(opts[wh]);
  24877. }
  24878. var stl = document.defaultView.getComputedStyle(root);
  24879. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24880. - (parseInt10(stl[plt]) || 0)
  24881. - (parseInt10(stl[prb]) || 0)) | 0;
  24882. }
  24883. function normalizeLineDash(lineType, lineWidth) {
  24884. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24885. return null;
  24886. }
  24887. return lineType === 'dashed'
  24888. ? [4 * lineWidth, 2 * lineWidth]
  24889. : lineType === 'dotted'
  24890. ? [lineWidth]
  24891. : isNumber(lineType)
  24892. ? [lineType] : isArray(lineType) ? lineType : null;
  24893. }
  24894. function getLineDash(el) {
  24895. var style = el.style;
  24896. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24897. var lineDashOffset = style.lineDashOffset;
  24898. if (lineDash) {
  24899. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24900. if (lineScale_1 && lineScale_1 !== 1) {
  24901. lineDash = map(lineDash, function (rawVal) {
  24902. return rawVal / lineScale_1;
  24903. });
  24904. lineDashOffset /= lineScale_1;
  24905. }
  24906. }
  24907. return [lineDash, lineDashOffset];
  24908. }
  24909. var pathProxyForDraw = new PathProxy(true);
  24910. function styleHasStroke(style) {
  24911. var stroke = style.stroke;
  24912. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24913. }
  24914. function isValidStrokeFillStyle(strokeOrFill) {
  24915. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24916. }
  24917. function styleHasFill(style) {
  24918. var fill = style.fill;
  24919. return fill != null && fill !== 'none';
  24920. }
  24921. function doFillPath(ctx, style) {
  24922. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24923. var originalGlobalAlpha = ctx.globalAlpha;
  24924. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24925. ctx.fill();
  24926. ctx.globalAlpha = originalGlobalAlpha;
  24927. }
  24928. else {
  24929. ctx.fill();
  24930. }
  24931. }
  24932. function doStrokePath(ctx, style) {
  24933. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24934. var originalGlobalAlpha = ctx.globalAlpha;
  24935. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24936. ctx.stroke();
  24937. ctx.globalAlpha = originalGlobalAlpha;
  24938. }
  24939. else {
  24940. ctx.stroke();
  24941. }
  24942. }
  24943. function createCanvasPattern(ctx, pattern, el) {
  24944. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24945. if (isImageReady(image)) {
  24946. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24947. if (typeof DOMMatrix === 'function'
  24948. && canvasPattern
  24949. && canvasPattern.setTransform) {
  24950. var matrix = new DOMMatrix();
  24951. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24952. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24953. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24954. canvasPattern.setTransform(matrix);
  24955. }
  24956. return canvasPattern;
  24957. }
  24958. }
  24959. function brushPath(ctx, el, style, inBatch) {
  24960. var _a;
  24961. var hasStroke = styleHasStroke(style);
  24962. var hasFill = styleHasFill(style);
  24963. var strokePercent = style.strokePercent;
  24964. var strokePart = strokePercent < 1;
  24965. var firstDraw = !el.path;
  24966. if ((!el.silent || strokePart) && firstDraw) {
  24967. el.createPathProxy();
  24968. }
  24969. var path = el.path || pathProxyForDraw;
  24970. var dirtyFlag = el.__dirty;
  24971. if (!inBatch) {
  24972. var fill = style.fill;
  24973. var stroke = style.stroke;
  24974. var hasFillGradient = hasFill && !!fill.colorStops;
  24975. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24976. var hasFillPattern = hasFill && !!fill.image;
  24977. var hasStrokePattern = hasStroke && !!stroke.image;
  24978. var fillGradient = void 0;
  24979. var strokeGradient = void 0;
  24980. var fillPattern = void 0;
  24981. var strokePattern = void 0;
  24982. var rect = void 0;
  24983. if (hasFillGradient || hasStrokeGradient) {
  24984. rect = el.getBoundingRect();
  24985. }
  24986. if (hasFillGradient) {
  24987. fillGradient = dirtyFlag
  24988. ? getCanvasGradient(ctx, fill, rect)
  24989. : el.__canvasFillGradient;
  24990. el.__canvasFillGradient = fillGradient;
  24991. }
  24992. if (hasStrokeGradient) {
  24993. strokeGradient = dirtyFlag
  24994. ? getCanvasGradient(ctx, stroke, rect)
  24995. : el.__canvasStrokeGradient;
  24996. el.__canvasStrokeGradient = strokeGradient;
  24997. }
  24998. if (hasFillPattern) {
  24999. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  25000. ? createCanvasPattern(ctx, fill, el)
  25001. : el.__canvasFillPattern;
  25002. el.__canvasFillPattern = fillPattern;
  25003. }
  25004. if (hasStrokePattern) {
  25005. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  25006. ? createCanvasPattern(ctx, stroke, el)
  25007. : el.__canvasStrokePattern;
  25008. el.__canvasStrokePattern = fillPattern;
  25009. }
  25010. if (hasFillGradient) {
  25011. ctx.fillStyle = fillGradient;
  25012. }
  25013. else if (hasFillPattern) {
  25014. if (fillPattern) {
  25015. ctx.fillStyle = fillPattern;
  25016. }
  25017. else {
  25018. hasFill = false;
  25019. }
  25020. }
  25021. if (hasStrokeGradient) {
  25022. ctx.strokeStyle = strokeGradient;
  25023. }
  25024. else if (hasStrokePattern) {
  25025. if (strokePattern) {
  25026. ctx.strokeStyle = strokePattern;
  25027. }
  25028. else {
  25029. hasStroke = false;
  25030. }
  25031. }
  25032. }
  25033. var scale = el.getGlobalScale();
  25034. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  25035. var lineDash;
  25036. var lineDashOffset;
  25037. if (ctx.setLineDash && style.lineDash) {
  25038. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  25039. }
  25040. var needsRebuild = true;
  25041. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  25042. path.setDPR(ctx.dpr);
  25043. if (strokePart) {
  25044. path.setContext(null);
  25045. }
  25046. else {
  25047. path.setContext(ctx);
  25048. needsRebuild = false;
  25049. }
  25050. path.reset();
  25051. el.buildPath(path, el.shape, inBatch);
  25052. path.toStatic();
  25053. el.pathUpdated();
  25054. }
  25055. if (needsRebuild) {
  25056. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  25057. }
  25058. if (lineDash) {
  25059. ctx.setLineDash(lineDash);
  25060. ctx.lineDashOffset = lineDashOffset;
  25061. }
  25062. if (!inBatch) {
  25063. if (style.strokeFirst) {
  25064. if (hasStroke) {
  25065. doStrokePath(ctx, style);
  25066. }
  25067. if (hasFill) {
  25068. doFillPath(ctx, style);
  25069. }
  25070. }
  25071. else {
  25072. if (hasFill) {
  25073. doFillPath(ctx, style);
  25074. }
  25075. if (hasStroke) {
  25076. doStrokePath(ctx, style);
  25077. }
  25078. }
  25079. }
  25080. if (lineDash) {
  25081. ctx.setLineDash([]);
  25082. }
  25083. }
  25084. function brushImage(ctx, el, style) {
  25085. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  25086. if (!image || !isImageReady(image)) {
  25087. return;
  25088. }
  25089. var x = style.x || 0;
  25090. var y = style.y || 0;
  25091. var width = el.getWidth();
  25092. var height = el.getHeight();
  25093. var aspect = image.width / image.height;
  25094. if (width == null && height != null) {
  25095. width = height * aspect;
  25096. }
  25097. else if (height == null && width != null) {
  25098. height = width / aspect;
  25099. }
  25100. else if (width == null && height == null) {
  25101. width = image.width;
  25102. height = image.height;
  25103. }
  25104. if (style.sWidth && style.sHeight) {
  25105. var sx = style.sx || 0;
  25106. var sy = style.sy || 0;
  25107. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  25108. }
  25109. else if (style.sx && style.sy) {
  25110. var sx = style.sx;
  25111. var sy = style.sy;
  25112. var sWidth = width - sx;
  25113. var sHeight = height - sy;
  25114. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  25115. }
  25116. else {
  25117. ctx.drawImage(image, x, y, width, height);
  25118. }
  25119. }
  25120. function brushText(ctx, el, style) {
  25121. var _a;
  25122. var text = style.text;
  25123. text != null && (text += '');
  25124. if (text) {
  25125. ctx.font = style.font || DEFAULT_FONT;
  25126. ctx.textAlign = style.textAlign;
  25127. ctx.textBaseline = style.textBaseline;
  25128. var lineDash = void 0;
  25129. var lineDashOffset = void 0;
  25130. if (ctx.setLineDash && style.lineDash) {
  25131. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  25132. }
  25133. if (lineDash) {
  25134. ctx.setLineDash(lineDash);
  25135. ctx.lineDashOffset = lineDashOffset;
  25136. }
  25137. if (style.strokeFirst) {
  25138. if (styleHasStroke(style)) {
  25139. ctx.strokeText(text, style.x, style.y);
  25140. }
  25141. if (styleHasFill(style)) {
  25142. ctx.fillText(text, style.x, style.y);
  25143. }
  25144. }
  25145. else {
  25146. if (styleHasFill(style)) {
  25147. ctx.fillText(text, style.x, style.y);
  25148. }
  25149. if (styleHasStroke(style)) {
  25150. ctx.strokeText(text, style.x, style.y);
  25151. }
  25152. }
  25153. if (lineDash) {
  25154. ctx.setLineDash([]);
  25155. }
  25156. }
  25157. }
  25158. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  25159. var STROKE_PROPS = [
  25160. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  25161. ];
  25162. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  25163. var styleChanged = false;
  25164. if (!forceSetAll) {
  25165. prevStyle = prevStyle || {};
  25166. if (style === prevStyle) {
  25167. return false;
  25168. }
  25169. }
  25170. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  25171. flushPathDrawn(ctx, scope);
  25172. styleChanged = true;
  25173. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  25174. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  25175. }
  25176. if (forceSetAll || style.blend !== prevStyle.blend) {
  25177. if (!styleChanged) {
  25178. flushPathDrawn(ctx, scope);
  25179. styleChanged = true;
  25180. }
  25181. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  25182. }
  25183. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  25184. var propName = SHADOW_NUMBER_PROPS[i];
  25185. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25186. if (!styleChanged) {
  25187. flushPathDrawn(ctx, scope);
  25188. styleChanged = true;
  25189. }
  25190. ctx[propName] = ctx.dpr * (style[propName] || 0);
  25191. }
  25192. }
  25193. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  25194. if (!styleChanged) {
  25195. flushPathDrawn(ctx, scope);
  25196. styleChanged = true;
  25197. }
  25198. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  25199. }
  25200. return styleChanged;
  25201. }
  25202. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  25203. var style = getStyle(el, scope.inHover);
  25204. var prevStyle = forceSetAll
  25205. ? null
  25206. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  25207. if (style === prevStyle) {
  25208. return false;
  25209. }
  25210. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  25211. if (forceSetAll || style.fill !== prevStyle.fill) {
  25212. if (!styleChanged) {
  25213. flushPathDrawn(ctx, scope);
  25214. styleChanged = true;
  25215. }
  25216. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  25217. }
  25218. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  25219. if (!styleChanged) {
  25220. flushPathDrawn(ctx, scope);
  25221. styleChanged = true;
  25222. }
  25223. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  25224. }
  25225. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  25226. if (!styleChanged) {
  25227. flushPathDrawn(ctx, scope);
  25228. styleChanged = true;
  25229. }
  25230. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  25231. }
  25232. if (el.hasStroke()) {
  25233. var lineWidth = style.lineWidth;
  25234. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  25235. if (ctx.lineWidth !== newLineWidth) {
  25236. if (!styleChanged) {
  25237. flushPathDrawn(ctx, scope);
  25238. styleChanged = true;
  25239. }
  25240. ctx.lineWidth = newLineWidth;
  25241. }
  25242. }
  25243. for (var i = 0; i < STROKE_PROPS.length; i++) {
  25244. var prop = STROKE_PROPS[i];
  25245. var propName = prop[0];
  25246. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25247. if (!styleChanged) {
  25248. flushPathDrawn(ctx, scope);
  25249. styleChanged = true;
  25250. }
  25251. ctx[propName] = style[propName] || prop[1];
  25252. }
  25253. }
  25254. return styleChanged;
  25255. }
  25256. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  25257. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  25258. }
  25259. function setContextTransform(ctx, el) {
  25260. var m = el.transform;
  25261. var dpr = ctx.dpr || 1;
  25262. if (m) {
  25263. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  25264. }
  25265. else {
  25266. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  25267. }
  25268. }
  25269. function updateClipStatus(clipPaths, ctx, scope) {
  25270. var allClipped = false;
  25271. for (var i = 0; i < clipPaths.length; i++) {
  25272. var clipPath = clipPaths[i];
  25273. allClipped = allClipped || clipPath.isZeroArea();
  25274. setContextTransform(ctx, clipPath);
  25275. ctx.beginPath();
  25276. clipPath.buildPath(ctx, clipPath.shape);
  25277. ctx.clip();
  25278. }
  25279. scope.allClipped = allClipped;
  25280. }
  25281. function isTransformChanged(m0, m1) {
  25282. if (m0 && m1) {
  25283. return m0[0] !== m1[0]
  25284. || m0[1] !== m1[1]
  25285. || m0[2] !== m1[2]
  25286. || m0[3] !== m1[3]
  25287. || m0[4] !== m1[4]
  25288. || m0[5] !== m1[5];
  25289. }
  25290. else if (!m0 && !m1) {
  25291. return false;
  25292. }
  25293. return true;
  25294. }
  25295. var DRAW_TYPE_PATH = 1;
  25296. var DRAW_TYPE_IMAGE = 2;
  25297. var DRAW_TYPE_TEXT = 3;
  25298. var DRAW_TYPE_INCREMENTAL = 4;
  25299. function canPathBatch(style) {
  25300. var hasFill = styleHasFill(style);
  25301. var hasStroke = styleHasStroke(style);
  25302. return !(style.lineDash
  25303. || !(+hasFill ^ +hasStroke)
  25304. || (hasFill && typeof style.fill !== 'string')
  25305. || (hasStroke && typeof style.stroke !== 'string')
  25306. || style.strokePercent < 1
  25307. || style.strokeOpacity < 1
  25308. || style.fillOpacity < 1);
  25309. }
  25310. function flushPathDrawn(ctx, scope) {
  25311. scope.batchFill && ctx.fill();
  25312. scope.batchStroke && ctx.stroke();
  25313. scope.batchFill = '';
  25314. scope.batchStroke = '';
  25315. }
  25316. function getStyle(el, inHover) {
  25317. return inHover ? (el.__hoverStyle || el.style) : el.style;
  25318. }
  25319. function brushSingle(ctx, el) {
  25320. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  25321. }
  25322. function brush(ctx, el, scope, isLast) {
  25323. var m = el.transform;
  25324. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  25325. el.__dirty &= ~REDRAW_BIT;
  25326. el.__isRendered = false;
  25327. return;
  25328. }
  25329. var clipPaths = el.__clipPaths;
  25330. var prevElClipPaths = scope.prevElClipPaths;
  25331. var forceSetTransform = false;
  25332. var forceSetStyle = false;
  25333. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  25334. if (prevElClipPaths && prevElClipPaths.length) {
  25335. flushPathDrawn(ctx, scope);
  25336. ctx.restore();
  25337. forceSetStyle = forceSetTransform = true;
  25338. scope.prevElClipPaths = null;
  25339. scope.allClipped = false;
  25340. scope.prevEl = null;
  25341. }
  25342. if (clipPaths && clipPaths.length) {
  25343. flushPathDrawn(ctx, scope);
  25344. ctx.save();
  25345. updateClipStatus(clipPaths, ctx, scope);
  25346. forceSetTransform = true;
  25347. }
  25348. scope.prevElClipPaths = clipPaths;
  25349. }
  25350. if (scope.allClipped) {
  25351. el.__isRendered = false;
  25352. return;
  25353. }
  25354. el.beforeBrush && el.beforeBrush();
  25355. el.innerBeforeBrush();
  25356. var prevEl = scope.prevEl;
  25357. if (!prevEl) {
  25358. forceSetStyle = forceSetTransform = true;
  25359. }
  25360. var canBatchPath = el instanceof Path
  25361. && el.autoBatch
  25362. && canPathBatch(el.style);
  25363. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  25364. flushPathDrawn(ctx, scope);
  25365. setContextTransform(ctx, el);
  25366. }
  25367. else if (!canBatchPath) {
  25368. flushPathDrawn(ctx, scope);
  25369. }
  25370. var style = getStyle(el, scope.inHover);
  25371. if (el instanceof Path) {
  25372. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  25373. forceSetStyle = true;
  25374. scope.lastDrawType = DRAW_TYPE_PATH;
  25375. }
  25376. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25377. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  25378. ctx.beginPath();
  25379. }
  25380. brushPath(ctx, el, style, canBatchPath);
  25381. if (canBatchPath) {
  25382. scope.batchFill = style.fill || '';
  25383. scope.batchStroke = style.stroke || '';
  25384. }
  25385. }
  25386. else {
  25387. if (el instanceof TSpan) {
  25388. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  25389. forceSetStyle = true;
  25390. scope.lastDrawType = DRAW_TYPE_TEXT;
  25391. }
  25392. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25393. brushText(ctx, el, style);
  25394. }
  25395. else if (el instanceof ZRImage) {
  25396. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  25397. forceSetStyle = true;
  25398. scope.lastDrawType = DRAW_TYPE_IMAGE;
  25399. }
  25400. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  25401. brushImage(ctx, el, style);
  25402. }
  25403. else if (el.getTemporalDisplayables) {
  25404. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  25405. forceSetStyle = true;
  25406. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  25407. }
  25408. brushIncremental(ctx, el, scope);
  25409. }
  25410. }
  25411. if (canBatchPath && isLast) {
  25412. flushPathDrawn(ctx, scope);
  25413. }
  25414. el.innerAfterBrush();
  25415. el.afterBrush && el.afterBrush();
  25416. scope.prevEl = el;
  25417. el.__dirty = 0;
  25418. el.__isRendered = true;
  25419. }
  25420. function brushIncremental(ctx, el, scope) {
  25421. var displayables = el.getDisplayables();
  25422. var temporalDisplayables = el.getTemporalDisplayables();
  25423. ctx.save();
  25424. var innerScope = {
  25425. prevElClipPaths: null,
  25426. prevEl: null,
  25427. allClipped: false,
  25428. viewWidth: scope.viewWidth,
  25429. viewHeight: scope.viewHeight,
  25430. inHover: scope.inHover
  25431. };
  25432. var i;
  25433. var len;
  25434. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  25435. var displayable = displayables[i];
  25436. displayable.beforeBrush && displayable.beforeBrush();
  25437. displayable.innerBeforeBrush();
  25438. brush(ctx, displayable, innerScope, i === len - 1);
  25439. displayable.innerAfterBrush();
  25440. displayable.afterBrush && displayable.afterBrush();
  25441. innerScope.prevEl = displayable;
  25442. }
  25443. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  25444. var displayable = temporalDisplayables[i_1];
  25445. displayable.beforeBrush && displayable.beforeBrush();
  25446. displayable.innerBeforeBrush();
  25447. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  25448. displayable.innerAfterBrush();
  25449. displayable.afterBrush && displayable.afterBrush();
  25450. innerScope.prevEl = displayable;
  25451. }
  25452. el.clearTemporalDisplayables();
  25453. el.notClear = true;
  25454. ctx.restore();
  25455. }
  25456. var decalMap = new WeakMap();
  25457. var decalCache = new LRU(100);
  25458. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  25459. /**
  25460. * Create or update pattern image from decal options
  25461. *
  25462. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  25463. * @return {Pattern} pattern with generated image, null if no decal
  25464. */
  25465. function createOrUpdatePatternFromDecal(decalObject, api) {
  25466. if (decalObject === 'none') {
  25467. return null;
  25468. }
  25469. var dpr = api.getDevicePixelRatio();
  25470. var zr = api.getZr();
  25471. var isSVG = zr.painter.type === 'svg';
  25472. if (decalObject.dirty) {
  25473. decalMap["delete"](decalObject);
  25474. }
  25475. var oldPattern = decalMap.get(decalObject);
  25476. if (oldPattern) {
  25477. return oldPattern;
  25478. }
  25479. var decalOpt = defaults(decalObject, {
  25480. symbol: 'rect',
  25481. symbolSize: 1,
  25482. symbolKeepAspect: true,
  25483. color: 'rgba(0, 0, 0, 0.2)',
  25484. backgroundColor: null,
  25485. dashArrayX: 5,
  25486. dashArrayY: 5,
  25487. rotation: 0,
  25488. maxTileWidth: 512,
  25489. maxTileHeight: 512
  25490. });
  25491. if (decalOpt.backgroundColor === 'none') {
  25492. decalOpt.backgroundColor = null;
  25493. }
  25494. var pattern = {
  25495. repeat: 'repeat'
  25496. };
  25497. setPatternnSource(pattern);
  25498. pattern.rotation = decalOpt.rotation;
  25499. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  25500. decalMap.set(decalObject, pattern);
  25501. decalObject.dirty = false;
  25502. return pattern;
  25503. function setPatternnSource(pattern) {
  25504. var keys = [dpr];
  25505. var isValidKey = true;
  25506. for (var i = 0; i < decalKeys.length; ++i) {
  25507. var value = decalOpt[decalKeys[i]];
  25508. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  25509. isValidKey = false;
  25510. break;
  25511. }
  25512. keys.push(value);
  25513. }
  25514. var cacheKey;
  25515. if (isValidKey) {
  25516. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  25517. var cache = decalCache.get(cacheKey);
  25518. if (cache) {
  25519. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  25520. }
  25521. }
  25522. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  25523. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  25524. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  25525. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  25526. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  25527. var canvas = !isSVG && platformApi.createCanvas();
  25528. var svgRoot = isSVG && {
  25529. tag: 'g',
  25530. attrs: {},
  25531. key: 'dcl',
  25532. children: []
  25533. };
  25534. var pSize = getPatternSize();
  25535. var ctx;
  25536. if (canvas) {
  25537. canvas.width = pSize.width * dpr;
  25538. canvas.height = pSize.height * dpr;
  25539. ctx = canvas.getContext('2d');
  25540. }
  25541. brushDecal();
  25542. if (isValidKey) {
  25543. decalCache.put(cacheKey, canvas || svgRoot);
  25544. }
  25545. pattern.image = canvas;
  25546. pattern.svgElement = svgRoot;
  25547. pattern.svgWidth = pSize.width;
  25548. pattern.svgHeight = pSize.height;
  25549. /**
  25550. * Get minimum length that can make a repeatable pattern.
  25551. *
  25552. * @return {Object} pattern width and height
  25553. */
  25554. function getPatternSize() {
  25555. /**
  25556. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25557. * |--- --- --- --- --- ...
  25558. * |-- -- -- -- -- -- -- -- ...
  25559. * |--- --- --- --- --- ...
  25560. * |-- -- -- -- -- -- -- -- ...
  25561. * So the minimum length of X is 15,
  25562. * which is the least common multiple of `3 + 2` and `2 + 1`
  25563. * |--- --- --- |--- --- ...
  25564. * |-- -- -- -- -- |-- -- -- ...
  25565. */
  25566. var width = 1;
  25567. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25568. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25569. }
  25570. var symbolRepeats = 1;
  25571. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25572. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25573. }
  25574. width *= symbolRepeats;
  25575. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25576. if ("development" !== 'production') {
  25577. var warn = function (attrName) {
  25578. /* eslint-disable-next-line */
  25579. console.warn("Calculated decal size is greater than " + attrName + " due to decal option settings so " + attrName + " is used for the decal size. Please consider changing the decal option to make a smaller decal or set " + attrName + " to be larger to avoid incontinuity.");
  25580. };
  25581. if (width > decalOpt.maxTileWidth) {
  25582. warn('maxTileWidth');
  25583. }
  25584. if (height > decalOpt.maxTileHeight) {
  25585. warn('maxTileHeight');
  25586. }
  25587. }
  25588. return {
  25589. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25590. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25591. };
  25592. }
  25593. function brushDecal() {
  25594. if (ctx) {
  25595. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25596. if (decalOpt.backgroundColor) {
  25597. ctx.fillStyle = decalOpt.backgroundColor;
  25598. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25599. }
  25600. }
  25601. var ySum = 0;
  25602. for (var i = 0; i < dashArrayY.length; ++i) {
  25603. ySum += dashArrayY[i];
  25604. }
  25605. if (ySum <= 0) {
  25606. // dashArrayY is 0, draw nothing
  25607. return;
  25608. }
  25609. var y = -lineBlockLengthY;
  25610. var yId = 0;
  25611. var yIdTotal = 0;
  25612. var xId0 = 0;
  25613. while (y < pSize.height) {
  25614. if (yId % 2 === 0) {
  25615. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25616. var x = 0;
  25617. var xId1 = 0;
  25618. var xId1Total = 0;
  25619. while (x < pSize.width * 2) {
  25620. var xSum = 0;
  25621. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25622. xSum += dashArrayX[xId0][i];
  25623. }
  25624. if (xSum <= 0) {
  25625. // Skip empty line
  25626. break;
  25627. }
  25628. // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25629. if (xId1 % 2 === 0) {
  25630. var size = (1 - decalOpt.symbolSize) * 0.5;
  25631. var left = x + dashArrayX[xId0][xId1] * size;
  25632. var top_1 = y + dashArrayY[yId] * size;
  25633. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25634. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25635. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25636. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25637. }
  25638. x += dashArrayX[xId0][xId1];
  25639. ++xId1Total;
  25640. ++xId1;
  25641. if (xId1 === dashArrayX[xId0].length) {
  25642. xId1 = 0;
  25643. }
  25644. }
  25645. ++xId0;
  25646. if (xId0 === dashArrayX.length) {
  25647. xId0 = 0;
  25648. }
  25649. }
  25650. y += dashArrayY[yId];
  25651. ++yIdTotal;
  25652. ++yId;
  25653. if (yId === dashArrayY.length) {
  25654. yId = 0;
  25655. }
  25656. }
  25657. function brushSymbol(x, y, width, height, symbolType) {
  25658. var scale = isSVG ? 1 : dpr;
  25659. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25660. if (isSVG) {
  25661. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25662. if (symbolVNode) {
  25663. svgRoot.children.push(symbolVNode);
  25664. }
  25665. } else {
  25666. // Paint to canvas for all other renderers.
  25667. brushSingle(ctx, symbol);
  25668. }
  25669. }
  25670. }
  25671. }
  25672. }
  25673. /**
  25674. * Convert symbol array into normalized array
  25675. *
  25676. * @param {string | (string | string[])[]} symbol symbol input
  25677. * @return {string[][]} normolized symbol array
  25678. */
  25679. function normalizeSymbolArray(symbol) {
  25680. if (!symbol || symbol.length === 0) {
  25681. return [['rect']];
  25682. }
  25683. if (isString(symbol)) {
  25684. return [[symbol]];
  25685. }
  25686. var isAllString = true;
  25687. for (var i = 0; i < symbol.length; ++i) {
  25688. if (!isString(symbol[i])) {
  25689. isAllString = false;
  25690. break;
  25691. }
  25692. }
  25693. if (isAllString) {
  25694. return normalizeSymbolArray([symbol]);
  25695. }
  25696. var result = [];
  25697. for (var i = 0; i < symbol.length; ++i) {
  25698. if (isString(symbol[i])) {
  25699. result.push([symbol[i]]);
  25700. } else {
  25701. result.push(symbol[i]);
  25702. }
  25703. }
  25704. return result;
  25705. }
  25706. /**
  25707. * Convert dash input into dashArray
  25708. *
  25709. * @param {DecalDashArrayX} dash dash input
  25710. * @return {number[][]} normolized dash array
  25711. */
  25712. function normalizeDashArrayX(dash) {
  25713. if (!dash || dash.length === 0) {
  25714. return [[0, 0]];
  25715. }
  25716. if (isNumber(dash)) {
  25717. var dashValue = Math.ceil(dash);
  25718. return [[dashValue, dashValue]];
  25719. }
  25720. /**
  25721. * [20, 5] should be normalized into [[20, 5]],
  25722. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25723. */
  25724. var isAllNumber = true;
  25725. for (var i = 0; i < dash.length; ++i) {
  25726. if (!isNumber(dash[i])) {
  25727. isAllNumber = false;
  25728. break;
  25729. }
  25730. }
  25731. if (isAllNumber) {
  25732. return normalizeDashArrayX([dash]);
  25733. }
  25734. var result = [];
  25735. for (var i = 0; i < dash.length; ++i) {
  25736. if (isNumber(dash[i])) {
  25737. var dashValue = Math.ceil(dash[i]);
  25738. result.push([dashValue, dashValue]);
  25739. } else {
  25740. var dashValue = map(dash[i], function (n) {
  25741. return Math.ceil(n);
  25742. });
  25743. if (dashValue.length % 2 === 1) {
  25744. // [4, 2, 1] means |---- - -- |---- - -- |
  25745. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25746. result.push(dashValue.concat(dashValue));
  25747. } else {
  25748. result.push(dashValue);
  25749. }
  25750. }
  25751. }
  25752. return result;
  25753. }
  25754. /**
  25755. * Convert dash input into dashArray
  25756. *
  25757. * @param {DecalDashArrayY} dash dash input
  25758. * @return {number[]} normolized dash array
  25759. */
  25760. function normalizeDashArrayY(dash) {
  25761. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25762. return [0, 0];
  25763. }
  25764. if (isNumber(dash)) {
  25765. var dashValue_1 = Math.ceil(dash);
  25766. return [dashValue_1, dashValue_1];
  25767. }
  25768. var dashValue = map(dash, function (n) {
  25769. return Math.ceil(n);
  25770. });
  25771. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25772. }
  25773. /**
  25774. * Get block length of each line. A block is the length of dash line and space.
  25775. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25776. * that, so the block length of this line is 5.
  25777. *
  25778. * @param {number[][]} dash dash array of X or Y
  25779. * @return {number[]} block length of each line
  25780. */
  25781. function getLineBlockLengthX(dash) {
  25782. return map(dash, function (line) {
  25783. return getLineBlockLengthY(line);
  25784. });
  25785. }
  25786. function getLineBlockLengthY(dash) {
  25787. var blockLength = 0;
  25788. for (var i = 0; i < dash.length; ++i) {
  25789. blockLength += dash[i];
  25790. }
  25791. if (dash.length % 2 === 1) {
  25792. // [4, 2, 1] means |---- - -- |---- - -- |
  25793. // So total length is (4 + 2 + 1) * 2
  25794. return blockLength * 2;
  25795. }
  25796. return blockLength;
  25797. }
  25798. function decalVisual(ecModel, api) {
  25799. ecModel.eachRawSeries(function (seriesModel) {
  25800. if (ecModel.isSeriesFiltered(seriesModel)) {
  25801. return;
  25802. }
  25803. var data = seriesModel.getData();
  25804. if (data.hasItemVisual()) {
  25805. data.each(function (idx) {
  25806. var decal = data.getItemVisual(idx, 'decal');
  25807. if (decal) {
  25808. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25809. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25810. }
  25811. });
  25812. }
  25813. var decal = data.getVisual('decal');
  25814. if (decal) {
  25815. var style = data.getVisual('style');
  25816. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25817. }
  25818. });
  25819. }
  25820. var lifecycle = new Eventful();
  25821. // Implementation of exported APIs. For example registerMap, getMap.
  25822. // The implementations will be registered when installing the component.
  25823. // Avoid these code being bundled to the core module.
  25824. var implsStore = {};
  25825. // TODO Type
  25826. function registerImpl(name, impl) {
  25827. if ("development" !== 'production') {
  25828. if (implsStore[name]) {
  25829. error("Already has an implementation of " + name + ".");
  25830. }
  25831. }
  25832. implsStore[name] = impl;
  25833. }
  25834. function getImpl(name) {
  25835. if ("development" !== 'production') {
  25836. if (!implsStore[name]) {
  25837. error("Implementation of " + name + " doesn't exists.");
  25838. }
  25839. }
  25840. return implsStore[name];
  25841. }
  25842. var version$1 = '5.6.0';
  25843. var dependencies = {
  25844. zrender: '5.6.1'
  25845. };
  25846. var TEST_FRAME_REMAIN_TIME = 1;
  25847. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  25848. // Some data processors depends on the stack result dimension (to calculate data extent).
  25849. // So data stack stage should be in front of data processing stage.
  25850. var PRIORITY_PROCESSOR_DATASTACK = 900;
  25851. // "Data filter" will block the stream, so it should be
  25852. // put at the beginning of data processing.
  25853. var PRIORITY_PROCESSOR_FILTER = 1000;
  25854. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25855. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25856. var PRIORITY_VISUAL_LAYOUT = 1000;
  25857. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25858. var PRIORITY_VISUAL_GLOBAL = 2000;
  25859. var PRIORITY_VISUAL_CHART = 3000;
  25860. var PRIORITY_VISUAL_COMPONENT = 4000;
  25861. // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25862. // overwrite the viusal result of component (like `visualMap`)
  25863. // using data item specific setting (like itemStyle.xxx on data item)
  25864. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500;
  25865. // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25866. // visual result like `symbolSize`.
  25867. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25868. var PRIORITY_VISUAL_BRUSH = 5000;
  25869. var PRIORITY_VISUAL_ARIA = 6000;
  25870. var PRIORITY_VISUAL_DECAL = 7000;
  25871. var PRIORITY = {
  25872. PROCESSOR: {
  25873. FILTER: PRIORITY_PROCESSOR_FILTER,
  25874. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25875. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25876. },
  25877. VISUAL: {
  25878. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25879. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25880. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25881. CHART: PRIORITY_VISUAL_CHART,
  25882. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25883. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25884. BRUSH: PRIORITY_VISUAL_BRUSH,
  25885. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25886. ARIA: PRIORITY_VISUAL_ARIA,
  25887. DECAL: PRIORITY_VISUAL_DECAL
  25888. }
  25889. };
  25890. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25891. // where they must not be invoked nestedly, except the only case: invoke
  25892. // dispatchAction with updateMethod "none" in main process.
  25893. // This flag is used to carry out this rule.
  25894. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25895. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25896. var PENDING_UPDATE = '__pendingUpdate';
  25897. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25898. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25899. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25900. var CONNECT_STATUS_PENDING = 0;
  25901. var CONNECT_STATUS_UPDATING = 1;
  25902. var CONNECT_STATUS_UPDATED = 2;
  25903. function createRegisterEventWithLowercaseECharts(method) {
  25904. return function () {
  25905. var args = [];
  25906. for (var _i = 0; _i < arguments.length; _i++) {
  25907. args[_i] = arguments[_i];
  25908. }
  25909. if (this.isDisposed()) {
  25910. disposedWarning(this.id);
  25911. return;
  25912. }
  25913. return toLowercaseNameAndCallEventful(this, method, args);
  25914. };
  25915. }
  25916. function createRegisterEventWithLowercaseMessageCenter(method) {
  25917. return function () {
  25918. var args = [];
  25919. for (var _i = 0; _i < arguments.length; _i++) {
  25920. args[_i] = arguments[_i];
  25921. }
  25922. return toLowercaseNameAndCallEventful(this, method, args);
  25923. };
  25924. }
  25925. function toLowercaseNameAndCallEventful(host, method, args) {
  25926. // `args[0]` is event name. Event name is all lowercase.
  25927. args[0] = args[0] && args[0].toLowerCase();
  25928. return Eventful.prototype[method].apply(host, args);
  25929. }
  25930. var MessageCenter = /** @class */function (_super) {
  25931. __extends(MessageCenter, _super);
  25932. function MessageCenter() {
  25933. return _super !== null && _super.apply(this, arguments) || this;
  25934. }
  25935. return MessageCenter;
  25936. }(Eventful);
  25937. var messageCenterProto = MessageCenter.prototype;
  25938. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25939. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off');
  25940. // ---------------------------------------
  25941. // Internal method names for class ECharts
  25942. // ---------------------------------------
  25943. var prepare;
  25944. var prepareView;
  25945. var updateDirectly;
  25946. var updateMethods;
  25947. var doConvertPixel;
  25948. var updateStreamModes;
  25949. var doDispatchAction;
  25950. var flushPendingActions;
  25951. var triggerUpdatedEvent;
  25952. var bindRenderedEvent;
  25953. var bindMouseEvent;
  25954. var render;
  25955. var renderComponents;
  25956. var renderSeries;
  25957. var createExtensionAPI;
  25958. var enableConnect;
  25959. var markStatusToUpdate;
  25960. var applyChangedStates;
  25961. var ECharts = /** @class */function (_super) {
  25962. __extends(ECharts, _super);
  25963. function ECharts(dom,
  25964. // Theme name or themeOption.
  25965. theme, opts) {
  25966. var _this = _super.call(this, new ECEventProcessor()) || this;
  25967. _this._chartsViews = [];
  25968. _this._chartsMap = {};
  25969. _this._componentsViews = [];
  25970. _this._componentsMap = {};
  25971. // Can't dispatch action during rendering procedure
  25972. _this._pendingActions = [];
  25973. opts = opts || {};
  25974. // Get theme by name
  25975. if (isString(theme)) {
  25976. theme = themeStorage[theme];
  25977. }
  25978. _this._dom = dom;
  25979. var defaultRenderer = 'canvas';
  25980. var defaultCoarsePointer = 'auto';
  25981. var defaultUseDirtyRect = false;
  25982. if ("development" !== 'production') {
  25983. var root = /* eslint-disable-next-line */
  25984. env.hasGlobalWindow ? window : global;
  25985. if (root) {
  25986. defaultRenderer = retrieve2(root.__ECHARTS__DEFAULT__RENDERER__, defaultRenderer);
  25987. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25988. defaultUseDirtyRect = retrieve2(root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__, defaultUseDirtyRect);
  25989. }
  25990. }
  25991. if (opts.ssr) {
  25992. registerSSRDataGetter(function (el) {
  25993. var ecData = getECData(el);
  25994. var dataIndex = ecData.dataIndex;
  25995. if (dataIndex == null) {
  25996. return;
  25997. }
  25998. var hashMap = createHashMap();
  25999. hashMap.set('series_index', ecData.seriesIndex);
  26000. hashMap.set('data_index', dataIndex);
  26001. ecData.ssrType && hashMap.set('ssr_type', ecData.ssrType);
  26002. return hashMap;
  26003. });
  26004. }
  26005. var zr = _this._zr = init(dom, {
  26006. renderer: opts.renderer || defaultRenderer,
  26007. devicePixelRatio: opts.devicePixelRatio,
  26008. width: opts.width,
  26009. height: opts.height,
  26010. ssr: opts.ssr,
  26011. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  26012. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  26013. pointerSize: opts.pointerSize
  26014. });
  26015. _this._ssr = opts.ssr;
  26016. // Expect 60 fps.
  26017. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  26018. theme = clone(theme);
  26019. theme && globalBackwardCompat(theme, true);
  26020. _this._theme = theme;
  26021. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  26022. _this._coordSysMgr = new CoordinateSystemManager();
  26023. var api = _this._api = createExtensionAPI(_this);
  26024. // Sort on demand
  26025. function prioritySortFunc(a, b) {
  26026. return a.__prio - b.__prio;
  26027. }
  26028. sort(visualFuncs, prioritySortFunc);
  26029. sort(dataProcessorFuncs, prioritySortFunc);
  26030. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  26031. _this._messageCenter = new MessageCenter();
  26032. // Init mouse events
  26033. _this._initEvents();
  26034. // In case some people write `window.onresize = chart.resize`
  26035. _this.resize = bind(_this.resize, _this);
  26036. zr.animation.on('frame', _this._onframe, _this);
  26037. bindRenderedEvent(zr, _this);
  26038. bindMouseEvent(zr, _this);
  26039. // ECharts instance can be used as value.
  26040. setAsPrimitive(_this);
  26041. return _this;
  26042. }
  26043. ECharts.prototype._onframe = function () {
  26044. if (this._disposed) {
  26045. return;
  26046. }
  26047. applyChangedStates(this);
  26048. var scheduler = this._scheduler;
  26049. // Lazy update
  26050. if (this[PENDING_UPDATE]) {
  26051. var silent = this[PENDING_UPDATE].silent;
  26052. this[IN_MAIN_PROCESS_KEY] = true;
  26053. try {
  26054. prepare(this);
  26055. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  26056. } catch (e) {
  26057. this[IN_MAIN_PROCESS_KEY] = false;
  26058. this[PENDING_UPDATE] = null;
  26059. throw e;
  26060. }
  26061. // At present, in each frame, zrender performs:
  26062. // (1) animation step forward.
  26063. // (2) trigger('frame') (where this `_onframe` is called)
  26064. // (3) zrender flush (render).
  26065. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  26066. // will render the final state of the elements before the real animation started.
  26067. this._zr.flush();
  26068. this[IN_MAIN_PROCESS_KEY] = false;
  26069. this[PENDING_UPDATE] = null;
  26070. flushPendingActions.call(this, silent);
  26071. triggerUpdatedEvent.call(this, silent);
  26072. }
  26073. // Avoid do both lazy update and progress in one frame.
  26074. else if (scheduler.unfinished) {
  26075. // Stream progress.
  26076. var remainTime = TEST_FRAME_REMAIN_TIME;
  26077. var ecModel = this._model;
  26078. var api = this._api;
  26079. scheduler.unfinished = false;
  26080. do {
  26081. var startTime = +new Date();
  26082. scheduler.performSeriesTasks(ecModel);
  26083. // Currently dataProcessorFuncs do not check threshold.
  26084. scheduler.performDataProcessorTasks(ecModel);
  26085. updateStreamModes(this, ecModel);
  26086. // Do not update coordinate system here. Because that coord system update in
  26087. // each frame is not a good user experience. So we follow the rule that
  26088. // the extent of the coordinate system is determined in the first frame (the
  26089. // frame is executed immediately after task reset.
  26090. // this._coordSysMgr.update(ecModel, api);
  26091. // console.log('--- ec frame visual ---', remainTime);
  26092. scheduler.performVisualTasks(ecModel);
  26093. renderSeries(this, this._model, api, 'remain', {});
  26094. remainTime -= +new Date() - startTime;
  26095. } while (remainTime > 0 && scheduler.unfinished);
  26096. // Call flush explicitly for trigger finished event.
  26097. if (!scheduler.unfinished) {
  26098. this._zr.flush();
  26099. }
  26100. // Else, zr flushing be ensue within the same frame,
  26101. // because zr flushing is after onframe event.
  26102. }
  26103. };
  26104. ECharts.prototype.getDom = function () {
  26105. return this._dom;
  26106. };
  26107. ECharts.prototype.getId = function () {
  26108. return this.id;
  26109. };
  26110. ECharts.prototype.getZr = function () {
  26111. return this._zr;
  26112. };
  26113. ECharts.prototype.isSSR = function () {
  26114. return this._ssr;
  26115. };
  26116. /* eslint-disable-next-line */
  26117. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  26118. if (this[IN_MAIN_PROCESS_KEY]) {
  26119. if ("development" !== 'production') {
  26120. error('`setOption` should not be called during main process.');
  26121. }
  26122. return;
  26123. }
  26124. if (this._disposed) {
  26125. disposedWarning(this.id);
  26126. return;
  26127. }
  26128. var silent;
  26129. var replaceMerge;
  26130. var transitionOpt;
  26131. if (isObject(notMerge)) {
  26132. lazyUpdate = notMerge.lazyUpdate;
  26133. silent = notMerge.silent;
  26134. replaceMerge = notMerge.replaceMerge;
  26135. transitionOpt = notMerge.transition;
  26136. notMerge = notMerge.notMerge;
  26137. }
  26138. this[IN_MAIN_PROCESS_KEY] = true;
  26139. if (!this._model || notMerge) {
  26140. var optionManager = new OptionManager(this._api);
  26141. var theme = this._theme;
  26142. var ecModel = this._model = new GlobalModel();
  26143. ecModel.scheduler = this._scheduler;
  26144. ecModel.ssr = this._ssr;
  26145. ecModel.init(null, null, null, theme, this._locale, optionManager);
  26146. }
  26147. this._model.setOption(option, {
  26148. replaceMerge: replaceMerge
  26149. }, optionPreprocessorFuncs);
  26150. var updateParams = {
  26151. seriesTransition: transitionOpt,
  26152. optionChanged: true
  26153. };
  26154. if (lazyUpdate) {
  26155. this[PENDING_UPDATE] = {
  26156. silent: silent,
  26157. updateParams: updateParams
  26158. };
  26159. this[IN_MAIN_PROCESS_KEY] = false;
  26160. // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  26161. // It should wake it up to make sure zrender start to render at the next frame.
  26162. this.getZr().wakeUp();
  26163. } else {
  26164. try {
  26165. prepare(this);
  26166. updateMethods.update.call(this, null, updateParams);
  26167. } catch (e) {
  26168. this[PENDING_UPDATE] = null;
  26169. this[IN_MAIN_PROCESS_KEY] = false;
  26170. throw e;
  26171. }
  26172. // Ensure zr refresh sychronously, and then pixel in canvas can be
  26173. // fetched after `setOption`.
  26174. if (!this._ssr) {
  26175. // not use flush when using ssr mode.
  26176. this._zr.flush();
  26177. }
  26178. this[PENDING_UPDATE] = null;
  26179. this[IN_MAIN_PROCESS_KEY] = false;
  26180. flushPendingActions.call(this, silent);
  26181. triggerUpdatedEvent.call(this, silent);
  26182. }
  26183. };
  26184. /**
  26185. * @deprecated
  26186. */
  26187. ECharts.prototype.setTheme = function () {
  26188. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  26189. };
  26190. // We don't want developers to use getModel directly.
  26191. ECharts.prototype.getModel = function () {
  26192. return this._model;
  26193. };
  26194. ECharts.prototype.getOption = function () {
  26195. return this._model && this._model.getOption();
  26196. };
  26197. ECharts.prototype.getWidth = function () {
  26198. return this._zr.getWidth();
  26199. };
  26200. ECharts.prototype.getHeight = function () {
  26201. return this._zr.getHeight();
  26202. };
  26203. ECharts.prototype.getDevicePixelRatio = function () {
  26204. return this._zr.painter.dpr
  26205. /* eslint-disable-next-line */ || env.hasGlobalWindow && window.devicePixelRatio || 1;
  26206. };
  26207. /**
  26208. * Get canvas which has all thing rendered
  26209. * @deprecated Use renderToCanvas instead.
  26210. */
  26211. ECharts.prototype.getRenderedCanvas = function (opts) {
  26212. if ("development" !== 'production') {
  26213. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  26214. }
  26215. return this.renderToCanvas(opts);
  26216. };
  26217. ECharts.prototype.renderToCanvas = function (opts) {
  26218. opts = opts || {};
  26219. var painter = this._zr.painter;
  26220. if ("development" !== 'production') {
  26221. if (painter.type !== 'canvas') {
  26222. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  26223. }
  26224. }
  26225. return painter.getRenderedCanvas({
  26226. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  26227. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  26228. });
  26229. };
  26230. ECharts.prototype.renderToSVGString = function (opts) {
  26231. opts = opts || {};
  26232. var painter = this._zr.painter;
  26233. if ("development" !== 'production') {
  26234. if (painter.type !== 'svg') {
  26235. throw new Error('renderToSVGString can only be used in the svg renderer.');
  26236. }
  26237. }
  26238. return painter.renderToString({
  26239. useViewBox: opts.useViewBox
  26240. });
  26241. };
  26242. /**
  26243. * Get svg data url
  26244. */
  26245. ECharts.prototype.getSvgDataURL = function () {
  26246. if (!env.svgSupported) {
  26247. return;
  26248. }
  26249. var zr = this._zr;
  26250. var list = zr.storage.getDisplayList();
  26251. // Stop animations
  26252. each(list, function (el) {
  26253. el.stopAnimation(null, true);
  26254. });
  26255. return zr.painter.toDataURL();
  26256. };
  26257. ECharts.prototype.getDataURL = function (opts) {
  26258. if (this._disposed) {
  26259. disposedWarning(this.id);
  26260. return;
  26261. }
  26262. opts = opts || {};
  26263. var excludeComponents = opts.excludeComponents;
  26264. var ecModel = this._model;
  26265. var excludesComponentViews = [];
  26266. var self = this;
  26267. each(excludeComponents, function (componentType) {
  26268. ecModel.eachComponent({
  26269. mainType: componentType
  26270. }, function (component) {
  26271. var view = self._componentsMap[component.__viewId];
  26272. if (!view.group.ignore) {
  26273. excludesComponentViews.push(view);
  26274. view.group.ignore = true;
  26275. }
  26276. });
  26277. });
  26278. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  26279. each(excludesComponentViews, function (view) {
  26280. view.group.ignore = false;
  26281. });
  26282. return url;
  26283. };
  26284. ECharts.prototype.getConnectedDataURL = function (opts) {
  26285. if (this._disposed) {
  26286. disposedWarning(this.id);
  26287. return;
  26288. }
  26289. var isSvg = opts.type === 'svg';
  26290. var groupId = this.group;
  26291. var mathMin = Math.min;
  26292. var mathMax = Math.max;
  26293. var MAX_NUMBER = Infinity;
  26294. if (connectedGroups[groupId]) {
  26295. var left_1 = MAX_NUMBER;
  26296. var top_1 = MAX_NUMBER;
  26297. var right_1 = -MAX_NUMBER;
  26298. var bottom_1 = -MAX_NUMBER;
  26299. var canvasList_1 = [];
  26300. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  26301. each(instances$1, function (chart, id) {
  26302. if (chart.group === groupId) {
  26303. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  26304. var boundingRect = chart.getDom().getBoundingClientRect();
  26305. left_1 = mathMin(boundingRect.left, left_1);
  26306. top_1 = mathMin(boundingRect.top, top_1);
  26307. right_1 = mathMax(boundingRect.right, right_1);
  26308. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  26309. canvasList_1.push({
  26310. dom: canvas,
  26311. left: boundingRect.left,
  26312. top: boundingRect.top
  26313. });
  26314. }
  26315. });
  26316. left_1 *= dpr_1;
  26317. top_1 *= dpr_1;
  26318. right_1 *= dpr_1;
  26319. bottom_1 *= dpr_1;
  26320. var width = right_1 - left_1;
  26321. var height = bottom_1 - top_1;
  26322. var targetCanvas = platformApi.createCanvas();
  26323. var zr_1 = init(targetCanvas, {
  26324. renderer: isSvg ? 'svg' : 'canvas'
  26325. });
  26326. zr_1.resize({
  26327. width: width,
  26328. height: height
  26329. });
  26330. if (isSvg) {
  26331. var content_1 = '';
  26332. each(canvasList_1, function (item) {
  26333. var x = item.left - left_1;
  26334. var y = item.top - top_1;
  26335. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  26336. });
  26337. zr_1.painter.getSvgRoot().innerHTML = content_1;
  26338. if (opts.connectedBackgroundColor) {
  26339. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  26340. }
  26341. zr_1.refreshImmediately();
  26342. return zr_1.painter.toDataURL();
  26343. } else {
  26344. // Background between the charts
  26345. if (opts.connectedBackgroundColor) {
  26346. zr_1.add(new Rect({
  26347. shape: {
  26348. x: 0,
  26349. y: 0,
  26350. width: width,
  26351. height: height
  26352. },
  26353. style: {
  26354. fill: opts.connectedBackgroundColor
  26355. }
  26356. }));
  26357. }
  26358. each(canvasList_1, function (item) {
  26359. var img = new ZRImage({
  26360. style: {
  26361. x: item.left * dpr_1 - left_1,
  26362. y: item.top * dpr_1 - top_1,
  26363. image: item.dom
  26364. }
  26365. });
  26366. zr_1.add(img);
  26367. });
  26368. zr_1.refreshImmediately();
  26369. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  26370. }
  26371. } else {
  26372. return this.getDataURL(opts);
  26373. }
  26374. };
  26375. ECharts.prototype.convertToPixel = function (finder, value) {
  26376. return doConvertPixel(this, 'convertToPixel', finder, value);
  26377. };
  26378. ECharts.prototype.convertFromPixel = function (finder, value) {
  26379. return doConvertPixel(this, 'convertFromPixel', finder, value);
  26380. };
  26381. /**
  26382. * Is the specified coordinate systems or components contain the given pixel point.
  26383. * @param {Array|number} value
  26384. * @return {boolean} result
  26385. */
  26386. ECharts.prototype.containPixel = function (finder, value) {
  26387. if (this._disposed) {
  26388. disposedWarning(this.id);
  26389. return;
  26390. }
  26391. var ecModel = this._model;
  26392. var result;
  26393. var findResult = parseFinder(ecModel, finder);
  26394. each(findResult, function (models, key) {
  26395. key.indexOf('Models') >= 0 && each(models, function (model) {
  26396. var coordSys = model.coordinateSystem;
  26397. if (coordSys && coordSys.containPoint) {
  26398. result = result || !!coordSys.containPoint(value);
  26399. } else if (key === 'seriesModels') {
  26400. var view = this._chartsMap[model.__viewId];
  26401. if (view && view.containPoint) {
  26402. result = result || view.containPoint(value, model);
  26403. } else {
  26404. if ("development" !== 'production') {
  26405. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  26406. }
  26407. }
  26408. } else {
  26409. if ("development" !== 'production') {
  26410. warn(key + ': containPoint is not supported');
  26411. }
  26412. }
  26413. }, this);
  26414. }, this);
  26415. return !!result;
  26416. };
  26417. /**
  26418. * Get visual from series or data.
  26419. * @param finder
  26420. * If string, e.g., 'series', means {seriesIndex: 0}.
  26421. * If Object, could contain some of these properties below:
  26422. * {
  26423. * seriesIndex / seriesId / seriesName,
  26424. * dataIndex / dataIndexInside
  26425. * }
  26426. * If dataIndex is not specified, series visual will be fetched,
  26427. * but not data item visual.
  26428. * If all of seriesIndex, seriesId, seriesName are not specified,
  26429. * visual will be fetched from first series.
  26430. * @param visualType 'color', 'symbol', 'symbolSize'
  26431. */
  26432. ECharts.prototype.getVisual = function (finder, visualType) {
  26433. var ecModel = this._model;
  26434. var parsedFinder = parseFinder(ecModel, finder, {
  26435. defaultMainType: 'series'
  26436. });
  26437. var seriesModel = parsedFinder.seriesModel;
  26438. if ("development" !== 'production') {
  26439. if (!seriesModel) {
  26440. warn('There is no specified series model');
  26441. }
  26442. }
  26443. var data = seriesModel.getData();
  26444. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  26445. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  26446. };
  26447. /**
  26448. * Get view of corresponding component model
  26449. */
  26450. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  26451. return this._componentsMap[componentModel.__viewId];
  26452. };
  26453. /**
  26454. * Get view of corresponding series model
  26455. */
  26456. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  26457. return this._chartsMap[seriesModel.__viewId];
  26458. };
  26459. ECharts.prototype._initEvents = function () {
  26460. var _this = this;
  26461. each(MOUSE_EVENT_NAMES, function (eveName) {
  26462. var handler = function (e) {
  26463. var ecModel = _this.getModel();
  26464. var el = e.target;
  26465. var params;
  26466. var isGlobalOut = eveName === 'globalout';
  26467. // no e.target when 'globalout'.
  26468. if (isGlobalOut) {
  26469. params = {};
  26470. } else {
  26471. el && findEventDispatcher(el, function (parent) {
  26472. var ecData = getECData(parent);
  26473. if (ecData && ecData.dataIndex != null) {
  26474. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  26475. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType, el) || {};
  26476. return true;
  26477. }
  26478. // If element has custom eventData of components
  26479. else if (ecData.eventData) {
  26480. params = extend({}, ecData.eventData);
  26481. return true;
  26482. }
  26483. }, true);
  26484. }
  26485. // Contract: if params prepared in mouse event,
  26486. // these properties must be specified:
  26487. // {
  26488. // componentType: string (component main type)
  26489. // componentIndex: number
  26490. // }
  26491. // Otherwise event query can not work.
  26492. if (params) {
  26493. var componentType = params.componentType;
  26494. var componentIndex = params.componentIndex;
  26495. // Special handling for historic reason: when trigger by
  26496. // markLine/markPoint/markArea, the componentType is
  26497. // 'markLine'/'markPoint'/'markArea', but we should better
  26498. // enable them to be queried by seriesIndex, since their
  26499. // option is set in each series.
  26500. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  26501. componentType = 'series';
  26502. componentIndex = params.seriesIndex;
  26503. }
  26504. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  26505. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  26506. if ("development" !== 'production') {
  26507. // `event.componentType` and `event[componentTpype + 'Index']` must not
  26508. // be missed, otherwise there is no way to distinguish source component.
  26509. // See `dataFormat.getDataParams`.
  26510. if (!isGlobalOut && !(model && view)) {
  26511. warn('model or view can not be found by params');
  26512. }
  26513. }
  26514. params.event = e;
  26515. params.type = eveName;
  26516. _this._$eventProcessor.eventInfo = {
  26517. targetEl: el,
  26518. packedEvent: params,
  26519. model: model,
  26520. view: view
  26521. };
  26522. _this.trigger(eveName, params);
  26523. }
  26524. };
  26525. // Consider that some component (like tooltip, brush, ...)
  26526. // register zr event handler, but user event handler might
  26527. // do anything, such as call `setOption` or `dispatchAction`,
  26528. // which probably update any of the content and probably
  26529. // cause problem if it is called previous other inner handlers.
  26530. handler.zrEventfulCallAtLast = true;
  26531. _this._zr.on(eveName, handler, _this);
  26532. });
  26533. each(eventActionMap, function (actionType, eventType) {
  26534. _this._messageCenter.on(eventType, function (event) {
  26535. this.trigger(eventType, event);
  26536. }, _this);
  26537. });
  26538. // Extra events
  26539. // TODO register?
  26540. each(['selectchanged'], function (eventType) {
  26541. _this._messageCenter.on(eventType, function (event) {
  26542. this.trigger(eventType, event);
  26543. }, _this);
  26544. });
  26545. handleLegacySelectEvents(this._messageCenter, this, this._api);
  26546. };
  26547. ECharts.prototype.isDisposed = function () {
  26548. return this._disposed;
  26549. };
  26550. ECharts.prototype.clear = function () {
  26551. if (this._disposed) {
  26552. disposedWarning(this.id);
  26553. return;
  26554. }
  26555. this.setOption({
  26556. series: []
  26557. }, true);
  26558. };
  26559. ECharts.prototype.dispose = function () {
  26560. if (this._disposed) {
  26561. disposedWarning(this.id);
  26562. return;
  26563. }
  26564. this._disposed = true;
  26565. var dom = this.getDom();
  26566. if (dom) {
  26567. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  26568. }
  26569. var chart = this;
  26570. var api = chart._api;
  26571. var ecModel = chart._model;
  26572. each(chart._componentsViews, function (component) {
  26573. component.dispose(ecModel, api);
  26574. });
  26575. each(chart._chartsViews, function (chart) {
  26576. chart.dispose(ecModel, api);
  26577. });
  26578. // Dispose after all views disposed
  26579. chart._zr.dispose();
  26580. // Set properties to null.
  26581. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  26582. chart._dom = chart._model = chart._chartsMap = chart._componentsMap = chart._chartsViews = chart._componentsViews = chart._scheduler = chart._api = chart._zr = chart._throttledZrFlush = chart._theme = chart._coordSysMgr = chart._messageCenter = null;
  26583. delete instances$1[chart.id];
  26584. };
  26585. /**
  26586. * Resize the chart
  26587. */
  26588. ECharts.prototype.resize = function (opts) {
  26589. if (this[IN_MAIN_PROCESS_KEY]) {
  26590. if ("development" !== 'production') {
  26591. error('`resize` should not be called during main process.');
  26592. }
  26593. return;
  26594. }
  26595. if (this._disposed) {
  26596. disposedWarning(this.id);
  26597. return;
  26598. }
  26599. this._zr.resize(opts);
  26600. var ecModel = this._model;
  26601. // Resize loading effect
  26602. this._loadingFX && this._loadingFX.resize();
  26603. if (!ecModel) {
  26604. return;
  26605. }
  26606. var needPrepare = ecModel.resetOption('media');
  26607. var silent = opts && opts.silent;
  26608. // There is some real cases that:
  26609. // chart.setOption(option, { lazyUpdate: true });
  26610. // chart.resize();
  26611. if (this[PENDING_UPDATE]) {
  26612. if (silent == null) {
  26613. silent = this[PENDING_UPDATE].silent;
  26614. }
  26615. needPrepare = true;
  26616. this[PENDING_UPDATE] = null;
  26617. }
  26618. this[IN_MAIN_PROCESS_KEY] = true;
  26619. try {
  26620. needPrepare && prepare(this);
  26621. updateMethods.update.call(this, {
  26622. type: 'resize',
  26623. animation: extend({
  26624. // Disable animation
  26625. duration: 0
  26626. }, opts && opts.animation)
  26627. });
  26628. } catch (e) {
  26629. this[IN_MAIN_PROCESS_KEY] = false;
  26630. throw e;
  26631. }
  26632. this[IN_MAIN_PROCESS_KEY] = false;
  26633. flushPendingActions.call(this, silent);
  26634. triggerUpdatedEvent.call(this, silent);
  26635. };
  26636. ECharts.prototype.showLoading = function (name, cfg) {
  26637. if (this._disposed) {
  26638. disposedWarning(this.id);
  26639. return;
  26640. }
  26641. if (isObject(name)) {
  26642. cfg = name;
  26643. name = '';
  26644. }
  26645. name = name || 'default';
  26646. this.hideLoading();
  26647. if (!loadingEffects[name]) {
  26648. if ("development" !== 'production') {
  26649. warn('Loading effects ' + name + ' not exists.');
  26650. }
  26651. return;
  26652. }
  26653. var el = loadingEffects[name](this._api, cfg);
  26654. var zr = this._zr;
  26655. this._loadingFX = el;
  26656. zr.add(el);
  26657. };
  26658. /**
  26659. * Hide loading effect
  26660. */
  26661. ECharts.prototype.hideLoading = function () {
  26662. if (this._disposed) {
  26663. disposedWarning(this.id);
  26664. return;
  26665. }
  26666. this._loadingFX && this._zr.remove(this._loadingFX);
  26667. this._loadingFX = null;
  26668. };
  26669. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26670. var payload = extend({}, eventObj);
  26671. payload.type = eventActionMap[eventObj.type];
  26672. return payload;
  26673. };
  26674. /**
  26675. * @param opt If pass boolean, means opt.silent
  26676. * @param opt.silent Default `false`. Whether trigger events.
  26677. * @param opt.flush Default `undefined`.
  26678. * true: Flush immediately, and then pixel in canvas can be fetched
  26679. * immediately. Caution: it might affect performance.
  26680. * false: Not flush.
  26681. * undefined: Auto decide whether perform flush.
  26682. */
  26683. ECharts.prototype.dispatchAction = function (payload, opt) {
  26684. if (this._disposed) {
  26685. disposedWarning(this.id);
  26686. return;
  26687. }
  26688. if (!isObject(opt)) {
  26689. opt = {
  26690. silent: !!opt
  26691. };
  26692. }
  26693. if (!actions[payload.type]) {
  26694. return;
  26695. }
  26696. // Avoid dispatch action before setOption. Especially in `connect`.
  26697. if (!this._model) {
  26698. return;
  26699. }
  26700. // May dispatchAction in rendering procedure
  26701. if (this[IN_MAIN_PROCESS_KEY]) {
  26702. this._pendingActions.push(payload);
  26703. return;
  26704. }
  26705. var silent = opt.silent;
  26706. doDispatchAction.call(this, payload, silent);
  26707. var flush = opt.flush;
  26708. if (flush) {
  26709. this._zr.flush();
  26710. } else if (flush !== false && env.browser.weChat) {
  26711. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26712. // hang when sliding page (on touch event), which cause that zr does not
  26713. // refresh until user interaction finished, which is not expected.
  26714. // But `dispatchAction` may be called too frequently when pan on touch
  26715. // screen, which impacts performance if do not throttle them.
  26716. this._throttledZrFlush();
  26717. }
  26718. flushPendingActions.call(this, silent);
  26719. triggerUpdatedEvent.call(this, silent);
  26720. };
  26721. ECharts.prototype.updateLabelLayout = function () {
  26722. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26723. // Not adding series labels.
  26724. // TODO
  26725. updatedSeries: []
  26726. });
  26727. };
  26728. ECharts.prototype.appendData = function (params) {
  26729. if (this._disposed) {
  26730. disposedWarning(this.id);
  26731. return;
  26732. }
  26733. var seriesIndex = params.seriesIndex;
  26734. var ecModel = this.getModel();
  26735. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26736. if ("development" !== 'production') {
  26737. assert(params.data && seriesModel);
  26738. }
  26739. seriesModel.appendData(params);
  26740. // Note: `appendData` does not support that update extent of coordinate
  26741. // system, util some scenario require that. In the expected usage of
  26742. // `appendData`, the initial extent of coordinate system should better
  26743. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26744. // the extent changed while `appendData`, the location of the painted
  26745. // graphic elements have to be changed, which make the usage of
  26746. // `appendData` meaningless.
  26747. this._scheduler.unfinished = true;
  26748. this.getZr().wakeUp();
  26749. };
  26750. // A work around for no `internal` modifier in ts yet but
  26751. // need to strictly hide private methods to JS users.
  26752. ECharts.internalField = function () {
  26753. prepare = function (ecIns) {
  26754. var scheduler = ecIns._scheduler;
  26755. scheduler.restorePipelines(ecIns._model);
  26756. scheduler.prepareStageTasks();
  26757. prepareView(ecIns, true);
  26758. prepareView(ecIns, false);
  26759. scheduler.plan();
  26760. };
  26761. /**
  26762. * Prepare view instances of charts and components
  26763. */
  26764. prepareView = function (ecIns, isComponent) {
  26765. var ecModel = ecIns._model;
  26766. var scheduler = ecIns._scheduler;
  26767. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26768. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26769. var zr = ecIns._zr;
  26770. var api = ecIns._api;
  26771. for (var i = 0; i < viewList.length; i++) {
  26772. viewList[i].__alive = false;
  26773. }
  26774. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26775. componentType !== 'series' && doPrepare(model);
  26776. }) : ecModel.eachSeries(doPrepare);
  26777. function doPrepare(model) {
  26778. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26779. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26780. // especially no id but have the same type & name & index. See the `model.id` generation
  26781. // rule in `makeIdAndName` and `viewId` generation rule here).
  26782. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26783. // the new model has nothing to do with the old model.
  26784. var requireNewView = model.__requireNewView;
  26785. // This command should not work twice.
  26786. model.__requireNewView = false;
  26787. // Consider: id same and type changed.
  26788. var viewId = '_ec_' + model.id + '_' + model.type;
  26789. var view = !requireNewView && viewMap[viewId];
  26790. if (!view) {
  26791. var classType = parseClassType(model.type);
  26792. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) :
  26793. // FIXME:TS
  26794. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26795. // For backward compat, still support a chart type declared as only subType
  26796. // like "liquidfill", but recommend "series.liquidfill"
  26797. // But need a base class to make a type series.
  26798. ChartView.getClass(classType.sub);
  26799. if ("development" !== 'production') {
  26800. assert(Clazz, classType.sub + ' does not exist.');
  26801. }
  26802. view = new Clazz();
  26803. view.init(ecModel, api);
  26804. viewMap[viewId] = view;
  26805. viewList.push(view);
  26806. zr.add(view.group);
  26807. }
  26808. model.__viewId = view.__id = viewId;
  26809. view.__alive = true;
  26810. view.__model = model;
  26811. view.group.__ecComponentInfo = {
  26812. mainType: model.mainType,
  26813. index: model.componentIndex
  26814. };
  26815. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26816. }
  26817. for (var i = 0; i < viewList.length;) {
  26818. var view = viewList[i];
  26819. if (!view.__alive) {
  26820. !isComponent && view.renderTask.dispose();
  26821. zr.remove(view.group);
  26822. view.dispose(ecModel, api);
  26823. viewList.splice(i, 1);
  26824. if (viewMap[view.__id] === view) {
  26825. delete viewMap[view.__id];
  26826. }
  26827. view.__id = view.group.__ecComponentInfo = null;
  26828. } else {
  26829. i++;
  26830. }
  26831. }
  26832. };
  26833. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26834. var ecModel = ecIns._model;
  26835. ecModel.setUpdatePayload(payload);
  26836. // broadcast
  26837. if (!mainType) {
  26838. // FIXME
  26839. // Chart will not be update directly here, except set dirty.
  26840. // But there is no such scenario now.
  26841. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26842. return;
  26843. }
  26844. var query = {};
  26845. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26846. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26847. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26848. var condition = {
  26849. mainType: mainType,
  26850. query: query
  26851. };
  26852. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26853. var excludeSeriesId = payload.excludeSeriesId;
  26854. var excludeSeriesIdMap;
  26855. if (excludeSeriesId != null) {
  26856. excludeSeriesIdMap = createHashMap();
  26857. each(normalizeToArray(excludeSeriesId), function (id) {
  26858. var modelId = convertOptionIdName(id, null);
  26859. if (modelId != null) {
  26860. excludeSeriesIdMap.set(modelId, true);
  26861. }
  26862. });
  26863. }
  26864. // If dispatchAction before setOption, do nothing.
  26865. ecModel && ecModel.eachComponent(condition, function (model) {
  26866. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26867. if (isExcluded) {
  26868. return;
  26869. }
  26870. if (isHighDownPayload(payload)) {
  26871. if (model instanceof SeriesModel) {
  26872. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26873. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26874. }
  26875. } else {
  26876. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26877. focusSelf = _a.focusSelf,
  26878. dispatchers = _a.dispatchers;
  26879. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26880. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26881. }
  26882. // PENDING:
  26883. // Whether to put this "enter emphasis" code in `ComponentView`,
  26884. // which will be the same as `ChartView` but might be not necessary
  26885. // and will be far from this logic.
  26886. if (dispatchers) {
  26887. each(dispatchers, function (dispatcher) {
  26888. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26889. });
  26890. }
  26891. }
  26892. } else if (isSelectChangePayload(payload)) {
  26893. // TODO geo
  26894. if (model instanceof SeriesModel) {
  26895. toggleSelectionFromPayload(model, payload, ecIns._api);
  26896. updateSeriesElementSelection(model);
  26897. markStatusToUpdate(ecIns);
  26898. }
  26899. }
  26900. }, ecIns);
  26901. ecModel && ecModel.eachComponent(condition, function (model) {
  26902. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26903. if (isExcluded) {
  26904. return;
  26905. }
  26906. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26907. }, ecIns);
  26908. function callView(view) {
  26909. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26910. }
  26911. };
  26912. updateMethods = {
  26913. prepareAndUpdate: function (payload) {
  26914. prepare(this);
  26915. updateMethods.update.call(this, payload, {
  26916. // Needs to mark option changed if newOption is given.
  26917. // It's from MagicType.
  26918. // TODO If use a separate flag optionChanged in payload?
  26919. optionChanged: payload.newOption != null
  26920. });
  26921. },
  26922. update: function (payload, updateParams) {
  26923. var ecModel = this._model;
  26924. var api = this._api;
  26925. var zr = this._zr;
  26926. var coordSysMgr = this._coordSysMgr;
  26927. var scheduler = this._scheduler;
  26928. // update before setOption
  26929. if (!ecModel) {
  26930. return;
  26931. }
  26932. ecModel.setUpdatePayload(payload);
  26933. scheduler.restoreData(ecModel, payload);
  26934. scheduler.performSeriesTasks(ecModel);
  26935. // TODO
  26936. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26937. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26938. // Create new coordinate system each update
  26939. // In LineView may save the old coordinate system and use it to get the original point.
  26940. coordSysMgr.create(ecModel, api);
  26941. scheduler.performDataProcessorTasks(ecModel, payload);
  26942. // Current stream render is not supported in data process. So we can update
  26943. // stream modes after data processing, where the filtered data is used to
  26944. // determine whether to use progressive rendering.
  26945. updateStreamModes(this, ecModel);
  26946. // We update stream modes before coordinate system updated, then the modes info
  26947. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26948. // the drawback is the full coord info can not be fetched. Fortunately this full
  26949. // coord is not required in stream mode updater currently.
  26950. coordSysMgr.update(ecModel, api);
  26951. clearColorPalette(ecModel);
  26952. scheduler.performVisualTasks(ecModel, payload);
  26953. render(this, ecModel, api, payload, updateParams);
  26954. // Set background
  26955. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26956. var darkMode = ecModel.get('darkMode');
  26957. zr.setBackgroundColor(backgroundColor);
  26958. // Force set dark mode.
  26959. if (darkMode != null && darkMode !== 'auto') {
  26960. zr.setDarkMode(darkMode);
  26961. }
  26962. lifecycle.trigger('afterupdate', ecModel, api);
  26963. },
  26964. updateTransform: function (payload) {
  26965. var _this = this;
  26966. var ecModel = this._model;
  26967. var api = this._api;
  26968. // update before setOption
  26969. if (!ecModel) {
  26970. return;
  26971. }
  26972. ecModel.setUpdatePayload(payload);
  26973. // ChartView.markUpdateMethod(payload, 'updateTransform');
  26974. var componentDirtyList = [];
  26975. ecModel.eachComponent(function (componentType, componentModel) {
  26976. if (componentType === 'series') {
  26977. return;
  26978. }
  26979. var componentView = _this.getViewOfComponentModel(componentModel);
  26980. if (componentView && componentView.__alive) {
  26981. if (componentView.updateTransform) {
  26982. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26983. result && result.update && componentDirtyList.push(componentView);
  26984. } else {
  26985. componentDirtyList.push(componentView);
  26986. }
  26987. }
  26988. });
  26989. var seriesDirtyMap = createHashMap();
  26990. ecModel.eachSeries(function (seriesModel) {
  26991. var chartView = _this._chartsMap[seriesModel.__viewId];
  26992. if (chartView.updateTransform) {
  26993. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26994. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26995. } else {
  26996. seriesDirtyMap.set(seriesModel.uid, 1);
  26997. }
  26998. });
  26999. clearColorPalette(ecModel);
  27000. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27001. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  27002. this._scheduler.performVisualTasks(ecModel, payload, {
  27003. setDirty: true,
  27004. dirtyMap: seriesDirtyMap
  27005. });
  27006. // Currently, not call render of components. Geo render cost a lot.
  27007. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  27008. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  27009. lifecycle.trigger('afterupdate', ecModel, api);
  27010. },
  27011. updateView: function (payload) {
  27012. var ecModel = this._model;
  27013. // update before setOption
  27014. if (!ecModel) {
  27015. return;
  27016. }
  27017. ecModel.setUpdatePayload(payload);
  27018. ChartView.markUpdateMethod(payload, 'updateView');
  27019. clearColorPalette(ecModel);
  27020. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27021. this._scheduler.performVisualTasks(ecModel, payload, {
  27022. setDirty: true
  27023. });
  27024. render(this, ecModel, this._api, payload, {});
  27025. lifecycle.trigger('afterupdate', ecModel, this._api);
  27026. },
  27027. updateVisual: function (payload) {
  27028. // updateMethods.update.call(this, payload);
  27029. var _this = this;
  27030. var ecModel = this._model;
  27031. // update before setOption
  27032. if (!ecModel) {
  27033. return;
  27034. }
  27035. ecModel.setUpdatePayload(payload);
  27036. // clear all visual
  27037. ecModel.eachSeries(function (seriesModel) {
  27038. seriesModel.getData().clearAllVisual();
  27039. });
  27040. // Perform visual
  27041. ChartView.markUpdateMethod(payload, 'updateVisual');
  27042. clearColorPalette(ecModel);
  27043. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27044. this._scheduler.performVisualTasks(ecModel, payload, {
  27045. visualType: 'visual',
  27046. setDirty: true
  27047. });
  27048. ecModel.eachComponent(function (componentType, componentModel) {
  27049. if (componentType !== 'series') {
  27050. var componentView = _this.getViewOfComponentModel(componentModel);
  27051. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  27052. }
  27053. });
  27054. ecModel.eachSeries(function (seriesModel) {
  27055. var chartView = _this._chartsMap[seriesModel.__viewId];
  27056. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  27057. });
  27058. lifecycle.trigger('afterupdate', ecModel, this._api);
  27059. },
  27060. updateLayout: function (payload) {
  27061. updateMethods.update.call(this, payload);
  27062. }
  27063. };
  27064. doConvertPixel = function (ecIns, methodName, finder, value) {
  27065. if (ecIns._disposed) {
  27066. disposedWarning(ecIns.id);
  27067. return;
  27068. }
  27069. var ecModel = ecIns._model;
  27070. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  27071. var result;
  27072. var parsedFinder = parseFinder(ecModel, finder);
  27073. for (var i = 0; i < coordSysList.length; i++) {
  27074. var coordSys = coordSysList[i];
  27075. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  27076. return result;
  27077. }
  27078. }
  27079. if ("development" !== 'production') {
  27080. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  27081. }
  27082. };
  27083. updateStreamModes = function (ecIns, ecModel) {
  27084. var chartsMap = ecIns._chartsMap;
  27085. var scheduler = ecIns._scheduler;
  27086. ecModel.eachSeries(function (seriesModel) {
  27087. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  27088. });
  27089. };
  27090. doDispatchAction = function (payload, silent) {
  27091. var _this = this;
  27092. var ecModel = this.getModel();
  27093. var payloadType = payload.type;
  27094. var escapeConnect = payload.escapeConnect;
  27095. var actionWrap = actions[payloadType];
  27096. var actionInfo = actionWrap.actionInfo;
  27097. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  27098. var updateMethod = cptTypeTmp.pop();
  27099. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  27100. this[IN_MAIN_PROCESS_KEY] = true;
  27101. var payloads = [payload];
  27102. var batched = false;
  27103. // Batch action
  27104. if (payload.batch) {
  27105. batched = true;
  27106. payloads = map(payload.batch, function (item) {
  27107. item = defaults(extend({}, item), payload);
  27108. item.batch = null;
  27109. return item;
  27110. });
  27111. }
  27112. var eventObjBatch = [];
  27113. var eventObj;
  27114. var isSelectChange = isSelectChangePayload(payload);
  27115. var isHighDown = isHighDownPayload(payload);
  27116. // Only leave blur once if there are multiple batches.
  27117. if (isHighDown) {
  27118. allLeaveBlur(this._api);
  27119. }
  27120. each(payloads, function (batchItem) {
  27121. // Action can specify the event by return it.
  27122. eventObj = actionWrap.action(batchItem, _this._model, _this._api);
  27123. // Emit event outside
  27124. eventObj = eventObj || extend({}, batchItem);
  27125. // Convert type to eventType
  27126. eventObj.type = actionInfo.event || eventObj.type;
  27127. eventObjBatch.push(eventObj);
  27128. // light update does not perform data process, layout and visual.
  27129. if (isHighDown) {
  27130. var _a = preParseFinder(payload),
  27131. queryOptionMap = _a.queryOptionMap,
  27132. mainTypeSpecified = _a.mainTypeSpecified;
  27133. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  27134. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  27135. markStatusToUpdate(_this);
  27136. } else if (isSelectChange) {
  27137. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  27138. // geo still use 'geoselect'.
  27139. updateDirectly(_this, updateMethod, batchItem, 'series');
  27140. markStatusToUpdate(_this);
  27141. } else if (cptType) {
  27142. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  27143. }
  27144. });
  27145. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  27146. try {
  27147. // Still dirty
  27148. if (this[PENDING_UPDATE]) {
  27149. prepare(this);
  27150. updateMethods.update.call(this, payload);
  27151. this[PENDING_UPDATE] = null;
  27152. } else {
  27153. updateMethods[updateMethod].call(this, payload);
  27154. }
  27155. } catch (e) {
  27156. this[IN_MAIN_PROCESS_KEY] = false;
  27157. throw e;
  27158. }
  27159. }
  27160. // Follow the rule of action batch
  27161. if (batched) {
  27162. eventObj = {
  27163. type: actionInfo.event || payloadType,
  27164. escapeConnect: escapeConnect,
  27165. batch: eventObjBatch
  27166. };
  27167. } else {
  27168. eventObj = eventObjBatch[0];
  27169. }
  27170. this[IN_MAIN_PROCESS_KEY] = false;
  27171. if (!silent) {
  27172. var messageCenter = this._messageCenter;
  27173. messageCenter.trigger(eventObj.type, eventObj);
  27174. // Extra triggered 'selectchanged' event
  27175. if (isSelectChange) {
  27176. var newObj = {
  27177. type: 'selectchanged',
  27178. escapeConnect: escapeConnect,
  27179. selected: getAllSelectedIndices(ecModel),
  27180. isFromClick: payload.isFromClick || false,
  27181. fromAction: payload.type,
  27182. fromActionPayload: payload
  27183. };
  27184. messageCenter.trigger(newObj.type, newObj);
  27185. }
  27186. }
  27187. };
  27188. flushPendingActions = function (silent) {
  27189. var pendingActions = this._pendingActions;
  27190. while (pendingActions.length) {
  27191. var payload = pendingActions.shift();
  27192. doDispatchAction.call(this, payload, silent);
  27193. }
  27194. };
  27195. triggerUpdatedEvent = function (silent) {
  27196. !silent && this.trigger('updated');
  27197. };
  27198. /**
  27199. * Event `rendered` is triggered when zr
  27200. * rendered. It is useful for realtime
  27201. * snapshot (reflect animation).
  27202. *
  27203. * Event `finished` is triggered when:
  27204. * (1) zrender rendering finished.
  27205. * (2) initial animation finished.
  27206. * (3) progressive rendering finished.
  27207. * (4) no pending action.
  27208. * (5) no delayed setOption needs to be processed.
  27209. */
  27210. bindRenderedEvent = function (zr, ecIns) {
  27211. zr.on('rendered', function (params) {
  27212. ecIns.trigger('rendered', params);
  27213. // The `finished` event should not be triggered repeatedly,
  27214. // so it should only be triggered when rendering indeed happens
  27215. // in zrender. (Consider the case that dipatchAction is keep
  27216. // triggering when mouse move).
  27217. if (
  27218. // Although zr is dirty if initial animation is not finished
  27219. // and this checking is called on frame, we also check
  27220. // animation finished for robustness.
  27221. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  27222. ecIns.trigger('finished');
  27223. }
  27224. });
  27225. };
  27226. bindMouseEvent = function (zr, ecIns) {
  27227. zr.on('mouseover', function (e) {
  27228. var el = e.target;
  27229. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  27230. if (dispatcher) {
  27231. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  27232. markStatusToUpdate(ecIns);
  27233. }
  27234. }).on('mouseout', function (e) {
  27235. var el = e.target;
  27236. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  27237. if (dispatcher) {
  27238. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  27239. markStatusToUpdate(ecIns);
  27240. }
  27241. }).on('click', function (e) {
  27242. var el = e.target;
  27243. var dispatcher = findEventDispatcher(el, function (target) {
  27244. return getECData(target).dataIndex != null;
  27245. }, true);
  27246. if (dispatcher) {
  27247. var actionType = dispatcher.selected ? 'unselect' : 'select';
  27248. var ecData = getECData(dispatcher);
  27249. ecIns._api.dispatchAction({
  27250. type: actionType,
  27251. dataType: ecData.dataType,
  27252. dataIndexInside: ecData.dataIndex,
  27253. seriesIndex: ecData.seriesIndex,
  27254. isFromClick: true
  27255. });
  27256. }
  27257. });
  27258. };
  27259. function clearColorPalette(ecModel) {
  27260. ecModel.clearColorPalette();
  27261. ecModel.eachSeries(function (seriesModel) {
  27262. seriesModel.clearColorPalette();
  27263. });
  27264. }
  27265. // Allocate zlevels for series and components
  27266. function allocateZlevels(ecModel) {
  27267. var componentZLevels = [];
  27268. var seriesZLevels = [];
  27269. var hasSeparateZLevel = false;
  27270. ecModel.eachComponent(function (componentType, componentModel) {
  27271. var zlevel = componentModel.get('zlevel') || 0;
  27272. var z = componentModel.get('z') || 0;
  27273. var zlevelKey = componentModel.getZLevelKey();
  27274. hasSeparateZLevel = hasSeparateZLevel || !!zlevelKey;
  27275. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  27276. zlevel: zlevel,
  27277. z: z,
  27278. idx: componentModel.componentIndex,
  27279. type: componentType,
  27280. key: zlevelKey
  27281. });
  27282. });
  27283. if (hasSeparateZLevel) {
  27284. // Series after component
  27285. var zLevels = componentZLevels.concat(seriesZLevels);
  27286. var lastSeriesZLevel_1;
  27287. var lastSeriesKey_1;
  27288. sort(zLevels, function (a, b) {
  27289. if (a.zlevel === b.zlevel) {
  27290. return a.z - b.z;
  27291. }
  27292. return a.zlevel - b.zlevel;
  27293. });
  27294. each(zLevels, function (item) {
  27295. var componentModel = ecModel.getComponent(item.type, item.idx);
  27296. var zlevel = item.zlevel;
  27297. var key = item.key;
  27298. if (lastSeriesZLevel_1 != null) {
  27299. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  27300. }
  27301. if (key) {
  27302. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  27303. zlevel++;
  27304. }
  27305. lastSeriesKey_1 = key;
  27306. } else if (lastSeriesKey_1) {
  27307. if (zlevel === lastSeriesZLevel_1) {
  27308. zlevel++;
  27309. }
  27310. lastSeriesKey_1 = '';
  27311. }
  27312. lastSeriesZLevel_1 = zlevel;
  27313. componentModel.setZLevel(zlevel);
  27314. });
  27315. }
  27316. }
  27317. render = function (ecIns, ecModel, api, payload, updateParams) {
  27318. allocateZlevels(ecModel);
  27319. renderComponents(ecIns, ecModel, api, payload, updateParams);
  27320. each(ecIns._chartsViews, function (chart) {
  27321. chart.__alive = false;
  27322. });
  27323. renderSeries(ecIns, ecModel, api, payload, updateParams);
  27324. // Remove groups of unrendered charts
  27325. each(ecIns._chartsViews, function (chart) {
  27326. if (!chart.__alive) {
  27327. chart.remove(ecModel, api);
  27328. }
  27329. });
  27330. };
  27331. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  27332. each(dirtyList || ecIns._componentsViews, function (componentView) {
  27333. var componentModel = componentView.__model;
  27334. clearStates(componentModel, componentView);
  27335. componentView.render(componentModel, ecModel, api, payload);
  27336. updateZ(componentModel, componentView);
  27337. updateStates(componentModel, componentView);
  27338. });
  27339. };
  27340. /**
  27341. * Render each chart and component
  27342. */
  27343. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  27344. // Render all charts
  27345. var scheduler = ecIns._scheduler;
  27346. updateParams = extend(updateParams || {}, {
  27347. updatedSeries: ecModel.getSeries()
  27348. });
  27349. // TODO progressive?
  27350. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  27351. var unfinished = false;
  27352. ecModel.eachSeries(function (seriesModel) {
  27353. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27354. chartView.__alive = true;
  27355. var renderTask = chartView.renderTask;
  27356. scheduler.updatePayload(renderTask, payload);
  27357. // TODO states on marker.
  27358. clearStates(seriesModel, chartView);
  27359. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  27360. renderTask.dirty();
  27361. }
  27362. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  27363. unfinished = true;
  27364. }
  27365. chartView.group.silent = !!seriesModel.get('silent');
  27366. // Should not call markRedraw on group, because it will disable zrender
  27367. // incremental render (always render from the __startIndex each frame)
  27368. // chartView.group.markRedraw();
  27369. updateBlend(seriesModel, chartView);
  27370. updateSeriesElementSelection(seriesModel);
  27371. });
  27372. scheduler.unfinished = unfinished || scheduler.unfinished;
  27373. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams);
  27374. // transition after label is layouted.
  27375. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  27376. ecModel.eachSeries(function (seriesModel) {
  27377. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27378. // Update Z after labels updated. Before applying states.
  27379. updateZ(seriesModel, chartView);
  27380. // NOTE: Update states after label is updated.
  27381. // label should be in normal status when layouting.
  27382. updateStates(seriesModel, chartView);
  27383. });
  27384. // If use hover layer
  27385. updateHoverLayerStatus(ecIns, ecModel);
  27386. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  27387. };
  27388. markStatusToUpdate = function (ecIns) {
  27389. ecIns[STATUS_NEEDS_UPDATE_KEY] = true;
  27390. // Wake up zrender if it's sleep. Let it update states in the next frame.
  27391. ecIns.getZr().wakeUp();
  27392. };
  27393. applyChangedStates = function (ecIns) {
  27394. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  27395. return;
  27396. }
  27397. ecIns.getZr().storage.traverse(function (el) {
  27398. // Not applied on removed elements, it may still in fading.
  27399. if (isElementRemoved(el)) {
  27400. return;
  27401. }
  27402. applyElementStates(el);
  27403. });
  27404. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  27405. };
  27406. function applyElementStates(el) {
  27407. var newStates = [];
  27408. var oldStates = el.currentStates;
  27409. // Keep other states.
  27410. for (var i = 0; i < oldStates.length; i++) {
  27411. var stateName = oldStates[i];
  27412. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  27413. newStates.push(stateName);
  27414. }
  27415. }
  27416. // Only use states when it's exists.
  27417. if (el.selected && el.states.select) {
  27418. newStates.push('select');
  27419. }
  27420. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  27421. newStates.push('emphasis');
  27422. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  27423. newStates.push('blur');
  27424. }
  27425. el.useStates(newStates);
  27426. }
  27427. function updateHoverLayerStatus(ecIns, ecModel) {
  27428. var zr = ecIns._zr;
  27429. var storage = zr.storage;
  27430. var elCount = 0;
  27431. storage.traverse(function (el) {
  27432. if (!el.isGroup) {
  27433. elCount++;
  27434. }
  27435. });
  27436. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  27437. ecModel.eachSeries(function (seriesModel) {
  27438. if (seriesModel.preventUsingHoverLayer) {
  27439. return;
  27440. }
  27441. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27442. if (chartView.__alive) {
  27443. chartView.eachRendered(function (el) {
  27444. if (el.states.emphasis) {
  27445. el.states.emphasis.hoverLayer = true;
  27446. }
  27447. });
  27448. }
  27449. });
  27450. }
  27451. }
  27452. /**
  27453. * Update chart and blend.
  27454. */
  27455. function updateBlend(seriesModel, chartView) {
  27456. var blendMode = seriesModel.get('blendMode') || null;
  27457. chartView.eachRendered(function (el) {
  27458. // FIXME marker and other components
  27459. if (!el.isGroup) {
  27460. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  27461. el.style.blend = blendMode;
  27462. }
  27463. });
  27464. }
  27465. function updateZ(model, view) {
  27466. if (model.preventAutoZ) {
  27467. return;
  27468. }
  27469. var z = model.get('z') || 0;
  27470. var zlevel = model.get('zlevel') || 0;
  27471. // Set z and zlevel
  27472. view.eachRendered(function (el) {
  27473. doUpdateZ(el, z, zlevel, -Infinity);
  27474. // Don't traverse the children because it has been traversed in _updateZ.
  27475. return true;
  27476. });
  27477. }
  27478. function doUpdateZ(el, z, zlevel, maxZ2) {
  27479. // Group may also have textContent
  27480. var label = el.getTextContent();
  27481. var labelLine = el.getTextGuideLine();
  27482. var isGroup = el.isGroup;
  27483. if (isGroup) {
  27484. // set z & zlevel of children elements of Group
  27485. var children = el.childrenRef();
  27486. for (var i = 0; i < children.length; i++) {
  27487. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  27488. }
  27489. } else {
  27490. // not Group
  27491. el.z = z;
  27492. el.zlevel = zlevel;
  27493. maxZ2 = Math.max(el.z2, maxZ2);
  27494. }
  27495. // always set z and zlevel if label/labelLine exists
  27496. if (label) {
  27497. label.z = z;
  27498. label.zlevel = zlevel;
  27499. // lift z2 of text content
  27500. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  27501. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  27502. }
  27503. if (labelLine) {
  27504. var textGuideLineConfig = el.textGuideLineConfig;
  27505. labelLine.z = z;
  27506. labelLine.zlevel = zlevel;
  27507. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  27508. }
  27509. return maxZ2;
  27510. }
  27511. // Clear states without animation.
  27512. // TODO States on component.
  27513. function clearStates(model, view) {
  27514. view.eachRendered(function (el) {
  27515. // Not applied on removed elements, it may still in fading.
  27516. if (isElementRemoved(el)) {
  27517. return;
  27518. }
  27519. var textContent = el.getTextContent();
  27520. var textGuide = el.getTextGuideLine();
  27521. if (el.stateTransition) {
  27522. el.stateTransition = null;
  27523. }
  27524. if (textContent && textContent.stateTransition) {
  27525. textContent.stateTransition = null;
  27526. }
  27527. if (textGuide && textGuide.stateTransition) {
  27528. textGuide.stateTransition = null;
  27529. }
  27530. // TODO If el is incremental.
  27531. if (el.hasState()) {
  27532. el.prevStates = el.currentStates;
  27533. el.clearStates();
  27534. } else if (el.prevStates) {
  27535. el.prevStates = null;
  27536. }
  27537. });
  27538. }
  27539. function updateStates(model, view) {
  27540. var stateAnimationModel = model.getModel('stateAnimation');
  27541. var enableAnimation = model.isAnimationEnabled();
  27542. var duration = stateAnimationModel.get('duration');
  27543. var stateTransition = duration > 0 ? {
  27544. duration: duration,
  27545. delay: stateAnimationModel.get('delay'),
  27546. easing: stateAnimationModel.get('easing')
  27547. // additive: stateAnimationModel.get('additive')
  27548. } : null;
  27549. view.eachRendered(function (el) {
  27550. if (el.states && el.states.emphasis) {
  27551. // Not applied on removed elements, it may still in fading.
  27552. if (isElementRemoved(el)) {
  27553. return;
  27554. }
  27555. if (el instanceof Path) {
  27556. savePathStates(el);
  27557. }
  27558. // Only updated on changed element. In case element is incremental and don't want to rerender.
  27559. // TODO, a more proper way?
  27560. if (el.__dirty) {
  27561. var prevStates = el.prevStates;
  27562. // Restore states without animation
  27563. if (prevStates) {
  27564. el.useStates(prevStates);
  27565. }
  27566. }
  27567. // Update state transition and enable animation again.
  27568. if (enableAnimation) {
  27569. el.stateTransition = stateTransition;
  27570. var textContent = el.getTextContent();
  27571. var textGuide = el.getTextGuideLine();
  27572. // TODO Is it necessary to animate label?
  27573. if (textContent) {
  27574. textContent.stateTransition = stateTransition;
  27575. }
  27576. if (textGuide) {
  27577. textGuide.stateTransition = stateTransition;
  27578. }
  27579. }
  27580. // Use highlighted and selected flag to toggle states.
  27581. if (el.__dirty) {
  27582. applyElementStates(el);
  27583. }
  27584. }
  27585. });
  27586. }
  27587. createExtensionAPI = function (ecIns) {
  27588. return new (/** @class */function (_super) {
  27589. __extends(class_1, _super);
  27590. function class_1() {
  27591. return _super !== null && _super.apply(this, arguments) || this;
  27592. }
  27593. class_1.prototype.getCoordinateSystems = function () {
  27594. return ecIns._coordSysMgr.getCoordinateSystems();
  27595. };
  27596. class_1.prototype.getComponentByElement = function (el) {
  27597. while (el) {
  27598. var modelInfo = el.__ecComponentInfo;
  27599. if (modelInfo != null) {
  27600. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  27601. }
  27602. el = el.parent;
  27603. }
  27604. };
  27605. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  27606. enterEmphasis(el, highlightDigit);
  27607. markStatusToUpdate(ecIns);
  27608. };
  27609. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  27610. leaveEmphasis(el, highlightDigit);
  27611. markStatusToUpdate(ecIns);
  27612. };
  27613. class_1.prototype.enterBlur = function (el) {
  27614. enterBlur(el);
  27615. markStatusToUpdate(ecIns);
  27616. };
  27617. class_1.prototype.leaveBlur = function (el) {
  27618. leaveBlur(el);
  27619. markStatusToUpdate(ecIns);
  27620. };
  27621. class_1.prototype.enterSelect = function (el) {
  27622. enterSelect(el);
  27623. markStatusToUpdate(ecIns);
  27624. };
  27625. class_1.prototype.leaveSelect = function (el) {
  27626. leaveSelect(el);
  27627. markStatusToUpdate(ecIns);
  27628. };
  27629. class_1.prototype.getModel = function () {
  27630. return ecIns.getModel();
  27631. };
  27632. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  27633. return ecIns.getViewOfComponentModel(componentModel);
  27634. };
  27635. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  27636. return ecIns.getViewOfSeriesModel(seriesModel);
  27637. };
  27638. return class_1;
  27639. }(ExtensionAPI))(ecIns);
  27640. };
  27641. enableConnect = function (chart) {
  27642. function updateConnectedChartsStatus(charts, status) {
  27643. for (var i = 0; i < charts.length; i++) {
  27644. var otherChart = charts[i];
  27645. otherChart[CONNECT_STATUS_KEY] = status;
  27646. }
  27647. }
  27648. each(eventActionMap, function (actionType, eventType) {
  27649. chart._messageCenter.on(eventType, function (event) {
  27650. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  27651. if (event && event.escapeConnect) {
  27652. return;
  27653. }
  27654. var action_1 = chart.makeActionFromEvent(event);
  27655. var otherCharts_1 = [];
  27656. each(instances$1, function (otherChart) {
  27657. if (otherChart !== chart && otherChart.group === chart.group) {
  27658. otherCharts_1.push(otherChart);
  27659. }
  27660. });
  27661. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27662. each(otherCharts_1, function (otherChart) {
  27663. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27664. otherChart.dispatchAction(action_1);
  27665. }
  27666. });
  27667. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27668. }
  27669. });
  27670. });
  27671. };
  27672. }();
  27673. return ECharts;
  27674. }(Eventful);
  27675. var echartsProto = ECharts.prototype;
  27676. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27677. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27678. /**
  27679. * @deprecated
  27680. */
  27681. // @ts-ignore
  27682. echartsProto.one = function (eventName, cb, ctx) {
  27683. var self = this;
  27684. deprecateLog('ECharts#one is deprecated.');
  27685. function wrapped() {
  27686. var args2 = [];
  27687. for (var _i = 0; _i < arguments.length; _i++) {
  27688. args2[_i] = arguments[_i];
  27689. }
  27690. cb && cb.apply && cb.apply(this, args2);
  27691. // @ts-ignore
  27692. self.off(eventName, wrapped);
  27693. }
  27694. // @ts-ignore
  27695. this.on.call(this, eventName, wrapped, ctx);
  27696. };
  27697. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27698. function disposedWarning(id) {
  27699. if ("development" !== 'production') {
  27700. warn('Instance ' + id + ' has been disposed');
  27701. }
  27702. }
  27703. var actions = {};
  27704. /**
  27705. * Map eventType to actionType
  27706. */
  27707. var eventActionMap = {};
  27708. var dataProcessorFuncs = [];
  27709. var optionPreprocessorFuncs = [];
  27710. var visualFuncs = [];
  27711. var themeStorage = {};
  27712. var loadingEffects = {};
  27713. var instances$1 = {};
  27714. var connectedGroups = {};
  27715. var idBase = +new Date() - 0;
  27716. var groupIdBase = +new Date() - 0;
  27717. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27718. /**
  27719. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27720. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27721. * @param opts.width Use clientWidth of the input `dom` by default.
  27722. * Can be 'auto' (the same as null/undefined)
  27723. * @param opts.height Use clientHeight of the input `dom` by default.
  27724. * Can be 'auto' (the same as null/undefined)
  27725. * @param opts.locale Specify the locale.
  27726. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27727. */
  27728. function init$1(dom, theme, opts) {
  27729. var isClient = !(opts && opts.ssr);
  27730. if (isClient) {
  27731. if ("development" !== 'production') {
  27732. if (!dom) {
  27733. throw new Error('Initialize failed: invalid dom.');
  27734. }
  27735. }
  27736. var existInstance = getInstanceByDom(dom);
  27737. if (existInstance) {
  27738. if ("development" !== 'production') {
  27739. warn('There is a chart instance already initialized on the dom.');
  27740. }
  27741. return existInstance;
  27742. }
  27743. if ("development" !== 'production') {
  27744. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27745. warn('Can\'t get DOM width or height. Please check ' + 'dom.clientWidth and dom.clientHeight. They should not be 0.' + 'For example, you may need to call this in the callback ' + 'of window.onload.');
  27746. }
  27747. }
  27748. }
  27749. var chart = new ECharts(dom, theme, opts);
  27750. chart.id = 'ec_' + idBase++;
  27751. instances$1[chart.id] = chart;
  27752. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27753. enableConnect(chart);
  27754. lifecycle.trigger('afterinit', chart);
  27755. return chart;
  27756. }
  27757. /**
  27758. * @usage
  27759. * (A)
  27760. * ```js
  27761. * let chart1 = echarts.init(dom1);
  27762. * let chart2 = echarts.init(dom2);
  27763. * chart1.group = 'xxx';
  27764. * chart2.group = 'xxx';
  27765. * echarts.connect('xxx');
  27766. * ```
  27767. * (B)
  27768. * ```js
  27769. * let chart1 = echarts.init(dom1);
  27770. * let chart2 = echarts.init(dom2);
  27771. * echarts.connect('xxx', [chart1, chart2]);
  27772. * ```
  27773. */
  27774. function connect(groupId) {
  27775. // Is array of charts
  27776. if (isArray(groupId)) {
  27777. var charts = groupId;
  27778. groupId = null;
  27779. // If any chart has group
  27780. each(charts, function (chart) {
  27781. if (chart.group != null) {
  27782. groupId = chart.group;
  27783. }
  27784. });
  27785. groupId = groupId || 'g_' + groupIdBase++;
  27786. each(charts, function (chart) {
  27787. chart.group = groupId;
  27788. });
  27789. }
  27790. connectedGroups[groupId] = true;
  27791. return groupId;
  27792. }
  27793. function disconnect(groupId) {
  27794. connectedGroups[groupId] = false;
  27795. }
  27796. /**
  27797. * Alias and backward compatibility
  27798. * @deprecated
  27799. */
  27800. var disConnect = disconnect;
  27801. /**
  27802. * Dispose a chart instance
  27803. */
  27804. function dispose$1(chart) {
  27805. if (isString(chart)) {
  27806. chart = instances$1[chart];
  27807. } else if (!(chart instanceof ECharts)) {
  27808. // Try to treat as dom
  27809. chart = getInstanceByDom(chart);
  27810. }
  27811. if (chart instanceof ECharts && !chart.isDisposed()) {
  27812. chart.dispose();
  27813. }
  27814. }
  27815. function getInstanceByDom(dom) {
  27816. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27817. }
  27818. function getInstanceById(key) {
  27819. return instances$1[key];
  27820. }
  27821. /**
  27822. * Register theme
  27823. */
  27824. function registerTheme(name, theme) {
  27825. themeStorage[name] = theme;
  27826. }
  27827. /**
  27828. * Register option preprocessor
  27829. */
  27830. function registerPreprocessor(preprocessorFunc) {
  27831. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27832. optionPreprocessorFuncs.push(preprocessorFunc);
  27833. }
  27834. }
  27835. function registerProcessor(priority, processor) {
  27836. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27837. }
  27838. /**
  27839. * Register postIniter
  27840. * @param {Function} postInitFunc
  27841. */
  27842. function registerPostInit(postInitFunc) {
  27843. registerUpdateLifecycle('afterinit', postInitFunc);
  27844. }
  27845. /**
  27846. * Register postUpdater
  27847. * @param {Function} postUpdateFunc
  27848. */
  27849. function registerPostUpdate(postUpdateFunc) {
  27850. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27851. }
  27852. function registerUpdateLifecycle(name, cb) {
  27853. lifecycle.on(name, cb);
  27854. }
  27855. function registerAction(actionInfo, eventName, action) {
  27856. if (isFunction(eventName)) {
  27857. action = eventName;
  27858. eventName = '';
  27859. }
  27860. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27861. event: eventName
  27862. }][0];
  27863. // Event name is all lowercase
  27864. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27865. eventName = actionInfo.event;
  27866. if (eventActionMap[eventName]) {
  27867. // Already registered.
  27868. return;
  27869. }
  27870. // Validate action type and event name.
  27871. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27872. if (!actions[actionType]) {
  27873. actions[actionType] = {
  27874. action: action,
  27875. actionInfo: actionInfo
  27876. };
  27877. }
  27878. eventActionMap[eventName] = actionType;
  27879. }
  27880. function registerCoordinateSystem(type, coordSysCreator) {
  27881. CoordinateSystemManager.register(type, coordSysCreator);
  27882. }
  27883. /**
  27884. * Get dimensions of specified coordinate system.
  27885. * @param {string} type
  27886. * @return {Array.<string|Object>}
  27887. */
  27888. function getCoordinateSystemDimensions(type) {
  27889. var coordSysCreator = CoordinateSystemManager.get(type);
  27890. if (coordSysCreator) {
  27891. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27892. }
  27893. }
  27894. function registerLayout(priority, layoutTask) {
  27895. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27896. }
  27897. function registerVisual(priority, visualTask) {
  27898. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27899. }
  27900. var registeredTasks = [];
  27901. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27902. if (isFunction(priority) || isObject(priority)) {
  27903. fn = priority;
  27904. priority = defaultPriority;
  27905. }
  27906. if ("development" !== 'production') {
  27907. if (isNaN(priority) || priority == null) {
  27908. throw new Error('Illegal priority');
  27909. }
  27910. // Check duplicate
  27911. each(targetList, function (wrap) {
  27912. assert(wrap.__raw !== fn);
  27913. });
  27914. }
  27915. // Already registered
  27916. if (indexOf(registeredTasks, fn) >= 0) {
  27917. return;
  27918. }
  27919. registeredTasks.push(fn);
  27920. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27921. stageHandler.__prio = priority;
  27922. stageHandler.__raw = fn;
  27923. targetList.push(stageHandler);
  27924. }
  27925. function registerLoading(name, loadingFx) {
  27926. loadingEffects[name] = loadingFx;
  27927. }
  27928. /**
  27929. * ZRender need a canvas context to do measureText.
  27930. * But in node environment canvas may be created by node-canvas.
  27931. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27932. *
  27933. *
  27934. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27935. *
  27936. * @example
  27937. * let Canvas = require('canvas');
  27938. * let echarts = require('echarts');
  27939. * echarts.setCanvasCreator(function () {
  27940. * // Small size is enough.
  27941. * return new Canvas(32, 32);
  27942. * });
  27943. */
  27944. function setCanvasCreator(creator) {
  27945. if ("development" !== 'production') {
  27946. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27947. }
  27948. setPlatformAPI({
  27949. createCanvas: creator
  27950. });
  27951. }
  27952. /**
  27953. * The parameters and usage: see `geoSourceManager.registerMap`.
  27954. * Compatible with previous `echarts.registerMap`.
  27955. */
  27956. function registerMap(mapName, geoJson, specialAreas) {
  27957. var registerMap = getImpl('registerMap');
  27958. registerMap && registerMap(mapName, geoJson, specialAreas);
  27959. }
  27960. function getMap(mapName) {
  27961. var getMap = getImpl('getMap');
  27962. return getMap && getMap(mapName);
  27963. }
  27964. var registerTransform = registerExternalTransform;
  27965. /**
  27966. * Globa dispatchAction to a specified chart instance.
  27967. */
  27968. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27969. // if (!payload || !payload.chartId) {
  27970. // // Must have chartId to find chart
  27971. // return;
  27972. // }
  27973. // const chart = instances[payload.chartId];
  27974. // if (chart) {
  27975. // chart.dispatchAction(payload, opt);
  27976. // }
  27977. // }
  27978. // Builtin global visual
  27979. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27980. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27981. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27982. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27983. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27984. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27985. registerPreprocessor(globalBackwardCompat);
  27986. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27987. registerLoading('default', defaultLoading);
  27988. // Default actions
  27989. registerAction({
  27990. type: HIGHLIGHT_ACTION_TYPE,
  27991. event: HIGHLIGHT_ACTION_TYPE,
  27992. update: HIGHLIGHT_ACTION_TYPE
  27993. }, noop);
  27994. registerAction({
  27995. type: DOWNPLAY_ACTION_TYPE,
  27996. event: DOWNPLAY_ACTION_TYPE,
  27997. update: DOWNPLAY_ACTION_TYPE
  27998. }, noop);
  27999. registerAction({
  28000. type: SELECT_ACTION_TYPE,
  28001. event: SELECT_ACTION_TYPE,
  28002. update: SELECT_ACTION_TYPE
  28003. }, noop);
  28004. registerAction({
  28005. type: UNSELECT_ACTION_TYPE,
  28006. event: UNSELECT_ACTION_TYPE,
  28007. update: UNSELECT_ACTION_TYPE
  28008. }, noop);
  28009. registerAction({
  28010. type: TOGGLE_SELECT_ACTION_TYPE,
  28011. event: TOGGLE_SELECT_ACTION_TYPE,
  28012. update: TOGGLE_SELECT_ACTION_TYPE
  28013. }, noop);
  28014. // Default theme
  28015. registerTheme('light', lightTheme);
  28016. registerTheme('dark', theme);
  28017. // For backward compatibility, where the namespace `dataTool` will
  28018. // be mounted on `echarts` is the extension `dataTool` is imported.
  28019. var dataTool = {};
  28020. var extensions = [];
  28021. var extensionRegisters = {
  28022. registerPreprocessor: registerPreprocessor,
  28023. registerProcessor: registerProcessor,
  28024. registerPostInit: registerPostInit,
  28025. registerPostUpdate: registerPostUpdate,
  28026. registerUpdateLifecycle: registerUpdateLifecycle,
  28027. registerAction: registerAction,
  28028. registerCoordinateSystem: registerCoordinateSystem,
  28029. registerLayout: registerLayout,
  28030. registerVisual: registerVisual,
  28031. registerTransform: registerTransform,
  28032. registerLoading: registerLoading,
  28033. registerMap: registerMap,
  28034. registerImpl: registerImpl,
  28035. PRIORITY: PRIORITY,
  28036. ComponentModel: ComponentModel,
  28037. ComponentView: ComponentView,
  28038. SeriesModel: SeriesModel,
  28039. ChartView: ChartView,
  28040. // TODO Use ComponentModel and SeriesModel instead of Constructor
  28041. registerComponentModel: function (ComponentModelClass) {
  28042. ComponentModel.registerClass(ComponentModelClass);
  28043. },
  28044. registerComponentView: function (ComponentViewClass) {
  28045. ComponentView.registerClass(ComponentViewClass);
  28046. },
  28047. registerSeriesModel: function (SeriesModelClass) {
  28048. SeriesModel.registerClass(SeriesModelClass);
  28049. },
  28050. registerChartView: function (ChartViewClass) {
  28051. ChartView.registerClass(ChartViewClass);
  28052. },
  28053. registerSubTypeDefaulter: function (componentType, defaulter) {
  28054. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  28055. },
  28056. registerPainter: function (painterType, PainterCtor) {
  28057. registerPainter(painterType, PainterCtor);
  28058. }
  28059. };
  28060. function use(ext) {
  28061. if (isArray(ext)) {
  28062. // use([ChartLine, ChartBar]);
  28063. each(ext, function (singleExt) {
  28064. use(singleExt);
  28065. });
  28066. return;
  28067. }
  28068. if (indexOf(extensions, ext) >= 0) {
  28069. return;
  28070. }
  28071. extensions.push(ext);
  28072. if (isFunction(ext)) {
  28073. ext = {
  28074. install: ext
  28075. };
  28076. }
  28077. ext.install(extensionRegisters);
  28078. }
  28079. /*
  28080. * Licensed to the Apache Software Foundation (ASF) under one
  28081. * or more contributor license agreements. See the NOTICE file
  28082. * distributed with this work for additional information
  28083. * regarding copyright ownership. The ASF licenses this file
  28084. * to you under the Apache License, Version 2.0 (the
  28085. * "License"); you may not use this file except in compliance
  28086. * with the License. You may obtain a copy of the License at
  28087. *
  28088. * http://www.apache.org/licenses/LICENSE-2.0
  28089. *
  28090. * Unless required by applicable law or agreed to in writing,
  28091. * software distributed under the License is distributed on an
  28092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28093. * KIND, either express or implied. See the License for the
  28094. * specific language governing permissions and limitations
  28095. * under the License.
  28096. */
  28097. /**
  28098. * AUTO-GENERATED FILE. DO NOT MODIFY.
  28099. */
  28100. /*
  28101. * Licensed to the Apache Software Foundation (ASF) under one
  28102. * or more contributor license agreements. See the NOTICE file
  28103. * distributed with this work for additional information
  28104. * regarding copyright ownership. The ASF licenses this file
  28105. * to you under the Apache License, Version 2.0 (the
  28106. * "License"); you may not use this file except in compliance
  28107. * with the License. You may obtain a copy of the License at
  28108. *
  28109. * http://www.apache.org/licenses/LICENSE-2.0
  28110. *
  28111. * Unless required by applicable law or agreed to in writing,
  28112. * software distributed under the License is distributed on an
  28113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28114. * KIND, either express or implied. See the License for the
  28115. * specific language governing permissions and limitations
  28116. * under the License.
  28117. */
  28118. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  28119. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  28120. }
  28121. function defaultKeyGetter(item) {
  28122. return item;
  28123. }
  28124. var DataDiffer = /** @class */function () {
  28125. /**
  28126. * @param context Can be visited by this.context in callback.
  28127. */
  28128. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context,
  28129. // By default: 'oneToOne'.
  28130. diffMode) {
  28131. this._old = oldArr;
  28132. this._new = newArr;
  28133. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  28134. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  28135. // Visible in callback via `this.context`;
  28136. this.context = context;
  28137. this._diffModeMultiple = diffMode === 'multiple';
  28138. }
  28139. /**
  28140. * Callback function when add a data
  28141. */
  28142. DataDiffer.prototype.add = function (func) {
  28143. this._add = func;
  28144. return this;
  28145. };
  28146. /**
  28147. * Callback function when update a data
  28148. */
  28149. DataDiffer.prototype.update = function (func) {
  28150. this._update = func;
  28151. return this;
  28152. };
  28153. /**
  28154. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28155. */
  28156. DataDiffer.prototype.updateManyToOne = function (func) {
  28157. this._updateManyToOne = func;
  28158. return this;
  28159. };
  28160. /**
  28161. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28162. */
  28163. DataDiffer.prototype.updateOneToMany = function (func) {
  28164. this._updateOneToMany = func;
  28165. return this;
  28166. };
  28167. /**
  28168. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28169. */
  28170. DataDiffer.prototype.updateManyToMany = function (func) {
  28171. this._updateManyToMany = func;
  28172. return this;
  28173. };
  28174. /**
  28175. * Callback function when remove a data
  28176. */
  28177. DataDiffer.prototype.remove = function (func) {
  28178. this._remove = func;
  28179. return this;
  28180. };
  28181. DataDiffer.prototype.execute = function () {
  28182. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  28183. };
  28184. DataDiffer.prototype._executeOneToOne = function () {
  28185. var oldArr = this._old;
  28186. var newArr = this._new;
  28187. var newDataIndexMap = {};
  28188. var oldDataKeyArr = new Array(oldArr.length);
  28189. var newDataKeyArr = new Array(newArr.length);
  28190. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  28191. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28192. for (var i = 0; i < oldArr.length; i++) {
  28193. var oldKey = oldDataKeyArr[i];
  28194. var newIdxMapVal = newDataIndexMap[oldKey];
  28195. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28196. // idx can never be empty array here. see 'set null' logic below.
  28197. if (newIdxMapValLen > 1) {
  28198. // Consider there is duplicate key (for example, use dataItem.name as key).
  28199. // We should make sure every item in newArr and oldArr can be visited.
  28200. var newIdx = newIdxMapVal.shift();
  28201. if (newIdxMapVal.length === 1) {
  28202. newDataIndexMap[oldKey] = newIdxMapVal[0];
  28203. }
  28204. this._update && this._update(newIdx, i);
  28205. } else if (newIdxMapValLen === 1) {
  28206. newDataIndexMap[oldKey] = null;
  28207. this._update && this._update(newIdxMapVal, i);
  28208. } else {
  28209. this._remove && this._remove(i);
  28210. }
  28211. }
  28212. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  28213. };
  28214. /**
  28215. * For example, consider the case:
  28216. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  28217. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  28218. * Where:
  28219. * o0, o1, n0 has key 'a' (many to one)
  28220. * o5, n4, n5, n6 has key 'b' (one to many)
  28221. * o2, n1 has key 'c' (one to one)
  28222. * n2, n3 has key 'd' (add)
  28223. * o3, o4 has key 'e' (remove)
  28224. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  28225. * Then:
  28226. * (The order of the following directives are not ensured.)
  28227. * this._updateManyToOne(n0, [o0, o1]);
  28228. * this._updateOneToMany([n4, n5, n6], o5);
  28229. * this._update(n1, o2);
  28230. * this._remove(o3);
  28231. * this._remove(o4);
  28232. * this._remove(o6);
  28233. * this._remove(o7);
  28234. * this._add(n2);
  28235. * this._add(n3);
  28236. * this._add(n7);
  28237. * this._add(n8);
  28238. */
  28239. DataDiffer.prototype._executeMultiple = function () {
  28240. var oldArr = this._old;
  28241. var newArr = this._new;
  28242. var oldDataIndexMap = {};
  28243. var newDataIndexMap = {};
  28244. var oldDataKeyArr = [];
  28245. var newDataKeyArr = [];
  28246. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  28247. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28248. for (var i = 0; i < oldDataKeyArr.length; i++) {
  28249. var oldKey = oldDataKeyArr[i];
  28250. var oldIdxMapVal = oldDataIndexMap[oldKey];
  28251. var newIdxMapVal = newDataIndexMap[oldKey];
  28252. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  28253. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28254. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  28255. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  28256. newDataIndexMap[oldKey] = null;
  28257. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  28258. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  28259. newDataIndexMap[oldKey] = null;
  28260. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  28261. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  28262. newDataIndexMap[oldKey] = null;
  28263. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  28264. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  28265. newDataIndexMap[oldKey] = null;
  28266. } else if (oldIdxMapValLen > 1) {
  28267. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  28268. this._remove && this._remove(oldIdxMapVal[i_1]);
  28269. }
  28270. } else {
  28271. this._remove && this._remove(oldIdxMapVal);
  28272. }
  28273. }
  28274. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  28275. };
  28276. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  28277. for (var i = 0; i < newDataKeyArr.length; i++) {
  28278. var newKey = newDataKeyArr[i];
  28279. var newIdxMapVal = newDataIndexMap[newKey];
  28280. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28281. if (idxMapValLen > 1) {
  28282. for (var j = 0; j < idxMapValLen; j++) {
  28283. this._add && this._add(newIdxMapVal[j]);
  28284. }
  28285. } else if (idxMapValLen === 1) {
  28286. this._add && this._add(newIdxMapVal);
  28287. }
  28288. // Support both `newDataKeyArr` are duplication removed or not removed.
  28289. newDataIndexMap[newKey] = null;
  28290. }
  28291. };
  28292. DataDiffer.prototype._initIndexMap = function (arr,
  28293. // Can be null.
  28294. map,
  28295. // In 'byKey', the output `keyArr` is duplication removed.
  28296. // In 'byIndex', the output `keyArr` is not duplication removed and
  28297. // its indices are accurately corresponding to `arr`.
  28298. keyArr, keyGetterName) {
  28299. var cbModeMultiple = this._diffModeMultiple;
  28300. for (var i = 0; i < arr.length; i++) {
  28301. // Add prefix to avoid conflict with Object.prototype.
  28302. var key = '_ec_' + this[keyGetterName](arr[i], i);
  28303. if (!cbModeMultiple) {
  28304. keyArr[i] = key;
  28305. }
  28306. if (!map) {
  28307. continue;
  28308. }
  28309. var idxMapVal = map[key];
  28310. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  28311. if (idxMapValLen === 0) {
  28312. // Simple optimize: in most cases, one index has one key,
  28313. // do not need array.
  28314. map[key] = i;
  28315. if (cbModeMultiple) {
  28316. keyArr.push(key);
  28317. }
  28318. } else if (idxMapValLen === 1) {
  28319. map[key] = [idxMapVal, i];
  28320. } else {
  28321. idxMapVal.push(i);
  28322. }
  28323. }
  28324. };
  28325. return DataDiffer;
  28326. }();
  28327. var DimensionUserOuput = /** @class */function () {
  28328. function DimensionUserOuput(encode, dimRequest) {
  28329. this._encode = encode;
  28330. this._schema = dimRequest;
  28331. }
  28332. DimensionUserOuput.prototype.get = function () {
  28333. return {
  28334. // Do not generate full dimension name until fist used.
  28335. fullDimensions: this._getFullDimensionNames(),
  28336. encode: this._encode
  28337. };
  28338. };
  28339. /**
  28340. * Get all data store dimension names.
  28341. * Theoretically a series data store is defined both by series and used dataset (if any).
  28342. * If some dimensions are omitted for performance reason in `this.dimensions`,
  28343. * the dimension name may not be auto-generated if user does not specify a dimension name.
  28344. * In this case, the dimension name is `null`/`undefined`.
  28345. */
  28346. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  28347. if (!this._cachedDimNames) {
  28348. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  28349. }
  28350. return this._cachedDimNames;
  28351. };
  28352. return DimensionUserOuput;
  28353. }();
  28354. function summarizeDimensions(data, schema) {
  28355. var summary = {};
  28356. var encode = summary.encode = {};
  28357. var notExtraCoordDimMap = createHashMap();
  28358. var defaultedLabel = [];
  28359. var defaultedTooltip = [];
  28360. var userOutputEncode = {};
  28361. each(data.dimensions, function (dimName) {
  28362. var dimItem = data.getDimensionInfo(dimName);
  28363. var coordDim = dimItem.coordDim;
  28364. if (coordDim) {
  28365. if ("development" !== 'production') {
  28366. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  28367. }
  28368. var coordDimIndex = dimItem.coordDimIndex;
  28369. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  28370. if (!dimItem.isExtraCoord) {
  28371. notExtraCoordDimMap.set(coordDim, 1);
  28372. // Use the last coord dim (and label friendly) as default label,
  28373. // because when dataset is used, it is hard to guess which dimension
  28374. // can be value dimension. If both show x, y on label is not look good,
  28375. // and conventionally y axis is focused more.
  28376. if (mayLabelDimType(dimItem.type)) {
  28377. defaultedLabel[0] = dimName;
  28378. }
  28379. // User output encode do not contain generated coords.
  28380. // And it only has index. User can use index to retrieve value from the raw item array.
  28381. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  28382. }
  28383. if (dimItem.defaultTooltip) {
  28384. defaultedTooltip.push(dimName);
  28385. }
  28386. }
  28387. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  28388. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  28389. var dimIndex = dimItem.otherDims[otherDim];
  28390. if (dimIndex != null && dimIndex !== false) {
  28391. encodeArr[dimIndex] = dimItem.name;
  28392. }
  28393. });
  28394. });
  28395. var dataDimsOnCoord = [];
  28396. var encodeFirstDimNotExtra = {};
  28397. notExtraCoordDimMap.each(function (v, coordDim) {
  28398. var dimArr = encode[coordDim];
  28399. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  28400. // Not necessary to remove duplicate, because a data
  28401. // dim canot on more than one coordDim.
  28402. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  28403. });
  28404. summary.dataDimsOnCoord = dataDimsOnCoord;
  28405. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  28406. return data.getDimensionInfo(dimName).storeDimIndex;
  28407. });
  28408. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  28409. var encodeLabel = encode.label;
  28410. // FIXME `encode.label` is not recommended, because formatter cannot be set
  28411. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  28412. if (encodeLabel && encodeLabel.length) {
  28413. defaultedLabel = encodeLabel.slice();
  28414. }
  28415. var encodeTooltip = encode.tooltip;
  28416. if (encodeTooltip && encodeTooltip.length) {
  28417. defaultedTooltip = encodeTooltip.slice();
  28418. } else if (!defaultedTooltip.length) {
  28419. defaultedTooltip = defaultedLabel.slice();
  28420. }
  28421. encode.defaultedLabel = defaultedLabel;
  28422. encode.defaultedTooltip = defaultedTooltip;
  28423. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  28424. return summary;
  28425. }
  28426. function getOrCreateEncodeArr(encode, dim) {
  28427. if (!encode.hasOwnProperty(dim)) {
  28428. encode[dim] = [];
  28429. }
  28430. return encode[dim];
  28431. }
  28432. // FIXME:TS should be type `AxisType`
  28433. function getDimensionTypeByAxis(axisType) {
  28434. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  28435. }
  28436. function mayLabelDimType(dimType) {
  28437. // In most cases, ordinal and time do not suitable for label.
  28438. // Ordinal info can be displayed on axis. Time is too long.
  28439. return !(dimType === 'ordinal' || dimType === 'time');
  28440. }
  28441. // function findTheLastDimMayLabel(data) {
  28442. // // Get last value dim
  28443. // let dimensions = data.dimensions.slice();
  28444. // let valueType;
  28445. // let valueDim;
  28446. // while (dimensions.length && (
  28447. // valueDim = dimensions.pop(),
  28448. // valueType = data.getDimensionInfo(valueDim).type,
  28449. // valueType === 'ordinal' || valueType === 'time'
  28450. // )) {} // jshint ignore:line
  28451. // return valueDim;
  28452. // }
  28453. var SeriesDimensionDefine = /** @class */function () {
  28454. /**
  28455. * @param opt All of the fields will be shallow copied.
  28456. */
  28457. function SeriesDimensionDefine(opt) {
  28458. /**
  28459. * The format of `otherDims` is:
  28460. * ```js
  28461. * {
  28462. * tooltip?: number
  28463. * label?: number
  28464. * itemName?: number
  28465. * seriesName?: number
  28466. * }
  28467. * ```
  28468. *
  28469. * A `series.encode` can specified these fields:
  28470. * ```js
  28471. * encode: {
  28472. * // "3, 1, 5" is the index of data dimension.
  28473. * tooltip: [3, 1, 5],
  28474. * label: [0, 3],
  28475. * ...
  28476. * }
  28477. * ```
  28478. * `otherDims` is the parse result of the `series.encode` above, like:
  28479. * ```js
  28480. * // Suppose the index of this data dimension is `3`.
  28481. * this.otherDims = {
  28482. * // `3` is at the index `0` of the `encode.tooltip`
  28483. * tooltip: 0,
  28484. * // `3` is at the index `1` of the `encode.label`
  28485. * label: 1
  28486. * };
  28487. * ```
  28488. *
  28489. * This prop should never be `null`/`undefined` after initialized.
  28490. */
  28491. this.otherDims = {};
  28492. if (opt != null) {
  28493. extend(this, opt);
  28494. }
  28495. }
  28496. return SeriesDimensionDefine;
  28497. }();
  28498. var inner$4 = makeInner();
  28499. var dimTypeShort = {
  28500. float: 'f',
  28501. int: 'i',
  28502. ordinal: 'o',
  28503. number: 'n',
  28504. time: 't'
  28505. };
  28506. /**
  28507. * Represents the dimension requirement of a series.
  28508. *
  28509. * NOTICE:
  28510. * When there are too many dimensions in dataset and many series, only the used dimensions
  28511. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  28512. * But users may query data by other unused dimension names.
  28513. * In this case, users can only query data if and only if they have defined dimension names
  28514. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  28515. * `source` dimensions.
  28516. */
  28517. var SeriesDataSchema = /** @class */function () {
  28518. function SeriesDataSchema(opt) {
  28519. this.dimensions = opt.dimensions;
  28520. this._dimOmitted = opt.dimensionOmitted;
  28521. this.source = opt.source;
  28522. this._fullDimCount = opt.fullDimensionCount;
  28523. this._updateDimOmitted(opt.dimensionOmitted);
  28524. }
  28525. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  28526. return this._dimOmitted;
  28527. };
  28528. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  28529. this._dimOmitted = dimensionOmitted;
  28530. if (!dimensionOmitted) {
  28531. return;
  28532. }
  28533. if (!this._dimNameMap) {
  28534. this._dimNameMap = ensureSourceDimNameMap(this.source);
  28535. }
  28536. };
  28537. /**
  28538. * @caution Can only be used when `dimensionOmitted: true`.
  28539. *
  28540. * Get index by user defined dimension name (i.e., not internal generate name).
  28541. * That is, get index from `dimensionsDefine`.
  28542. * If no `dimensionsDefine`, or no name get, return -1.
  28543. */
  28544. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  28545. return retrieve2(this._dimNameMap.get(dimName), -1);
  28546. };
  28547. /**
  28548. * @caution Can only be used when `dimensionOmitted: true`.
  28549. *
  28550. * Notice: may return `null`/`undefined` if user not specify dimension names.
  28551. */
  28552. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  28553. var dimensionsDefine = this.source.dimensionsDefine;
  28554. if (dimensionsDefine) {
  28555. return dimensionsDefine[dimIndex];
  28556. }
  28557. };
  28558. SeriesDataSchema.prototype.makeStoreSchema = function () {
  28559. var dimCount = this._fullDimCount;
  28560. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  28561. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount);
  28562. // If source don't have dimensions or series don't omit unsed dimensions.
  28563. // Generate from seriesDimList directly
  28564. var dimHash = '';
  28565. var dims = [];
  28566. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  28567. var property = void 0;
  28568. var type = void 0;
  28569. var ordinalMeta = void 0;
  28570. var seriesDimDef = this.dimensions[seriesDimIdx];
  28571. // The list has been sorted by `storeDimIndex` asc.
  28572. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28573. property = willRetrieveDataByName ? seriesDimDef.name : null;
  28574. type = seriesDimDef.type;
  28575. ordinalMeta = seriesDimDef.ordinalMeta;
  28576. seriesDimIdx++;
  28577. } else {
  28578. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28579. if (sourceDimDef) {
  28580. property = willRetrieveDataByName ? sourceDimDef.name : null;
  28581. type = sourceDimDef.type;
  28582. }
  28583. }
  28584. dims.push({
  28585. property: property,
  28586. type: type,
  28587. ordinalMeta: ordinalMeta
  28588. });
  28589. // If retrieving data by index,
  28590. // use <index, type, ordinalMeta> to determine whether data can be shared.
  28591. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  28592. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  28593. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  28594. // use <property, type, ordinalMeta> in hash.
  28595. if (willRetrieveDataByName && property != null
  28596. // For data stack, we have make sure each series has its own dim on this store.
  28597. // So we do not add property to hash to make sure they can share this store.
  28598. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  28599. dimHash += makeHashStrict
  28600. // Use escape character '`' in case that property name contains '$'.
  28601. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2')
  28602. // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  28603. : property;
  28604. }
  28605. dimHash += '$';
  28606. dimHash += dimTypeShort[type] || 'f';
  28607. if (ordinalMeta) {
  28608. dimHash += ordinalMeta.uid;
  28609. }
  28610. dimHash += '$';
  28611. }
  28612. // Source from endpoint(usually series) will be read differently
  28613. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  28614. // So we use this three props as key.
  28615. var source = this.source;
  28616. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  28617. return {
  28618. dimensions: dims,
  28619. hash: hash
  28620. };
  28621. };
  28622. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  28623. var result = [];
  28624. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  28625. var name_1 = void 0;
  28626. var seriesDimDef = this.dimensions[seriesDimIdx];
  28627. // The list has been sorted by `storeDimIndex` asc.
  28628. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28629. if (!seriesDimDef.isCalculationCoord) {
  28630. name_1 = seriesDimDef.name;
  28631. }
  28632. seriesDimIdx++;
  28633. } else {
  28634. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28635. if (sourceDimDef) {
  28636. name_1 = sourceDimDef.name;
  28637. }
  28638. }
  28639. result.push(name_1);
  28640. }
  28641. return result;
  28642. };
  28643. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  28644. this.dimensions.push(dimDef);
  28645. dimDef.isCalculationCoord = true;
  28646. this._fullDimCount++;
  28647. // If append dimension on a data store, consider the store
  28648. // might be shared by different series, series dimensions not
  28649. // really map to store dimensions.
  28650. this._updateDimOmitted(true);
  28651. };
  28652. return SeriesDataSchema;
  28653. }();
  28654. function isSeriesDataSchema(schema) {
  28655. return schema instanceof SeriesDataSchema;
  28656. }
  28657. function createDimNameMap(dimsDef) {
  28658. var dataDimNameMap = createHashMap();
  28659. for (var i = 0; i < (dimsDef || []).length; i++) {
  28660. var dimDefItemRaw = dimsDef[i];
  28661. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  28662. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28663. dataDimNameMap.set(userDimName, i);
  28664. }
  28665. }
  28666. return dataDimNameMap;
  28667. }
  28668. function ensureSourceDimNameMap(source) {
  28669. var innerSource = inner$4(source);
  28670. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  28671. }
  28672. function shouldOmitUnusedDimensions(dimCount) {
  28673. return dimCount > 30;
  28674. }
  28675. var isObject$2 = isObject;
  28676. var map$1 = map;
  28677. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array;
  28678. // Use prefix to avoid index to be the same as otherIdList[idx],
  28679. // which will cause weird update animation.
  28680. var ID_PREFIX = 'e\0\0';
  28681. var INDEX_NOT_FOUND = -1;
  28682. // type SeriesDimensionIndex = DimensionIndex;
  28683. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28684. var CLONE_PROPERTIES = ['_approximateExtent'];
  28685. // -----------------------------
  28686. // Internal method declarations:
  28687. // -----------------------------
  28688. var prepareInvertedIndex;
  28689. var getId;
  28690. var getIdNameFromStore;
  28691. var normalizeDimensions;
  28692. var transferProperties;
  28693. var cloneListForMapAndSample;
  28694. var makeIdFromName;
  28695. var SeriesData = /** @class */function () {
  28696. /**
  28697. * @param dimensionsInput.dimensions
  28698. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28699. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28700. */
  28701. function SeriesData(dimensionsInput, hostModel) {
  28702. this.type = 'list';
  28703. this._dimOmitted = false;
  28704. this._nameList = [];
  28705. this._idList = [];
  28706. // Models of data option is stored sparse for optimizing memory cost
  28707. // Never used yet (not used yet).
  28708. // private _optionModels: Model[] = [];
  28709. // Global visual properties after visual coding
  28710. this._visual = {};
  28711. // Global layout properties.
  28712. this._layout = {};
  28713. // Item visual properties after visual coding
  28714. this._itemVisuals = [];
  28715. // Item layout properties after layout
  28716. this._itemLayouts = [];
  28717. // Graphic elements
  28718. this._graphicEls = [];
  28719. // key: dim, value: extent
  28720. this._approximateExtent = {};
  28721. this._calculationInfo = {};
  28722. // Having detected that there is data item is non primitive type
  28723. // (in type `OptionDataItemObject`).
  28724. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28725. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28726. this.hasItemOption = false;
  28727. // Methods that create a new list based on this list should be listed here.
  28728. // Notice that those method should `RETURN` the new list.
  28729. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'minmaxDownSample', 'lttbDownSample', 'map'];
  28730. // Methods that change indices of this list should be listed here.
  28731. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28732. this.DOWNSAMPLE_METHODS = ['downSample', 'minmaxDownSample', 'lttbDownSample'];
  28733. var dimensions;
  28734. var assignStoreDimIdx = false;
  28735. if (isSeriesDataSchema(dimensionsInput)) {
  28736. dimensions = dimensionsInput.dimensions;
  28737. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28738. this._schema = dimensionsInput;
  28739. } else {
  28740. assignStoreDimIdx = true;
  28741. dimensions = dimensionsInput;
  28742. }
  28743. dimensions = dimensions || ['x', 'y'];
  28744. var dimensionInfos = {};
  28745. var dimensionNames = [];
  28746. var invertedIndicesMap = {};
  28747. var needsHasOwn = false;
  28748. var emptyObj = {};
  28749. for (var i = 0; i < dimensions.length; i++) {
  28750. // Use the original dimensions[i], where other flag props may exists.
  28751. var dimInfoInput = dimensions[i];
  28752. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28753. name: dimInfoInput
  28754. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28755. var dimensionName = dimensionInfo.name;
  28756. dimensionInfo.type = dimensionInfo.type || 'float';
  28757. if (!dimensionInfo.coordDim) {
  28758. dimensionInfo.coordDim = dimensionName;
  28759. dimensionInfo.coordDimIndex = 0;
  28760. }
  28761. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28762. dimensionNames.push(dimensionName);
  28763. dimensionInfos[dimensionName] = dimensionInfo;
  28764. if (emptyObj[dimensionName] != null) {
  28765. needsHasOwn = true;
  28766. }
  28767. if (dimensionInfo.createInvertedIndices) {
  28768. invertedIndicesMap[dimensionName] = [];
  28769. }
  28770. if (otherDims.itemName === 0) {
  28771. this._nameDimIdx = i;
  28772. }
  28773. if (otherDims.itemId === 0) {
  28774. this._idDimIdx = i;
  28775. }
  28776. if ("development" !== 'production') {
  28777. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28778. }
  28779. if (assignStoreDimIdx) {
  28780. dimensionInfo.storeDimIndex = i;
  28781. }
  28782. }
  28783. this.dimensions = dimensionNames;
  28784. this._dimInfos = dimensionInfos;
  28785. this._initGetDimensionInfo(needsHasOwn);
  28786. this.hostModel = hostModel;
  28787. this._invertedIndicesMap = invertedIndicesMap;
  28788. if (this._dimOmitted) {
  28789. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28790. each(dimensionNames, function (dimName) {
  28791. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28792. });
  28793. }
  28794. }
  28795. /**
  28796. *
  28797. * Get concrete dimension name by dimension name or dimension index.
  28798. * If input a dimension name, do not validate whether the dimension name exits.
  28799. *
  28800. * @caution
  28801. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28802. * Because only those dimensions will have auto-generated dimension names if not
  28803. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28804. *
  28805. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28806. * ```js
  28807. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28808. * ```
  28809. *
  28810. * @return Concrete dim name.
  28811. */
  28812. SeriesData.prototype.getDimension = function (dim) {
  28813. var dimIdx = this._recognizeDimIndex(dim);
  28814. if (dimIdx == null) {
  28815. return dim;
  28816. }
  28817. dimIdx = dim;
  28818. if (!this._dimOmitted) {
  28819. return this.dimensions[dimIdx];
  28820. }
  28821. // Retrieve from series dimension definition because it probably contains
  28822. // generated dimension name (like 'x', 'y').
  28823. var dimName = this._dimIdxToName.get(dimIdx);
  28824. if (dimName != null) {
  28825. return dimName;
  28826. }
  28827. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28828. if (sourceDimDef) {
  28829. return sourceDimDef.name;
  28830. }
  28831. };
  28832. /**
  28833. * Get dimension index in data store. Return -1 if not found.
  28834. * Can be used to index value from getRawValue.
  28835. */
  28836. SeriesData.prototype.getDimensionIndex = function (dim) {
  28837. var dimIdx = this._recognizeDimIndex(dim);
  28838. if (dimIdx != null) {
  28839. return dimIdx;
  28840. }
  28841. if (dim == null) {
  28842. return -1;
  28843. }
  28844. var dimInfo = this._getDimInfo(dim);
  28845. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28846. };
  28847. /**
  28848. * The meanings of the input parameter `dim`:
  28849. *
  28850. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28851. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28852. * + If dim is a number-like string (e.g., `"1"`):
  28853. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28854. * it means that concrete name.
  28855. * + If not, it will be converted to a number, which means the index of the dimension.
  28856. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28857. * dimension setting, although now it seems that it is not a good idea.)
  28858. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28859. * if no dimension name is defined as `"1"`.
  28860. * + If dim is a not-number-like string, it means the concrete dim name.
  28861. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28862. * or customized in `dimensions` property of option like `"age"`.
  28863. *
  28864. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28865. */
  28866. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28867. if (isNumber(dim)
  28868. // If being a number-like string but not being defined as a dimension name.
  28869. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28870. return +dim;
  28871. }
  28872. };
  28873. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28874. var dimIdx = this.getDimensionIndex(dim);
  28875. if ("development" !== 'production') {
  28876. if (dimIdx == null) {
  28877. throw new Error('Unknown dimension ' + dim);
  28878. }
  28879. }
  28880. return dimIdx;
  28881. };
  28882. /**
  28883. * Get type and calculation info of particular dimension
  28884. * @param dim
  28885. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28886. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28887. */
  28888. SeriesData.prototype.getDimensionInfo = function (dim) {
  28889. // Do not clone, because there may be categories in dimInfo.
  28890. return this._getDimInfo(this.getDimension(dim));
  28891. };
  28892. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28893. var dimensionInfos = this._dimInfos;
  28894. this._getDimInfo = needsHasOwn ? function (dimName) {
  28895. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28896. } : function (dimName) {
  28897. return dimensionInfos[dimName];
  28898. };
  28899. };
  28900. /**
  28901. * concrete dimension name list on coord.
  28902. */
  28903. SeriesData.prototype.getDimensionsOnCoord = function () {
  28904. return this._dimSummary.dataDimsOnCoord.slice();
  28905. };
  28906. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28907. var dimensionsSummary = this._dimSummary;
  28908. if (idx == null) {
  28909. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28910. }
  28911. var dims = dimensionsSummary.encode[coordDim];
  28912. return dims ? dims[idx] : null;
  28913. };
  28914. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28915. var dimensionsSummary = this._dimSummary;
  28916. var dims = dimensionsSummary.encode[coordDim];
  28917. return (dims || []).slice();
  28918. };
  28919. SeriesData.prototype.getStore = function () {
  28920. return this._store;
  28921. };
  28922. /**
  28923. * Initialize from data
  28924. * @param data source or data or data store.
  28925. * @param nameList The name of a datum is used on data diff and
  28926. * default label/tooltip.
  28927. * A name can be specified in encode.itemName,
  28928. * or dataItem.name (only for series option data),
  28929. * or provided in nameList from outside.
  28930. */
  28931. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28932. var _this = this;
  28933. var store;
  28934. if (data instanceof DataStore) {
  28935. store = data;
  28936. }
  28937. if (!store) {
  28938. var dimensions = this.dimensions;
  28939. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28940. store = new DataStore();
  28941. var dimensionInfos = map$1(dimensions, function (dimName) {
  28942. return {
  28943. type: _this._dimInfos[dimName].type,
  28944. property: dimName
  28945. };
  28946. });
  28947. store.initData(provider, dimensionInfos, dimValueGetter);
  28948. }
  28949. this._store = store;
  28950. // Reset
  28951. this._nameList = (nameList || []).slice();
  28952. this._idList = [];
  28953. this._nameRepeatCount = {};
  28954. this._doInit(0, store.count());
  28955. // Cache summary info for fast visit. See "dimensionHelper".
  28956. // Needs to be initialized after store is prepared.
  28957. this._dimSummary = summarizeDimensions(this, this._schema);
  28958. this.userOutput = this._dimSummary.userOutput;
  28959. };
  28960. /**
  28961. * Caution: Can be only called on raw data (before `this._indices` created).
  28962. */
  28963. SeriesData.prototype.appendData = function (data) {
  28964. var range = this._store.appendData(data);
  28965. this._doInit(range[0], range[1]);
  28966. };
  28967. /**
  28968. * Caution: Can be only called on raw data (before `this._indices` created).
  28969. * This method does not modify `rawData` (`dataProvider`), but only
  28970. * add values to store.
  28971. *
  28972. * The final count will be increased by `Math.max(values.length, names.length)`.
  28973. *
  28974. * @param values That is the SourceType: 'arrayRows', like
  28975. * [
  28976. * [12, 33, 44],
  28977. * [NaN, 43, 1],
  28978. * ['-', 'asdf', 0]
  28979. * ]
  28980. * Each item is exactly corresponding to a dimension.
  28981. */
  28982. SeriesData.prototype.appendValues = function (values, names) {
  28983. var _a = this._store.appendValues(values, names && names.length),
  28984. start = _a.start,
  28985. end = _a.end;
  28986. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28987. this._updateOrdinalMeta();
  28988. if (names) {
  28989. for (var idx = start; idx < end; idx++) {
  28990. var sourceIdx = idx - start;
  28991. this._nameList[idx] = names[sourceIdx];
  28992. if (shouldMakeIdFromName) {
  28993. makeIdFromName(this, idx);
  28994. }
  28995. }
  28996. }
  28997. };
  28998. SeriesData.prototype._updateOrdinalMeta = function () {
  28999. var store = this._store;
  29000. var dimensions = this.dimensions;
  29001. for (var i = 0; i < dimensions.length; i++) {
  29002. var dimInfo = this._dimInfos[dimensions[i]];
  29003. if (dimInfo.ordinalMeta) {
  29004. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  29005. }
  29006. }
  29007. };
  29008. SeriesData.prototype._shouldMakeIdFromName = function () {
  29009. var provider = this._store.getProvider();
  29010. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  29011. };
  29012. SeriesData.prototype._doInit = function (start, end) {
  29013. if (start >= end) {
  29014. return;
  29015. }
  29016. var store = this._store;
  29017. var provider = store.getProvider();
  29018. this._updateOrdinalMeta();
  29019. var nameList = this._nameList;
  29020. var idList = this._idList;
  29021. var sourceFormat = provider.getSource().sourceFormat;
  29022. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29023. // Each data item is value
  29024. // [1, 2]
  29025. // 2
  29026. // Bar chart, line chart which uses category axis
  29027. // only gives the 'y' value. 'x' value is the indices of category
  29028. // Use a tempValue to normalize the value to be a (x, y) value
  29029. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  29030. // This kind of ids and names are always stored `_nameList` and `_idList`.
  29031. if (isFormatOriginal && !provider.pure) {
  29032. var sharedDataItem = [];
  29033. for (var idx = start; idx < end; idx++) {
  29034. // NOTICE: Try not to write things into dataItem
  29035. var dataItem = provider.getItem(idx, sharedDataItem);
  29036. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  29037. this.hasItemOption = true;
  29038. }
  29039. if (dataItem) {
  29040. var itemName = dataItem.name;
  29041. if (nameList[idx] == null && itemName != null) {
  29042. nameList[idx] = convertOptionIdName(itemName, null);
  29043. }
  29044. var itemId = dataItem.id;
  29045. if (idList[idx] == null && itemId != null) {
  29046. idList[idx] = convertOptionIdName(itemId, null);
  29047. }
  29048. }
  29049. }
  29050. }
  29051. if (this._shouldMakeIdFromName()) {
  29052. for (var idx = start; idx < end; idx++) {
  29053. makeIdFromName(this, idx);
  29054. }
  29055. }
  29056. prepareInvertedIndex(this);
  29057. };
  29058. /**
  29059. * PENDING: In fact currently this function is only used to short-circuit
  29060. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  29061. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  29062. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  29063. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  29064. * But if we add "custom data filter" in future, which is not "axis related", this method may
  29065. * be still needed.
  29066. *
  29067. * Optimize for the scenario that data is filtered by a given extent.
  29068. * Consider that if data amount is more than hundreds of thousand,
  29069. * extent calculation will cost more than 10ms and the cache will
  29070. * be erased because of the filtering.
  29071. */
  29072. SeriesData.prototype.getApproximateExtent = function (dim) {
  29073. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  29074. };
  29075. /**
  29076. * Calculate extent on a filtered data might be time consuming.
  29077. * Approximate extent is only used for: calculate extent of filtered data outside.
  29078. */
  29079. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  29080. dim = this.getDimension(dim);
  29081. this._approximateExtent[dim] = extent.slice();
  29082. };
  29083. SeriesData.prototype.getCalculationInfo = function (key) {
  29084. return this._calculationInfo[key];
  29085. };
  29086. SeriesData.prototype.setCalculationInfo = function (key, value) {
  29087. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  29088. };
  29089. /**
  29090. * @return Never be null/undefined. `number` will be converted to string. Because:
  29091. * In most cases, name is used in display, where returning a string is more convenient.
  29092. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  29093. * rule that name `2` equals to name `'2'`.
  29094. */
  29095. SeriesData.prototype.getName = function (idx) {
  29096. var rawIndex = this.getRawIndex(idx);
  29097. var name = this._nameList[rawIndex];
  29098. if (name == null && this._nameDimIdx != null) {
  29099. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  29100. }
  29101. if (name == null) {
  29102. name = '';
  29103. }
  29104. return name;
  29105. };
  29106. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  29107. var ordinal = this._store.get(dimIdx, idx);
  29108. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  29109. if (ordinalMeta) {
  29110. return ordinalMeta.categories[ordinal];
  29111. }
  29112. return ordinal;
  29113. };
  29114. /**
  29115. * @return Never null/undefined. `number` will be converted to string. Because:
  29116. * In all cases having encountered at present, id is used in making diff comparison, which
  29117. * are usually based on hash map. We can keep the rule that the internal id are always string
  29118. * (treat `2` is the same as `'2'`) to make the related logic simple.
  29119. */
  29120. SeriesData.prototype.getId = function (idx) {
  29121. return getId(this, this.getRawIndex(idx));
  29122. };
  29123. SeriesData.prototype.count = function () {
  29124. return this._store.count();
  29125. };
  29126. /**
  29127. * Get value. Return NaN if idx is out of range.
  29128. *
  29129. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  29130. */
  29131. SeriesData.prototype.get = function (dim, idx) {
  29132. var store = this._store;
  29133. var dimInfo = this._dimInfos[dim];
  29134. if (dimInfo) {
  29135. return store.get(dimInfo.storeDimIndex, idx);
  29136. }
  29137. };
  29138. /**
  29139. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  29140. */
  29141. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  29142. var store = this._store;
  29143. var dimInfo = this._dimInfos[dim];
  29144. if (dimInfo) {
  29145. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  29146. }
  29147. };
  29148. SeriesData.prototype.getIndices = function () {
  29149. return this._store.getIndices();
  29150. };
  29151. SeriesData.prototype.getDataExtent = function (dim) {
  29152. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  29153. };
  29154. SeriesData.prototype.getSum = function (dim) {
  29155. return this._store.getSum(this._getStoreDimIndex(dim));
  29156. };
  29157. SeriesData.prototype.getMedian = function (dim) {
  29158. return this._store.getMedian(this._getStoreDimIndex(dim));
  29159. };
  29160. SeriesData.prototype.getValues = function (dimensions, idx) {
  29161. var _this = this;
  29162. var store = this._store;
  29163. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  29164. return _this._getStoreDimIndex(dim);
  29165. }), idx) : store.getValues(dimensions);
  29166. };
  29167. /**
  29168. * If value is NaN. Including '-'
  29169. * Only check the coord dimensions.
  29170. */
  29171. SeriesData.prototype.hasValue = function (idx) {
  29172. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  29173. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  29174. // Ordinal type originally can be string or number.
  29175. // But when an ordinal type is used on coord, it can
  29176. // not be string but only number. So we can also use isNaN.
  29177. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  29178. return false;
  29179. }
  29180. }
  29181. return true;
  29182. };
  29183. /**
  29184. * Retrieve the index with given name
  29185. */
  29186. SeriesData.prototype.indexOfName = function (name) {
  29187. for (var i = 0, len = this._store.count(); i < len; i++) {
  29188. if (this.getName(i) === name) {
  29189. return i;
  29190. }
  29191. }
  29192. return -1;
  29193. };
  29194. SeriesData.prototype.getRawIndex = function (idx) {
  29195. return this._store.getRawIndex(idx);
  29196. };
  29197. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  29198. return this._store.indexOfRawIndex(rawIndex);
  29199. };
  29200. /**
  29201. * Only support the dimension which inverted index created.
  29202. * Do not support other cases until required.
  29203. * @param dim concrete dim
  29204. * @param value ordinal index
  29205. * @return rawIndex
  29206. */
  29207. SeriesData.prototype.rawIndexOf = function (dim, value) {
  29208. var invertedIndices = dim && this._invertedIndicesMap[dim];
  29209. if ("development" !== 'production') {
  29210. if (!invertedIndices) {
  29211. throw new Error('Do not supported yet');
  29212. }
  29213. }
  29214. var rawIndex = invertedIndices && invertedIndices[value];
  29215. if (rawIndex == null || isNaN(rawIndex)) {
  29216. return INDEX_NOT_FOUND;
  29217. }
  29218. return rawIndex;
  29219. };
  29220. /**
  29221. * Retrieve the index of nearest value
  29222. * @param dim
  29223. * @param value
  29224. * @param [maxDistance=Infinity]
  29225. * @return If and only if multiple indices has
  29226. * the same value, they are put to the result.
  29227. */
  29228. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  29229. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  29230. };
  29231. SeriesData.prototype.each = function (dims, cb, ctx) {
  29232. if (isFunction(dims)) {
  29233. ctx = cb;
  29234. cb = dims;
  29235. dims = [];
  29236. }
  29237. // ctxCompat just for compat echarts3
  29238. var fCtx = ctx || this;
  29239. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29240. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29241. };
  29242. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  29243. if (isFunction(dims)) {
  29244. ctx = cb;
  29245. cb = dims;
  29246. dims = [];
  29247. }
  29248. // ctxCompat just for compat echarts3
  29249. var fCtx = ctx || this;
  29250. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29251. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29252. return this;
  29253. };
  29254. /**
  29255. * Select data in range. (For optimization of filter)
  29256. * (Manually inline code, support 5 million data filtering in data zoom.)
  29257. */
  29258. SeriesData.prototype.selectRange = function (range) {
  29259. var _this = this;
  29260. var innerRange = {};
  29261. var dims = keys(range);
  29262. each(dims, function (dim) {
  29263. var dimIdx = _this._getStoreDimIndex(dim);
  29264. innerRange[dimIdx] = range[dim];
  29265. });
  29266. this._store = this._store.selectRange(innerRange);
  29267. return this;
  29268. };
  29269. /* eslint-enable max-len */
  29270. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  29271. if (isFunction(dims)) {
  29272. ctx = cb;
  29273. cb = dims;
  29274. dims = [];
  29275. }
  29276. // ctxCompat just for compat echarts3
  29277. ctx = ctx || this;
  29278. var result = [];
  29279. this.each(dims, function () {
  29280. result.push(cb && cb.apply(this, arguments));
  29281. }, ctx);
  29282. return result;
  29283. };
  29284. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  29285. // ctxCompat just for compat echarts3
  29286. var fCtx = ctx || ctxCompat || this;
  29287. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29288. var list = cloneListForMapAndSample(this);
  29289. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29290. return list;
  29291. };
  29292. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  29293. var _this = this;
  29294. // ctxCompat just for compat echarts3
  29295. var fCtx = ctx || ctxCompat || this;
  29296. if ("development" !== 'production') {
  29297. each(normalizeDimensions(dims), function (dim) {
  29298. var dimInfo = _this.getDimensionInfo(dim);
  29299. if (!dimInfo.isCalculationCoord) {
  29300. console.error('Danger: only stack dimension can be modified');
  29301. }
  29302. });
  29303. }
  29304. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29305. // If do shallow clone here, if there are too many stacked series,
  29306. // it still cost lots of memory, because `_store.dimensions` are not shared.
  29307. // We should consider there probably be shallow clone happen in each series
  29308. // in consequent filter/map.
  29309. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29310. };
  29311. /**
  29312. * Large data down sampling on given dimension
  29313. * @param sampleIndex Sample index for name and id
  29314. */
  29315. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  29316. var list = cloneListForMapAndSample(this);
  29317. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  29318. return list;
  29319. };
  29320. /**
  29321. * Large data down sampling using min-max
  29322. * @param {string} valueDimension
  29323. * @param {number} rate
  29324. */
  29325. SeriesData.prototype.minmaxDownSample = function (valueDimension, rate) {
  29326. var list = cloneListForMapAndSample(this);
  29327. list._store = this._store.minmaxDownSample(this._getStoreDimIndex(valueDimension), rate);
  29328. return list;
  29329. };
  29330. /**
  29331. * Large data down sampling using largest-triangle-three-buckets
  29332. * @param {string} valueDimension
  29333. * @param {number} targetCount
  29334. */
  29335. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  29336. var list = cloneListForMapAndSample(this);
  29337. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  29338. return list;
  29339. };
  29340. SeriesData.prototype.getRawDataItem = function (idx) {
  29341. return this._store.getRawDataItem(idx);
  29342. };
  29343. /**
  29344. * Get model of one data item.
  29345. */
  29346. // TODO: Type of data item
  29347. SeriesData.prototype.getItemModel = function (idx) {
  29348. var hostModel = this.hostModel;
  29349. var dataItem = this.getRawDataItem(idx);
  29350. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  29351. };
  29352. /**
  29353. * Create a data differ
  29354. */
  29355. SeriesData.prototype.diff = function (otherList) {
  29356. var thisList = this;
  29357. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  29358. return getId(otherList, idx);
  29359. }, function (idx) {
  29360. return getId(thisList, idx);
  29361. });
  29362. };
  29363. /**
  29364. * Get visual property.
  29365. */
  29366. SeriesData.prototype.getVisual = function (key) {
  29367. var visual = this._visual;
  29368. return visual && visual[key];
  29369. };
  29370. SeriesData.prototype.setVisual = function (kvObj, val) {
  29371. this._visual = this._visual || {};
  29372. if (isObject$2(kvObj)) {
  29373. extend(this._visual, kvObj);
  29374. } else {
  29375. this._visual[kvObj] = val;
  29376. }
  29377. };
  29378. /**
  29379. * Get visual property of single data item
  29380. */
  29381. // eslint-disable-next-line
  29382. SeriesData.prototype.getItemVisual = function (idx, key) {
  29383. var itemVisual = this._itemVisuals[idx];
  29384. var val = itemVisual && itemVisual[key];
  29385. if (val == null) {
  29386. // Use global visual property
  29387. return this.getVisual(key);
  29388. }
  29389. return val;
  29390. };
  29391. /**
  29392. * If exists visual property of single data item
  29393. */
  29394. SeriesData.prototype.hasItemVisual = function () {
  29395. return this._itemVisuals.length > 0;
  29396. };
  29397. /**
  29398. * Make sure itemVisual property is unique
  29399. */
  29400. // TODO: use key to save visual to reduce memory.
  29401. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  29402. var itemVisuals = this._itemVisuals;
  29403. var itemVisual = itemVisuals[idx];
  29404. if (!itemVisual) {
  29405. itemVisual = itemVisuals[idx] = {};
  29406. }
  29407. var val = itemVisual[key];
  29408. if (val == null) {
  29409. val = this.getVisual(key);
  29410. // TODO Performance?
  29411. if (isArray(val)) {
  29412. val = val.slice();
  29413. } else if (isObject$2(val)) {
  29414. val = extend({}, val);
  29415. }
  29416. itemVisual[key] = val;
  29417. }
  29418. return val;
  29419. };
  29420. // eslint-disable-next-line
  29421. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  29422. var itemVisual = this._itemVisuals[idx] || {};
  29423. this._itemVisuals[idx] = itemVisual;
  29424. if (isObject$2(key)) {
  29425. extend(itemVisual, key);
  29426. } else {
  29427. itemVisual[key] = value;
  29428. }
  29429. };
  29430. /**
  29431. * Clear itemVisuals and list visual.
  29432. */
  29433. SeriesData.prototype.clearAllVisual = function () {
  29434. this._visual = {};
  29435. this._itemVisuals = [];
  29436. };
  29437. SeriesData.prototype.setLayout = function (key, val) {
  29438. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  29439. };
  29440. /**
  29441. * Get layout property.
  29442. */
  29443. SeriesData.prototype.getLayout = function (key) {
  29444. return this._layout[key];
  29445. };
  29446. /**
  29447. * Get layout of single data item
  29448. */
  29449. SeriesData.prototype.getItemLayout = function (idx) {
  29450. return this._itemLayouts[idx];
  29451. };
  29452. /**
  29453. * Set layout of single data item
  29454. */
  29455. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  29456. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  29457. };
  29458. /**
  29459. * Clear all layout of single data item
  29460. */
  29461. SeriesData.prototype.clearItemLayouts = function () {
  29462. this._itemLayouts.length = 0;
  29463. };
  29464. /**
  29465. * Set graphic element relative to data. It can be set as null
  29466. */
  29467. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  29468. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  29469. setCommonECData(seriesIndex, this.dataType, idx, el);
  29470. this._graphicEls[idx] = el;
  29471. };
  29472. SeriesData.prototype.getItemGraphicEl = function (idx) {
  29473. return this._graphicEls[idx];
  29474. };
  29475. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  29476. each(this._graphicEls, function (el, idx) {
  29477. if (el) {
  29478. cb && cb.call(context, el, idx);
  29479. }
  29480. });
  29481. };
  29482. /**
  29483. * Shallow clone a new list except visual and layout properties, and graph elements.
  29484. * New list only change the indices.
  29485. */
  29486. SeriesData.prototype.cloneShallow = function (list) {
  29487. if (!list) {
  29488. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  29489. }
  29490. transferProperties(list, this);
  29491. list._store = this._store;
  29492. return list;
  29493. };
  29494. /**
  29495. * Wrap some method to add more feature
  29496. */
  29497. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  29498. var originalMethod = this[methodName];
  29499. if (!isFunction(originalMethod)) {
  29500. return;
  29501. }
  29502. this.__wrappedMethods = this.__wrappedMethods || [];
  29503. this.__wrappedMethods.push(methodName);
  29504. this[methodName] = function () {
  29505. var res = originalMethod.apply(this, arguments);
  29506. return injectFunction.apply(this, [res].concat(slice(arguments)));
  29507. };
  29508. };
  29509. // ----------------------------------------------------------
  29510. // A work around for internal method visiting private member.
  29511. // ----------------------------------------------------------
  29512. SeriesData.internalField = function () {
  29513. prepareInvertedIndex = function (data) {
  29514. var invertedIndicesMap = data._invertedIndicesMap;
  29515. each(invertedIndicesMap, function (invertedIndices, dim) {
  29516. var dimInfo = data._dimInfos[dim];
  29517. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  29518. var ordinalMeta = dimInfo.ordinalMeta;
  29519. var store = data._store;
  29520. if (ordinalMeta) {
  29521. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length);
  29522. // The default value of TypedArray is 0. To avoid miss
  29523. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  29524. for (var i = 0; i < invertedIndices.length; i++) {
  29525. invertedIndices[i] = INDEX_NOT_FOUND;
  29526. }
  29527. for (var i = 0; i < store.count(); i++) {
  29528. // Only support the case that all values are distinct.
  29529. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  29530. }
  29531. }
  29532. });
  29533. };
  29534. getIdNameFromStore = function (data, dimIdx, idx) {
  29535. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  29536. };
  29537. /**
  29538. * @see the comment of `List['getId']`.
  29539. */
  29540. getId = function (data, rawIndex) {
  29541. var id = data._idList[rawIndex];
  29542. if (id == null && data._idDimIdx != null) {
  29543. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  29544. }
  29545. if (id == null) {
  29546. id = ID_PREFIX + rawIndex;
  29547. }
  29548. return id;
  29549. };
  29550. normalizeDimensions = function (dimensions) {
  29551. if (!isArray(dimensions)) {
  29552. dimensions = dimensions != null ? [dimensions] : [];
  29553. }
  29554. return dimensions;
  29555. };
  29556. /**
  29557. * Data in excludeDimensions is copied, otherwise transferred.
  29558. */
  29559. cloneListForMapAndSample = function (original) {
  29560. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel);
  29561. // FIXME If needs stackedOn, value may already been stacked
  29562. transferProperties(list, original);
  29563. return list;
  29564. };
  29565. transferProperties = function (target, source) {
  29566. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  29567. if (source.hasOwnProperty(propName)) {
  29568. target[propName] = source[propName];
  29569. }
  29570. });
  29571. target.__wrappedMethods = source.__wrappedMethods;
  29572. each(CLONE_PROPERTIES, function (propName) {
  29573. target[propName] = clone(source[propName]);
  29574. });
  29575. target._calculationInfo = extend({}, source._calculationInfo);
  29576. };
  29577. makeIdFromName = function (data, idx) {
  29578. var nameList = data._nameList;
  29579. var idList = data._idList;
  29580. var nameDimIdx = data._nameDimIdx;
  29581. var idDimIdx = data._idDimIdx;
  29582. var name = nameList[idx];
  29583. var id = idList[idx];
  29584. if (name == null && nameDimIdx != null) {
  29585. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  29586. }
  29587. if (id == null && idDimIdx != null) {
  29588. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  29589. }
  29590. if (id == null && name != null) {
  29591. var nameRepeatCount = data._nameRepeatCount;
  29592. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  29593. id = name;
  29594. if (nmCnt > 1) {
  29595. id += '__ec__' + nmCnt;
  29596. }
  29597. idList[idx] = id;
  29598. }
  29599. };
  29600. }();
  29601. return SeriesData;
  29602. }();
  29603. /**
  29604. * For outside usage compat (like echarts-gl are using it).
  29605. */
  29606. function createDimensions(source, opt) {
  29607. return prepareSeriesDataSchema(source, opt).dimensions;
  29608. }
  29609. /**
  29610. * This method builds the relationship between:
  29611. * + "what the coord sys or series requires (see `coordDimensions`)",
  29612. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  29613. * + "what the data source provids (see `source`)".
  29614. *
  29615. * Some guess strategy will be adapted if user does not define something.
  29616. * If no 'value' dimension specified, the first no-named dimension will be
  29617. * named as 'value'.
  29618. *
  29619. * @return The results are always sorted by `storeDimIndex` asc.
  29620. */
  29621. function prepareSeriesDataSchema(
  29622. // TODO: TYPE completeDimensions type
  29623. source, opt) {
  29624. if (!isSourceInstance(source)) {
  29625. source = createSourceFromSeriesDataOption(source);
  29626. }
  29627. opt = opt || {};
  29628. var sysDims = opt.coordDimensions || [];
  29629. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  29630. var coordDimNameMap = createHashMap();
  29631. var resultList = [];
  29632. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount);
  29633. // Try to ignore unused dimensions if sharing a high dimension datastore
  29634. // 30 is an experience value.
  29635. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  29636. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  29637. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  29638. var encodeDef = opt.encodeDefine;
  29639. if (!encodeDef && opt.encodeDefaulter) {
  29640. encodeDef = opt.encodeDefaulter(source, dimCount);
  29641. }
  29642. var encodeDefMap = createHashMap(encodeDef);
  29643. var indicesMap = new CtorInt32Array(dimCount);
  29644. for (var i = 0; i < indicesMap.length; i++) {
  29645. indicesMap[i] = -1;
  29646. }
  29647. function getResultItem(dimIdx) {
  29648. var idx = indicesMap[dimIdx];
  29649. if (idx < 0) {
  29650. var dimDefItemRaw = dimsDef[dimIdx];
  29651. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  29652. name: dimDefItemRaw
  29653. };
  29654. var resultItem = new SeriesDimensionDefine();
  29655. var userDimName = dimDefItem.name;
  29656. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  29657. // Only if `series.dimensions` is defined in option
  29658. // displayName, will be set, and dimension will be displayed vertically in
  29659. // tooltip by default.
  29660. resultItem.name = resultItem.displayName = userDimName;
  29661. }
  29662. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  29663. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  29664. var newIdx = resultList.length;
  29665. indicesMap[dimIdx] = newIdx;
  29666. resultItem.storeDimIndex = dimIdx;
  29667. resultList.push(resultItem);
  29668. return resultItem;
  29669. }
  29670. return resultList[idx];
  29671. }
  29672. if (!omitUnusedDimensions) {
  29673. for (var i = 0; i < dimCount; i++) {
  29674. getResultItem(i);
  29675. }
  29676. }
  29677. // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  29678. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  29679. var dataDims = normalizeToArray(dataDimsRaw).slice();
  29680. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  29681. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  29682. // this case.
  29683. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  29684. encodeDefMap.set(coordDim, false);
  29685. return;
  29686. }
  29687. var validDataDims = encodeDefMap.set(coordDim, []);
  29688. each(dataDims, function (resultDimIdxOrName, idx) {
  29689. // The input resultDimIdx can be dim name or index.
  29690. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  29691. if (resultDimIdx != null && resultDimIdx < dimCount) {
  29692. validDataDims[idx] = resultDimIdx;
  29693. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  29694. }
  29695. });
  29696. });
  29697. // Apply templates and default order from `sysDims`.
  29698. var availDimIdx = 0;
  29699. each(sysDims, function (sysDimItemRaw) {
  29700. var coordDim;
  29701. var sysDimItemDimsDef;
  29702. var sysDimItemOtherDims;
  29703. var sysDimItem;
  29704. if (isString(sysDimItemRaw)) {
  29705. coordDim = sysDimItemRaw;
  29706. sysDimItem = {};
  29707. } else {
  29708. sysDimItem = sysDimItemRaw;
  29709. coordDim = sysDimItem.name;
  29710. var ordinalMeta = sysDimItem.ordinalMeta;
  29711. sysDimItem.ordinalMeta = null;
  29712. sysDimItem = extend({}, sysDimItem);
  29713. sysDimItem.ordinalMeta = ordinalMeta;
  29714. // `coordDimIndex` should not be set directly.
  29715. sysDimItemDimsDef = sysDimItem.dimsDef;
  29716. sysDimItemOtherDims = sysDimItem.otherDims;
  29717. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  29718. }
  29719. var dataDims = encodeDefMap.get(coordDim);
  29720. // negative resultDimIdx means no need to mapping.
  29721. if (dataDims === false) {
  29722. return;
  29723. }
  29724. dataDims = normalizeToArray(dataDims);
  29725. // dimensions provides default dim sequences.
  29726. if (!dataDims.length) {
  29727. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29728. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29729. availDimIdx++;
  29730. }
  29731. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29732. }
  29733. }
  29734. // Apply templates.
  29735. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29736. var resultItem = getResultItem(resultDimIdx);
  29737. // Coordinate system has a higher priority on dim type than source.
  29738. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29739. resultItem.type = sysDimItem.type;
  29740. }
  29741. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29742. if (resultItem.name == null && sysDimItemDimsDef) {
  29743. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29744. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29745. name: sysDimItemDimsDefItem
  29746. });
  29747. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29748. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29749. }
  29750. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29751. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29752. });
  29753. });
  29754. function applyDim(resultItem, coordDim, coordDimIndex) {
  29755. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29756. resultItem.otherDims[coordDim] = coordDimIndex;
  29757. } else {
  29758. resultItem.coordDim = coordDim;
  29759. resultItem.coordDimIndex = coordDimIndex;
  29760. coordDimNameMap.set(coordDim, true);
  29761. }
  29762. }
  29763. // Make sure the first extra dim is 'value'.
  29764. var generateCoord = opt.generateCoord;
  29765. var generateCoordCount = opt.generateCoordCount;
  29766. var fromZero = generateCoordCount != null;
  29767. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29768. var extra = generateCoord || 'value';
  29769. function ifNoNameFillWithCoordName(resultItem) {
  29770. if (resultItem.name == null) {
  29771. // Duplication will be removed in the next step.
  29772. resultItem.name = resultItem.coordDim;
  29773. }
  29774. }
  29775. // Set dim `name` and other `coordDim` and other props.
  29776. if (!omitUnusedDimensions) {
  29777. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29778. var resultItem = getResultItem(resultDimIdx);
  29779. var coordDim = resultItem.coordDim;
  29780. if (coordDim == null) {
  29781. // TODO no need to generate coordDim for isExtraCoord?
  29782. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29783. resultItem.coordDimIndex = 0;
  29784. // Series specified generateCoord is using out.
  29785. if (!generateCoord || generateCoordCount <= 0) {
  29786. resultItem.isExtraCoord = true;
  29787. }
  29788. generateCoordCount--;
  29789. }
  29790. ifNoNameFillWithCoordName(resultItem);
  29791. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must
  29792. // Consider the case:
  29793. // {
  29794. // dataset: {source: [
  29795. // ['2001', 123],
  29796. // ['2002', 456],
  29797. // ...
  29798. // ['The others', 987],
  29799. // ]},
  29800. // series: {type: 'pie'}
  29801. // }
  29802. // The first column should better be treated as a "ordinal" although it
  29803. // might not be detected as an "ordinal" by `guessOrdinal`.
  29804. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29805. resultItem.type = 'ordinal';
  29806. }
  29807. }
  29808. } else {
  29809. each(resultList, function (resultItem) {
  29810. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29811. ifNoNameFillWithCoordName(resultItem);
  29812. });
  29813. // Sort dimensions: there are some rule that use the last dim as label,
  29814. // and for some latter travel process easier.
  29815. resultList.sort(function (item0, item1) {
  29816. return item0.storeDimIndex - item1.storeDimIndex;
  29817. });
  29818. }
  29819. removeDuplication(resultList);
  29820. return new SeriesDataSchema({
  29821. source: source,
  29822. dimensions: resultList,
  29823. fullDimensionCount: dimCount,
  29824. dimensionOmitted: omitUnusedDimensions
  29825. });
  29826. }
  29827. function removeDuplication(result) {
  29828. var duplicationMap = createHashMap();
  29829. for (var i = 0; i < result.length; i++) {
  29830. var dim = result[i];
  29831. var dimOriginalName = dim.name;
  29832. var count = duplicationMap.get(dimOriginalName) || 0;
  29833. if (count > 0) {
  29834. // Starts from 0.
  29835. dim.name = dimOriginalName + (count - 1);
  29836. }
  29837. count++;
  29838. duplicationMap.set(dimOriginalName, count);
  29839. }
  29840. }
  29841. // ??? TODO
  29842. // Originally detect dimCount by data[0]. Should we
  29843. // optimize it to only by sysDims and dimensions and encode.
  29844. // So only necessary dims will be initialized.
  29845. // But
  29846. // (1) custom series should be considered. where other dims
  29847. // may be visited.
  29848. // (2) sometimes user need to calculate bubble size or use visualMap
  29849. // on other dimensions besides coordSys needed.
  29850. // So, dims that is not used by system, should be shared in data store?
  29851. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29852. // Note that the result dimCount should not small than columns count
  29853. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29854. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29855. each(sysDims, function (sysDimItem) {
  29856. var sysDimItemDimsDef;
  29857. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29858. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29859. }
  29860. });
  29861. return dimCount;
  29862. }
  29863. function genCoordDimName(name, map, fromZero) {
  29864. if (fromZero || map.hasKey(name)) {
  29865. var i = 0;
  29866. while (map.hasKey(name + i)) {
  29867. i++;
  29868. }
  29869. name += i;
  29870. }
  29871. map.set(name, true);
  29872. return name;
  29873. }
  29874. /**
  29875. * @class
  29876. * For example:
  29877. * {
  29878. * coordSysName: 'cartesian2d',
  29879. * coordSysDims: ['x', 'y', ...],
  29880. * axisMap: HashMap({
  29881. * x: xAxisModel,
  29882. * y: yAxisModel
  29883. * }),
  29884. * categoryAxisMap: HashMap({
  29885. * x: xAxisModel,
  29886. * y: undefined
  29887. * }),
  29888. * // The index of the first category axis in `coordSysDims`.
  29889. * // `null/undefined` means no category axis exists.
  29890. * firstCategoryDimIndex: 1,
  29891. * // To replace user specified encode.
  29892. * }
  29893. */
  29894. var CoordSysInfo = /** @class */function () {
  29895. function CoordSysInfo(coordSysName) {
  29896. this.coordSysDims = [];
  29897. this.axisMap = createHashMap();
  29898. this.categoryAxisMap = createHashMap();
  29899. this.coordSysName = coordSysName;
  29900. }
  29901. return CoordSysInfo;
  29902. }();
  29903. function getCoordSysInfoBySeries(seriesModel) {
  29904. var coordSysName = seriesModel.get('coordinateSystem');
  29905. var result = new CoordSysInfo(coordSysName);
  29906. var fetch = fetchers[coordSysName];
  29907. if (fetch) {
  29908. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29909. return result;
  29910. }
  29911. }
  29912. var fetchers = {
  29913. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29914. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29915. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29916. if ("development" !== 'production') {
  29917. if (!xAxisModel) {
  29918. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29919. }
  29920. if (!yAxisModel) {
  29921. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29922. }
  29923. }
  29924. result.coordSysDims = ['x', 'y'];
  29925. axisMap.set('x', xAxisModel);
  29926. axisMap.set('y', yAxisModel);
  29927. if (isCategory(xAxisModel)) {
  29928. categoryAxisMap.set('x', xAxisModel);
  29929. result.firstCategoryDimIndex = 0;
  29930. }
  29931. if (isCategory(yAxisModel)) {
  29932. categoryAxisMap.set('y', yAxisModel);
  29933. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29934. }
  29935. },
  29936. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29937. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29938. if ("development" !== 'production') {
  29939. if (!singleAxisModel) {
  29940. throw new Error('singleAxis should be specified.');
  29941. }
  29942. }
  29943. result.coordSysDims = ['single'];
  29944. axisMap.set('single', singleAxisModel);
  29945. if (isCategory(singleAxisModel)) {
  29946. categoryAxisMap.set('single', singleAxisModel);
  29947. result.firstCategoryDimIndex = 0;
  29948. }
  29949. },
  29950. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29951. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29952. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29953. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29954. if ("development" !== 'production') {
  29955. if (!angleAxisModel) {
  29956. throw new Error('angleAxis option not found');
  29957. }
  29958. if (!radiusAxisModel) {
  29959. throw new Error('radiusAxis option not found');
  29960. }
  29961. }
  29962. result.coordSysDims = ['radius', 'angle'];
  29963. axisMap.set('radius', radiusAxisModel);
  29964. axisMap.set('angle', angleAxisModel);
  29965. if (isCategory(radiusAxisModel)) {
  29966. categoryAxisMap.set('radius', radiusAxisModel);
  29967. result.firstCategoryDimIndex = 0;
  29968. }
  29969. if (isCategory(angleAxisModel)) {
  29970. categoryAxisMap.set('angle', angleAxisModel);
  29971. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29972. }
  29973. },
  29974. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29975. result.coordSysDims = ['lng', 'lat'];
  29976. },
  29977. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29978. var ecModel = seriesModel.ecModel;
  29979. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29980. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29981. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29982. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29983. var axisDim = coordSysDims[index];
  29984. axisMap.set(axisDim, axisModel);
  29985. if (isCategory(axisModel)) {
  29986. categoryAxisMap.set(axisDim, axisModel);
  29987. if (result.firstCategoryDimIndex == null) {
  29988. result.firstCategoryDimIndex = index;
  29989. }
  29990. }
  29991. });
  29992. }
  29993. };
  29994. function isCategory(axisModel) {
  29995. return axisModel.get('type') === 'category';
  29996. }
  29997. /**
  29998. * Note that it is too complicated to support 3d stack by value
  29999. * (have to create two-dimension inverted index), so in 3d case
  30000. * we just support that stacked by index.
  30001. *
  30002. * @param seriesModel
  30003. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  30004. * The input will be modified.
  30005. * @param opt
  30006. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  30007. * @param opt.byIndex=false
  30008. * @return calculationInfo
  30009. * {
  30010. * stackedDimension: string
  30011. * stackedByDimension: string
  30012. * isStackedByIndex: boolean
  30013. * stackedOverDimension: string
  30014. * stackResultDimension: string
  30015. * }
  30016. */
  30017. function enableDataStack(seriesModel, dimensionsInput, opt) {
  30018. opt = opt || {};
  30019. var byIndex = opt.byIndex;
  30020. var stackedCoordDimension = opt.stackedCoordDimension;
  30021. var dimensionDefineList;
  30022. var schema;
  30023. var store;
  30024. if (isLegacyDimensionsInput(dimensionsInput)) {
  30025. dimensionDefineList = dimensionsInput;
  30026. } else {
  30027. schema = dimensionsInput.schema;
  30028. dimensionDefineList = schema.dimensions;
  30029. store = dimensionsInput.store;
  30030. }
  30031. // Compatibal: when `stack` is set as '', do not stack.
  30032. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  30033. var stackedByDimInfo;
  30034. var stackedDimInfo;
  30035. var stackResultDimension;
  30036. var stackedOverDimension;
  30037. each(dimensionDefineList, function (dimensionInfo, index) {
  30038. if (isString(dimensionInfo)) {
  30039. dimensionDefineList[index] = dimensionInfo = {
  30040. name: dimensionInfo
  30041. };
  30042. }
  30043. if (mayStack && !dimensionInfo.isExtraCoord) {
  30044. // Find the first ordinal dimension as the stackedByDimInfo.
  30045. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  30046. stackedByDimInfo = dimensionInfo;
  30047. }
  30048. // Find the first stackable dimension as the stackedDimInfo.
  30049. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  30050. stackedDimInfo = dimensionInfo;
  30051. }
  30052. }
  30053. });
  30054. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  30055. // Compatible with previous design, value axis (time axis) only stack by index.
  30056. // It may make sense if the user provides elaborately constructed data.
  30057. byIndex = true;
  30058. }
  30059. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  30060. // That put stack logic in List is for using conveniently in echarts extensions, but it
  30061. // might not be a good way.
  30062. if (stackedDimInfo) {
  30063. // Use a weird name that not duplicated with other names.
  30064. // Also need to use seriesModel.id as postfix because different
  30065. // series may share same data store. The stack dimension needs to be distinguished.
  30066. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  30067. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id;
  30068. // Create inverted index to fast query index by value.
  30069. if (stackedByDimInfo) {
  30070. stackedByDimInfo.createInvertedIndices = true;
  30071. }
  30072. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  30073. var stackedDimType = stackedDimInfo.type;
  30074. var stackedDimCoordIndex_1 = 0;
  30075. each(dimensionDefineList, function (dimensionInfo) {
  30076. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  30077. stackedDimCoordIndex_1++;
  30078. }
  30079. });
  30080. var stackedOverDimensionDefine = {
  30081. name: stackResultDimension,
  30082. coordDim: stackedDimCoordDim_1,
  30083. coordDimIndex: stackedDimCoordIndex_1,
  30084. type: stackedDimType,
  30085. isExtraCoord: true,
  30086. isCalculationCoord: true,
  30087. storeDimIndex: dimensionDefineList.length
  30088. };
  30089. var stackResultDimensionDefine = {
  30090. name: stackedOverDimension,
  30091. // This dimension contains stack base (generally, 0), so do not set it as
  30092. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  30093. coordDim: stackedOverDimension,
  30094. coordDimIndex: stackedDimCoordIndex_1 + 1,
  30095. type: stackedDimType,
  30096. isExtraCoord: true,
  30097. isCalculationCoord: true,
  30098. storeDimIndex: dimensionDefineList.length + 1
  30099. };
  30100. if (schema) {
  30101. if (store) {
  30102. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  30103. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  30104. }
  30105. schema.appendCalculationDimension(stackedOverDimensionDefine);
  30106. schema.appendCalculationDimension(stackResultDimensionDefine);
  30107. } else {
  30108. dimensionDefineList.push(stackedOverDimensionDefine);
  30109. dimensionDefineList.push(stackResultDimensionDefine);
  30110. }
  30111. }
  30112. return {
  30113. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  30114. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  30115. isStackedByIndex: byIndex,
  30116. stackedOverDimension: stackedOverDimension,
  30117. stackResultDimension: stackResultDimension
  30118. };
  30119. }
  30120. function isLegacyDimensionsInput(dimensionsInput) {
  30121. return !isSeriesDataSchema(dimensionsInput.schema);
  30122. }
  30123. function isDimensionStacked(data, stackedDim) {
  30124. // Each single series only maps to one pair of axis. So we do not need to
  30125. // check stackByDim, whatever stacked by a dimension or stacked by index.
  30126. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  30127. }
  30128. function getStackedDimension(data, targetDim) {
  30129. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  30130. }
  30131. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  30132. var coordSysName = seriesModel.get('coordinateSystem');
  30133. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  30134. var coordSysDimDefs;
  30135. if (coordSysInfo && coordSysInfo.coordSysDims) {
  30136. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  30137. var dimInfo = {
  30138. name: dim
  30139. };
  30140. var axisModel = coordSysInfo.axisMap.get(dim);
  30141. if (axisModel) {
  30142. var axisType = axisModel.get('type');
  30143. dimInfo.type = getDimensionTypeByAxis(axisType);
  30144. }
  30145. return dimInfo;
  30146. });
  30147. }
  30148. if (!coordSysDimDefs) {
  30149. // Get dimensions from registered coordinate system
  30150. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  30151. }
  30152. return coordSysDimDefs;
  30153. }
  30154. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  30155. var firstCategoryDimIndex;
  30156. var hasNameEncode;
  30157. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  30158. var coordDim = dimInfo.coordDim;
  30159. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  30160. if (categoryAxisModel) {
  30161. if (firstCategoryDimIndex == null) {
  30162. firstCategoryDimIndex = dimIndex;
  30163. }
  30164. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  30165. if (createInvertedIndices) {
  30166. dimInfo.createInvertedIndices = true;
  30167. }
  30168. }
  30169. if (dimInfo.otherDims.itemName != null) {
  30170. hasNameEncode = true;
  30171. }
  30172. });
  30173. if (!hasNameEncode && firstCategoryDimIndex != null) {
  30174. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  30175. }
  30176. return firstCategoryDimIndex;
  30177. }
  30178. /**
  30179. * Caution: there are side effects to `sourceManager` in this method.
  30180. * Should better only be called in `Series['getInitialData']`.
  30181. */
  30182. function createSeriesData(sourceRaw, seriesModel, opt) {
  30183. opt = opt || {};
  30184. var sourceManager = seriesModel.getSourceManager();
  30185. var source;
  30186. var isOriginalSource = false;
  30187. if (sourceRaw) {
  30188. isOriginalSource = true;
  30189. source = createSourceFromSeriesDataOption(sourceRaw);
  30190. } else {
  30191. source = sourceManager.getSource();
  30192. // Is series.data. not dataset.
  30193. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  30194. }
  30195. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  30196. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  30197. var useEncodeDefaulter = opt.useEncodeDefaulter;
  30198. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  30199. var createDimensionOptions = {
  30200. coordDimensions: coordSysDimDefs,
  30201. generateCoord: opt.generateCoord,
  30202. encodeDefine: seriesModel.getEncode(),
  30203. encodeDefaulter: encodeDefaulter,
  30204. canOmitUnusedDimensions: !isOriginalSource
  30205. };
  30206. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  30207. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  30208. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  30209. var stackCalculationInfo = enableDataStack(seriesModel, {
  30210. schema: schema,
  30211. store: store
  30212. });
  30213. var data = new SeriesData(schema, seriesModel);
  30214. data.setCalculationInfo(stackCalculationInfo);
  30215. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  30216. // Use dataIndex as ordinal value in categoryAxis
  30217. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  30218. } : null;
  30219. data.hasItemOption = false;
  30220. data.initData(
  30221. // Try to reuse the data store in sourceManager if using dataset.
  30222. isOriginalSource ? source : store, null, dimValueGetter);
  30223. return data;
  30224. }
  30225. function isNeedCompleteOrdinalData(source) {
  30226. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  30227. var sampleItem = firstDataNotNull(source.data || []);
  30228. return !isArray(getDataItemValue(sampleItem));
  30229. }
  30230. }
  30231. function firstDataNotNull(arr) {
  30232. var i = 0;
  30233. while (i < arr.length && arr[i] == null) {
  30234. i++;
  30235. }
  30236. return arr[i];
  30237. }
  30238. var Scale = /** @class */function () {
  30239. function Scale(setting) {
  30240. this._setting = setting || {};
  30241. this._extent = [Infinity, -Infinity];
  30242. }
  30243. Scale.prototype.getSetting = function (name) {
  30244. return this._setting[name];
  30245. };
  30246. /**
  30247. * Set extent from data
  30248. */
  30249. Scale.prototype.unionExtent = function (other) {
  30250. var extent = this._extent;
  30251. other[0] < extent[0] && (extent[0] = other[0]);
  30252. other[1] > extent[1] && (extent[1] = other[1]);
  30253. // not setExtent because in log axis it may transformed to power
  30254. // this.setExtent(extent[0], extent[1]);
  30255. };
  30256. /**
  30257. * Set extent from data
  30258. */
  30259. Scale.prototype.unionExtentFromData = function (data, dim) {
  30260. this.unionExtent(data.getApproximateExtent(dim));
  30261. };
  30262. /**
  30263. * Get extent
  30264. *
  30265. * Extent is always in increase order.
  30266. */
  30267. Scale.prototype.getExtent = function () {
  30268. return this._extent.slice();
  30269. };
  30270. /**
  30271. * Set extent
  30272. */
  30273. Scale.prototype.setExtent = function (start, end) {
  30274. var thisExtent = this._extent;
  30275. if (!isNaN(start)) {
  30276. thisExtent[0] = start;
  30277. }
  30278. if (!isNaN(end)) {
  30279. thisExtent[1] = end;
  30280. }
  30281. };
  30282. /**
  30283. * If value is in extent range
  30284. */
  30285. Scale.prototype.isInExtentRange = function (value) {
  30286. return this._extent[0] <= value && this._extent[1] >= value;
  30287. };
  30288. /**
  30289. * When axis extent depends on data and no data exists,
  30290. * axis ticks should not be drawn, which is named 'blank'.
  30291. */
  30292. Scale.prototype.isBlank = function () {
  30293. return this._isBlank;
  30294. };
  30295. /**
  30296. * When axis extent depends on data and no data exists,
  30297. * axis ticks should not be drawn, which is named 'blank'.
  30298. */
  30299. Scale.prototype.setBlank = function (isBlank) {
  30300. this._isBlank = isBlank;
  30301. };
  30302. return Scale;
  30303. }();
  30304. enableClassManagement(Scale);
  30305. var uidBase = 0;
  30306. var OrdinalMeta = /** @class */function () {
  30307. function OrdinalMeta(opt) {
  30308. this.categories = opt.categories || [];
  30309. this._needCollect = opt.needCollect;
  30310. this._deduplication = opt.deduplication;
  30311. this.uid = ++uidBase;
  30312. }
  30313. OrdinalMeta.createByAxisModel = function (axisModel) {
  30314. var option = axisModel.option;
  30315. var data = option.data;
  30316. var categories = data && map(data, getName);
  30317. return new OrdinalMeta({
  30318. categories: categories,
  30319. needCollect: !categories,
  30320. // deduplication is default in axis.
  30321. deduplication: option.dedplication !== false
  30322. });
  30323. };
  30324. OrdinalMeta.prototype.getOrdinal = function (category) {
  30325. // @ts-ignore
  30326. return this._getOrCreateMap().get(category);
  30327. };
  30328. /**
  30329. * @return The ordinal. If not found, return NaN.
  30330. */
  30331. OrdinalMeta.prototype.parseAndCollect = function (category) {
  30332. var index;
  30333. var needCollect = this._needCollect;
  30334. // The value of category dim can be the index of the given category set.
  30335. // This feature is only supported when !needCollect, because we should
  30336. // consider a common case: a value is 2017, which is a number but is
  30337. // expected to be tread as a category. This case usually happen in dataset,
  30338. // where it happent to be no need of the index feature.
  30339. if (!isString(category) && !needCollect) {
  30340. return category;
  30341. }
  30342. // Optimize for the scenario:
  30343. // category is ['2012-01-01', '2012-01-02', ...], where the input
  30344. // data has been ensured not duplicate and is large data.
  30345. // Notice, if a dataset dimension provide categroies, usually echarts
  30346. // should remove duplication except user tell echarts dont do that
  30347. // (set axis.deduplication = false), because echarts do not know whether
  30348. // the values in the category dimension has duplication (consider the
  30349. // parallel-aqi example)
  30350. if (needCollect && !this._deduplication) {
  30351. index = this.categories.length;
  30352. this.categories[index] = category;
  30353. return index;
  30354. }
  30355. var map = this._getOrCreateMap();
  30356. // @ts-ignore
  30357. index = map.get(category);
  30358. if (index == null) {
  30359. if (needCollect) {
  30360. index = this.categories.length;
  30361. this.categories[index] = category;
  30362. // @ts-ignore
  30363. map.set(category, index);
  30364. } else {
  30365. index = NaN;
  30366. }
  30367. }
  30368. return index;
  30369. };
  30370. // Consider big data, do not create map until needed.
  30371. OrdinalMeta.prototype._getOrCreateMap = function () {
  30372. return this._map || (this._map = createHashMap(this.categories));
  30373. };
  30374. return OrdinalMeta;
  30375. }();
  30376. function getName(obj) {
  30377. if (isObject(obj) && obj.value != null) {
  30378. return obj.value;
  30379. } else {
  30380. return obj + '';
  30381. }
  30382. }
  30383. function isValueNice(val) {
  30384. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  30385. var f = Math.abs(val / exp10);
  30386. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  30387. }
  30388. function isIntervalOrLogScale(scale) {
  30389. return scale.type === 'interval' || scale.type === 'log';
  30390. }
  30391. /**
  30392. * @param extent Both extent[0] and extent[1] should be valid number.
  30393. * Should be extent[0] < extent[1].
  30394. * @param splitNumber splitNumber should be >= 1.
  30395. */
  30396. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  30397. var result = {};
  30398. var span = extent[1] - extent[0];
  30399. var interval = result.interval = nice(span / splitNumber, true);
  30400. if (minInterval != null && interval < minInterval) {
  30401. interval = result.interval = minInterval;
  30402. }
  30403. if (maxInterval != null && interval > maxInterval) {
  30404. interval = result.interval = maxInterval;
  30405. }
  30406. // Tow more digital for tick.
  30407. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  30408. // Niced extent inside original extent
  30409. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  30410. fixExtent(niceTickExtent, extent);
  30411. return result;
  30412. }
  30413. function increaseInterval(interval) {
  30414. var exp10 = Math.pow(10, quantityExponent(interval));
  30415. // Increase interval
  30416. var f = interval / exp10;
  30417. if (!f) {
  30418. f = 1;
  30419. } else if (f === 2) {
  30420. f = 3;
  30421. } else if (f === 3) {
  30422. f = 5;
  30423. } else {
  30424. // f is 1 or 5
  30425. f *= 2;
  30426. }
  30427. return round(f * exp10);
  30428. }
  30429. /**
  30430. * @return interval precision
  30431. */
  30432. function getIntervalPrecision(interval) {
  30433. // Tow more digital for tick.
  30434. return getPrecision(interval) + 2;
  30435. }
  30436. function clamp(niceTickExtent, idx, extent) {
  30437. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30438. }
  30439. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30440. function fixExtent(niceTickExtent, extent) {
  30441. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30442. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30443. clamp(niceTickExtent, 0, extent);
  30444. clamp(niceTickExtent, 1, extent);
  30445. if (niceTickExtent[0] > niceTickExtent[1]) {
  30446. niceTickExtent[0] = niceTickExtent[1];
  30447. }
  30448. }
  30449. function contain$1(val, extent) {
  30450. return val >= extent[0] && val <= extent[1];
  30451. }
  30452. function normalize$1(val, extent) {
  30453. if (extent[1] === extent[0]) {
  30454. return 0.5;
  30455. }
  30456. return (val - extent[0]) / (extent[1] - extent[0]);
  30457. }
  30458. function scale$2(val, extent) {
  30459. return val * (extent[1] - extent[0]) + extent[0];
  30460. }
  30461. var OrdinalScale = /** @class */function (_super) {
  30462. __extends(OrdinalScale, _super);
  30463. function OrdinalScale(setting) {
  30464. var _this = _super.call(this, setting) || this;
  30465. _this.type = 'ordinal';
  30466. var ordinalMeta = _this.getSetting('ordinalMeta');
  30467. // Caution: Should not use instanceof, consider ec-extensions using
  30468. // import approach to get OrdinalMeta class.
  30469. if (!ordinalMeta) {
  30470. ordinalMeta = new OrdinalMeta({});
  30471. }
  30472. if (isArray(ordinalMeta)) {
  30473. ordinalMeta = new OrdinalMeta({
  30474. categories: map(ordinalMeta, function (item) {
  30475. return isObject(item) ? item.value : item;
  30476. })
  30477. });
  30478. }
  30479. _this._ordinalMeta = ordinalMeta;
  30480. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  30481. return _this;
  30482. }
  30483. OrdinalScale.prototype.parse = function (val) {
  30484. // Caution: Math.round(null) will return `0` rather than `NaN`
  30485. if (val == null) {
  30486. return NaN;
  30487. }
  30488. return isString(val) ? this._ordinalMeta.getOrdinal(val)
  30489. // val might be float.
  30490. : Math.round(val);
  30491. };
  30492. OrdinalScale.prototype.contain = function (rank) {
  30493. rank = this.parse(rank);
  30494. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  30495. };
  30496. /**
  30497. * Normalize given rank or name to linear [0, 1]
  30498. * @param val raw ordinal number.
  30499. * @return normalized value in [0, 1].
  30500. */
  30501. OrdinalScale.prototype.normalize = function (val) {
  30502. val = this._getTickNumber(this.parse(val));
  30503. return normalize$1(val, this._extent);
  30504. };
  30505. /**
  30506. * @param val normalized value in [0, 1].
  30507. * @return raw ordinal number.
  30508. */
  30509. OrdinalScale.prototype.scale = function (val) {
  30510. val = Math.round(scale$2(val, this._extent));
  30511. return this.getRawOrdinalNumber(val);
  30512. };
  30513. OrdinalScale.prototype.getTicks = function () {
  30514. var ticks = [];
  30515. var extent = this._extent;
  30516. var rank = extent[0];
  30517. while (rank <= extent[1]) {
  30518. ticks.push({
  30519. value: rank
  30520. });
  30521. rank++;
  30522. }
  30523. return ticks;
  30524. };
  30525. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  30526. // Not support.
  30527. return;
  30528. };
  30529. /**
  30530. * @see `Ordinal['_ordinalNumbersByTick']`
  30531. */
  30532. OrdinalScale.prototype.setSortInfo = function (info) {
  30533. if (info == null) {
  30534. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  30535. return;
  30536. }
  30537. var infoOrdinalNumbers = info.ordinalNumbers;
  30538. var ordinalsByTick = this._ordinalNumbersByTick = [];
  30539. var ticksByOrdinal = this._ticksByOrdinalNumber = [];
  30540. // Unnecessary support negative tick in `realtimeSort`.
  30541. var tickNum = 0;
  30542. var allCategoryLen = this._ordinalMeta.categories.length;
  30543. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  30544. var ordinalNumber = infoOrdinalNumbers[tickNum];
  30545. ordinalsByTick[tickNum] = ordinalNumber;
  30546. ticksByOrdinal[ordinalNumber] = tickNum;
  30547. }
  30548. // Handle that `series.data` only covers part of the `axis.category.data`.
  30549. var unusedOrdinal = 0;
  30550. for (; tickNum < allCategoryLen; ++tickNum) {
  30551. while (ticksByOrdinal[unusedOrdinal] != null) {
  30552. unusedOrdinal++;
  30553. }
  30554. ordinalsByTick.push(unusedOrdinal);
  30555. ticksByOrdinal[unusedOrdinal] = tickNum;
  30556. }
  30557. };
  30558. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  30559. var ticksByOrdinalNumber = this._ticksByOrdinalNumber;
  30560. // also support ordinal out of range of `ordinalMeta.categories.length`,
  30561. // where ordinal numbers are used as tick value directly.
  30562. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  30563. };
  30564. /**
  30565. * @usage
  30566. * ```js
  30567. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  30568. *
  30569. * // case0
  30570. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  30571. * // case1
  30572. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  30573. * // case2
  30574. * const coord = axis.dataToCoord(ordinalNumber);
  30575. * ```
  30576. *
  30577. * @param {OrdinalNumber} tickNumber index of display
  30578. */
  30579. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  30580. var ordinalNumbersByTick = this._ordinalNumbersByTick;
  30581. // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  30582. // where ordinal numbers are used as tick value directly.
  30583. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  30584. };
  30585. /**
  30586. * Get item on tick
  30587. */
  30588. OrdinalScale.prototype.getLabel = function (tick) {
  30589. if (!this.isBlank()) {
  30590. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  30591. var cateogry = this._ordinalMeta.categories[ordinalNumber];
  30592. // Note that if no data, ordinalMeta.categories is an empty array.
  30593. // Return empty if it's not exist.
  30594. return cateogry == null ? '' : cateogry + '';
  30595. }
  30596. };
  30597. OrdinalScale.prototype.count = function () {
  30598. return this._extent[1] - this._extent[0] + 1;
  30599. };
  30600. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  30601. this.unionExtent(data.getApproximateExtent(dim));
  30602. };
  30603. /**
  30604. * @override
  30605. * If value is in extent range
  30606. */
  30607. OrdinalScale.prototype.isInExtentRange = function (value) {
  30608. value = this._getTickNumber(value);
  30609. return this._extent[0] <= value && this._extent[1] >= value;
  30610. };
  30611. OrdinalScale.prototype.getOrdinalMeta = function () {
  30612. return this._ordinalMeta;
  30613. };
  30614. OrdinalScale.prototype.calcNiceTicks = function () {};
  30615. OrdinalScale.prototype.calcNiceExtent = function () {};
  30616. OrdinalScale.type = 'ordinal';
  30617. return OrdinalScale;
  30618. }(Scale);
  30619. Scale.registerClass(OrdinalScale);
  30620. var roundNumber = round;
  30621. var IntervalScale = /** @class */function (_super) {
  30622. __extends(IntervalScale, _super);
  30623. function IntervalScale() {
  30624. var _this = _super !== null && _super.apply(this, arguments) || this;
  30625. _this.type = 'interval';
  30626. // Step is calculated in adjustExtent.
  30627. _this._interval = 0;
  30628. _this._intervalPrecision = 2;
  30629. return _this;
  30630. }
  30631. IntervalScale.prototype.parse = function (val) {
  30632. return val;
  30633. };
  30634. IntervalScale.prototype.contain = function (val) {
  30635. return contain$1(val, this._extent);
  30636. };
  30637. IntervalScale.prototype.normalize = function (val) {
  30638. return normalize$1(val, this._extent);
  30639. };
  30640. IntervalScale.prototype.scale = function (val) {
  30641. return scale$2(val, this._extent);
  30642. };
  30643. IntervalScale.prototype.setExtent = function (start, end) {
  30644. var thisExtent = this._extent;
  30645. // start,end may be a Number like '25',so...
  30646. if (!isNaN(start)) {
  30647. thisExtent[0] = parseFloat(start);
  30648. }
  30649. if (!isNaN(end)) {
  30650. thisExtent[1] = parseFloat(end);
  30651. }
  30652. };
  30653. IntervalScale.prototype.unionExtent = function (other) {
  30654. var extent = this._extent;
  30655. other[0] < extent[0] && (extent[0] = other[0]);
  30656. other[1] > extent[1] && (extent[1] = other[1]);
  30657. // unionExtent may called by it's sub classes
  30658. this.setExtent(extent[0], extent[1]);
  30659. };
  30660. IntervalScale.prototype.getInterval = function () {
  30661. return this._interval;
  30662. };
  30663. IntervalScale.prototype.setInterval = function (interval) {
  30664. this._interval = interval;
  30665. // Dropped auto calculated niceExtent and use user-set extent.
  30666. // We assume user wants to set both interval, min, max to get a better result.
  30667. this._niceExtent = this._extent.slice();
  30668. this._intervalPrecision = getIntervalPrecision(interval);
  30669. };
  30670. /**
  30671. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30672. */
  30673. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  30674. var interval = this._interval;
  30675. var extent = this._extent;
  30676. var niceTickExtent = this._niceExtent;
  30677. var intervalPrecision = this._intervalPrecision;
  30678. var ticks = [];
  30679. // If interval is 0, return [];
  30680. if (!interval) {
  30681. return ticks;
  30682. }
  30683. // Consider this case: using dataZoom toolbox, zoom and zoom.
  30684. var safeLimit = 10000;
  30685. if (extent[0] < niceTickExtent[0]) {
  30686. if (expandToNicedExtent) {
  30687. ticks.push({
  30688. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  30689. });
  30690. } else {
  30691. ticks.push({
  30692. value: extent[0]
  30693. });
  30694. }
  30695. }
  30696. var tick = niceTickExtent[0];
  30697. while (tick <= niceTickExtent[1]) {
  30698. ticks.push({
  30699. value: tick
  30700. });
  30701. // Avoid rounding error
  30702. tick = roundNumber(tick + interval, intervalPrecision);
  30703. if (tick === ticks[ticks.length - 1].value) {
  30704. // Consider out of safe float point, e.g.,
  30705. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30706. break;
  30707. }
  30708. if (ticks.length > safeLimit) {
  30709. return [];
  30710. }
  30711. }
  30712. // Consider this case: the last item of ticks is smaller
  30713. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30714. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  30715. if (extent[1] > lastNiceTick) {
  30716. if (expandToNicedExtent) {
  30717. ticks.push({
  30718. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  30719. });
  30720. } else {
  30721. ticks.push({
  30722. value: extent[1]
  30723. });
  30724. }
  30725. }
  30726. return ticks;
  30727. };
  30728. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  30729. var ticks = this.getTicks(true);
  30730. var minorTicks = [];
  30731. var extent = this.getExtent();
  30732. for (var i = 1; i < ticks.length; i++) {
  30733. var nextTick = ticks[i];
  30734. var prevTick = ticks[i - 1];
  30735. var count = 0;
  30736. var minorTicksGroup = [];
  30737. var interval = nextTick.value - prevTick.value;
  30738. var minorInterval = interval / splitNumber;
  30739. while (count < splitNumber - 1) {
  30740. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval);
  30741. // For the first and last interval. The count may be less than splitNumber.
  30742. if (minorTick > extent[0] && minorTick < extent[1]) {
  30743. minorTicksGroup.push(minorTick);
  30744. }
  30745. count++;
  30746. }
  30747. minorTicks.push(minorTicksGroup);
  30748. }
  30749. return minorTicks;
  30750. };
  30751. /**
  30752. * @param opt.precision If 'auto', use nice presision.
  30753. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  30754. */
  30755. IntervalScale.prototype.getLabel = function (data, opt) {
  30756. if (data == null) {
  30757. return '';
  30758. }
  30759. var precision = opt && opt.precision;
  30760. if (precision == null) {
  30761. precision = getPrecision(data.value) || 0;
  30762. } else if (precision === 'auto') {
  30763. // Should be more precise then tick.
  30764. precision = this._intervalPrecision;
  30765. }
  30766. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30767. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30768. var dataNum = roundNumber(data.value, precision, true);
  30769. return addCommas(dataNum);
  30770. };
  30771. /**
  30772. * @param splitNumber By default `5`.
  30773. */
  30774. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30775. splitNumber = splitNumber || 5;
  30776. var extent = this._extent;
  30777. var span = extent[1] - extent[0];
  30778. if (!isFinite(span)) {
  30779. return;
  30780. }
  30781. // User may set axis min 0 and data are all negative
  30782. // FIXME If it needs to reverse ?
  30783. if (span < 0) {
  30784. span = -span;
  30785. extent.reverse();
  30786. }
  30787. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30788. this._intervalPrecision = result.intervalPrecision;
  30789. this._interval = result.interval;
  30790. this._niceExtent = result.niceTickExtent;
  30791. };
  30792. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30793. var extent = this._extent;
  30794. // If extent start and end are same, expand them
  30795. if (extent[0] === extent[1]) {
  30796. if (extent[0] !== 0) {
  30797. // Expand extent
  30798. // Note that extents can be both negative. See #13154
  30799. var expandSize = Math.abs(extent[0]);
  30800. // In the fowllowing case
  30801. // Axis has been fixed max 100
  30802. // Plus data are all 100 and axis extent are [100, 100].
  30803. // Extend to the both side will cause expanded max is larger than fixed max.
  30804. // So only expand to the smaller side.
  30805. if (!opt.fixMax) {
  30806. extent[1] += expandSize / 2;
  30807. extent[0] -= expandSize / 2;
  30808. } else {
  30809. extent[0] -= expandSize / 2;
  30810. }
  30811. } else {
  30812. extent[1] = 1;
  30813. }
  30814. }
  30815. var span = extent[1] - extent[0];
  30816. // If there are no data and extent are [Infinity, -Infinity]
  30817. if (!isFinite(span)) {
  30818. extent[0] = 0;
  30819. extent[1] = 1;
  30820. }
  30821. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30822. // let extent = this._extent;
  30823. var interval = this._interval;
  30824. if (!opt.fixMin) {
  30825. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30826. }
  30827. if (!opt.fixMax) {
  30828. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30829. }
  30830. };
  30831. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30832. this._niceExtent = [min, max];
  30833. };
  30834. IntervalScale.type = 'interval';
  30835. return IntervalScale;
  30836. }(Scale);
  30837. Scale.registerClass(IntervalScale);
  30838. /* global Float32Array */
  30839. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30840. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30841. function createFloat32Array(arg) {
  30842. if (isArray(arg)) {
  30843. // Return self directly if don't support TypedArray.
  30844. return supportFloat32Array ? new Float32Array(arg) : arg;
  30845. }
  30846. // Else is number
  30847. return new Float32ArrayCtor(arg);
  30848. }
  30849. var STACK_PREFIX = '__ec_stack_';
  30850. function getSeriesStackId(seriesModel) {
  30851. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30852. }
  30853. function getAxisKey(axis) {
  30854. return axis.dim + axis.index;
  30855. }
  30856. function prepareLayoutBarSeries(seriesType, ecModel) {
  30857. var seriesModels = [];
  30858. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30859. // Check series coordinate, do layout for cartesian2d only
  30860. if (isOnCartesian(seriesModel)) {
  30861. seriesModels.push(seriesModel);
  30862. }
  30863. });
  30864. return seriesModels;
  30865. }
  30866. /**
  30867. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30868. * values.
  30869. * This works for time axes, value axes, and log axes.
  30870. * For a single time axis, return value is in the form like
  30871. * {'x_0': [1000000]}.
  30872. * The value of 1000000 is in milliseconds.
  30873. */
  30874. function getValueAxesMinGaps(barSeries) {
  30875. /**
  30876. * Map from axis.index to values.
  30877. * For a single time axis, axisValues is in the form like
  30878. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30879. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30880. * series.
  30881. */
  30882. var axisValues = {};
  30883. each(barSeries, function (seriesModel) {
  30884. var cartesian = seriesModel.coordinateSystem;
  30885. var baseAxis = cartesian.getBaseAxis();
  30886. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30887. return;
  30888. }
  30889. var data = seriesModel.getData();
  30890. var key = baseAxis.dim + '_' + baseAxis.index;
  30891. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30892. var store = data.getStore();
  30893. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30894. var value = store.get(dimIdx, i);
  30895. if (!axisValues[key]) {
  30896. // No previous data for the axis
  30897. axisValues[key] = [value];
  30898. } else {
  30899. // No value in previous series
  30900. axisValues[key].push(value);
  30901. }
  30902. // Ignore duplicated time values in the same axis
  30903. }
  30904. });
  30905. var axisMinGaps = {};
  30906. for (var key in axisValues) {
  30907. if (axisValues.hasOwnProperty(key)) {
  30908. var valuesInAxis = axisValues[key];
  30909. if (valuesInAxis) {
  30910. // Sort axis values into ascending order to calculate gaps
  30911. valuesInAxis.sort(function (a, b) {
  30912. return a - b;
  30913. });
  30914. var min = null;
  30915. for (var j = 1; j < valuesInAxis.length; ++j) {
  30916. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30917. if (delta > 0) {
  30918. // Ignore 0 delta because they are of the same axis value
  30919. min = min === null ? delta : Math.min(min, delta);
  30920. }
  30921. }
  30922. // Set to null if only have one data
  30923. axisMinGaps[key] = min;
  30924. }
  30925. }
  30926. }
  30927. return axisMinGaps;
  30928. }
  30929. function makeColumnLayout(barSeries) {
  30930. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30931. var seriesInfoList = [];
  30932. each(barSeries, function (seriesModel) {
  30933. var cartesian = seriesModel.coordinateSystem;
  30934. var baseAxis = cartesian.getBaseAxis();
  30935. var axisExtent = baseAxis.getExtent();
  30936. var bandWidth;
  30937. if (baseAxis.type === 'category') {
  30938. bandWidth = baseAxis.getBandWidth();
  30939. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30940. var key = baseAxis.dim + '_' + baseAxis.index;
  30941. var minGap = axisMinGaps[key];
  30942. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30943. var scale = baseAxis.scale.getExtent();
  30944. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30945. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30946. } else {
  30947. var data = seriesModel.getData();
  30948. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30949. }
  30950. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30951. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30952. var barMinWidth = parsePercent$1(
  30953. // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30954. // the auto-calculated bar width might be less than 0.5 / 1.
  30955. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30956. var barGap = seriesModel.get('barGap');
  30957. var barCategoryGap = seriesModel.get('barCategoryGap');
  30958. seriesInfoList.push({
  30959. bandWidth: bandWidth,
  30960. barWidth: barWidth,
  30961. barMaxWidth: barMaxWidth,
  30962. barMinWidth: barMinWidth,
  30963. barGap: barGap,
  30964. barCategoryGap: barCategoryGap,
  30965. axisKey: getAxisKey(baseAxis),
  30966. stackId: getSeriesStackId(seriesModel)
  30967. });
  30968. });
  30969. return doCalBarWidthAndOffset(seriesInfoList);
  30970. }
  30971. function doCalBarWidthAndOffset(seriesInfoList) {
  30972. // Columns info on each category axis. Key is cartesian name
  30973. var columnsMap = {};
  30974. each(seriesInfoList, function (seriesInfo, idx) {
  30975. var axisKey = seriesInfo.axisKey;
  30976. var bandWidth = seriesInfo.bandWidth;
  30977. var columnsOnAxis = columnsMap[axisKey] || {
  30978. bandWidth: bandWidth,
  30979. remainedWidth: bandWidth,
  30980. autoWidthCount: 0,
  30981. categoryGap: null,
  30982. gap: '20%',
  30983. stacks: {}
  30984. };
  30985. var stacks = columnsOnAxis.stacks;
  30986. columnsMap[axisKey] = columnsOnAxis;
  30987. var stackId = seriesInfo.stackId;
  30988. if (!stacks[stackId]) {
  30989. columnsOnAxis.autoWidthCount++;
  30990. }
  30991. stacks[stackId] = stacks[stackId] || {
  30992. width: 0,
  30993. maxWidth: 0
  30994. };
  30995. // Caution: In a single coordinate system, these barGrid attributes
  30996. // will be shared by series. Consider that they have default values,
  30997. // only the attributes set on the last series will work.
  30998. // Do not change this fact unless there will be a break change.
  30999. var barWidth = seriesInfo.barWidth;
  31000. if (barWidth && !stacks[stackId].width) {
  31001. // See #6312, do not restrict width.
  31002. stacks[stackId].width = barWidth;
  31003. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  31004. columnsOnAxis.remainedWidth -= barWidth;
  31005. }
  31006. var barMaxWidth = seriesInfo.barMaxWidth;
  31007. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  31008. var barMinWidth = seriesInfo.barMinWidth;
  31009. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  31010. var barGap = seriesInfo.barGap;
  31011. barGap != null && (columnsOnAxis.gap = barGap);
  31012. var barCategoryGap = seriesInfo.barCategoryGap;
  31013. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  31014. });
  31015. var result = {};
  31016. each(columnsMap, function (columnsOnAxis, coordSysName) {
  31017. result[coordSysName] = {};
  31018. var stacks = columnsOnAxis.stacks;
  31019. var bandWidth = columnsOnAxis.bandWidth;
  31020. var categoryGapPercent = columnsOnAxis.categoryGap;
  31021. if (categoryGapPercent == null) {
  31022. var columnCount = keys(stacks).length;
  31023. // More columns in one group
  31024. // the spaces between group is smaller. Or the column will be too thin.
  31025. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  31026. }
  31027. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  31028. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  31029. var remainedWidth = columnsOnAxis.remainedWidth;
  31030. var autoWidthCount = columnsOnAxis.autoWidthCount;
  31031. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31032. autoWidth = Math.max(autoWidth, 0);
  31033. // Find if any auto calculated bar exceeded maxBarWidth
  31034. each(stacks, function (column) {
  31035. var maxWidth = column.maxWidth;
  31036. var minWidth = column.minWidth;
  31037. if (!column.width) {
  31038. var finalWidth = autoWidth;
  31039. if (maxWidth && maxWidth < finalWidth) {
  31040. finalWidth = Math.min(maxWidth, remainedWidth);
  31041. }
  31042. // `minWidth` has higher priority. `minWidth` decide that whether the
  31043. // bar is able to be visible. So `minWidth` should not be restricted
  31044. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  31045. // the extreme cases for `value` axis, bars are allowed to overlap
  31046. // with each other if `minWidth` specified.
  31047. if (minWidth && minWidth > finalWidth) {
  31048. finalWidth = minWidth;
  31049. }
  31050. if (finalWidth !== autoWidth) {
  31051. column.width = finalWidth;
  31052. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31053. autoWidthCount--;
  31054. }
  31055. } else {
  31056. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  31057. // CSS does. Because barWidth can be a percent value, where
  31058. // `barMaxWidth` can be used to restrict the final width.
  31059. var finalWidth = column.width;
  31060. if (maxWidth) {
  31061. finalWidth = Math.min(finalWidth, maxWidth);
  31062. }
  31063. // `minWidth` has higher priority, as described above
  31064. if (minWidth) {
  31065. finalWidth = Math.max(finalWidth, minWidth);
  31066. }
  31067. column.width = finalWidth;
  31068. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31069. autoWidthCount--;
  31070. }
  31071. });
  31072. // Recalculate width again
  31073. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31074. autoWidth = Math.max(autoWidth, 0);
  31075. var widthSum = 0;
  31076. var lastColumn;
  31077. each(stacks, function (column, idx) {
  31078. if (!column.width) {
  31079. column.width = autoWidth;
  31080. }
  31081. lastColumn = column;
  31082. widthSum += column.width * (1 + barGapPercent);
  31083. });
  31084. if (lastColumn) {
  31085. widthSum -= lastColumn.width * barGapPercent;
  31086. }
  31087. var offset = -widthSum / 2;
  31088. each(stacks, function (column, stackId) {
  31089. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  31090. bandWidth: bandWidth,
  31091. offset: offset,
  31092. width: column.width
  31093. };
  31094. offset += column.width * (1 + barGapPercent);
  31095. });
  31096. });
  31097. return result;
  31098. }
  31099. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  31100. if (barWidthAndOffset && axis) {
  31101. var result = barWidthAndOffset[getAxisKey(axis)];
  31102. if (result != null && seriesModel != null) {
  31103. return result[getSeriesStackId(seriesModel)];
  31104. }
  31105. return result;
  31106. }
  31107. }
  31108. function layout(seriesType, ecModel) {
  31109. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  31110. var barWidthAndOffset = makeColumnLayout(seriesModels);
  31111. each(seriesModels, function (seriesModel) {
  31112. var data = seriesModel.getData();
  31113. var cartesian = seriesModel.coordinateSystem;
  31114. var baseAxis = cartesian.getBaseAxis();
  31115. var stackId = getSeriesStackId(seriesModel);
  31116. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  31117. var columnOffset = columnLayoutInfo.offset;
  31118. var columnWidth = columnLayoutInfo.width;
  31119. data.setLayout({
  31120. bandWidth: columnLayoutInfo.bandWidth,
  31121. offset: columnOffset,
  31122. size: columnWidth
  31123. });
  31124. });
  31125. }
  31126. // TODO: Do not support stack in large mode yet.
  31127. function createProgressiveLayout(seriesType) {
  31128. return {
  31129. seriesType: seriesType,
  31130. plan: createRenderPlanner(),
  31131. reset: function (seriesModel) {
  31132. if (!isOnCartesian(seriesModel)) {
  31133. return;
  31134. }
  31135. var data = seriesModel.getData();
  31136. var cartesian = seriesModel.coordinateSystem;
  31137. var baseAxis = cartesian.getBaseAxis();
  31138. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31139. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  31140. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  31141. var drawBackground = seriesModel.get('showBackground', true);
  31142. var valueDim = data.mapDimension(valueAxis.dim);
  31143. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31144. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  31145. var isValueAxisH = valueAxis.isHorizontal();
  31146. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  31147. var isLarge = isInLargeMode(seriesModel);
  31148. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  31149. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim);
  31150. // Layout info.
  31151. var columnWidth = data.getLayout('size');
  31152. var columnOffset = data.getLayout('offset');
  31153. return {
  31154. progress: function (params, data) {
  31155. var count = params.count;
  31156. var largePoints = isLarge && createFloat32Array(count * 3);
  31157. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  31158. var largeDataIndices = isLarge && createFloat32Array(count);
  31159. var coordLayout = cartesian.master.getRect();
  31160. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  31161. var dataIndex;
  31162. var store = data.getStore();
  31163. var idxOffset = 0;
  31164. while ((dataIndex = params.next()) != null) {
  31165. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  31166. var baseValue = store.get(baseDimIdx, dataIndex);
  31167. var baseCoord = valueAxisStart;
  31168. var stackStartValue = void 0;
  31169. // Because of the barMinHeight, we can not use the value in
  31170. // stackResultDimension directly.
  31171. if (stacked) {
  31172. stackStartValue = +value - store.get(valueDimIdx, dataIndex);
  31173. }
  31174. var x = void 0;
  31175. var y = void 0;
  31176. var width = void 0;
  31177. var height = void 0;
  31178. if (isValueAxisH) {
  31179. var coord = cartesian.dataToPoint([value, baseValue]);
  31180. if (stacked) {
  31181. var startCoord = cartesian.dataToPoint([stackStartValue, baseValue]);
  31182. baseCoord = startCoord[0];
  31183. }
  31184. x = baseCoord;
  31185. y = coord[1] + columnOffset;
  31186. width = coord[0] - baseCoord;
  31187. height = columnWidth;
  31188. if (Math.abs(width) < barMinHeight) {
  31189. width = (width < 0 ? -1 : 1) * barMinHeight;
  31190. }
  31191. } else {
  31192. var coord = cartesian.dataToPoint([baseValue, value]);
  31193. if (stacked) {
  31194. var startCoord = cartesian.dataToPoint([baseValue, stackStartValue]);
  31195. baseCoord = startCoord[1];
  31196. }
  31197. x = coord[0] + columnOffset;
  31198. y = baseCoord;
  31199. width = columnWidth;
  31200. height = coord[1] - baseCoord;
  31201. if (Math.abs(height) < barMinHeight) {
  31202. // Include zero to has a positive bar
  31203. height = (height <= 0 ? -1 : 1) * barMinHeight;
  31204. }
  31205. }
  31206. if (!isLarge) {
  31207. data.setItemLayout(dataIndex, {
  31208. x: x,
  31209. y: y,
  31210. width: width,
  31211. height: height
  31212. });
  31213. } else {
  31214. largePoints[idxOffset] = x;
  31215. largePoints[idxOffset + 1] = y;
  31216. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  31217. if (largeBackgroundPoints) {
  31218. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  31219. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  31220. largeBackgroundPoints[idxOffset + 2] = bgSize;
  31221. }
  31222. largeDataIndices[dataIndex] = dataIndex;
  31223. }
  31224. idxOffset += 3;
  31225. }
  31226. if (isLarge) {
  31227. data.setLayout({
  31228. largePoints: largePoints,
  31229. largeDataIndices: largeDataIndices,
  31230. largeBackgroundPoints: largeBackgroundPoints,
  31231. valueAxisHorizontal: isValueAxisH
  31232. });
  31233. }
  31234. }
  31235. };
  31236. }
  31237. };
  31238. }
  31239. function isOnCartesian(seriesModel) {
  31240. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  31241. }
  31242. function isInLargeMode(seriesModel) {
  31243. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  31244. }
  31245. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  31246. function getValueAxisStart(baseAxis, valueAxis) {
  31247. var startValue = valueAxis.model.get('startValue');
  31248. if (!startValue) {
  31249. startValue = 0;
  31250. }
  31251. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? startValue > 0 ? startValue : 1 : startValue));
  31252. }
  31253. // FIXME 公用?
  31254. var bisect = function (a, x, lo, hi) {
  31255. while (lo < hi) {
  31256. var mid = lo + hi >>> 1;
  31257. if (a[mid][1] < x) {
  31258. lo = mid + 1;
  31259. } else {
  31260. hi = mid;
  31261. }
  31262. }
  31263. return lo;
  31264. };
  31265. var TimeScale = /** @class */function (_super) {
  31266. __extends(TimeScale, _super);
  31267. function TimeScale(settings) {
  31268. var _this = _super.call(this, settings) || this;
  31269. _this.type = 'time';
  31270. return _this;
  31271. }
  31272. /**
  31273. * Get label is mainly for other components like dataZoom, tooltip.
  31274. */
  31275. TimeScale.prototype.getLabel = function (tick) {
  31276. var useUTC = this.getSetting('useUTC');
  31277. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  31278. };
  31279. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  31280. var isUTC = this.getSetting('useUTC');
  31281. var lang = this.getSetting('locale');
  31282. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  31283. };
  31284. /**
  31285. * @override
  31286. */
  31287. TimeScale.prototype.getTicks = function () {
  31288. var interval = this._interval;
  31289. var extent = this._extent;
  31290. var ticks = [];
  31291. // If interval is 0, return [];
  31292. if (!interval) {
  31293. return ticks;
  31294. }
  31295. ticks.push({
  31296. value: extent[0],
  31297. level: 0
  31298. });
  31299. var useUTC = this.getSetting('useUTC');
  31300. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  31301. ticks = ticks.concat(innerTicks);
  31302. ticks.push({
  31303. value: extent[1],
  31304. level: 0
  31305. });
  31306. return ticks;
  31307. };
  31308. TimeScale.prototype.calcNiceExtent = function (opt) {
  31309. var extent = this._extent;
  31310. // If extent start and end are same, expand them
  31311. if (extent[0] === extent[1]) {
  31312. // Expand extent
  31313. extent[0] -= ONE_DAY;
  31314. extent[1] += ONE_DAY;
  31315. }
  31316. // If there are no data and extent are [Infinity, -Infinity]
  31317. if (extent[1] === -Infinity && extent[0] === Infinity) {
  31318. var d = new Date();
  31319. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  31320. extent[0] = extent[1] - ONE_DAY;
  31321. }
  31322. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31323. };
  31324. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  31325. approxTickNum = approxTickNum || 10;
  31326. var extent = this._extent;
  31327. var span = extent[1] - extent[0];
  31328. this._approxInterval = span / approxTickNum;
  31329. if (minInterval != null && this._approxInterval < minInterval) {
  31330. this._approxInterval = minInterval;
  31331. }
  31332. if (maxInterval != null && this._approxInterval > maxInterval) {
  31333. this._approxInterval = maxInterval;
  31334. }
  31335. var scaleIntervalsLen = scaleIntervals.length;
  31336. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1);
  31337. // Interval that can be used to calculate ticks
  31338. this._interval = scaleIntervals[idx][1];
  31339. // Min level used when picking ticks from top down.
  31340. // We check one more level to avoid the ticks are to sparse in some case.
  31341. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  31342. };
  31343. TimeScale.prototype.parse = function (val) {
  31344. // val might be float.
  31345. return isNumber(val) ? val : +parseDate(val);
  31346. };
  31347. TimeScale.prototype.contain = function (val) {
  31348. return contain$1(this.parse(val), this._extent);
  31349. };
  31350. TimeScale.prototype.normalize = function (val) {
  31351. return normalize$1(this.parse(val), this._extent);
  31352. };
  31353. TimeScale.prototype.scale = function (val) {
  31354. return scale$2(val, this._extent);
  31355. };
  31356. TimeScale.type = 'time';
  31357. return TimeScale;
  31358. }(IntervalScale);
  31359. /**
  31360. * This implementation was originally copied from "d3.js"
  31361. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  31362. * with some modifications made for this program.
  31363. * See the license statement at the head of this file.
  31364. */
  31365. var scaleIntervals = [
  31366. // Format interval
  31367. ['second', ONE_SECOND], ['minute', ONE_MINUTE], ['hour', ONE_HOUR], ['quarter-day', ONE_HOUR * 6], ['half-day', ONE_HOUR * 12], ['day', ONE_DAY * 1.2], ['half-week', ONE_DAY * 3.5], ['week', ONE_DAY * 7], ['month', ONE_DAY * 31], ['quarter', ONE_DAY * 95], ['half-year', ONE_YEAR / 2], ['year', ONE_YEAR] // 1Y
  31368. ];
  31369. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  31370. var dateA = parseDate(valueA);
  31371. var dateB = parseDate(valueB);
  31372. var isSame = function (unit) {
  31373. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  31374. };
  31375. var isSameYear = function () {
  31376. return isSame('year');
  31377. };
  31378. // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  31379. // const isSameQuater = () => isSameYear() && isSame('quarter');
  31380. var isSameMonth = function () {
  31381. return isSameYear() && isSame('month');
  31382. };
  31383. var isSameDay = function () {
  31384. return isSameMonth() && isSame('day');
  31385. };
  31386. // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  31387. var isSameHour = function () {
  31388. return isSameDay() && isSame('hour');
  31389. };
  31390. var isSameMinute = function () {
  31391. return isSameHour() && isSame('minute');
  31392. };
  31393. var isSameSecond = function () {
  31394. return isSameMinute() && isSame('second');
  31395. };
  31396. var isSameMilliSecond = function () {
  31397. return isSameSecond() && isSame('millisecond');
  31398. };
  31399. switch (unit) {
  31400. case 'year':
  31401. return isSameYear();
  31402. case 'month':
  31403. return isSameMonth();
  31404. case 'day':
  31405. return isSameDay();
  31406. case 'hour':
  31407. return isSameHour();
  31408. case 'minute':
  31409. return isSameMinute();
  31410. case 'second':
  31411. return isSameSecond();
  31412. case 'millisecond':
  31413. return isSameMilliSecond();
  31414. }
  31415. }
  31416. // const primaryUnitGetters = {
  31417. // year: fullYearGetterName(),
  31418. // month: monthGetterName(),
  31419. // day: dateGetterName(),
  31420. // hour: hoursGetterName(),
  31421. // minute: minutesGetterName(),
  31422. // second: secondsGetterName(),
  31423. // millisecond: millisecondsGetterName()
  31424. // };
  31425. // const primaryUnitUTCGetters = {
  31426. // year: fullYearGetterName(true),
  31427. // month: monthGetterName(true),
  31428. // day: dateGetterName(true),
  31429. // hour: hoursGetterName(true),
  31430. // minute: minutesGetterName(true),
  31431. // second: secondsGetterName(true),
  31432. // millisecond: millisecondsGetterName(true)
  31433. // };
  31434. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  31435. // step = step || 1;
  31436. // switch (getPrimaryTimeUnit(unitName)) {
  31437. // case 'year':
  31438. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  31439. // break;
  31440. // case 'month':
  31441. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  31442. // break;
  31443. // case 'day':
  31444. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  31445. // break;
  31446. // case 'hour':
  31447. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  31448. // break;
  31449. // case 'minute':
  31450. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  31451. // break;
  31452. // case 'second':
  31453. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  31454. // break;
  31455. // case 'millisecond':
  31456. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  31457. // break;
  31458. // }
  31459. // return date.getTime();
  31460. // }
  31461. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  31462. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  31463. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  31464. function getDateInterval(approxInterval, daysInMonth) {
  31465. approxInterval /= ONE_DAY;
  31466. return approxInterval > 16 ? 16
  31467. // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  31468. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  31469. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  31470. }
  31471. function getMonthInterval(approxInterval) {
  31472. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  31473. approxInterval /= APPROX_ONE_MONTH;
  31474. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  31475. }
  31476. function getHourInterval(approxInterval) {
  31477. approxInterval /= ONE_HOUR;
  31478. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  31479. }
  31480. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  31481. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  31482. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  31483. }
  31484. function getMillisecondsInterval(approxInterval) {
  31485. return nice(approxInterval, true);
  31486. }
  31487. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  31488. var outDate = new Date(date);
  31489. switch (getPrimaryTimeUnit(unitName)) {
  31490. case 'year':
  31491. case 'month':
  31492. outDate[monthSetterName(isUTC)](0);
  31493. case 'day':
  31494. outDate[dateSetterName(isUTC)](1);
  31495. case 'hour':
  31496. outDate[hoursSetterName(isUTC)](0);
  31497. case 'minute':
  31498. outDate[minutesSetterName(isUTC)](0);
  31499. case 'second':
  31500. outDate[secondsSetterName(isUTC)](0);
  31501. outDate[millisecondsSetterName(isUTC)](0);
  31502. }
  31503. return outDate.getTime();
  31504. }
  31505. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  31506. var safeLimit = 10000;
  31507. var unitNames = timeUnits;
  31508. var iter = 0;
  31509. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  31510. var date = new Date(minTimestamp);
  31511. var dateTime = minTimestamp;
  31512. var d = date[getMethodName]();
  31513. // if (isDate) {
  31514. // d -= 1; // Starts with 0; PENDING
  31515. // }
  31516. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  31517. out.push({
  31518. value: dateTime
  31519. });
  31520. d += interval;
  31521. date[setMethodName](d);
  31522. dateTime = date.getTime();
  31523. }
  31524. // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  31525. out.push({
  31526. value: dateTime,
  31527. notAdd: true
  31528. });
  31529. }
  31530. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  31531. var newAddedTicks = [];
  31532. var isFirstLevel = !lastLevelTicks.length;
  31533. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  31534. return;
  31535. }
  31536. if (isFirstLevel) {
  31537. lastLevelTicks = [{
  31538. // TODO Optimize. Not include so may ticks.
  31539. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  31540. }, {
  31541. value: extent[1]
  31542. }];
  31543. }
  31544. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  31545. var startTick = lastLevelTicks[i].value;
  31546. var endTick = lastLevelTicks[i + 1].value;
  31547. if (startTick === endTick) {
  31548. continue;
  31549. }
  31550. var interval = void 0;
  31551. var getterName = void 0;
  31552. var setterName = void 0;
  31553. var isDate = false;
  31554. switch (unitName) {
  31555. case 'year':
  31556. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  31557. getterName = fullYearGetterName(isUTC);
  31558. setterName = fullYearSetterName(isUTC);
  31559. break;
  31560. case 'half-year':
  31561. case 'quarter':
  31562. case 'month':
  31563. interval = getMonthInterval(approxInterval);
  31564. getterName = monthGetterName(isUTC);
  31565. setterName = monthSetterName(isUTC);
  31566. break;
  31567. case 'week': // PENDING If week is added. Ignore day.
  31568. case 'half-week':
  31569. case 'day':
  31570. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  31571. getterName = dateGetterName(isUTC);
  31572. setterName = dateSetterName(isUTC);
  31573. isDate = true;
  31574. break;
  31575. case 'half-day':
  31576. case 'quarter-day':
  31577. case 'hour':
  31578. interval = getHourInterval(approxInterval);
  31579. getterName = hoursGetterName(isUTC);
  31580. setterName = hoursSetterName(isUTC);
  31581. break;
  31582. case 'minute':
  31583. interval = getMinutesAndSecondsInterval(approxInterval, true);
  31584. getterName = minutesGetterName(isUTC);
  31585. setterName = minutesSetterName(isUTC);
  31586. break;
  31587. case 'second':
  31588. interval = getMinutesAndSecondsInterval(approxInterval, false);
  31589. getterName = secondsGetterName(isUTC);
  31590. setterName = secondsSetterName(isUTC);
  31591. break;
  31592. case 'millisecond':
  31593. interval = getMillisecondsInterval(approxInterval);
  31594. getterName = millisecondsGetterName(isUTC);
  31595. setterName = millisecondsSetterName(isUTC);
  31596. break;
  31597. }
  31598. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  31599. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  31600. // Add nearest years to the left extent.
  31601. levelTicks.unshift({
  31602. value: levelTicks[0].value - interval
  31603. });
  31604. }
  31605. }
  31606. for (var i = 0; i < newAddedTicks.length; i++) {
  31607. levelTicks.push(newAddedTicks[i]);
  31608. }
  31609. // newAddedTicks.length && console.log(unitName, newAddedTicks);
  31610. return newAddedTicks;
  31611. }
  31612. var levelsTicks = [];
  31613. var currentLevelTicks = [];
  31614. var tickCount = 0;
  31615. var lastLevelTickCount = 0;
  31616. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  31617. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  31618. if (!isPrimaryTimeUnit(unitNames[i])) {
  31619. // TODO
  31620. continue;
  31621. }
  31622. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  31623. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  31624. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  31625. if (currentLevelTicks.length) {
  31626. lastLevelTickCount = tickCount;
  31627. // Remove the duplicate so the tick count can be precisely.
  31628. currentLevelTicks.sort(function (a, b) {
  31629. return a.value - b.value;
  31630. });
  31631. var levelTicksRemoveDuplicated = [];
  31632. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  31633. var tickValue = currentLevelTicks[i_1].value;
  31634. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  31635. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  31636. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  31637. tickCount++;
  31638. }
  31639. }
  31640. }
  31641. var targetTickNum = (extent[1] - extent[0]) / approxInterval;
  31642. // Added too much in this level and not too less in last level
  31643. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  31644. break;
  31645. }
  31646. // Only treat primary time unit as one level.
  31647. levelsTicks.push(levelTicksRemoveDuplicated);
  31648. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  31649. break;
  31650. }
  31651. }
  31652. // Reset if next unitName is primary
  31653. currentLevelTicks = [];
  31654. }
  31655. }
  31656. if ("development" !== 'production') {
  31657. if (iter >= safeLimit) {
  31658. warn('Exceed safe limit.');
  31659. }
  31660. }
  31661. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  31662. return filter(levelTicks, function (tick) {
  31663. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  31664. });
  31665. }), function (levelTicks) {
  31666. return levelTicks.length > 0;
  31667. });
  31668. var ticks = [];
  31669. var maxLevel = levelsTicksInExtent.length - 1;
  31670. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  31671. var levelTicks = levelsTicksInExtent[i];
  31672. for (var k = 0; k < levelTicks.length; ++k) {
  31673. ticks.push({
  31674. value: levelTicks[k].value,
  31675. level: maxLevel - i
  31676. });
  31677. }
  31678. }
  31679. ticks.sort(function (a, b) {
  31680. return a.value - b.value;
  31681. });
  31682. // Remove duplicates
  31683. var result = [];
  31684. for (var i = 0; i < ticks.length; ++i) {
  31685. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  31686. result.push(ticks[i]);
  31687. }
  31688. }
  31689. return result;
  31690. }
  31691. Scale.registerClass(TimeScale);
  31692. var scaleProto = Scale.prototype;
  31693. // FIXME:TS refactor: not good to call it directly with `this`?
  31694. var intervalScaleProto = IntervalScale.prototype;
  31695. var roundingErrorFix = round;
  31696. var mathFloor = Math.floor;
  31697. var mathCeil = Math.ceil;
  31698. var mathPow$1 = Math.pow;
  31699. var mathLog = Math.log;
  31700. var LogScale = /** @class */function (_super) {
  31701. __extends(LogScale, _super);
  31702. function LogScale() {
  31703. var _this = _super !== null && _super.apply(this, arguments) || this;
  31704. _this.type = 'log';
  31705. _this.base = 10;
  31706. _this._originalScale = new IntervalScale();
  31707. // FIXME:TS actually used by `IntervalScale`
  31708. _this._interval = 0;
  31709. return _this;
  31710. }
  31711. /**
  31712. * @param Whether expand the ticks to niced extent.
  31713. */
  31714. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  31715. var originalScale = this._originalScale;
  31716. var extent = this._extent;
  31717. var originalExtent = originalScale.getExtent();
  31718. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  31719. return map(ticks, function (tick) {
  31720. var val = tick.value;
  31721. var powVal = round(mathPow$1(this.base, val));
  31722. // Fix #4158
  31723. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  31724. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  31725. return {
  31726. value: powVal
  31727. };
  31728. }, this);
  31729. };
  31730. LogScale.prototype.setExtent = function (start, end) {
  31731. var base = mathLog(this.base);
  31732. // log(-Infinity) is NaN, so safe guard here
  31733. start = mathLog(Math.max(0, start)) / base;
  31734. end = mathLog(Math.max(0, end)) / base;
  31735. intervalScaleProto.setExtent.call(this, start, end);
  31736. };
  31737. /**
  31738. * @return {number} end
  31739. */
  31740. LogScale.prototype.getExtent = function () {
  31741. var base = this.base;
  31742. var extent = scaleProto.getExtent.call(this);
  31743. extent[0] = mathPow$1(base, extent[0]);
  31744. extent[1] = mathPow$1(base, extent[1]);
  31745. // Fix #4158
  31746. var originalScale = this._originalScale;
  31747. var originalExtent = originalScale.getExtent();
  31748. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31749. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31750. return extent;
  31751. };
  31752. LogScale.prototype.unionExtent = function (extent) {
  31753. this._originalScale.unionExtent(extent);
  31754. var base = this.base;
  31755. extent[0] = mathLog(extent[0]) / mathLog(base);
  31756. extent[1] = mathLog(extent[1]) / mathLog(base);
  31757. scaleProto.unionExtent.call(this, extent);
  31758. };
  31759. LogScale.prototype.unionExtentFromData = function (data, dim) {
  31760. // TODO
  31761. // filter value that <= 0
  31762. this.unionExtent(data.getApproximateExtent(dim));
  31763. };
  31764. /**
  31765. * Update interval and extent of intervals for nice ticks
  31766. * @param approxTickNum default 10 Given approx tick number
  31767. */
  31768. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  31769. approxTickNum = approxTickNum || 10;
  31770. var extent = this._extent;
  31771. var span = extent[1] - extent[0];
  31772. if (span === Infinity || span <= 0) {
  31773. return;
  31774. }
  31775. var interval = quantity(span);
  31776. var err = approxTickNum / span * interval;
  31777. // Filter ticks to get closer to the desired count.
  31778. if (err <= 0.5) {
  31779. interval *= 10;
  31780. }
  31781. // Interval should be integer
  31782. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31783. interval *= 10;
  31784. }
  31785. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  31786. this._interval = interval;
  31787. this._niceExtent = niceExtent;
  31788. };
  31789. LogScale.prototype.calcNiceExtent = function (opt) {
  31790. intervalScaleProto.calcNiceExtent.call(this, opt);
  31791. this._fixMin = opt.fixMin;
  31792. this._fixMax = opt.fixMax;
  31793. };
  31794. LogScale.prototype.parse = function (val) {
  31795. return val;
  31796. };
  31797. LogScale.prototype.contain = function (val) {
  31798. val = mathLog(val) / mathLog(this.base);
  31799. return contain$1(val, this._extent);
  31800. };
  31801. LogScale.prototype.normalize = function (val) {
  31802. val = mathLog(val) / mathLog(this.base);
  31803. return normalize$1(val, this._extent);
  31804. };
  31805. LogScale.prototype.scale = function (val) {
  31806. val = scale$2(val, this._extent);
  31807. return mathPow$1(this.base, val);
  31808. };
  31809. LogScale.type = 'log';
  31810. return LogScale;
  31811. }(Scale);
  31812. var proto = LogScale.prototype;
  31813. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31814. proto.getLabel = intervalScaleProto.getLabel;
  31815. function fixRoundingError(val, originalVal) {
  31816. return roundingErrorFix(val, getPrecision(originalVal));
  31817. }
  31818. Scale.registerClass(LogScale);
  31819. var ScaleRawExtentInfo = /** @class */function () {
  31820. function ScaleRawExtentInfo(scale, model,
  31821. // Usually: data extent from all series on this axis.
  31822. originalExtent) {
  31823. this._prepareParams(scale, model, originalExtent);
  31824. }
  31825. /**
  31826. * Parameters depending on outside (like model, user callback)
  31827. * are prepared and fixed here.
  31828. */
  31829. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model,
  31830. // Usually: data extent from all series on this axis.
  31831. dataExtent) {
  31832. if (dataExtent[1] < dataExtent[0]) {
  31833. dataExtent = [NaN, NaN];
  31834. }
  31835. this._dataMin = dataExtent[0];
  31836. this._dataMax = dataExtent[1];
  31837. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31838. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31839. var axisMinValue = model.get('min', true);
  31840. if (axisMinValue == null) {
  31841. axisMinValue = model.get('startValue', true);
  31842. }
  31843. var modelMinRaw = this._modelMinRaw = axisMinValue;
  31844. if (isFunction(modelMinRaw)) {
  31845. // This callback always provides users the full data extent (before data is filtered).
  31846. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31847. min: dataExtent[0],
  31848. max: dataExtent[1]
  31849. }));
  31850. } else if (modelMinRaw !== 'dataMin') {
  31851. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31852. }
  31853. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31854. if (isFunction(modelMaxRaw)) {
  31855. // This callback always provides users the full data extent (before data is filtered).
  31856. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31857. min: dataExtent[0],
  31858. max: dataExtent[1]
  31859. }));
  31860. } else if (modelMaxRaw !== 'dataMax') {
  31861. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31862. }
  31863. if (isOrdinal) {
  31864. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31865. // and progressive rendering is using, here the category result might just only contain
  31866. // the processed chunk rather than the entire result.
  31867. this._axisDataLen = model.getCategories().length;
  31868. } else {
  31869. var boundaryGap = model.get('boundaryGap');
  31870. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31871. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31872. if ("development" !== 'production') {
  31873. console.warn('Boolean type for boundaryGap is only ' + 'allowed for ordinal axis. Please use string in ' + 'percentage instead, e.g., "20%". Currently, ' + 'boundaryGap is set to be 0.');
  31874. }
  31875. this._boundaryGapInner = [0, 0];
  31876. } else {
  31877. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31878. }
  31879. }
  31880. };
  31881. /**
  31882. * Calculate extent by prepared parameters.
  31883. * This method has no external dependency and can be called duplicatedly,
  31884. * getting the same result.
  31885. * If parameters changed, should call this method to recalcuate.
  31886. */
  31887. ScaleRawExtentInfo.prototype.calculate = function () {
  31888. // Notice: When min/max is not set (that is, when there are null/undefined,
  31889. // which is the most common case), these cases should be ensured:
  31890. // (1) For 'ordinal', show all axis.data.
  31891. // (2) For others:
  31892. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31893. // disabled).
  31894. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31895. // be the result that originalExtent enlarged by boundaryGap.
  31896. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31897. var isOrdinal = this._isOrdinal;
  31898. var dataMin = this._dataMin;
  31899. var dataMax = this._dataMax;
  31900. var axisDataLen = this._axisDataLen;
  31901. var boundaryGapInner = this._boundaryGapInner;
  31902. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null;
  31903. // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31904. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31905. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31906. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum;
  31907. // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31908. var minFixed = min != null;
  31909. var maxFixed = max != null;
  31910. if (min == null) {
  31911. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31912. }
  31913. if (max == null) {
  31914. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31915. }
  31916. (min == null || !isFinite(min)) && (min = NaN);
  31917. (max == null || !isFinite(max)) && (max = NaN);
  31918. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen;
  31919. // If data extent modified, need to recalculated to ensure cross zero.
  31920. if (this._needCrossZero) {
  31921. // Axis is over zero and min is not set
  31922. if (min > 0 && max > 0 && !minFixed) {
  31923. min = 0;
  31924. // minFixed = true;
  31925. }
  31926. // Axis is under zero and max is not set
  31927. if (min < 0 && max < 0 && !maxFixed) {
  31928. max = 0;
  31929. // maxFixed = true;
  31930. }
  31931. // PENDING:
  31932. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31933. // that the results processed by boundaryGap are positive/negative?
  31934. // If so, here `minFixed`/`maxFixed` need to be set.
  31935. }
  31936. var determinedMin = this._determinedMin;
  31937. var determinedMax = this._determinedMax;
  31938. if (determinedMin != null) {
  31939. min = determinedMin;
  31940. minFixed = true;
  31941. }
  31942. if (determinedMax != null) {
  31943. max = determinedMax;
  31944. maxFixed = true;
  31945. }
  31946. // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31947. // `NaN` means min/max axis is blank.
  31948. return {
  31949. min: min,
  31950. max: max,
  31951. minFixed: minFixed,
  31952. maxFixed: maxFixed,
  31953. isBlank: isBlank
  31954. };
  31955. };
  31956. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31957. if ("development" !== 'production') {
  31958. assert(!this.frozen);
  31959. }
  31960. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31961. };
  31962. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31963. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31964. if ("development" !== 'production') {
  31965. assert(!this.frozen
  31966. // Earse them usually means logic flaw.
  31967. && this[attr] == null);
  31968. }
  31969. this[attr] = val;
  31970. };
  31971. ScaleRawExtentInfo.prototype.freeze = function () {
  31972. // @ts-ignore
  31973. this.frozen = true;
  31974. };
  31975. return ScaleRawExtentInfo;
  31976. }();
  31977. var DETERMINED_MIN_MAX_ATTR = {
  31978. min: '_determinedMin',
  31979. max: '_determinedMax'
  31980. };
  31981. var DATA_MIN_MAX_ATTR = {
  31982. min: '_dataMin',
  31983. max: '_dataMax'
  31984. };
  31985. /**
  31986. * Get scale min max and related info only depends on model settings.
  31987. * This method can be called after coordinate system created.
  31988. * For example, in data processing stage.
  31989. *
  31990. * Scale extent info probably be required multiple times during a workflow.
  31991. * For example:
  31992. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31993. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31994. * (3) `coordSys.update` use it to finally decide the scale extent.
  31995. * But the callback of `min`/`max` should not be called multiple times.
  31996. * The code below should not be implemented repeatedly either.
  31997. * So we cache the result in the scale instance, which will be recreated at the beginning
  31998. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31999. */
  32000. function ensureScaleRawExtentInfo(scale, model,
  32001. // Usually: data extent from all series on this axis.
  32002. originalExtent) {
  32003. // Do not permit to recreate.
  32004. var rawExtentInfo = scale.rawExtentInfo;
  32005. if (rawExtentInfo) {
  32006. return rawExtentInfo;
  32007. }
  32008. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent);
  32009. // @ts-ignore
  32010. scale.rawExtentInfo = rawExtentInfo;
  32011. return rawExtentInfo;
  32012. }
  32013. function parseAxisModelMinMax(scale, minMax) {
  32014. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  32015. }
  32016. /**
  32017. * Get axis scale extent before niced.
  32018. * Item of returned array can only be number (including Infinity and NaN).
  32019. *
  32020. * Caution:
  32021. * Precondition of calling this method:
  32022. * The scale extent has been initialized using series data extent via
  32023. * `scale.setExtent` or `scale.unionExtentFromData`;
  32024. */
  32025. function getScaleExtent(scale, model) {
  32026. var scaleType = scale.type;
  32027. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  32028. scale.setBlank(rawExtentResult.isBlank);
  32029. var min = rawExtentResult.min;
  32030. var max = rawExtentResult.max;
  32031. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  32032. // is base axis
  32033. // FIXME
  32034. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  32035. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  32036. // Should not depend on series type `bar`?
  32037. // (3) Fix that might overlap when using dataZoom.
  32038. // (4) Consider other chart types using `barGrid`?
  32039. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  32040. var ecModel = model.ecModel;
  32041. if (ecModel && scaleType === 'time' /* || scaleType === 'interval' */) {
  32042. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  32043. var isBaseAxisAndHasBarSeries_1 = false;
  32044. each(barSeriesModels, function (seriesModel) {
  32045. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  32046. });
  32047. if (isBaseAxisAndHasBarSeries_1) {
  32048. // Calculate placement of bars on axis. TODO should be decoupled
  32049. // with barLayout
  32050. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  32051. // Adjust axis min and max to account for overflow
  32052. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  32053. min = adjustedScale.min;
  32054. max = adjustedScale.max;
  32055. }
  32056. }
  32057. return {
  32058. extent: [min, max],
  32059. // "fix" means "fixed", the value should not be
  32060. // changed in the subsequent steps.
  32061. fixMin: rawExtentResult.minFixed,
  32062. fixMax: rawExtentResult.maxFixed
  32063. };
  32064. }
  32065. function adjustScaleForOverflow(min, max, model,
  32066. // Only support cartesian coord yet.
  32067. barWidthAndOffset) {
  32068. // Get Axis Length
  32069. var axisExtent = model.axis.getExtent();
  32070. var axisLength = Math.abs(axisExtent[1] - axisExtent[0]);
  32071. // Get bars on current base axis and calculate min and max overflow
  32072. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  32073. if (barsOnCurrentAxis === undefined) {
  32074. return {
  32075. min: min,
  32076. max: max
  32077. };
  32078. }
  32079. var minOverflow = Infinity;
  32080. each(barsOnCurrentAxis, function (item) {
  32081. minOverflow = Math.min(item.offset, minOverflow);
  32082. });
  32083. var maxOverflow = -Infinity;
  32084. each(barsOnCurrentAxis, function (item) {
  32085. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  32086. });
  32087. minOverflow = Math.abs(minOverflow);
  32088. maxOverflow = Math.abs(maxOverflow);
  32089. var totalOverFlow = minOverflow + maxOverflow;
  32090. // Calculate required buffer based on old range and overflow
  32091. var oldRange = max - min;
  32092. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  32093. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  32094. max += overflowBuffer * (maxOverflow / totalOverFlow);
  32095. min -= overflowBuffer * (minOverflow / totalOverFlow);
  32096. return {
  32097. min: min,
  32098. max: max
  32099. };
  32100. }
  32101. // Precondition of calling this method:
  32102. // The scale extent has been initialized using series data extent via
  32103. // `scale.setExtent` or `scale.unionExtentFromData`;
  32104. function niceScaleExtent(scale, inModel) {
  32105. var model = inModel;
  32106. var extentInfo = getScaleExtent(scale, model);
  32107. var extent = extentInfo.extent;
  32108. var splitNumber = model.get('splitNumber');
  32109. if (scale instanceof LogScale) {
  32110. scale.base = model.get('logBase');
  32111. }
  32112. var scaleType = scale.type;
  32113. var interval = model.get('interval');
  32114. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  32115. scale.setExtent(extent[0], extent[1]);
  32116. scale.calcNiceExtent({
  32117. splitNumber: splitNumber,
  32118. fixMin: extentInfo.fixMin,
  32119. fixMax: extentInfo.fixMax,
  32120. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  32121. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  32122. });
  32123. // If some one specified the min, max. And the default calculated interval
  32124. // is not good enough. He can specify the interval. It is often appeared
  32125. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32126. // to be 60.
  32127. // FIXME
  32128. if (interval != null) {
  32129. scale.setInterval && scale.setInterval(interval);
  32130. }
  32131. }
  32132. /**
  32133. * @param axisType Default retrieve from model.type
  32134. */
  32135. function createScaleByModel(model, axisType) {
  32136. axisType = axisType || model.get('type');
  32137. if (axisType) {
  32138. switch (axisType) {
  32139. // Buildin scale
  32140. case 'category':
  32141. return new OrdinalScale({
  32142. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  32143. extent: [Infinity, -Infinity]
  32144. });
  32145. case 'time':
  32146. return new TimeScale({
  32147. locale: model.ecModel.getLocaleModel(),
  32148. useUTC: model.ecModel.get('useUTC')
  32149. });
  32150. default:
  32151. // case 'value'/'interval', 'log', or others.
  32152. return new (Scale.getClass(axisType) || IntervalScale)();
  32153. }
  32154. }
  32155. }
  32156. /**
  32157. * Check if the axis cross 0
  32158. */
  32159. function ifAxisCrossZero(axis) {
  32160. var dataExtent = axis.scale.getExtent();
  32161. var min = dataExtent[0];
  32162. var max = dataExtent[1];
  32163. return !(min > 0 && max > 0 || min < 0 && max < 0);
  32164. }
  32165. /**
  32166. * @param axis
  32167. * @return Label formatter function.
  32168. * param: {number} tickValue,
  32169. * param: {number} idx, the index in all ticks.
  32170. * If category axis, this param is not required.
  32171. * return: {string} label string.
  32172. */
  32173. function makeLabelFormatter(axis) {
  32174. var labelFormatter = axis.getLabelModel().get('formatter');
  32175. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32176. if (axis.scale.type === 'time') {
  32177. return function (tpl) {
  32178. return function (tick, idx) {
  32179. return axis.scale.getFormattedLabel(tick, idx, tpl);
  32180. };
  32181. }(labelFormatter);
  32182. } else if (isString(labelFormatter)) {
  32183. return function (tpl) {
  32184. return function (tick) {
  32185. // For category axis, get raw value; for numeric axis,
  32186. // get formatted label like '1,333,444'.
  32187. var label = axis.scale.getLabel(tick);
  32188. var text = tpl.replace('{value}', label != null ? label : '');
  32189. return text;
  32190. };
  32191. }(labelFormatter);
  32192. } else if (isFunction(labelFormatter)) {
  32193. return function (cb) {
  32194. return function (tick, idx) {
  32195. // The original intention of `idx` is "the index of the tick in all ticks".
  32196. // But the previous implementation of category axis do not consider the
  32197. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32198. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32199. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32200. // the definition here for back compatibility.
  32201. if (categoryTickStart != null) {
  32202. idx = tick.value - categoryTickStart;
  32203. }
  32204. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  32205. level: tick.level
  32206. } : null);
  32207. };
  32208. }(labelFormatter);
  32209. } else {
  32210. return function (tick) {
  32211. return axis.scale.getLabel(tick);
  32212. };
  32213. }
  32214. }
  32215. function getAxisRawValue(axis, tick) {
  32216. // In category axis with data zoom, tick is not the original
  32217. // index of axis.data. So tick should not be exposed to user
  32218. // in category axis.
  32219. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  32220. }
  32221. /**
  32222. * @param axis
  32223. * @return Be null/undefined if no labels.
  32224. */
  32225. function estimateLabelUnionRect(axis) {
  32226. var axisModel = axis.model;
  32227. var scale = axis.scale;
  32228. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  32229. return;
  32230. }
  32231. var realNumberScaleTicks;
  32232. var tickCount;
  32233. var categoryScaleExtent = scale.getExtent();
  32234. // Optimize for large category data, avoid call `getTicks()`.
  32235. if (scale instanceof OrdinalScale) {
  32236. tickCount = scale.count();
  32237. } else {
  32238. realNumberScaleTicks = scale.getTicks();
  32239. tickCount = realNumberScaleTicks.length;
  32240. }
  32241. var axisLabelModel = axis.getLabelModel();
  32242. var labelFormatter = makeLabelFormatter(axis);
  32243. var rect;
  32244. var step = 1;
  32245. // Simple optimization for large amount of labels
  32246. if (tickCount > 40) {
  32247. step = Math.ceil(tickCount / 40);
  32248. }
  32249. for (var i = 0; i < tickCount; i += step) {
  32250. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  32251. value: categoryScaleExtent[0] + i
  32252. };
  32253. var label = labelFormatter(tick, i);
  32254. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32255. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32256. rect ? rect.union(singleRect) : rect = singleRect;
  32257. }
  32258. return rect;
  32259. }
  32260. function rotateTextRect(textRect, rotate) {
  32261. var rotateRadians = rotate * Math.PI / 180;
  32262. var beforeWidth = textRect.width;
  32263. var beforeHeight = textRect.height;
  32264. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  32265. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  32266. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  32267. return rotatedRect;
  32268. }
  32269. /**
  32270. * @param model axisLabelModel or axisTickModel
  32271. * @return {number|String} Can be null|'auto'|number|function
  32272. */
  32273. function getOptionCategoryInterval(model) {
  32274. var interval = model.get('interval');
  32275. return interval == null ? 'auto' : interval;
  32276. }
  32277. /**
  32278. * Set `categoryInterval` as 0 implicitly indicates that
  32279. * show all labels regardless of overlap.
  32280. * @param {Object} axis axisModel.axis
  32281. */
  32282. function shouldShowAllLabels(axis) {
  32283. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32284. }
  32285. function getDataDimensionsOnAxis(data, axisDim) {
  32286. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  32287. var dataDimMap = {};
  32288. // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  32289. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  32290. // there has been stacked result dim?
  32291. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  32292. // For example, the extent of the original dimension
  32293. // is [0.1, 0.5], the extent of the `stackResultDimension`
  32294. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  32295. // because there is no graphic corresponding to [0.1, 0.5].
  32296. // See the case in `test/area-stack.html` `main1`, where area line
  32297. // stack needs `yAxis` not start from 0.
  32298. dataDimMap[getStackedDimension(data, dataDim)] = true;
  32299. });
  32300. return keys(dataDimMap);
  32301. }
  32302. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  32303. if (data) {
  32304. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  32305. var seriesExtent = data.getApproximateExtent(dim);
  32306. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  32307. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  32308. });
  32309. }
  32310. }
  32311. /*
  32312. * Licensed to the Apache Software Foundation (ASF) under one
  32313. * or more contributor license agreements. See the NOTICE file
  32314. * distributed with this work for additional information
  32315. * regarding copyright ownership. The ASF licenses this file
  32316. * to you under the Apache License, Version 2.0 (the
  32317. * "License"); you may not use this file except in compliance
  32318. * with the License. You may obtain a copy of the License at
  32319. *
  32320. * http://www.apache.org/licenses/LICENSE-2.0
  32321. *
  32322. * Unless required by applicable law or agreed to in writing,
  32323. * software distributed under the License is distributed on an
  32324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32325. * KIND, either express or implied. See the License for the
  32326. * specific language governing permissions and limitations
  32327. * under the License.
  32328. */
  32329. /**
  32330. * AUTO-GENERATED FILE. DO NOT MODIFY.
  32331. */
  32332. /*
  32333. * Licensed to the Apache Software Foundation (ASF) under one
  32334. * or more contributor license agreements. See the NOTICE file
  32335. * distributed with this work for additional information
  32336. * regarding copyright ownership. The ASF licenses this file
  32337. * to you under the Apache License, Version 2.0 (the
  32338. * "License"); you may not use this file except in compliance
  32339. * with the License. You may obtain a copy of the License at
  32340. *
  32341. * http://www.apache.org/licenses/LICENSE-2.0
  32342. *
  32343. * Unless required by applicable law or agreed to in writing,
  32344. * software distributed under the License is distributed on an
  32345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32346. * KIND, either express or implied. See the License for the
  32347. * specific language governing permissions and limitations
  32348. * under the License.
  32349. */
  32350. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  32351. var AxisModelCommonMixin = /** @class */function () {
  32352. function AxisModelCommonMixin() {}
  32353. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  32354. var option = this.option;
  32355. return !option.scale;
  32356. };
  32357. /**
  32358. * Should be implemented by each axis model if necessary.
  32359. * @return coordinate system model
  32360. */
  32361. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  32362. return;
  32363. };
  32364. return AxisModelCommonMixin;
  32365. }();
  32366. /**
  32367. * Create a multi dimension List structure from seriesModel.
  32368. */
  32369. function createList(seriesModel) {
  32370. return createSeriesData(null, seriesModel);
  32371. }
  32372. var dataStack$1 = {
  32373. isDimensionStacked: isDimensionStacked,
  32374. enableDataStack: enableDataStack,
  32375. getStackedDimension: getStackedDimension
  32376. };
  32377. /**
  32378. * Create scale
  32379. * @param {Array.<number>} dataExtent
  32380. * @param {Object|module:echarts/Model} option If `optoin.type`
  32381. * is secified, it can only be `'value'` currently.
  32382. */
  32383. function createScale(dataExtent, option) {
  32384. var axisModel = option;
  32385. if (!(option instanceof Model)) {
  32386. axisModel = new Model(option);
  32387. // FIXME
  32388. // Currently AxisModelCommonMixin has nothing to do with the
  32389. // the requirements of `axisHelper.createScaleByModel`. For
  32390. // example the methods `getCategories` and `getOrdinalMeta`
  32391. // are required for `'category'` axis, and ecModel is required
  32392. // for `'time'` axis. But occasionally echarts-gl happened
  32393. // to only use `'value'` axis.
  32394. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  32395. }
  32396. var scale = createScaleByModel(axisModel);
  32397. scale.setExtent(dataExtent[0], dataExtent[1]);
  32398. niceScaleExtent(scale, axisModel);
  32399. return scale;
  32400. }
  32401. /**
  32402. * Mixin common methods to axis model,
  32403. *
  32404. * Include methods
  32405. * `getFormattedLabels() => Array.<string>`
  32406. * `getCategories() => Array.<string>`
  32407. * `getMin(origin: boolean) => number`
  32408. * `getMax(origin: boolean) => number`
  32409. * `getNeedCrossZero() => boolean`
  32410. */
  32411. function mixinAxisModelCommonMethods(Model) {
  32412. mixin(Model, AxisModelCommonMixin);
  32413. }
  32414. function createTextStyle$1(textStyleModel, opts) {
  32415. opts = opts || {};
  32416. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  32417. }
  32418. var helper = /*#__PURE__*/Object.freeze({
  32419. __proto__: null,
  32420. createList: createList,
  32421. getLayoutRect: getLayoutRect,
  32422. dataStack: dataStack$1,
  32423. createScale: createScale,
  32424. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  32425. getECData: getECData,
  32426. createTextStyle: createTextStyle$1,
  32427. createDimensions: createDimensions,
  32428. createSymbol: createSymbol,
  32429. enableHoverEmphasis: enableHoverEmphasis
  32430. });
  32431. var EPSILON$4 = 1e-8;
  32432. function isAroundEqual$1(a, b) {
  32433. return Math.abs(a - b) < EPSILON$4;
  32434. }
  32435. function contain$2(points, x, y) {
  32436. var w = 0;
  32437. var p = points[0];
  32438. if (!p) {
  32439. return false;
  32440. }
  32441. for (var i = 1; i < points.length; i++) {
  32442. var p2 = points[i];
  32443. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  32444. p = p2;
  32445. }
  32446. var p0 = points[0];
  32447. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  32448. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  32449. }
  32450. return w !== 0;
  32451. }
  32452. var TMP_TRANSFORM = [];
  32453. function transformPoints(points, transform) {
  32454. for (var p = 0; p < points.length; p++) {
  32455. applyTransform(points[p], points[p], transform);
  32456. }
  32457. }
  32458. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  32459. for (var i = 0; i < points.length; i++) {
  32460. var p = points[i];
  32461. if (projection) {
  32462. // projection may return null point.
  32463. p = projection.project(p);
  32464. }
  32465. if (p && isFinite(p[0]) && isFinite(p[1])) {
  32466. min(min$1, min$1, p);
  32467. max(max$1, max$1, p);
  32468. }
  32469. }
  32470. }
  32471. function centroid(points) {
  32472. var signedArea = 0;
  32473. var cx = 0;
  32474. var cy = 0;
  32475. var len = points.length;
  32476. var x0 = points[len - 1][0];
  32477. var y0 = points[len - 1][1];
  32478. // Polygon should been closed.
  32479. for (var i = 0; i < len; i++) {
  32480. var x1 = points[i][0];
  32481. var y1 = points[i][1];
  32482. var a = x0 * y1 - x1 * y0;
  32483. signedArea += a;
  32484. cx += (x0 + x1) * a;
  32485. cy += (y0 + y1) * a;
  32486. x0 = x1;
  32487. y0 = y1;
  32488. }
  32489. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  32490. }
  32491. var Region = /** @class */function () {
  32492. function Region(name) {
  32493. this.name = name;
  32494. }
  32495. Region.prototype.setCenter = function (center) {
  32496. this._center = center;
  32497. };
  32498. /**
  32499. * Get center point in data unit. That is,
  32500. * for GeoJSONRegion, the unit is lat/lng,
  32501. * for GeoSVGRegion, the unit is SVG local coord.
  32502. */
  32503. Region.prototype.getCenter = function () {
  32504. var center = this._center;
  32505. if (!center) {
  32506. // In most cases there are no need to calculate this center.
  32507. // So calculate only when called.
  32508. center = this._center = this.calcCenter();
  32509. }
  32510. return center;
  32511. };
  32512. return Region;
  32513. }();
  32514. var GeoJSONPolygonGeometry = /** @class */function () {
  32515. function GeoJSONPolygonGeometry(exterior, interiors) {
  32516. this.type = 'polygon';
  32517. this.exterior = exterior;
  32518. this.interiors = interiors;
  32519. }
  32520. return GeoJSONPolygonGeometry;
  32521. }();
  32522. var GeoJSONLineStringGeometry = /** @class */function () {
  32523. function GeoJSONLineStringGeometry(points) {
  32524. this.type = 'linestring';
  32525. this.points = points;
  32526. }
  32527. return GeoJSONLineStringGeometry;
  32528. }();
  32529. var GeoJSONRegion = /** @class */function (_super) {
  32530. __extends(GeoJSONRegion, _super);
  32531. function GeoJSONRegion(name, geometries, cp) {
  32532. var _this = _super.call(this, name) || this;
  32533. _this.type = 'geoJSON';
  32534. _this.geometries = geometries;
  32535. _this._center = cp && [cp[0], cp[1]];
  32536. return _this;
  32537. }
  32538. GeoJSONRegion.prototype.calcCenter = function () {
  32539. var geometries = this.geometries;
  32540. var largestGeo;
  32541. var largestGeoSize = 0;
  32542. for (var i = 0; i < geometries.length; i++) {
  32543. var geo = geometries[i];
  32544. var exterior = geo.exterior;
  32545. // Simple trick to use points count instead of polygon area as region size.
  32546. // Ignore linestring
  32547. var size = exterior && exterior.length;
  32548. if (size > largestGeoSize) {
  32549. largestGeo = geo;
  32550. largestGeoSize = size;
  32551. }
  32552. }
  32553. if (largestGeo) {
  32554. return centroid(largestGeo.exterior);
  32555. }
  32556. // from bounding rect by default.
  32557. var rect = this.getBoundingRect();
  32558. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32559. };
  32560. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  32561. var rect = this._rect;
  32562. // Always recalculate if using projection.
  32563. if (rect && !projection) {
  32564. return rect;
  32565. }
  32566. var min = [Infinity, Infinity];
  32567. var max = [-Infinity, -Infinity];
  32568. var geometries = this.geometries;
  32569. each(geometries, function (geo) {
  32570. if (geo.type === 'polygon') {
  32571. // Doesn't consider hole
  32572. updateBBoxFromPoints(geo.exterior, min, max, projection);
  32573. } else {
  32574. each(geo.points, function (points) {
  32575. updateBBoxFromPoints(points, min, max, projection);
  32576. });
  32577. }
  32578. });
  32579. // Normalie invalid bounding.
  32580. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  32581. min[0] = min[1] = max[0] = max[1] = 0;
  32582. }
  32583. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  32584. if (!projection) {
  32585. this._rect = rect;
  32586. }
  32587. return rect;
  32588. };
  32589. GeoJSONRegion.prototype.contain = function (coord) {
  32590. var rect = this.getBoundingRect();
  32591. var geometries = this.geometries;
  32592. if (!rect.contain(coord[0], coord[1])) {
  32593. return false;
  32594. }
  32595. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  32596. var geo = geometries[i];
  32597. // Only support polygon.
  32598. if (geo.type !== 'polygon') {
  32599. continue;
  32600. }
  32601. var exterior = geo.exterior;
  32602. var interiors = geo.interiors;
  32603. if (contain$2(exterior, coord[0], coord[1])) {
  32604. // Not in the region if point is in the hole.
  32605. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  32606. if (contain$2(interiors[k], coord[0], coord[1])) {
  32607. continue loopGeo;
  32608. }
  32609. }
  32610. return true;
  32611. }
  32612. }
  32613. return false;
  32614. };
  32615. /**
  32616. * Transform the raw coords to target bounding.
  32617. * @param x
  32618. * @param y
  32619. * @param width
  32620. * @param height
  32621. */
  32622. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  32623. var rect = this.getBoundingRect();
  32624. var aspect = rect.width / rect.height;
  32625. if (!width) {
  32626. width = aspect * height;
  32627. } else if (!height) {
  32628. height = width / aspect;
  32629. }
  32630. var target = new BoundingRect(x, y, width, height);
  32631. var transform = rect.calculateTransform(target);
  32632. var geometries = this.geometries;
  32633. for (var i = 0; i < geometries.length; i++) {
  32634. var geo = geometries[i];
  32635. if (geo.type === 'polygon') {
  32636. transformPoints(geo.exterior, transform);
  32637. each(geo.interiors, function (interior) {
  32638. transformPoints(interior, transform);
  32639. });
  32640. } else {
  32641. each(geo.points, function (points) {
  32642. transformPoints(points, transform);
  32643. });
  32644. }
  32645. }
  32646. rect = this._rect;
  32647. rect.copy(target);
  32648. // Update center
  32649. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32650. };
  32651. GeoJSONRegion.prototype.cloneShallow = function (name) {
  32652. name == null && (name = this.name);
  32653. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  32654. newRegion._rect = this._rect;
  32655. newRegion.transformTo = null; // Simply avoid to be called.
  32656. return newRegion;
  32657. };
  32658. return GeoJSONRegion;
  32659. }(Region);
  32660. var GeoSVGRegion = /** @class */function (_super) {
  32661. __extends(GeoSVGRegion, _super);
  32662. function GeoSVGRegion(name, elOnlyForCalculate) {
  32663. var _this = _super.call(this, name) || this;
  32664. _this.type = 'geoSVG';
  32665. _this._elOnlyForCalculate = elOnlyForCalculate;
  32666. return _this;
  32667. }
  32668. GeoSVGRegion.prototype.calcCenter = function () {
  32669. var el = this._elOnlyForCalculate;
  32670. var rect = el.getBoundingRect();
  32671. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32672. var mat = identity(TMP_TRANSFORM);
  32673. var target = el;
  32674. while (target && !target.isGeoSVGGraphicRoot) {
  32675. mul$1(mat, target.getLocalTransform(), mat);
  32676. target = target.parent;
  32677. }
  32678. invert(mat, mat);
  32679. applyTransform(center, center, mat);
  32680. return center;
  32681. };
  32682. return GeoSVGRegion;
  32683. }(Region);
  32684. function decode(json) {
  32685. if (!json.UTF8Encoding) {
  32686. return json;
  32687. }
  32688. var jsonCompressed = json;
  32689. var encodeScale = jsonCompressed.UTF8Scale;
  32690. if (encodeScale == null) {
  32691. encodeScale = 1024;
  32692. }
  32693. var features = jsonCompressed.features;
  32694. each(features, function (feature) {
  32695. var geometry = feature.geometry;
  32696. var encodeOffsets = geometry.encodeOffsets;
  32697. var coordinates = geometry.coordinates;
  32698. // Geometry may be appeded manually in the script after json loaded.
  32699. // In this case this geometry is usually not encoded.
  32700. if (!encodeOffsets) {
  32701. return;
  32702. }
  32703. switch (geometry.type) {
  32704. case 'LineString':
  32705. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  32706. break;
  32707. case 'Polygon':
  32708. decodeRings(coordinates, encodeOffsets, encodeScale);
  32709. break;
  32710. case 'MultiLineString':
  32711. decodeRings(coordinates, encodeOffsets, encodeScale);
  32712. break;
  32713. case 'MultiPolygon':
  32714. each(coordinates, function (rings, idx) {
  32715. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  32716. });
  32717. }
  32718. });
  32719. // Has been decoded
  32720. jsonCompressed.UTF8Encoding = false;
  32721. return jsonCompressed;
  32722. }
  32723. function decodeRings(rings, encodeOffsets, encodeScale) {
  32724. for (var c = 0; c < rings.length; c++) {
  32725. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  32726. }
  32727. }
  32728. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  32729. var result = [];
  32730. var prevX = encodeOffsets[0];
  32731. var prevY = encodeOffsets[1];
  32732. for (var i = 0; i < coordinate.length; i += 2) {
  32733. var x = coordinate.charCodeAt(i) - 64;
  32734. var y = coordinate.charCodeAt(i + 1) - 64;
  32735. // ZigZag decoding
  32736. x = x >> 1 ^ -(x & 1);
  32737. y = y >> 1 ^ -(y & 1);
  32738. // Delta deocding
  32739. x += prevX;
  32740. y += prevY;
  32741. prevX = x;
  32742. prevY = y;
  32743. // Dequantize
  32744. result.push([x / encodeScale, y / encodeScale]);
  32745. }
  32746. return result;
  32747. }
  32748. function parseGeoJSON(geoJson, nameProperty) {
  32749. geoJson = decode(geoJson);
  32750. return map(filter(geoJson.features, function (featureObj) {
  32751. // Output of mapshaper may have geometry null
  32752. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  32753. }), function (featureObj) {
  32754. var properties = featureObj.properties;
  32755. var geo = featureObj.geometry;
  32756. var geometries = [];
  32757. switch (geo.type) {
  32758. case 'Polygon':
  32759. var coordinates = geo.coordinates;
  32760. // According to the GeoJSON specification.
  32761. // First must be exterior, and the rest are all interior(holes).
  32762. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  32763. break;
  32764. case 'MultiPolygon':
  32765. each(geo.coordinates, function (item) {
  32766. if (item[0]) {
  32767. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  32768. }
  32769. });
  32770. break;
  32771. case 'LineString':
  32772. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  32773. break;
  32774. case 'MultiLineString':
  32775. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  32776. }
  32777. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  32778. region.properties = properties;
  32779. return region;
  32780. });
  32781. }
  32782. var number = /*#__PURE__*/Object.freeze({
  32783. __proto__: null,
  32784. linearMap: linearMap,
  32785. round: round,
  32786. asc: asc,
  32787. getPrecision: getPrecision,
  32788. getPrecisionSafe: getPrecisionSafe,
  32789. getPixelPrecision: getPixelPrecision,
  32790. getPercentWithPrecision: getPercentWithPrecision,
  32791. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  32792. remRadian: remRadian,
  32793. isRadianAroundZero: isRadianAroundZero,
  32794. parseDate: parseDate,
  32795. quantity: quantity,
  32796. quantityExponent: quantityExponent,
  32797. nice: nice,
  32798. quantile: quantile,
  32799. reformIntervals: reformIntervals,
  32800. isNumeric: isNumeric,
  32801. numericToNumber: numericToNumber
  32802. });
  32803. var time = /*#__PURE__*/Object.freeze({
  32804. __proto__: null,
  32805. parse: parseDate,
  32806. format: format
  32807. });
  32808. var graphic$1 = /*#__PURE__*/Object.freeze({
  32809. __proto__: null,
  32810. extendShape: extendShape,
  32811. extendPath: extendPath,
  32812. makePath: makePath,
  32813. makeImage: makeImage,
  32814. mergePath: mergePath$1,
  32815. resizePath: resizePath,
  32816. createIcon: createIcon,
  32817. updateProps: updateProps,
  32818. initProps: initProps,
  32819. getTransform: getTransform,
  32820. clipPointsByRect: clipPointsByRect,
  32821. clipRectByRect: clipRectByRect,
  32822. registerShape: registerShape,
  32823. getShapeClass: getShapeClass,
  32824. Group: Group,
  32825. Image: ZRImage,
  32826. Text: ZRText,
  32827. Circle: Circle,
  32828. Ellipse: Ellipse,
  32829. Sector: Sector,
  32830. Ring: Ring,
  32831. Polygon: Polygon,
  32832. Polyline: Polyline,
  32833. Rect: Rect,
  32834. Line: Line,
  32835. BezierCurve: BezierCurve,
  32836. Arc: Arc,
  32837. IncrementalDisplayable: IncrementalDisplayable,
  32838. CompoundPath: CompoundPath,
  32839. LinearGradient: LinearGradient,
  32840. RadialGradient: RadialGradient,
  32841. BoundingRect: BoundingRect
  32842. });
  32843. var format$1 = /*#__PURE__*/Object.freeze({
  32844. __proto__: null,
  32845. addCommas: addCommas,
  32846. toCamelCase: toCamelCase,
  32847. normalizeCssArray: normalizeCssArray$1,
  32848. encodeHTML: encodeHTML,
  32849. formatTpl: formatTpl,
  32850. getTooltipMarker: getTooltipMarker,
  32851. formatTime: formatTime,
  32852. capitalFirst: capitalFirst,
  32853. truncateText: truncateText,
  32854. getTextRect: getTextRect
  32855. });
  32856. var util$1 = /*#__PURE__*/Object.freeze({
  32857. __proto__: null,
  32858. map: map,
  32859. each: each,
  32860. indexOf: indexOf,
  32861. inherits: inherits,
  32862. reduce: reduce,
  32863. filter: filter,
  32864. bind: bind,
  32865. curry: curry,
  32866. isArray: isArray,
  32867. isString: isString,
  32868. isObject: isObject,
  32869. isFunction: isFunction,
  32870. extend: extend,
  32871. defaults: defaults,
  32872. clone: clone,
  32873. merge: merge
  32874. });
  32875. var inner$5 = makeInner();
  32876. function tickValuesToNumbers(axis, values) {
  32877. var nums = map(values, function (val) {
  32878. return axis.scale.parse(val);
  32879. });
  32880. if (axis.type === 'time' && nums.length > 0) {
  32881. // Time axis needs duplicate first/last tick (see TimeScale.getTicks())
  32882. // The first and last tick/label don't get drawn
  32883. nums.sort();
  32884. nums.unshift(nums[0]);
  32885. nums.push(nums[nums.length - 1]);
  32886. }
  32887. return nums;
  32888. }
  32889. function createAxisLabels(axis) {
  32890. var custom = axis.getLabelModel().get('customValues');
  32891. if (custom) {
  32892. var labelFormatter_1 = makeLabelFormatter(axis);
  32893. var extent_1 = axis.scale.getExtent();
  32894. var tickNumbers = tickValuesToNumbers(axis, custom);
  32895. var ticks = filter(tickNumbers, function (val) {
  32896. return val >= extent_1[0] && val <= extent_1[1];
  32897. });
  32898. return {
  32899. labels: map(ticks, function (numval) {
  32900. var tick = {
  32901. value: numval
  32902. };
  32903. return {
  32904. formattedLabel: labelFormatter_1(tick),
  32905. rawLabel: axis.scale.getLabel(tick),
  32906. tickValue: numval
  32907. };
  32908. })
  32909. };
  32910. }
  32911. // Only ordinal scale support tick interval
  32912. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32913. }
  32914. /**
  32915. * @param {module:echats/coord/Axis} axis
  32916. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32917. * @return {Object} {
  32918. * ticks: Array.<number>
  32919. * tickCategoryInterval: number
  32920. * }
  32921. */
  32922. function createAxisTicks(axis, tickModel) {
  32923. var custom = axis.getTickModel().get('customValues');
  32924. if (custom) {
  32925. var extent_2 = axis.scale.getExtent();
  32926. var tickNumbers = tickValuesToNumbers(axis, custom);
  32927. return {
  32928. ticks: filter(tickNumbers, function (val) {
  32929. return val >= extent_2[0] && val <= extent_2[1];
  32930. })
  32931. };
  32932. }
  32933. // Only ordinal scale support tick interval
  32934. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32935. ticks: map(axis.scale.getTicks(), function (tick) {
  32936. return tick.value;
  32937. })
  32938. };
  32939. }
  32940. function makeCategoryLabels(axis) {
  32941. var labelModel = axis.getLabelModel();
  32942. var result = makeCategoryLabelsActually(axis, labelModel);
  32943. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32944. labels: [],
  32945. labelCategoryInterval: result.labelCategoryInterval
  32946. } : result;
  32947. }
  32948. function makeCategoryLabelsActually(axis, labelModel) {
  32949. var labelsCache = getListCache(axis, 'labels');
  32950. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32951. var result = listCacheGet(labelsCache, optionLabelInterval);
  32952. if (result) {
  32953. return result;
  32954. }
  32955. var labels;
  32956. var numericLabelInterval;
  32957. if (isFunction(optionLabelInterval)) {
  32958. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32959. } else {
  32960. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32961. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32962. }
  32963. // Cache to avoid calling interval function repeatedly.
  32964. return listCacheSet(labelsCache, optionLabelInterval, {
  32965. labels: labels,
  32966. labelCategoryInterval: numericLabelInterval
  32967. });
  32968. }
  32969. function makeCategoryTicks(axis, tickModel) {
  32970. var ticksCache = getListCache(axis, 'ticks');
  32971. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32972. var result = listCacheGet(ticksCache, optionTickInterval);
  32973. if (result) {
  32974. return result;
  32975. }
  32976. var ticks;
  32977. var tickCategoryInterval;
  32978. // Optimize for the case that large category data and no label displayed,
  32979. // we should not return all ticks.
  32980. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32981. ticks = [];
  32982. }
  32983. if (isFunction(optionTickInterval)) {
  32984. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32985. }
  32986. // Always use label interval by default despite label show. Consider this
  32987. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32988. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32989. else if (optionTickInterval === 'auto') {
  32990. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32991. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32992. ticks = map(labelsResult.labels, function (labelItem) {
  32993. return labelItem.tickValue;
  32994. });
  32995. } else {
  32996. tickCategoryInterval = optionTickInterval;
  32997. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32998. }
  32999. // Cache to avoid calling interval function repeatedly.
  33000. return listCacheSet(ticksCache, optionTickInterval, {
  33001. ticks: ticks,
  33002. tickCategoryInterval: tickCategoryInterval
  33003. });
  33004. }
  33005. function makeRealNumberLabels(axis) {
  33006. var ticks = axis.scale.getTicks();
  33007. var labelFormatter = makeLabelFormatter(axis);
  33008. return {
  33009. labels: map(ticks, function (tick, idx) {
  33010. return {
  33011. level: tick.level,
  33012. formattedLabel: labelFormatter(tick, idx),
  33013. rawLabel: axis.scale.getLabel(tick),
  33014. tickValue: tick.value
  33015. };
  33016. })
  33017. };
  33018. }
  33019. function getListCache(axis, prop) {
  33020. // Because key can be a function, and cache size always is small, we use array cache.
  33021. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  33022. }
  33023. function listCacheGet(cache, key) {
  33024. for (var i = 0; i < cache.length; i++) {
  33025. if (cache[i].key === key) {
  33026. return cache[i].value;
  33027. }
  33028. }
  33029. }
  33030. function listCacheSet(cache, key, value) {
  33031. cache.push({
  33032. key: key,
  33033. value: value
  33034. });
  33035. return value;
  33036. }
  33037. function makeAutoCategoryInterval(axis) {
  33038. var result = inner$5(axis).autoInterval;
  33039. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  33040. }
  33041. /**
  33042. * Calculate interval for category axis ticks and labels.
  33043. * To get precise result, at least one of `getRotate` and `isHorizontal`
  33044. * should be implemented in axis.
  33045. */
  33046. function calculateCategoryInterval(axis) {
  33047. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  33048. var labelFormatter = makeLabelFormatter(axis);
  33049. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  33050. var ordinalScale = axis.scale;
  33051. var ordinalExtent = ordinalScale.getExtent();
  33052. // Providing this method is for optimization:
  33053. // avoid generating a long array by `getTicks`
  33054. // in large category data case.
  33055. var tickCount = ordinalScale.count();
  33056. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  33057. return 0;
  33058. }
  33059. var step = 1;
  33060. // Simple optimization. Empirical value: tick count should less than 40.
  33061. if (tickCount > 40) {
  33062. step = Math.max(1, Math.floor(tickCount / 40));
  33063. }
  33064. var tickValue = ordinalExtent[0];
  33065. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  33066. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  33067. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  33068. var maxW = 0;
  33069. var maxH = 0;
  33070. // Caution: Performance sensitive for large category data.
  33071. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  33072. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33073. var width = 0;
  33074. var height = 0;
  33075. // Not precise, do not consider align and vertical align
  33076. // and each distance from axis line yet.
  33077. var rect = getBoundingRect(labelFormatter({
  33078. value: tickValue
  33079. }), params.font, 'center', 'top');
  33080. // Magic number
  33081. width = rect.width * 1.3;
  33082. height = rect.height * 1.3;
  33083. // Min size, void long loop.
  33084. maxW = Math.max(maxW, width, 7);
  33085. maxH = Math.max(maxH, height, 7);
  33086. }
  33087. var dw = maxW / unitW;
  33088. var dh = maxH / unitH;
  33089. // 0/0 is NaN, 1/0 is Infinity.
  33090. isNaN(dw) && (dw = Infinity);
  33091. isNaN(dh) && (dh = Infinity);
  33092. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  33093. var cache = inner$5(axis.model);
  33094. var axisExtent = axis.getExtent();
  33095. var lastAutoInterval = cache.lastAutoInterval;
  33096. var lastTickCount = cache.lastTickCount;
  33097. // Use cache to keep interval stable while moving zoom window,
  33098. // otherwise the calculated interval might jitter when the zoom
  33099. // window size is close to the interval-changing size.
  33100. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  33101. // The jitter will cause that sometimes the displayed labels are
  33102. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  33103. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  33104. // Always choose the bigger one, otherwise the critical
  33105. // point is not the same when zooming in or zooming out.
  33106. && lastAutoInterval > interval
  33107. // If the axis change is caused by chart resize, the cache should not
  33108. // be used. Otherwise some hidden labels might not be shown again.
  33109. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  33110. interval = lastAutoInterval;
  33111. }
  33112. // Only update cache if cache not used, otherwise the
  33113. // changing of interval is too insensitive.
  33114. else {
  33115. cache.lastTickCount = tickCount;
  33116. cache.lastAutoInterval = interval;
  33117. cache.axisExtent0 = axisExtent[0];
  33118. cache.axisExtent1 = axisExtent[1];
  33119. }
  33120. return interval;
  33121. }
  33122. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33123. var labelModel = axis.getLabelModel();
  33124. return {
  33125. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  33126. labelRotate: labelModel.get('rotate') || 0,
  33127. font: labelModel.getFont()
  33128. };
  33129. }
  33130. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33131. var labelFormatter = makeLabelFormatter(axis);
  33132. var ordinalScale = axis.scale;
  33133. var ordinalExtent = ordinalScale.getExtent();
  33134. var labelModel = axis.getLabelModel();
  33135. var result = [];
  33136. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33137. var step = Math.max((categoryInterval || 0) + 1, 1);
  33138. var startTick = ordinalExtent[0];
  33139. var tickCount = ordinalScale.count();
  33140. // Calculate start tick based on zero if possible to keep label consistent
  33141. // while zooming and moving while interval > 0. Otherwise the selection
  33142. // of displayable ticks and symbols probably keep changing.
  33143. // 3 is empirical value.
  33144. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33145. startTick = Math.round(Math.ceil(startTick / step) * step);
  33146. }
  33147. // (1) Only add min max label here but leave overlap checking
  33148. // to render stage, which also ensure the returned list
  33149. // suitable for splitLine and splitArea rendering.
  33150. // (2) Scales except category always contain min max label so
  33151. // do not need to perform this process.
  33152. var showAllLabel = shouldShowAllLabels(axis);
  33153. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33154. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33155. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33156. addItem(ordinalExtent[0]);
  33157. }
  33158. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33159. var tickValue = startTick;
  33160. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33161. addItem(tickValue);
  33162. }
  33163. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33164. addItem(ordinalExtent[1]);
  33165. }
  33166. function addItem(tickValue) {
  33167. var tickObj = {
  33168. value: tickValue
  33169. };
  33170. result.push(onlyTick ? tickValue : {
  33171. formattedLabel: labelFormatter(tickObj),
  33172. rawLabel: ordinalScale.getLabel(tickObj),
  33173. tickValue: tickValue
  33174. });
  33175. }
  33176. return result;
  33177. }
  33178. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33179. var ordinalScale = axis.scale;
  33180. var labelFormatter = makeLabelFormatter(axis);
  33181. var result = [];
  33182. each(ordinalScale.getTicks(), function (tick) {
  33183. var rawLabel = ordinalScale.getLabel(tick);
  33184. var tickValue = tick.value;
  33185. if (categoryInterval(tick.value, rawLabel)) {
  33186. result.push(onlyTick ? tickValue : {
  33187. formattedLabel: labelFormatter(tick),
  33188. rawLabel: rawLabel,
  33189. tickValue: tickValue
  33190. });
  33191. }
  33192. });
  33193. return result;
  33194. }
  33195. var NORMALIZED_EXTENT = [0, 1];
  33196. /**
  33197. * Base class of Axis.
  33198. */
  33199. var Axis = /** @class */function () {
  33200. function Axis(dim, scale, extent) {
  33201. this.onBand = false;
  33202. this.inverse = false;
  33203. this.dim = dim;
  33204. this.scale = scale;
  33205. this._extent = extent || [0, 0];
  33206. }
  33207. /**
  33208. * If axis extent contain given coord
  33209. */
  33210. Axis.prototype.contain = function (coord) {
  33211. var extent = this._extent;
  33212. var min = Math.min(extent[0], extent[1]);
  33213. var max = Math.max(extent[0], extent[1]);
  33214. return coord >= min && coord <= max;
  33215. };
  33216. /**
  33217. * If axis extent contain given data
  33218. */
  33219. Axis.prototype.containData = function (data) {
  33220. return this.scale.contain(data);
  33221. };
  33222. /**
  33223. * Get coord extent.
  33224. */
  33225. Axis.prototype.getExtent = function () {
  33226. return this._extent.slice();
  33227. };
  33228. /**
  33229. * Get precision used for formatting
  33230. */
  33231. Axis.prototype.getPixelPrecision = function (dataExtent) {
  33232. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  33233. };
  33234. /**
  33235. * Set coord extent
  33236. */
  33237. Axis.prototype.setExtent = function (start, end) {
  33238. var extent = this._extent;
  33239. extent[0] = start;
  33240. extent[1] = end;
  33241. };
  33242. /**
  33243. * Convert data to coord. Data is the rank if it has an ordinal scale
  33244. */
  33245. Axis.prototype.dataToCoord = function (data, clamp) {
  33246. var extent = this._extent;
  33247. var scale = this.scale;
  33248. data = scale.normalize(data);
  33249. if (this.onBand && scale.type === 'ordinal') {
  33250. extent = extent.slice();
  33251. fixExtentWithBands(extent, scale.count());
  33252. }
  33253. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33254. };
  33255. /**
  33256. * Convert coord to data. Data is the rank if it has an ordinal scale
  33257. */
  33258. Axis.prototype.coordToData = function (coord, clamp) {
  33259. var extent = this._extent;
  33260. var scale = this.scale;
  33261. if (this.onBand && scale.type === 'ordinal') {
  33262. extent = extent.slice();
  33263. fixExtentWithBands(extent, scale.count());
  33264. }
  33265. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33266. return this.scale.scale(t);
  33267. };
  33268. /**
  33269. * Convert pixel point to data in axis
  33270. */
  33271. Axis.prototype.pointToData = function (point, clamp) {
  33272. // Should be implemented in derived class if necessary.
  33273. return;
  33274. };
  33275. /**
  33276. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33277. * `axis.getTicksCoords` considers `onBand`, which is used by
  33278. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33279. * @param opt.tickModel default: axis.model.getModel('axisTick')
  33280. * @param opt.clamp If `true`, the first and the last
  33281. * tick must be at the axis end points. Otherwise, clip ticks
  33282. * that outside the axis extent.
  33283. */
  33284. Axis.prototype.getTicksCoords = function (opt) {
  33285. opt = opt || {};
  33286. var tickModel = opt.tickModel || this.getTickModel();
  33287. var result = createAxisTicks(this, tickModel);
  33288. var ticks = result.ticks;
  33289. var ticksCoords = map(ticks, function (tickVal) {
  33290. return {
  33291. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  33292. tickValue: tickVal
  33293. };
  33294. }, this);
  33295. var alignWithLabel = tickModel.get('alignWithLabel');
  33296. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  33297. return ticksCoords;
  33298. };
  33299. Axis.prototype.getMinorTicksCoords = function () {
  33300. if (this.scale.type === 'ordinal') {
  33301. // Category axis doesn't support minor ticks
  33302. return [];
  33303. }
  33304. var minorTickModel = this.model.getModel('minorTick');
  33305. var splitNumber = minorTickModel.get('splitNumber');
  33306. // Protection.
  33307. if (!(splitNumber > 0 && splitNumber < 100)) {
  33308. splitNumber = 5;
  33309. }
  33310. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33311. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33312. return map(minorTicksGroup, function (minorTick) {
  33313. return {
  33314. coord: this.dataToCoord(minorTick),
  33315. tickValue: minorTick
  33316. };
  33317. }, this);
  33318. }, this);
  33319. return minorTicksCoords;
  33320. };
  33321. Axis.prototype.getViewLabels = function () {
  33322. return createAxisLabels(this).labels;
  33323. };
  33324. Axis.prototype.getLabelModel = function () {
  33325. return this.model.getModel('axisLabel');
  33326. };
  33327. /**
  33328. * Notice here we only get the default tick model. For splitLine
  33329. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33330. * manually when calling `getTicksCoords`.
  33331. * In GL, this method may be overridden to:
  33332. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33333. */
  33334. Axis.prototype.getTickModel = function () {
  33335. return this.model.getModel('axisTick');
  33336. };
  33337. /**
  33338. * Get width of band
  33339. */
  33340. Axis.prototype.getBandWidth = function () {
  33341. var axisExtent = this._extent;
  33342. var dataExtent = this.scale.getExtent();
  33343. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  33344. // Fix #2728, avoid NaN when only one data.
  33345. len === 0 && (len = 1);
  33346. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33347. return Math.abs(size) / len;
  33348. };
  33349. /**
  33350. * Only be called in category axis.
  33351. * Can be overridden, consider other axes like in 3D.
  33352. * @return Auto interval for cateogry axis tick and label
  33353. */
  33354. Axis.prototype.calculateCategoryInterval = function () {
  33355. return calculateCategoryInterval(this);
  33356. };
  33357. return Axis;
  33358. }();
  33359. function fixExtentWithBands(extent, nTick) {
  33360. var size = extent[1] - extent[0];
  33361. var len = nTick;
  33362. var margin = size / len / 2;
  33363. extent[0] += margin;
  33364. extent[1] -= margin;
  33365. }
  33366. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33367. // |---1---|---2---|---3---|---4---|.
  33368. // So the displayed ticks and splitLine/splitArea should between
  33369. // each data item, otherwise cause misleading (e.g., split tow bars
  33370. // of a single data item when there are two bar series).
  33371. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33372. // splitLine/spliteArea should layout appropriately corresponding
  33373. // to displayed labels. (So we should not use `getBandWidth` in this
  33374. // case).
  33375. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33376. var ticksLen = ticksCoords.length;
  33377. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33378. return;
  33379. }
  33380. var axisExtent = axis.getExtent();
  33381. var last;
  33382. var diffSize;
  33383. if (ticksLen === 1) {
  33384. ticksCoords[0].coord = axisExtent[0];
  33385. last = ticksCoords[1] = {
  33386. coord: axisExtent[1],
  33387. tickValue: ticksCoords[0].tickValue
  33388. };
  33389. } else {
  33390. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33391. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33392. each(ticksCoords, function (ticksItem) {
  33393. ticksItem.coord -= shift_1 / 2;
  33394. });
  33395. var dataExtent = axis.scale.getExtent();
  33396. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33397. last = {
  33398. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize,
  33399. tickValue: dataExtent[1] + 1
  33400. };
  33401. ticksCoords.push(last);
  33402. }
  33403. var inverse = axisExtent[0] > axisExtent[1];
  33404. // Handling clamp.
  33405. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33406. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  33407. }
  33408. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33409. ticksCoords.unshift({
  33410. coord: axisExtent[0]
  33411. });
  33412. }
  33413. if (littleThan(axisExtent[1], last.coord)) {
  33414. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  33415. }
  33416. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33417. ticksCoords.push({
  33418. coord: axisExtent[1]
  33419. });
  33420. }
  33421. function littleThan(a, b) {
  33422. // Avoid rounding error cause calculated tick coord different with extent.
  33423. // It may cause an extra unnecessary tick added.
  33424. a = round(a);
  33425. b = round(b);
  33426. return inverse ? a > b : a < b;
  33427. }
  33428. }
  33429. // --------------------- Deprecated Extension Methods ---------------------
  33430. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  33431. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  33432. // class Bar3DModel extends ComponentModel {}
  33433. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  33434. // echarts.use(install);
  33435. function extendComponentModel(proto) {
  33436. var Model = ComponentModel.extend(proto);
  33437. ComponentModel.registerClass(Model);
  33438. return Model;
  33439. }
  33440. function extendComponentView(proto) {
  33441. var View = ComponentView.extend(proto);
  33442. ComponentView.registerClass(View);
  33443. return View;
  33444. }
  33445. function extendSeriesModel(proto) {
  33446. var Model = SeriesModel.extend(proto);
  33447. SeriesModel.registerClass(Model);
  33448. return Model;
  33449. }
  33450. function extendChartView(proto) {
  33451. var View = ChartView.extend(proto);
  33452. ChartView.registerClass(View);
  33453. return View;
  33454. }
  33455. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  33456. var dx = x - x1;
  33457. var dy = y - y1;
  33458. var dx1 = x2 - x1;
  33459. var dy1 = y2 - y1;
  33460. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  33461. dx1 /= lineLen;
  33462. dy1 /= lineLen;
  33463. // dot product
  33464. var projectedLen = dx * dx1 + dy * dy1;
  33465. var t = projectedLen / lineLen;
  33466. if (limitToEnds) {
  33467. t = Math.min(Math.max(t, 0), 1);
  33468. }
  33469. t *= lineLen;
  33470. var ox = out[0] = x1 + t * dx1;
  33471. var oy = out[1] = y1 + t * dy1;
  33472. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33473. }
  33474. // Temporal variable for intermediate usage.
  33475. var pt0 = new Point();
  33476. var pt1 = new Point();
  33477. var pt2 = new Point();
  33478. var dir = new Point();
  33479. var dir2 = new Point();
  33480. // Temporal variable for the limitTurnAngle function
  33481. var tmpArr = [];
  33482. var tmpProjPoint = new Point();
  33483. /**
  33484. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33485. * @param linePoints
  33486. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33487. */
  33488. function limitTurnAngle(linePoints, minTurnAngle) {
  33489. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33490. return;
  33491. }
  33492. minTurnAngle = minTurnAngle / 180 * Math.PI;
  33493. // The line points can be
  33494. // /pt1----pt2 (label)
  33495. // /
  33496. // pt0/
  33497. pt0.fromArray(linePoints[0]);
  33498. pt1.fromArray(linePoints[1]);
  33499. pt2.fromArray(linePoints[2]);
  33500. Point.sub(dir, pt0, pt1);
  33501. Point.sub(dir2, pt2, pt1);
  33502. var len1 = dir.len();
  33503. var len2 = dir2.len();
  33504. if (len1 < 1e-3 || len2 < 1e-3) {
  33505. return;
  33506. }
  33507. dir.scale(1 / len1);
  33508. dir2.scale(1 / len2);
  33509. var angleCos = dir.dot(dir2);
  33510. var minTurnAngleCos = Math.cos(minTurnAngle);
  33511. if (minTurnAngleCos < angleCos) {
  33512. // Smaller than minTurnAngle
  33513. // Calculate project point of pt0 on pt1-pt2
  33514. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33515. tmpProjPoint.fromArray(tmpArr);
  33516. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33517. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle));
  33518. // Limit the new calculated connect point between pt1 and pt2.
  33519. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33520. if (isNaN(t)) {
  33521. return;
  33522. }
  33523. if (t < 0) {
  33524. Point.copy(tmpProjPoint, pt1);
  33525. } else if (t > 1) {
  33526. Point.copy(tmpProjPoint, pt2);
  33527. }
  33528. tmpProjPoint.toArray(linePoints[1]);
  33529. }
  33530. }
  33531. /**
  33532. * Limit the angle of line and the surface
  33533. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33534. */
  33535. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33536. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33537. return;
  33538. }
  33539. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33540. pt0.fromArray(linePoints[0]);
  33541. pt1.fromArray(linePoints[1]);
  33542. pt2.fromArray(linePoints[2]);
  33543. Point.sub(dir, pt1, pt0);
  33544. Point.sub(dir2, pt2, pt1);
  33545. var len1 = dir.len();
  33546. var len2 = dir2.len();
  33547. if (len1 < 1e-3 || len2 < 1e-3) {
  33548. return;
  33549. }
  33550. dir.scale(1 / len1);
  33551. dir2.scale(1 / len2);
  33552. var angleCos = dir.dot(surfaceNormal);
  33553. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33554. if (angleCos < maxSurfaceAngleCos) {
  33555. // Calculate project point of pt0 on pt1-pt2
  33556. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33557. tmpProjPoint.fromArray(tmpArr);
  33558. var HALF_PI = Math.PI / 2;
  33559. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33560. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33561. if (newAngle >= HALF_PI) {
  33562. // parallel
  33563. Point.copy(tmpProjPoint, pt2);
  33564. } else {
  33565. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33566. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle));
  33567. // Limit the new calculated connect point between pt1 and pt2.
  33568. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33569. if (isNaN(t)) {
  33570. return;
  33571. }
  33572. if (t < 0) {
  33573. Point.copy(tmpProjPoint, pt1);
  33574. } else if (t > 1) {
  33575. Point.copy(tmpProjPoint, pt2);
  33576. }
  33577. }
  33578. tmpProjPoint.toArray(linePoints[1]);
  33579. }
  33580. }
  33581. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33582. var isNormal = stateName === 'normal';
  33583. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName);
  33584. // Make sure display.
  33585. stateObj.ignore = ignore;
  33586. // Set smooth
  33587. var smooth = stateModel.get('smooth');
  33588. if (smooth && smooth === true) {
  33589. smooth = 0.3;
  33590. }
  33591. stateObj.shape = stateObj.shape || {};
  33592. if (smooth > 0) {
  33593. stateObj.shape.smooth = smooth;
  33594. }
  33595. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33596. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33597. }
  33598. function buildLabelLinePath(path, shape) {
  33599. var smooth = shape.smooth;
  33600. var points = shape.points;
  33601. if (!points) {
  33602. return;
  33603. }
  33604. path.moveTo(points[0][0], points[0][1]);
  33605. if (smooth > 0 && points.length >= 3) {
  33606. var len1 = dist(points[0], points[1]);
  33607. var len2 = dist(points[1], points[2]);
  33608. if (!len1 || !len2) {
  33609. path.lineTo(points[1][0], points[1][1]);
  33610. path.lineTo(points[2][0], points[2][1]);
  33611. return;
  33612. }
  33613. var moveLen = Math.min(len1, len2) * smooth;
  33614. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  33615. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  33616. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  33617. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  33618. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  33619. } else {
  33620. for (var i = 1; i < points.length; i++) {
  33621. path.lineTo(points[i][0], points[i][1]);
  33622. }
  33623. }
  33624. }
  33625. /**
  33626. * Create a label line if necessary and set it's style.
  33627. */
  33628. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  33629. var labelLine = targetEl.getTextGuideLine();
  33630. var label = targetEl.getTextContent();
  33631. if (!label) {
  33632. // Not show label line if there is no label.
  33633. if (labelLine) {
  33634. targetEl.removeTextGuideLine();
  33635. }
  33636. return;
  33637. }
  33638. var normalModel = statesModels.normal;
  33639. var showNormal = normalModel.get('show');
  33640. var labelIgnoreNormal = label.ignore;
  33641. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  33642. var stateName = DISPLAY_STATES[i];
  33643. var stateModel = statesModels[stateName];
  33644. var isNormal = stateName === 'normal';
  33645. if (stateModel) {
  33646. var stateShow = stateModel.get('show');
  33647. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  33648. if (isLabelIgnored // Not show when label is not shown in this state.
  33649. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  33650. ) {
  33651. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  33652. if (stateObj) {
  33653. stateObj.ignore = true;
  33654. }
  33655. if (!!labelLine) {
  33656. setLabelLineState(labelLine, true, stateName, stateModel);
  33657. }
  33658. continue;
  33659. }
  33660. // Create labelLine if not exists
  33661. if (!labelLine) {
  33662. labelLine = new Polyline();
  33663. targetEl.setTextGuideLine(labelLine);
  33664. // Reset state of normal because it's new created.
  33665. // NOTE: NORMAL should always been the first!
  33666. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  33667. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  33668. }
  33669. // Use same state proxy.
  33670. if (targetEl.stateProxy) {
  33671. labelLine.stateProxy = targetEl.stateProxy;
  33672. }
  33673. }
  33674. setLabelLineState(labelLine, false, stateName, stateModel);
  33675. }
  33676. }
  33677. if (labelLine) {
  33678. defaults(labelLine.style, defaultStyle);
  33679. // Not fill.
  33680. labelLine.style.fill = null;
  33681. var showAbove = normalModel.get('showAbove');
  33682. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  33683. labelLineConfig.showAbove = showAbove || false;
  33684. // Custom the buildPath.
  33685. labelLine.buildPath = buildLabelLinePath;
  33686. }
  33687. }
  33688. function getLabelLineStatesModels(itemModel, labelLineName) {
  33689. labelLineName = labelLineName || 'labelLine';
  33690. var statesModels = {
  33691. normal: itemModel.getModel(labelLineName)
  33692. };
  33693. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  33694. var stateName = SPECIAL_STATES[i];
  33695. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  33696. }
  33697. return statesModels;
  33698. }
  33699. function prepareLayoutList(input) {
  33700. var list = [];
  33701. for (var i = 0; i < input.length; i++) {
  33702. var rawItem = input[i];
  33703. if (rawItem.defaultAttr.ignore) {
  33704. continue;
  33705. }
  33706. var label = rawItem.label;
  33707. var transform = label.getComputedTransform();
  33708. // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  33709. var localRect = label.getBoundingRect();
  33710. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  33711. var minMargin = label.style.margin || 0;
  33712. var globalRect = localRect.clone();
  33713. globalRect.applyTransform(transform);
  33714. globalRect.x -= minMargin / 2;
  33715. globalRect.y -= minMargin / 2;
  33716. globalRect.width += minMargin;
  33717. globalRect.height += minMargin;
  33718. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  33719. list.push({
  33720. label: label,
  33721. labelLine: rawItem.labelLine,
  33722. rect: globalRect,
  33723. localRect: localRect,
  33724. obb: obb,
  33725. priority: rawItem.priority,
  33726. defaultAttr: rawItem.defaultAttr,
  33727. layoutOption: rawItem.computedLayoutOption,
  33728. axisAligned: isAxisAligned,
  33729. transform: transform
  33730. });
  33731. }
  33732. return list;
  33733. }
  33734. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  33735. var len = list.length;
  33736. if (len < 2) {
  33737. return;
  33738. }
  33739. list.sort(function (a, b) {
  33740. return a.rect[xyDim] - b.rect[xyDim];
  33741. });
  33742. var lastPos = 0;
  33743. var delta;
  33744. var adjusted = false;
  33745. var totalShifts = 0;
  33746. for (var i = 0; i < len; i++) {
  33747. var item = list[i];
  33748. var rect = item.rect;
  33749. delta = rect[xyDim] - lastPos;
  33750. if (delta < 0) {
  33751. // shiftForward(i, len, -delta);
  33752. rect[xyDim] -= delta;
  33753. item.label[xyDim] -= delta;
  33754. adjusted = true;
  33755. }
  33756. var shift = Math.max(-delta, 0);
  33757. totalShifts += shift;
  33758. lastPos = rect[xyDim] + rect[sizeDim];
  33759. }
  33760. if (totalShifts > 0 && balanceShift) {
  33761. // Shift back to make the distribution more equally.
  33762. shiftList(-totalShifts / len, 0, len);
  33763. }
  33764. // TODO bleedMargin?
  33765. var first = list[0];
  33766. var last = list[len - 1];
  33767. var minGap;
  33768. var maxGap;
  33769. updateMinMaxGap();
  33770. // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  33771. minGap < 0 && squeezeGaps(-minGap, 0.8);
  33772. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  33773. updateMinMaxGap();
  33774. takeBoundsGap(minGap, maxGap, 1);
  33775. takeBoundsGap(maxGap, minGap, -1);
  33776. // Handle bailout when there is not enough space.
  33777. updateMinMaxGap();
  33778. if (minGap < 0) {
  33779. squeezeWhenBailout(-minGap);
  33780. }
  33781. if (maxGap < 0) {
  33782. squeezeWhenBailout(maxGap);
  33783. }
  33784. function updateMinMaxGap() {
  33785. minGap = first.rect[xyDim] - minBound;
  33786. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  33787. }
  33788. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  33789. if (gapThisBound < 0) {
  33790. // Move from other gap if can.
  33791. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  33792. if (moveFromMaxGap > 0) {
  33793. shiftList(moveFromMaxGap * moveDir, 0, len);
  33794. var remained = moveFromMaxGap + gapThisBound;
  33795. if (remained < 0) {
  33796. squeezeGaps(-remained * moveDir, 1);
  33797. }
  33798. } else {
  33799. squeezeGaps(-gapThisBound * moveDir, 1);
  33800. }
  33801. }
  33802. }
  33803. function shiftList(delta, start, end) {
  33804. if (delta !== 0) {
  33805. adjusted = true;
  33806. }
  33807. for (var i = start; i < end; i++) {
  33808. var item = list[i];
  33809. var rect = item.rect;
  33810. rect[xyDim] += delta;
  33811. item.label[xyDim] += delta;
  33812. }
  33813. }
  33814. // Squeeze gaps if the labels exceed margin.
  33815. function squeezeGaps(delta, maxSqeezePercent) {
  33816. var gaps = [];
  33817. var totalGaps = 0;
  33818. for (var i = 1; i < len; i++) {
  33819. var prevItemRect = list[i - 1].rect;
  33820. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  33821. gaps.push(gap);
  33822. totalGaps += gap;
  33823. }
  33824. if (!totalGaps) {
  33825. return;
  33826. }
  33827. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  33828. if (delta > 0) {
  33829. for (var i = 0; i < len - 1; i++) {
  33830. // Distribute the shift delta to all gaps.
  33831. var movement = gaps[i] * squeezePercent;
  33832. // Forward
  33833. shiftList(movement, 0, i + 1);
  33834. }
  33835. } else {
  33836. // Backward
  33837. for (var i = len - 1; i > 0; i--) {
  33838. // Distribute the shift delta to all gaps.
  33839. var movement = gaps[i - 1] * squeezePercent;
  33840. shiftList(-movement, i, len);
  33841. }
  33842. }
  33843. }
  33844. /**
  33845. * Squeeze to allow overlap if there is no more space available.
  33846. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  33847. */
  33848. function squeezeWhenBailout(delta) {
  33849. var dir = delta < 0 ? -1 : 1;
  33850. delta = Math.abs(delta);
  33851. var moveForEachLabel = Math.ceil(delta / (len - 1));
  33852. for (var i = 0; i < len - 1; i++) {
  33853. if (dir > 0) {
  33854. // Forward
  33855. shiftList(moveForEachLabel, 0, i + 1);
  33856. } else {
  33857. // Backward
  33858. shiftList(-moveForEachLabel, len - i - 1, len);
  33859. }
  33860. delta -= moveForEachLabel;
  33861. if (delta <= 0) {
  33862. return;
  33863. }
  33864. }
  33865. }
  33866. return adjusted;
  33867. }
  33868. /**
  33869. * Adjust labels on y direction to avoid overlap.
  33870. */
  33871. function shiftLayoutOnY(list, topBound, bottomBound,
  33872. // If average the shifts on all labels and add them to 0
  33873. balanceShift) {
  33874. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  33875. }
  33876. function hideOverlap(labelList) {
  33877. var displayedLabels = [];
  33878. // TODO, render overflow visible first, put in the displayedLabels.
  33879. labelList.sort(function (a, b) {
  33880. return b.priority - a.priority;
  33881. });
  33882. var globalRect = new BoundingRect(0, 0, 0, 0);
  33883. function hideEl(el) {
  33884. if (!el.ignore) {
  33885. // Show on emphasis.
  33886. var emphasisState = el.ensureState('emphasis');
  33887. if (emphasisState.ignore == null) {
  33888. emphasisState.ignore = false;
  33889. }
  33890. }
  33891. el.ignore = true;
  33892. }
  33893. for (var i = 0; i < labelList.length; i++) {
  33894. var labelItem = labelList[i];
  33895. var isAxisAligned = labelItem.axisAligned;
  33896. var localRect = labelItem.localRect;
  33897. var transform = labelItem.transform;
  33898. var label = labelItem.label;
  33899. var labelLine = labelItem.labelLine;
  33900. globalRect.copy(labelItem.rect);
  33901. // Add a threshold because layout may be aligned precisely.
  33902. globalRect.width -= 0.1;
  33903. globalRect.height -= 0.1;
  33904. globalRect.x += 0.05;
  33905. globalRect.y += 0.05;
  33906. var obb = labelItem.obb;
  33907. var overlapped = false;
  33908. for (var j = 0; j < displayedLabels.length; j++) {
  33909. var existsTextCfg = displayedLabels[j];
  33910. // Fast rejection.
  33911. if (!globalRect.intersect(existsTextCfg.rect)) {
  33912. continue;
  33913. }
  33914. if (isAxisAligned && existsTextCfg.axisAligned) {
  33915. // Is overlapped
  33916. overlapped = true;
  33917. break;
  33918. }
  33919. if (!existsTextCfg.obb) {
  33920. // If self is not axis aligned. But other is.
  33921. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  33922. }
  33923. if (!obb) {
  33924. // If self is axis aligned. But other is not.
  33925. obb = new OrientedBoundingRect(localRect, transform);
  33926. }
  33927. if (obb.intersect(existsTextCfg.obb)) {
  33928. overlapped = true;
  33929. break;
  33930. }
  33931. }
  33932. // TODO Callback to determine if this overlap should be handled?
  33933. if (overlapped) {
  33934. hideEl(label);
  33935. labelLine && hideEl(labelLine);
  33936. } else {
  33937. label.attr('ignore', labelItem.defaultAttr.ignore);
  33938. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33939. displayedLabels.push(labelItem);
  33940. }
  33941. }
  33942. }
  33943. var mathSin$4 = Math.sin;
  33944. var mathCos$4 = Math.cos;
  33945. var PI$4 = Math.PI;
  33946. var PI2$6 = Math.PI * 2;
  33947. var degree = 180 / PI$4;
  33948. var SVGPathRebuilder = (function () {
  33949. function SVGPathRebuilder() {
  33950. }
  33951. SVGPathRebuilder.prototype.reset = function (precision) {
  33952. this._start = true;
  33953. this._d = [];
  33954. this._str = '';
  33955. this._p = Math.pow(10, precision || 4);
  33956. };
  33957. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  33958. this._add('M', x, y);
  33959. };
  33960. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  33961. this._add('L', x, y);
  33962. };
  33963. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  33964. this._add('C', x, y, x2, y2, x3, y3);
  33965. };
  33966. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  33967. this._add('Q', x, y, x2, y2);
  33968. };
  33969. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  33970. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  33971. };
  33972. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  33973. var dTheta = endAngle - startAngle;
  33974. var clockwise = !anticlockwise;
  33975. var dThetaPositive = Math.abs(dTheta);
  33976. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  33977. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  33978. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  33979. var large = false;
  33980. if (isCircle) {
  33981. large = true;
  33982. }
  33983. else if (isAroundZero$1(dThetaPositive)) {
  33984. large = false;
  33985. }
  33986. else {
  33987. large = (unifiedTheta >= PI$4) === !!clockwise;
  33988. }
  33989. var x0 = cx + rx * mathCos$4(startAngle);
  33990. var y0 = cy + ry * mathSin$4(startAngle);
  33991. if (this._start) {
  33992. this._add('M', x0, y0);
  33993. }
  33994. var xRot = Math.round(psi * degree);
  33995. if (isCircle) {
  33996. var p = 1 / this._p;
  33997. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$6 - p);
  33998. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  33999. if (p > 1e-2) {
  34000. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  34001. }
  34002. }
  34003. else {
  34004. var x = cx + rx * mathCos$4(endAngle);
  34005. var y = cy + ry * mathSin$4(endAngle);
  34006. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  34007. }
  34008. };
  34009. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  34010. this._add('M', x, y);
  34011. this._add('l', w, 0);
  34012. this._add('l', 0, h);
  34013. this._add('l', -w, 0);
  34014. this._add('Z');
  34015. };
  34016. SVGPathRebuilder.prototype.closePath = function () {
  34017. if (this._d.length > 0) {
  34018. this._add('Z');
  34019. }
  34020. };
  34021. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  34022. var vals = [];
  34023. var p = this._p;
  34024. for (var i = 1; i < arguments.length; i++) {
  34025. var val = arguments[i];
  34026. if (isNaN(val)) {
  34027. this._invalid = true;
  34028. return;
  34029. }
  34030. vals.push(Math.round(val * p) / p);
  34031. }
  34032. this._d.push(cmd + vals.join(' '));
  34033. this._start = cmd === 'Z';
  34034. };
  34035. SVGPathRebuilder.prototype.generateStr = function () {
  34036. this._str = this._invalid ? '' : this._d.join('');
  34037. this._d = [];
  34038. };
  34039. SVGPathRebuilder.prototype.getStr = function () {
  34040. return this._str;
  34041. };
  34042. return SVGPathRebuilder;
  34043. }());
  34044. var NONE = 'none';
  34045. var mathRound$1 = Math.round;
  34046. function pathHasFill(style) {
  34047. var fill = style.fill;
  34048. return fill != null && fill !== NONE;
  34049. }
  34050. function pathHasStroke(style) {
  34051. var stroke = style.stroke;
  34052. return stroke != null && stroke !== NONE;
  34053. }
  34054. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  34055. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  34056. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  34057. var opacity = style.opacity == null ? 1 : style.opacity;
  34058. if (el instanceof ZRImage) {
  34059. updateAttr('opacity', opacity);
  34060. return;
  34061. }
  34062. if (pathHasFill(style)) {
  34063. var fill = normalizeColor(style.fill);
  34064. updateAttr('fill', fill.color);
  34065. var fillOpacity = style.fillOpacity != null
  34066. ? style.fillOpacity * fill.opacity * opacity
  34067. : fill.opacity * opacity;
  34068. if (forceUpdate || fillOpacity < 1) {
  34069. updateAttr('fill-opacity', fillOpacity);
  34070. }
  34071. }
  34072. else {
  34073. updateAttr('fill', NONE);
  34074. }
  34075. if (pathHasStroke(style)) {
  34076. var stroke = normalizeColor(style.stroke);
  34077. updateAttr('stroke', stroke.color);
  34078. var strokeScale = style.strokeNoScale
  34079. ? el.getLineScale()
  34080. : 1;
  34081. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  34082. var strokeOpacity = style.strokeOpacity != null
  34083. ? style.strokeOpacity * stroke.opacity * opacity
  34084. : stroke.opacity * opacity;
  34085. var strokeFirst = style.strokeFirst;
  34086. if (forceUpdate || strokeWidth !== 1) {
  34087. updateAttr('stroke-width', strokeWidth);
  34088. }
  34089. if (forceUpdate || strokeFirst) {
  34090. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  34091. }
  34092. if (forceUpdate || strokeOpacity < 1) {
  34093. updateAttr('stroke-opacity', strokeOpacity);
  34094. }
  34095. if (style.lineDash) {
  34096. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  34097. if (lineDash) {
  34098. lineDashOffset = mathRound$1(lineDashOffset || 0);
  34099. updateAttr('stroke-dasharray', lineDash.join(','));
  34100. if (lineDashOffset || forceUpdate) {
  34101. updateAttr('stroke-dashoffset', lineDashOffset);
  34102. }
  34103. }
  34104. }
  34105. else if (forceUpdate) {
  34106. updateAttr('stroke-dasharray', NONE);
  34107. }
  34108. for (var i = 0; i < strokeProps.length; i++) {
  34109. var propName = strokeProps[i];
  34110. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  34111. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  34112. val && updateAttr(svgStrokeProps[i], val);
  34113. }
  34114. }
  34115. }
  34116. else if (forceUpdate) {
  34117. updateAttr('stroke', NONE);
  34118. }
  34119. }
  34120. var SVGNS = 'http://www.w3.org/2000/svg';
  34121. var XLINKNS = 'http://www.w3.org/1999/xlink';
  34122. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  34123. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  34124. var META_DATA_PREFIX = 'ecmeta_';
  34125. function createElement(name) {
  34126. return document.createElementNS(SVGNS, name);
  34127. }
  34128. function createVNode(tag, key, attrs, children, text) {
  34129. return {
  34130. tag: tag,
  34131. attrs: attrs || {},
  34132. children: children,
  34133. text: text,
  34134. key: key
  34135. };
  34136. }
  34137. function createElementOpen(name, attrs) {
  34138. var attrsStr = [];
  34139. if (attrs) {
  34140. for (var key in attrs) {
  34141. var val = attrs[key];
  34142. var part = key;
  34143. if (val === false) {
  34144. continue;
  34145. }
  34146. else if (val !== true && val != null) {
  34147. part += "=\"" + val + "\"";
  34148. }
  34149. attrsStr.push(part);
  34150. }
  34151. }
  34152. return "<" + name + " " + attrsStr.join(' ') + ">";
  34153. }
  34154. function createElementClose(name) {
  34155. return "</" + name + ">";
  34156. }
  34157. function vNodeToString(el, opts) {
  34158. opts = opts || {};
  34159. var S = opts.newline ? '\n' : '';
  34160. function convertElToString(el) {
  34161. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  34162. return createElementOpen(tag, attrs)
  34163. + (tag !== 'style' ? encodeHTML(text) : text || '')
  34164. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  34165. + createElementClose(tag);
  34166. }
  34167. return convertElToString(el);
  34168. }
  34169. function getCssString(selectorNodes, animationNodes, opts) {
  34170. opts = opts || {};
  34171. var S = opts.newline ? '\n' : '';
  34172. var bracketBegin = " {" + S;
  34173. var bracketEnd = S + "}";
  34174. var selectors = map(keys(selectorNodes), function (className) {
  34175. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  34176. return attrName + ":" + selectorNodes[className][attrName] + ";";
  34177. }).join(S) + bracketEnd;
  34178. }).join(S);
  34179. var animations = map(keys(animationNodes), function (animationName) {
  34180. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  34181. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  34182. var val = animationNodes[animationName][percent][attrName];
  34183. if (attrName === 'd') {
  34184. val = "path(\"" + val + "\")";
  34185. }
  34186. return attrName + ":" + val + ";";
  34187. }).join(S) + bracketEnd;
  34188. }).join(S) + bracketEnd;
  34189. }).join(S);
  34190. if (!selectors && !animations) {
  34191. return '';
  34192. }
  34193. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  34194. }
  34195. function createBrushScope(zrId) {
  34196. return {
  34197. zrId: zrId,
  34198. shadowCache: {},
  34199. patternCache: {},
  34200. gradientCache: {},
  34201. clipPathCache: {},
  34202. defs: {},
  34203. cssNodes: {},
  34204. cssAnims: {},
  34205. cssStyleCache: {},
  34206. cssAnimIdx: 0,
  34207. shadowIdx: 0,
  34208. gradientIdx: 0,
  34209. patternIdx: 0,
  34210. clipPathIdx: 0
  34211. };
  34212. }
  34213. function createSVGVNode(width, height, children, useViewBox) {
  34214. return createVNode('svg', 'root', {
  34215. 'width': width,
  34216. 'height': height,
  34217. 'xmlns': SVGNS,
  34218. 'xmlns:xlink': XLINKNS,
  34219. 'version': '1.1',
  34220. 'baseProfile': 'full',
  34221. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  34222. }, children);
  34223. }
  34224. var cssClassIdx = 0;
  34225. function getClassId() {
  34226. return cssClassIdx++;
  34227. }
  34228. var EASING_MAP = {
  34229. cubicIn: '0.32,0,0.67,0',
  34230. cubicOut: '0.33,1,0.68,1',
  34231. cubicInOut: '0.65,0,0.35,1',
  34232. quadraticIn: '0.11,0,0.5,0',
  34233. quadraticOut: '0.5,1,0.89,1',
  34234. quadraticInOut: '0.45,0,0.55,1',
  34235. quarticIn: '0.5,0,0.75,0',
  34236. quarticOut: '0.25,1,0.5,1',
  34237. quarticInOut: '0.76,0,0.24,1',
  34238. quinticIn: '0.64,0,0.78,0',
  34239. quinticOut: '0.22,1,0.36,1',
  34240. quinticInOut: '0.83,0,0.17,1',
  34241. sinusoidalIn: '0.12,0,0.39,0',
  34242. sinusoidalOut: '0.61,1,0.88,1',
  34243. sinusoidalInOut: '0.37,0,0.63,1',
  34244. exponentialIn: '0.7,0,0.84,0',
  34245. exponentialOut: '0.16,1,0.3,1',
  34246. exponentialInOut: '0.87,0,0.13,1',
  34247. circularIn: '0.55,0,1,0.45',
  34248. circularOut: '0,0.55,0.45,1',
  34249. circularInOut: '0.85,0,0.15,1'
  34250. };
  34251. var transformOriginKey = 'transform-origin';
  34252. function buildPathString(el, kfShape, path) {
  34253. var shape = extend({}, el.shape);
  34254. extend(shape, kfShape);
  34255. el.buildPath(path, shape);
  34256. var svgPathBuilder = new SVGPathRebuilder();
  34257. svgPathBuilder.reset(getPathPrecision(el));
  34258. path.rebuildPath(svgPathBuilder, 1);
  34259. svgPathBuilder.generateStr();
  34260. return svgPathBuilder.getStr();
  34261. }
  34262. function setTransformOrigin(target, transform) {
  34263. var originX = transform.originX, originY = transform.originY;
  34264. if (originX || originY) {
  34265. target[transformOriginKey] = originX + "px " + originY + "px";
  34266. }
  34267. }
  34268. var ANIMATE_STYLE_MAP = {
  34269. fill: 'fill',
  34270. opacity: 'opacity',
  34271. lineWidth: 'stroke-width',
  34272. lineDashOffset: 'stroke-dashoffset'
  34273. };
  34274. function addAnimation(cssAnim, scope) {
  34275. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  34276. scope.cssAnims[animationName] = cssAnim;
  34277. return animationName;
  34278. }
  34279. function createCompoundPathCSSAnimation(el, attrs, scope) {
  34280. var paths = el.shape.paths;
  34281. var composedAnim = {};
  34282. var cssAnimationCfg;
  34283. var cssAnimationName;
  34284. each(paths, function (path) {
  34285. var subScope = createBrushScope(scope.zrId);
  34286. subScope.animation = true;
  34287. createCSSAnimation(path, {}, subScope, true);
  34288. var cssAnims = subScope.cssAnims;
  34289. var cssNodes = subScope.cssNodes;
  34290. var animNames = keys(cssAnims);
  34291. var len = animNames.length;
  34292. if (!len) {
  34293. return;
  34294. }
  34295. cssAnimationName = animNames[len - 1];
  34296. var lastAnim = cssAnims[cssAnimationName];
  34297. for (var percent in lastAnim) {
  34298. var kf = lastAnim[percent];
  34299. composedAnim[percent] = composedAnim[percent] || { d: '' };
  34300. composedAnim[percent].d += kf.d || '';
  34301. }
  34302. for (var className in cssNodes) {
  34303. var val = cssNodes[className].animation;
  34304. if (val.indexOf(cssAnimationName) >= 0) {
  34305. cssAnimationCfg = val;
  34306. }
  34307. }
  34308. });
  34309. if (!cssAnimationCfg) {
  34310. return;
  34311. }
  34312. attrs.d = false;
  34313. var animationName = addAnimation(composedAnim, scope);
  34314. return cssAnimationCfg.replace(cssAnimationName, animationName);
  34315. }
  34316. function getEasingFunc(easing) {
  34317. return isString(easing)
  34318. ? EASING_MAP[easing]
  34319. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  34320. : createCubicEasingFunc(easing) ? easing : ''
  34321. : '';
  34322. }
  34323. function createCSSAnimation(el, attrs, scope, onlyShape) {
  34324. var animators = el.animators;
  34325. var len = animators.length;
  34326. var cssAnimations = [];
  34327. if (el instanceof CompoundPath) {
  34328. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  34329. if (animationCfg) {
  34330. cssAnimations.push(animationCfg);
  34331. }
  34332. else if (!len) {
  34333. return;
  34334. }
  34335. }
  34336. else if (!len) {
  34337. return;
  34338. }
  34339. var groupAnimators = {};
  34340. for (var i = 0; i < len; i++) {
  34341. var animator = animators[i];
  34342. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  34343. var easing = getEasingFunc(animator.getClip().easing);
  34344. var delay = animator.getDelay();
  34345. if (easing) {
  34346. cfgArr.push(easing);
  34347. }
  34348. else {
  34349. cfgArr.push('linear');
  34350. }
  34351. if (delay) {
  34352. cfgArr.push(delay / 1000 + 's');
  34353. }
  34354. if (animator.getLoop()) {
  34355. cfgArr.push('infinite');
  34356. }
  34357. var cfg = cfgArr.join(' ');
  34358. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  34359. groupAnimators[cfg][1].push(animator);
  34360. }
  34361. function createSingleCSSAnimation(groupAnimator) {
  34362. var animators = groupAnimator[1];
  34363. var len = animators.length;
  34364. var transformKfs = {};
  34365. var shapeKfs = {};
  34366. var finalKfs = {};
  34367. var animationTimingFunctionAttrName = 'animation-timing-function';
  34368. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  34369. var tracks = animator.getTracks();
  34370. var maxTime = animator.getMaxTime();
  34371. for (var k = 0; k < tracks.length; k++) {
  34372. var track = tracks[k];
  34373. if (track.needsAnimate()) {
  34374. var kfs = track.keyframes;
  34375. var attrName = track.propName;
  34376. toCssAttrName && (attrName = toCssAttrName(attrName));
  34377. if (attrName) {
  34378. for (var i = 0; i < kfs.length; i++) {
  34379. var kf = kfs[i];
  34380. var percent = Math.round(kf.time / maxTime * 100) + '%';
  34381. var kfEasing = getEasingFunc(kf.easing);
  34382. var rawValue = kf.rawValue;
  34383. if (isString(rawValue) || isNumber(rawValue)) {
  34384. cssKfs[percent] = cssKfs[percent] || {};
  34385. cssKfs[percent][attrName] = kf.rawValue;
  34386. if (kfEasing) {
  34387. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  34388. }
  34389. }
  34390. }
  34391. }
  34392. }
  34393. }
  34394. }
  34395. for (var i = 0; i < len; i++) {
  34396. var animator = animators[i];
  34397. var targetProp = animator.targetName;
  34398. if (!targetProp) {
  34399. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  34400. }
  34401. else if (targetProp === 'shape') {
  34402. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  34403. }
  34404. }
  34405. for (var percent in transformKfs) {
  34406. var transform = {};
  34407. copyTransform(transform, el);
  34408. extend(transform, transformKfs[percent]);
  34409. var str = getSRTTransformString(transform);
  34410. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  34411. finalKfs[percent] = str ? {
  34412. transform: str
  34413. } : {};
  34414. setTransformOrigin(finalKfs[percent], transform);
  34415. if (timingFunction) {
  34416. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34417. }
  34418. }
  34419. var path;
  34420. var canAnimateShape = true;
  34421. for (var percent in shapeKfs) {
  34422. finalKfs[percent] = finalKfs[percent] || {};
  34423. var isFirst = !path;
  34424. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  34425. if (isFirst) {
  34426. path = new PathProxy();
  34427. }
  34428. var len_1 = path.len();
  34429. path.reset();
  34430. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  34431. var newLen = path.len();
  34432. if (!isFirst && len_1 !== newLen) {
  34433. canAnimateShape = false;
  34434. break;
  34435. }
  34436. if (timingFunction) {
  34437. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34438. }
  34439. }
  34440. if (!canAnimateShape) {
  34441. for (var percent in finalKfs) {
  34442. delete finalKfs[percent].d;
  34443. }
  34444. }
  34445. if (!onlyShape) {
  34446. for (var i = 0; i < len; i++) {
  34447. var animator = animators[i];
  34448. var targetProp = animator.targetName;
  34449. if (targetProp === 'style') {
  34450. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  34451. }
  34452. }
  34453. }
  34454. var percents = keys(finalKfs);
  34455. var allTransformOriginSame = true;
  34456. var transformOrigin;
  34457. for (var i = 1; i < percents.length; i++) {
  34458. var p0 = percents[i - 1];
  34459. var p1 = percents[i];
  34460. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  34461. allTransformOriginSame = false;
  34462. break;
  34463. }
  34464. transformOrigin = finalKfs[p0][transformOriginKey];
  34465. }
  34466. if (allTransformOriginSame && transformOrigin) {
  34467. for (var percent in finalKfs) {
  34468. if (finalKfs[percent][transformOriginKey]) {
  34469. delete finalKfs[percent][transformOriginKey];
  34470. }
  34471. }
  34472. attrs[transformOriginKey] = transformOrigin;
  34473. }
  34474. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  34475. var animationName = addAnimation(finalKfs, scope);
  34476. return animationName + " " + groupAnimator[0] + " both";
  34477. }
  34478. }
  34479. for (var key in groupAnimators) {
  34480. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  34481. if (animationCfg) {
  34482. cssAnimations.push(animationCfg);
  34483. }
  34484. }
  34485. if (cssAnimations.length) {
  34486. var className = scope.zrId + '-cls-' + getClassId();
  34487. scope.cssNodes['.' + className] = {
  34488. animation: cssAnimations.join(',')
  34489. };
  34490. attrs["class"] = className;
  34491. }
  34492. }
  34493. function createCSSEmphasis(el, attrs, scope) {
  34494. if (!el.ignore) {
  34495. if (el.isSilent()) {
  34496. var style = {
  34497. 'pointer-events': 'none'
  34498. };
  34499. setClassAttribute(style, attrs, scope, true);
  34500. }
  34501. else {
  34502. var emphasisStyle = el.states.emphasis && el.states.emphasis.style
  34503. ? el.states.emphasis.style
  34504. : {};
  34505. var fill = emphasisStyle.fill;
  34506. if (!fill) {
  34507. var normalFill = el.style && el.style.fill;
  34508. var selectFill = el.states.select
  34509. && el.states.select.style
  34510. && el.states.select.style.fill;
  34511. var fromFill = el.currentStates.indexOf('select') >= 0
  34512. ? (selectFill || normalFill)
  34513. : normalFill;
  34514. if (fromFill) {
  34515. fill = liftColor(fromFill);
  34516. }
  34517. }
  34518. var lineWidth = emphasisStyle.lineWidth;
  34519. if (lineWidth) {
  34520. var scaleX = (!emphasisStyle.strokeNoScale && el.transform)
  34521. ? el.transform[0]
  34522. : 1;
  34523. lineWidth = lineWidth / scaleX;
  34524. }
  34525. var style = {
  34526. cursor: 'pointer'
  34527. };
  34528. if (fill) {
  34529. style.fill = fill;
  34530. }
  34531. if (emphasisStyle.stroke) {
  34532. style.stroke = emphasisStyle.stroke;
  34533. }
  34534. if (lineWidth) {
  34535. style['stroke-width'] = lineWidth;
  34536. }
  34537. setClassAttribute(style, attrs, scope, true);
  34538. }
  34539. }
  34540. }
  34541. function setClassAttribute(style, attrs, scope, withHover) {
  34542. var styleKey = JSON.stringify(style);
  34543. var className = scope.cssStyleCache[styleKey];
  34544. if (!className) {
  34545. className = scope.zrId + '-cls-' + getClassId();
  34546. scope.cssStyleCache[styleKey] = className;
  34547. scope.cssNodes['.' + className + (withHover ? ':hover' : '')] = style;
  34548. }
  34549. attrs["class"] = attrs["class"] ? (attrs["class"] + ' ' + className) : className;
  34550. }
  34551. var round$2 = Math.round;
  34552. function isImageLike$1(val) {
  34553. return val && isString(val.src);
  34554. }
  34555. function isCanvasLike(val) {
  34556. return val && isFunction(val.toDataURL);
  34557. }
  34558. function setStyleAttrs(attrs, style, el, scope) {
  34559. mapStyleToAttrs(function (key, val) {
  34560. var isFillStroke = key === 'fill' || key === 'stroke';
  34561. if (isFillStroke && isGradient(val)) {
  34562. setGradient(style, attrs, key, scope);
  34563. }
  34564. else if (isFillStroke && isPattern(val)) {
  34565. setPattern(el, attrs, key, scope);
  34566. }
  34567. else {
  34568. attrs[key] = val;
  34569. }
  34570. if (isFillStroke && scope.ssr && val === 'none') {
  34571. attrs['pointer-events'] = 'visible';
  34572. }
  34573. }, style, el, false);
  34574. setShadow(el, attrs, scope);
  34575. }
  34576. function setMetaData(attrs, el) {
  34577. var metaData = getElementSSRData(el);
  34578. if (metaData) {
  34579. metaData.each(function (val, key) {
  34580. val != null && (attrs[(META_DATA_PREFIX + key).toLowerCase()] = val + '');
  34581. });
  34582. if (el.isSilent()) {
  34583. attrs[META_DATA_PREFIX + 'silent'] = 'true';
  34584. }
  34585. }
  34586. }
  34587. function noRotateScale(m) {
  34588. return isAroundZero$1(m[0] - 1)
  34589. && isAroundZero$1(m[1])
  34590. && isAroundZero$1(m[2])
  34591. && isAroundZero$1(m[3] - 1);
  34592. }
  34593. function noTranslate(m) {
  34594. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  34595. }
  34596. function setTransform(attrs, m, compress) {
  34597. if (m && !(noTranslate(m) && noRotateScale(m))) {
  34598. var mul = compress ? 10 : 1e4;
  34599. attrs.transform = noRotateScale(m)
  34600. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  34601. }
  34602. }
  34603. function convertPolyShape(shape, attrs, mul) {
  34604. var points = shape.points;
  34605. var strArr = [];
  34606. for (var i = 0; i < points.length; i++) {
  34607. strArr.push(round$2(points[i][0] * mul) / mul);
  34608. strArr.push(round$2(points[i][1] * mul) / mul);
  34609. }
  34610. attrs.points = strArr.join(' ');
  34611. }
  34612. function validatePolyShape(shape) {
  34613. return !shape.smooth;
  34614. }
  34615. function createAttrsConvert(desc) {
  34616. var normalizedDesc = map(desc, function (item) {
  34617. return (typeof item === 'string' ? [item, item] : item);
  34618. });
  34619. return function (shape, attrs, mul) {
  34620. for (var i = 0; i < normalizedDesc.length; i++) {
  34621. var item = normalizedDesc[i];
  34622. var val = shape[item[0]];
  34623. if (val != null) {
  34624. attrs[item[1]] = round$2(val * mul) / mul;
  34625. }
  34626. }
  34627. };
  34628. }
  34629. var builtinShapesDef = {
  34630. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  34631. polyline: [convertPolyShape, validatePolyShape],
  34632. polygon: [convertPolyShape, validatePolyShape]
  34633. };
  34634. function hasShapeAnimation(el) {
  34635. var animators = el.animators;
  34636. for (var i = 0; i < animators.length; i++) {
  34637. if (animators[i].targetName === 'shape') {
  34638. return true;
  34639. }
  34640. }
  34641. return false;
  34642. }
  34643. function brushSVGPath(el, scope) {
  34644. var style = el.style;
  34645. var shape = el.shape;
  34646. var builtinShpDef = builtinShapesDef[el.type];
  34647. var attrs = {};
  34648. var needsAnimate = scope.animation;
  34649. var svgElType = 'path';
  34650. var strokePercent = el.style.strokePercent;
  34651. var precision = (scope.compress && getPathPrecision(el)) || 4;
  34652. if (builtinShpDef
  34653. && !scope.willUpdate
  34654. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  34655. && !(needsAnimate && hasShapeAnimation(el))
  34656. && !(strokePercent < 1)) {
  34657. svgElType = el.type;
  34658. var mul = Math.pow(10, precision);
  34659. builtinShpDef[0](shape, attrs, mul);
  34660. }
  34661. else {
  34662. var needBuildPath = !el.path || el.shapeChanged();
  34663. if (!el.path) {
  34664. el.createPathProxy();
  34665. }
  34666. var path = el.path;
  34667. if (needBuildPath) {
  34668. path.beginPath();
  34669. el.buildPath(path, el.shape);
  34670. el.pathUpdated();
  34671. }
  34672. var pathVersion = path.getVersion();
  34673. var elExt = el;
  34674. var svgPathBuilder = elExt.__svgPathBuilder;
  34675. if (elExt.__svgPathVersion !== pathVersion
  34676. || !svgPathBuilder
  34677. || strokePercent !== elExt.__svgPathStrokePercent) {
  34678. if (!svgPathBuilder) {
  34679. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  34680. }
  34681. svgPathBuilder.reset(precision);
  34682. path.rebuildPath(svgPathBuilder, strokePercent);
  34683. svgPathBuilder.generateStr();
  34684. elExt.__svgPathVersion = pathVersion;
  34685. elExt.__svgPathStrokePercent = strokePercent;
  34686. }
  34687. attrs.d = svgPathBuilder.getStr();
  34688. }
  34689. setTransform(attrs, el.transform);
  34690. setStyleAttrs(attrs, style, el, scope);
  34691. setMetaData(attrs, el);
  34692. scope.animation && createCSSAnimation(el, attrs, scope);
  34693. scope.emphasis && createCSSEmphasis(el, attrs, scope);
  34694. return createVNode(svgElType, el.id + '', attrs);
  34695. }
  34696. function brushSVGImage(el, scope) {
  34697. var style = el.style;
  34698. var image = style.image;
  34699. if (image && !isString(image)) {
  34700. if (isImageLike$1(image)) {
  34701. image = image.src;
  34702. }
  34703. else if (isCanvasLike(image)) {
  34704. image = image.toDataURL();
  34705. }
  34706. }
  34707. if (!image) {
  34708. return;
  34709. }
  34710. var x = style.x || 0;
  34711. var y = style.y || 0;
  34712. var dw = style.width;
  34713. var dh = style.height;
  34714. var attrs = {
  34715. href: image,
  34716. width: dw,
  34717. height: dh
  34718. };
  34719. if (x) {
  34720. attrs.x = x;
  34721. }
  34722. if (y) {
  34723. attrs.y = y;
  34724. }
  34725. setTransform(attrs, el.transform);
  34726. setStyleAttrs(attrs, style, el, scope);
  34727. setMetaData(attrs, el);
  34728. scope.animation && createCSSAnimation(el, attrs, scope);
  34729. return createVNode('image', el.id + '', attrs);
  34730. }
  34731. function brushSVGTSpan(el, scope) {
  34732. var style = el.style;
  34733. var text = style.text;
  34734. text != null && (text += '');
  34735. if (!text || isNaN(style.x) || isNaN(style.y)) {
  34736. return;
  34737. }
  34738. var font = style.font || DEFAULT_FONT;
  34739. var x = style.x || 0;
  34740. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  34741. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  34742. || style.textAlign;
  34743. var attrs = {
  34744. 'dominant-baseline': 'central',
  34745. 'text-anchor': textAlign
  34746. };
  34747. if (hasSeparateFont(style)) {
  34748. var separatedFontStr = '';
  34749. var fontStyle = style.fontStyle;
  34750. var fontSize = parseFontSize(style.fontSize);
  34751. if (!parseFloat(fontSize)) {
  34752. return;
  34753. }
  34754. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  34755. var fontWeight = style.fontWeight;
  34756. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  34757. if (fontStyle && fontStyle !== 'normal') {
  34758. separatedFontStr += "font-style:" + fontStyle + ";";
  34759. }
  34760. if (fontWeight && fontWeight !== 'normal') {
  34761. separatedFontStr += "font-weight:" + fontWeight + ";";
  34762. }
  34763. attrs.style = separatedFontStr;
  34764. }
  34765. else {
  34766. attrs.style = "font: " + font;
  34767. }
  34768. if (text.match(/\s/)) {
  34769. attrs['xml:space'] = 'preserve';
  34770. }
  34771. if (x) {
  34772. attrs.x = x;
  34773. }
  34774. if (y) {
  34775. attrs.y = y;
  34776. }
  34777. setTransform(attrs, el.transform);
  34778. setStyleAttrs(attrs, style, el, scope);
  34779. setMetaData(attrs, el);
  34780. scope.animation && createCSSAnimation(el, attrs, scope);
  34781. return createVNode('text', el.id + '', attrs, undefined, text);
  34782. }
  34783. function brush$1(el, scope) {
  34784. if (el instanceof Path) {
  34785. return brushSVGPath(el, scope);
  34786. }
  34787. else if (el instanceof ZRImage) {
  34788. return brushSVGImage(el, scope);
  34789. }
  34790. else if (el instanceof TSpan) {
  34791. return brushSVGTSpan(el, scope);
  34792. }
  34793. }
  34794. function setShadow(el, attrs, scope) {
  34795. var style = el.style;
  34796. if (hasShadow(style)) {
  34797. var shadowKey = getShadowKey(el);
  34798. var shadowCache = scope.shadowCache;
  34799. var shadowId = shadowCache[shadowKey];
  34800. if (!shadowId) {
  34801. var globalScale = el.getGlobalScale();
  34802. var scaleX = globalScale[0];
  34803. var scaleY = globalScale[1];
  34804. if (!scaleX || !scaleY) {
  34805. return;
  34806. }
  34807. var offsetX = style.shadowOffsetX || 0;
  34808. var offsetY = style.shadowOffsetY || 0;
  34809. var blur_1 = style.shadowBlur;
  34810. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  34811. var stdDx = blur_1 / 2 / scaleX;
  34812. var stdDy = blur_1 / 2 / scaleY;
  34813. var stdDeviation = stdDx + ' ' + stdDy;
  34814. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  34815. scope.defs[shadowId] = createVNode('filter', shadowId, {
  34816. 'id': shadowId,
  34817. 'x': '-100%',
  34818. 'y': '-100%',
  34819. 'width': '300%',
  34820. 'height': '300%'
  34821. }, [
  34822. createVNode('feDropShadow', '', {
  34823. 'dx': offsetX / scaleX,
  34824. 'dy': offsetY / scaleY,
  34825. 'stdDeviation': stdDeviation,
  34826. 'flood-color': color,
  34827. 'flood-opacity': opacity
  34828. })
  34829. ]);
  34830. shadowCache[shadowKey] = shadowId;
  34831. }
  34832. attrs.filter = getIdURL(shadowId);
  34833. }
  34834. }
  34835. function setGradient(style, attrs, target, scope) {
  34836. var val = style[target];
  34837. var gradientTag;
  34838. var gradientAttrs = {
  34839. 'gradientUnits': val.global
  34840. ? 'userSpaceOnUse'
  34841. : 'objectBoundingBox'
  34842. };
  34843. if (isLinearGradient(val)) {
  34844. gradientTag = 'linearGradient';
  34845. gradientAttrs.x1 = val.x;
  34846. gradientAttrs.y1 = val.y;
  34847. gradientAttrs.x2 = val.x2;
  34848. gradientAttrs.y2 = val.y2;
  34849. }
  34850. else if (isRadialGradient(val)) {
  34851. gradientTag = 'radialGradient';
  34852. gradientAttrs.cx = retrieve2(val.x, 0.5);
  34853. gradientAttrs.cy = retrieve2(val.y, 0.5);
  34854. gradientAttrs.r = retrieve2(val.r, 0.5);
  34855. }
  34856. else {
  34857. if ("development" !== 'production') {
  34858. logError('Illegal gradient type.');
  34859. }
  34860. return;
  34861. }
  34862. var colors = val.colorStops;
  34863. var colorStops = [];
  34864. for (var i = 0, len = colors.length; i < len; ++i) {
  34865. var offset = round4(colors[i].offset) * 100 + '%';
  34866. var stopColor = colors[i].color;
  34867. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  34868. var stopsAttrs = {
  34869. 'offset': offset
  34870. };
  34871. stopsAttrs['stop-color'] = color;
  34872. if (opacity < 1) {
  34873. stopsAttrs['stop-opacity'] = opacity;
  34874. }
  34875. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  34876. }
  34877. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  34878. var gradientKey = vNodeToString(gradientVNode);
  34879. var gradientCache = scope.gradientCache;
  34880. var gradientId = gradientCache[gradientKey];
  34881. if (!gradientId) {
  34882. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  34883. gradientCache[gradientKey] = gradientId;
  34884. gradientAttrs.id = gradientId;
  34885. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  34886. }
  34887. attrs[target] = getIdURL(gradientId);
  34888. }
  34889. function setPattern(el, attrs, target, scope) {
  34890. var val = el.style[target];
  34891. var boundingRect = el.getBoundingRect();
  34892. var patternAttrs = {};
  34893. var repeat = val.repeat;
  34894. var noRepeat = repeat === 'no-repeat';
  34895. var repeatX = repeat === 'repeat-x';
  34896. var repeatY = repeat === 'repeat-y';
  34897. var child;
  34898. if (isImagePattern(val)) {
  34899. var imageWidth_1 = val.imageWidth;
  34900. var imageHeight_1 = val.imageHeight;
  34901. var imageSrc = void 0;
  34902. var patternImage = val.image;
  34903. if (isString(patternImage)) {
  34904. imageSrc = patternImage;
  34905. }
  34906. else if (isImageLike$1(patternImage)) {
  34907. imageSrc = patternImage.src;
  34908. }
  34909. else if (isCanvasLike(patternImage)) {
  34910. imageSrc = patternImage.toDataURL();
  34911. }
  34912. if (typeof Image === 'undefined') {
  34913. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  34914. assert(imageWidth_1, errMsg);
  34915. assert(imageHeight_1, errMsg);
  34916. }
  34917. else if (imageWidth_1 == null || imageHeight_1 == null) {
  34918. var setSizeToVNode_1 = function (vNode, img) {
  34919. if (vNode) {
  34920. var svgEl = vNode.elm;
  34921. var width = imageWidth_1 || img.width;
  34922. var height = imageHeight_1 || img.height;
  34923. if (vNode.tag === 'pattern') {
  34924. if (repeatX) {
  34925. height = 1;
  34926. width /= boundingRect.width;
  34927. }
  34928. else if (repeatY) {
  34929. width = 1;
  34930. height /= boundingRect.height;
  34931. }
  34932. }
  34933. vNode.attrs.width = width;
  34934. vNode.attrs.height = height;
  34935. if (svgEl) {
  34936. svgEl.setAttribute('width', width);
  34937. svgEl.setAttribute('height', height);
  34938. }
  34939. }
  34940. };
  34941. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  34942. noRepeat || setSizeToVNode_1(patternVNode, img);
  34943. setSizeToVNode_1(child, img);
  34944. });
  34945. if (createdImage && createdImage.width && createdImage.height) {
  34946. imageWidth_1 = imageWidth_1 || createdImage.width;
  34947. imageHeight_1 = imageHeight_1 || createdImage.height;
  34948. }
  34949. }
  34950. child = createVNode('image', 'img', {
  34951. href: imageSrc,
  34952. width: imageWidth_1,
  34953. height: imageHeight_1
  34954. });
  34955. patternAttrs.width = imageWidth_1;
  34956. patternAttrs.height = imageHeight_1;
  34957. }
  34958. else if (val.svgElement) {
  34959. child = clone(val.svgElement);
  34960. patternAttrs.width = val.svgWidth;
  34961. patternAttrs.height = val.svgHeight;
  34962. }
  34963. if (!child) {
  34964. return;
  34965. }
  34966. var patternWidth;
  34967. var patternHeight;
  34968. if (noRepeat) {
  34969. patternWidth = patternHeight = 1;
  34970. }
  34971. else if (repeatX) {
  34972. patternHeight = 1;
  34973. patternWidth = patternAttrs.width / boundingRect.width;
  34974. }
  34975. else if (repeatY) {
  34976. patternWidth = 1;
  34977. patternHeight = patternAttrs.height / boundingRect.height;
  34978. }
  34979. else {
  34980. patternAttrs.patternUnits = 'userSpaceOnUse';
  34981. }
  34982. if (patternWidth != null && !isNaN(patternWidth)) {
  34983. patternAttrs.width = patternWidth;
  34984. }
  34985. if (patternHeight != null && !isNaN(patternHeight)) {
  34986. patternAttrs.height = patternHeight;
  34987. }
  34988. var patternTransform = getSRTTransformString(val);
  34989. patternTransform && (patternAttrs.patternTransform = patternTransform);
  34990. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  34991. var patternKey = vNodeToString(patternVNode);
  34992. var patternCache = scope.patternCache;
  34993. var patternId = patternCache[patternKey];
  34994. if (!patternId) {
  34995. patternId = scope.zrId + '-p' + scope.patternIdx++;
  34996. patternCache[patternKey] = patternId;
  34997. patternAttrs.id = patternId;
  34998. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  34999. }
  35000. attrs[target] = getIdURL(patternId);
  35001. }
  35002. function setClipPath(clipPath, attrs, scope) {
  35003. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  35004. var clipPathId = clipPathCache[clipPath.id];
  35005. if (!clipPathId) {
  35006. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  35007. var clipPathAttrs = {
  35008. id: clipPathId
  35009. };
  35010. clipPathCache[clipPath.id] = clipPathId;
  35011. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  35012. }
  35013. attrs['clip-path'] = getIdURL(clipPathId);
  35014. }
  35015. function createTextNode(text) {
  35016. return document.createTextNode(text);
  35017. }
  35018. function insertBefore(parentNode, newNode, referenceNode) {
  35019. parentNode.insertBefore(newNode, referenceNode);
  35020. }
  35021. function removeChild(node, child) {
  35022. node.removeChild(child);
  35023. }
  35024. function appendChild(node, child) {
  35025. node.appendChild(child);
  35026. }
  35027. function parentNode(node) {
  35028. return node.parentNode;
  35029. }
  35030. function nextSibling(node) {
  35031. return node.nextSibling;
  35032. }
  35033. function setTextContent(node, text) {
  35034. node.textContent = text;
  35035. }
  35036. var colonChar = 58;
  35037. var xChar = 120;
  35038. var emptyNode = createVNode('', '');
  35039. function isUndef(s) {
  35040. return s === undefined;
  35041. }
  35042. function isDef(s) {
  35043. return s !== undefined;
  35044. }
  35045. function createKeyToOldIdx(children, beginIdx, endIdx) {
  35046. var map = {};
  35047. for (var i = beginIdx; i <= endIdx; ++i) {
  35048. var key = children[i].key;
  35049. if (key !== undefined) {
  35050. if ("development" !== 'production') {
  35051. if (map[key] != null) {
  35052. console.error("Duplicate key " + key);
  35053. }
  35054. }
  35055. map[key] = i;
  35056. }
  35057. }
  35058. return map;
  35059. }
  35060. function sameVnode(vnode1, vnode2) {
  35061. var isSameKey = vnode1.key === vnode2.key;
  35062. var isSameTag = vnode1.tag === vnode2.tag;
  35063. return isSameTag && isSameKey;
  35064. }
  35065. function createElm(vnode) {
  35066. var i;
  35067. var children = vnode.children;
  35068. var tag = vnode.tag;
  35069. if (isDef(tag)) {
  35070. var elm = (vnode.elm = createElement(tag));
  35071. updateAttrs(emptyNode, vnode);
  35072. if (isArray(children)) {
  35073. for (i = 0; i < children.length; ++i) {
  35074. var ch = children[i];
  35075. if (ch != null) {
  35076. appendChild(elm, createElm(ch));
  35077. }
  35078. }
  35079. }
  35080. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  35081. appendChild(elm, createTextNode(vnode.text));
  35082. }
  35083. }
  35084. else {
  35085. vnode.elm = createTextNode(vnode.text);
  35086. }
  35087. return vnode.elm;
  35088. }
  35089. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  35090. for (; startIdx <= endIdx; ++startIdx) {
  35091. var ch = vnodes[startIdx];
  35092. if (ch != null) {
  35093. insertBefore(parentElm, createElm(ch), before);
  35094. }
  35095. }
  35096. }
  35097. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  35098. for (; startIdx <= endIdx; ++startIdx) {
  35099. var ch = vnodes[startIdx];
  35100. if (ch != null) {
  35101. if (isDef(ch.tag)) {
  35102. var parent_1 = parentNode(ch.elm);
  35103. removeChild(parent_1, ch.elm);
  35104. }
  35105. else {
  35106. removeChild(parentElm, ch.elm);
  35107. }
  35108. }
  35109. }
  35110. }
  35111. function updateAttrs(oldVnode, vnode) {
  35112. var key;
  35113. var elm = vnode.elm;
  35114. var oldAttrs = oldVnode && oldVnode.attrs || {};
  35115. var attrs = vnode.attrs || {};
  35116. if (oldAttrs === attrs) {
  35117. return;
  35118. }
  35119. for (key in attrs) {
  35120. var cur = attrs[key];
  35121. var old = oldAttrs[key];
  35122. if (old !== cur) {
  35123. if (cur === true) {
  35124. elm.setAttribute(key, '');
  35125. }
  35126. else if (cur === false) {
  35127. elm.removeAttribute(key);
  35128. }
  35129. else {
  35130. if (key === 'style') {
  35131. elm.style.cssText = cur;
  35132. }
  35133. else if (key.charCodeAt(0) !== xChar) {
  35134. elm.setAttribute(key, cur);
  35135. }
  35136. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  35137. elm.setAttributeNS(XMLNS, key, cur);
  35138. }
  35139. else if (key.charCodeAt(3) === colonChar) {
  35140. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  35141. }
  35142. else if (key.charCodeAt(5) === colonChar) {
  35143. elm.setAttributeNS(XLINKNS, key, cur);
  35144. }
  35145. else {
  35146. elm.setAttribute(key, cur);
  35147. }
  35148. }
  35149. }
  35150. }
  35151. for (key in oldAttrs) {
  35152. if (!(key in attrs)) {
  35153. elm.removeAttribute(key);
  35154. }
  35155. }
  35156. }
  35157. function updateChildren(parentElm, oldCh, newCh) {
  35158. var oldStartIdx = 0;
  35159. var newStartIdx = 0;
  35160. var oldEndIdx = oldCh.length - 1;
  35161. var oldStartVnode = oldCh[0];
  35162. var oldEndVnode = oldCh[oldEndIdx];
  35163. var newEndIdx = newCh.length - 1;
  35164. var newStartVnode = newCh[0];
  35165. var newEndVnode = newCh[newEndIdx];
  35166. var oldKeyToIdx;
  35167. var idxInOld;
  35168. var elmToMove;
  35169. var before;
  35170. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  35171. if (oldStartVnode == null) {
  35172. oldStartVnode = oldCh[++oldStartIdx];
  35173. }
  35174. else if (oldEndVnode == null) {
  35175. oldEndVnode = oldCh[--oldEndIdx];
  35176. }
  35177. else if (newStartVnode == null) {
  35178. newStartVnode = newCh[++newStartIdx];
  35179. }
  35180. else if (newEndVnode == null) {
  35181. newEndVnode = newCh[--newEndIdx];
  35182. }
  35183. else if (sameVnode(oldStartVnode, newStartVnode)) {
  35184. patchVnode(oldStartVnode, newStartVnode);
  35185. oldStartVnode = oldCh[++oldStartIdx];
  35186. newStartVnode = newCh[++newStartIdx];
  35187. }
  35188. else if (sameVnode(oldEndVnode, newEndVnode)) {
  35189. patchVnode(oldEndVnode, newEndVnode);
  35190. oldEndVnode = oldCh[--oldEndIdx];
  35191. newEndVnode = newCh[--newEndIdx];
  35192. }
  35193. else if (sameVnode(oldStartVnode, newEndVnode)) {
  35194. patchVnode(oldStartVnode, newEndVnode);
  35195. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  35196. oldStartVnode = oldCh[++oldStartIdx];
  35197. newEndVnode = newCh[--newEndIdx];
  35198. }
  35199. else if (sameVnode(oldEndVnode, newStartVnode)) {
  35200. patchVnode(oldEndVnode, newStartVnode);
  35201. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  35202. oldEndVnode = oldCh[--oldEndIdx];
  35203. newStartVnode = newCh[++newStartIdx];
  35204. }
  35205. else {
  35206. if (isUndef(oldKeyToIdx)) {
  35207. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  35208. }
  35209. idxInOld = oldKeyToIdx[newStartVnode.key];
  35210. if (isUndef(idxInOld)) {
  35211. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35212. }
  35213. else {
  35214. elmToMove = oldCh[idxInOld];
  35215. if (elmToMove.tag !== newStartVnode.tag) {
  35216. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35217. }
  35218. else {
  35219. patchVnode(elmToMove, newStartVnode);
  35220. oldCh[idxInOld] = undefined;
  35221. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  35222. }
  35223. }
  35224. newStartVnode = newCh[++newStartIdx];
  35225. }
  35226. }
  35227. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  35228. if (oldStartIdx > oldEndIdx) {
  35229. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  35230. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  35231. }
  35232. else {
  35233. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  35234. }
  35235. }
  35236. }
  35237. function patchVnode(oldVnode, vnode) {
  35238. var elm = (vnode.elm = oldVnode.elm);
  35239. var oldCh = oldVnode.children;
  35240. var ch = vnode.children;
  35241. if (oldVnode === vnode) {
  35242. return;
  35243. }
  35244. updateAttrs(oldVnode, vnode);
  35245. if (isUndef(vnode.text)) {
  35246. if (isDef(oldCh) && isDef(ch)) {
  35247. if (oldCh !== ch) {
  35248. updateChildren(elm, oldCh, ch);
  35249. }
  35250. }
  35251. else if (isDef(ch)) {
  35252. if (isDef(oldVnode.text)) {
  35253. setTextContent(elm, '');
  35254. }
  35255. addVnodes(elm, null, ch, 0, ch.length - 1);
  35256. }
  35257. else if (isDef(oldCh)) {
  35258. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35259. }
  35260. else if (isDef(oldVnode.text)) {
  35261. setTextContent(elm, '');
  35262. }
  35263. }
  35264. else if (oldVnode.text !== vnode.text) {
  35265. if (isDef(oldCh)) {
  35266. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35267. }
  35268. setTextContent(elm, vnode.text);
  35269. }
  35270. }
  35271. function patch(oldVnode, vnode) {
  35272. if (sameVnode(oldVnode, vnode)) {
  35273. patchVnode(oldVnode, vnode);
  35274. }
  35275. else {
  35276. var elm = oldVnode.elm;
  35277. var parent_2 = parentNode(elm);
  35278. createElm(vnode);
  35279. if (parent_2 !== null) {
  35280. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  35281. removeVnodes(parent_2, [oldVnode], 0, 0);
  35282. }
  35283. }
  35284. return vnode;
  35285. }
  35286. var svgId = 0;
  35287. var SVGPainter = (function () {
  35288. function SVGPainter(root, storage, opts) {
  35289. this.type = 'svg';
  35290. this.refreshHover = createMethodNotSupport('refreshHover');
  35291. this.configLayer = createMethodNotSupport('configLayer');
  35292. this.storage = storage;
  35293. this._opts = opts = extend({}, opts);
  35294. this.root = root;
  35295. this._id = 'zr' + svgId++;
  35296. this._oldVNode = createSVGVNode(opts.width, opts.height);
  35297. if (root && !opts.ssr) {
  35298. var viewport = this._viewport = document.createElement('div');
  35299. viewport.style.cssText = 'position:relative;overflow:hidden';
  35300. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  35301. updateAttrs(null, this._oldVNode);
  35302. viewport.appendChild(svgDom);
  35303. root.appendChild(viewport);
  35304. }
  35305. this.resize(opts.width, opts.height);
  35306. }
  35307. SVGPainter.prototype.getType = function () {
  35308. return this.type;
  35309. };
  35310. SVGPainter.prototype.getViewportRoot = function () {
  35311. return this._viewport;
  35312. };
  35313. SVGPainter.prototype.getViewportRootOffset = function () {
  35314. var viewportRoot = this.getViewportRoot();
  35315. if (viewportRoot) {
  35316. return {
  35317. offsetLeft: viewportRoot.offsetLeft || 0,
  35318. offsetTop: viewportRoot.offsetTop || 0
  35319. };
  35320. }
  35321. };
  35322. SVGPainter.prototype.getSvgDom = function () {
  35323. return this._svgDom;
  35324. };
  35325. SVGPainter.prototype.refresh = function () {
  35326. if (this.root) {
  35327. var vnode = this.renderToVNode({
  35328. willUpdate: true
  35329. });
  35330. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  35331. patch(this._oldVNode, vnode);
  35332. this._oldVNode = vnode;
  35333. }
  35334. };
  35335. SVGPainter.prototype.renderOneToVNode = function (el) {
  35336. return brush$1(el, createBrushScope(this._id));
  35337. };
  35338. SVGPainter.prototype.renderToVNode = function (opts) {
  35339. opts = opts || {};
  35340. var list = this.storage.getDisplayList(true);
  35341. var width = this._width;
  35342. var height = this._height;
  35343. var scope = createBrushScope(this._id);
  35344. scope.animation = opts.animation;
  35345. scope.willUpdate = opts.willUpdate;
  35346. scope.compress = opts.compress;
  35347. scope.emphasis = opts.emphasis;
  35348. scope.ssr = this._opts.ssr;
  35349. var children = [];
  35350. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  35351. bgVNode && children.push(bgVNode);
  35352. var mainVNode = !opts.compress
  35353. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  35354. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  35355. mainVNode && children.push(mainVNode);
  35356. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  35357. if (defs.length) {
  35358. children.push(createVNode('defs', 'defs', {}, defs));
  35359. }
  35360. if (opts.animation) {
  35361. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  35362. if (animationCssStr) {
  35363. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  35364. children.push(styleNode);
  35365. }
  35366. }
  35367. return createSVGVNode(width, height, children, opts.useViewBox);
  35368. };
  35369. SVGPainter.prototype.renderToString = function (opts) {
  35370. opts = opts || {};
  35371. return vNodeToString(this.renderToVNode({
  35372. animation: retrieve2(opts.cssAnimation, true),
  35373. emphasis: retrieve2(opts.cssEmphasis, true),
  35374. willUpdate: false,
  35375. compress: true,
  35376. useViewBox: retrieve2(opts.useViewBox, true)
  35377. }), { newline: true });
  35378. };
  35379. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35380. this._backgroundColor = backgroundColor;
  35381. };
  35382. SVGPainter.prototype.getSvgRoot = function () {
  35383. return this._mainVNode && this._mainVNode.elm;
  35384. };
  35385. SVGPainter.prototype._paintList = function (list, scope, out) {
  35386. var listLen = list.length;
  35387. var clipPathsGroupsStack = [];
  35388. var clipPathsGroupsStackDepth = 0;
  35389. var currentClipPathGroup;
  35390. var prevClipPaths;
  35391. var clipGroupNodeIdx = 0;
  35392. for (var i = 0; i < listLen; i++) {
  35393. var displayable = list[i];
  35394. if (!displayable.invisible) {
  35395. var clipPaths = displayable.__clipPaths;
  35396. var len = clipPaths && clipPaths.length || 0;
  35397. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  35398. var lca = void 0;
  35399. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  35400. if (clipPaths && prevClipPaths
  35401. && clipPaths[lca] === prevClipPaths[lca]) {
  35402. break;
  35403. }
  35404. }
  35405. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  35406. clipPathsGroupsStackDepth--;
  35407. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  35408. }
  35409. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  35410. var groupAttrs = {};
  35411. setClipPath(clipPaths[i_2], groupAttrs, scope);
  35412. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  35413. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  35414. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  35415. currentClipPathGroup = g;
  35416. }
  35417. prevClipPaths = clipPaths;
  35418. var ret = brush$1(displayable, scope);
  35419. if (ret) {
  35420. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  35421. }
  35422. }
  35423. }
  35424. };
  35425. SVGPainter.prototype.resize = function (width, height) {
  35426. var opts = this._opts;
  35427. var root = this.root;
  35428. var viewport = this._viewport;
  35429. width != null && (opts.width = width);
  35430. height != null && (opts.height = height);
  35431. if (root && viewport) {
  35432. viewport.style.display = 'none';
  35433. width = getSize(root, 0, opts);
  35434. height = getSize(root, 1, opts);
  35435. viewport.style.display = '';
  35436. }
  35437. if (this._width !== width || this._height !== height) {
  35438. this._width = width;
  35439. this._height = height;
  35440. if (viewport) {
  35441. var viewportStyle = viewport.style;
  35442. viewportStyle.width = width + 'px';
  35443. viewportStyle.height = height + 'px';
  35444. }
  35445. if (!isPattern(this._backgroundColor)) {
  35446. var svgDom = this._svgDom;
  35447. if (svgDom) {
  35448. svgDom.setAttribute('width', width);
  35449. svgDom.setAttribute('height', height);
  35450. }
  35451. var bgEl = this._bgVNode && this._bgVNode.elm;
  35452. if (bgEl) {
  35453. bgEl.setAttribute('width', width);
  35454. bgEl.setAttribute('height', height);
  35455. }
  35456. }
  35457. else {
  35458. this.refresh();
  35459. }
  35460. }
  35461. };
  35462. SVGPainter.prototype.getWidth = function () {
  35463. return this._width;
  35464. };
  35465. SVGPainter.prototype.getHeight = function () {
  35466. return this._height;
  35467. };
  35468. SVGPainter.prototype.dispose = function () {
  35469. if (this.root) {
  35470. this.root.innerHTML = '';
  35471. }
  35472. this._svgDom =
  35473. this._viewport =
  35474. this.storage =
  35475. this._oldVNode =
  35476. this._bgVNode =
  35477. this._mainVNode = null;
  35478. };
  35479. SVGPainter.prototype.clear = function () {
  35480. if (this._svgDom) {
  35481. this._svgDom.innerHTML = null;
  35482. }
  35483. this._oldVNode = null;
  35484. };
  35485. SVGPainter.prototype.toDataURL = function (base64) {
  35486. var str = this.renderToString();
  35487. var prefix = 'data:image/svg+xml;';
  35488. if (base64) {
  35489. str = encodeBase64(str);
  35490. return str && prefix + 'base64,' + str;
  35491. }
  35492. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  35493. };
  35494. return SVGPainter;
  35495. }());
  35496. function createMethodNotSupport(method) {
  35497. return function () {
  35498. if ("development" !== 'production') {
  35499. logError('In SVG mode painter not support method "' + method + '"');
  35500. }
  35501. };
  35502. }
  35503. function createBackgroundVNode(width, height, backgroundColor, scope) {
  35504. var bgVNode;
  35505. if (backgroundColor && backgroundColor !== 'none') {
  35506. bgVNode = createVNode('rect', 'bg', {
  35507. width: width,
  35508. height: height,
  35509. x: '0',
  35510. y: '0'
  35511. });
  35512. if (isGradient(backgroundColor)) {
  35513. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  35514. }
  35515. else if (isPattern(backgroundColor)) {
  35516. setPattern({
  35517. style: {
  35518. fill: backgroundColor
  35519. },
  35520. dirty: noop,
  35521. getBoundingRect: function () { return ({ width: width, height: height }); }
  35522. }, bgVNode.attrs, 'fill', scope);
  35523. }
  35524. else {
  35525. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35526. bgVNode.attrs.fill = color;
  35527. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  35528. }
  35529. }
  35530. return bgVNode;
  35531. }
  35532. function install(registers) {
  35533. registers.registerPainter('svg', SVGPainter);
  35534. }
  35535. function createDom(id, painter, dpr) {
  35536. var newDom = platformApi.createCanvas();
  35537. var width = painter.getWidth();
  35538. var height = painter.getHeight();
  35539. var newDomStyle = newDom.style;
  35540. if (newDomStyle) {
  35541. newDomStyle.position = 'absolute';
  35542. newDomStyle.left = '0';
  35543. newDomStyle.top = '0';
  35544. newDomStyle.width = width + 'px';
  35545. newDomStyle.height = height + 'px';
  35546. newDom.setAttribute('data-zr-dom-id', id);
  35547. }
  35548. newDom.width = width * dpr;
  35549. newDom.height = height * dpr;
  35550. return newDom;
  35551. }
  35552. var Layer = (function (_super) {
  35553. __extends(Layer, _super);
  35554. function Layer(id, painter, dpr) {
  35555. var _this = _super.call(this) || this;
  35556. _this.motionBlur = false;
  35557. _this.lastFrameAlpha = 0.7;
  35558. _this.dpr = 1;
  35559. _this.virtual = false;
  35560. _this.config = {};
  35561. _this.incremental = false;
  35562. _this.zlevel = 0;
  35563. _this.maxRepaintRectCount = 5;
  35564. _this.__dirty = true;
  35565. _this.__firstTimePaint = true;
  35566. _this.__used = false;
  35567. _this.__drawIndex = 0;
  35568. _this.__startIndex = 0;
  35569. _this.__endIndex = 0;
  35570. _this.__prevStartIndex = null;
  35571. _this.__prevEndIndex = null;
  35572. var dom;
  35573. dpr = dpr || devicePixelRatio;
  35574. if (typeof id === 'string') {
  35575. dom = createDom(id, painter, dpr);
  35576. }
  35577. else if (isObject(id)) {
  35578. dom = id;
  35579. id = dom.id;
  35580. }
  35581. _this.id = id;
  35582. _this.dom = dom;
  35583. var domStyle = dom.style;
  35584. if (domStyle) {
  35585. disableUserSelect(dom);
  35586. dom.onselectstart = function () { return false; };
  35587. domStyle.padding = '0';
  35588. domStyle.margin = '0';
  35589. domStyle.borderWidth = '0';
  35590. }
  35591. _this.painter = painter;
  35592. _this.dpr = dpr;
  35593. return _this;
  35594. }
  35595. Layer.prototype.getElementCount = function () {
  35596. return this.__endIndex - this.__startIndex;
  35597. };
  35598. Layer.prototype.afterBrush = function () {
  35599. this.__prevStartIndex = this.__startIndex;
  35600. this.__prevEndIndex = this.__endIndex;
  35601. };
  35602. Layer.prototype.initContext = function () {
  35603. this.ctx = this.dom.getContext('2d');
  35604. this.ctx.dpr = this.dpr;
  35605. };
  35606. Layer.prototype.setUnpainted = function () {
  35607. this.__firstTimePaint = true;
  35608. };
  35609. Layer.prototype.createBackBuffer = function () {
  35610. var dpr = this.dpr;
  35611. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  35612. this.ctxBack = this.domBack.getContext('2d');
  35613. if (dpr !== 1) {
  35614. this.ctxBack.scale(dpr, dpr);
  35615. }
  35616. };
  35617. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  35618. if (this.__firstTimePaint) {
  35619. this.__firstTimePaint = false;
  35620. return null;
  35621. }
  35622. var mergedRepaintRects = [];
  35623. var maxRepaintRectCount = this.maxRepaintRectCount;
  35624. var full = false;
  35625. var pendingRect = new BoundingRect(0, 0, 0, 0);
  35626. function addRectToMergePool(rect) {
  35627. if (!rect.isFinite() || rect.isZero()) {
  35628. return;
  35629. }
  35630. if (mergedRepaintRects.length === 0) {
  35631. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35632. boundingRect.copy(rect);
  35633. mergedRepaintRects.push(boundingRect);
  35634. }
  35635. else {
  35636. var isMerged = false;
  35637. var minDeltaArea = Infinity;
  35638. var bestRectToMergeIdx = 0;
  35639. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  35640. var mergedRect = mergedRepaintRects[i];
  35641. if (mergedRect.intersect(rect)) {
  35642. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  35643. pendingRect_1.copy(mergedRect);
  35644. pendingRect_1.union(rect);
  35645. mergedRepaintRects[i] = pendingRect_1;
  35646. isMerged = true;
  35647. break;
  35648. }
  35649. else if (full) {
  35650. pendingRect.copy(rect);
  35651. pendingRect.union(mergedRect);
  35652. var aArea = rect.width * rect.height;
  35653. var bArea = mergedRect.width * mergedRect.height;
  35654. var pendingArea = pendingRect.width * pendingRect.height;
  35655. var deltaArea = pendingArea - aArea - bArea;
  35656. if (deltaArea < minDeltaArea) {
  35657. minDeltaArea = deltaArea;
  35658. bestRectToMergeIdx = i;
  35659. }
  35660. }
  35661. }
  35662. if (full) {
  35663. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  35664. isMerged = true;
  35665. }
  35666. if (!isMerged) {
  35667. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35668. boundingRect.copy(rect);
  35669. mergedRepaintRects.push(boundingRect);
  35670. }
  35671. if (!full) {
  35672. full = mergedRepaintRects.length >= maxRepaintRectCount;
  35673. }
  35674. }
  35675. }
  35676. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  35677. var el = displayList[i];
  35678. if (el) {
  35679. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35680. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  35681. ? el.getPrevPaintRect()
  35682. : null;
  35683. if (prevRect) {
  35684. addRectToMergePool(prevRect);
  35685. }
  35686. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  35687. ? el.getPaintRect()
  35688. : null;
  35689. if (curRect) {
  35690. addRectToMergePool(curRect);
  35691. }
  35692. }
  35693. }
  35694. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  35695. var el = prevList[i];
  35696. var shouldPaint = el && el.shouldBePainted(viewWidth, viewHeight, true, true);
  35697. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  35698. var prevRect = el.getPrevPaintRect();
  35699. if (prevRect) {
  35700. addRectToMergePool(prevRect);
  35701. }
  35702. }
  35703. }
  35704. var hasIntersections;
  35705. do {
  35706. hasIntersections = false;
  35707. for (var i = 0; i < mergedRepaintRects.length;) {
  35708. if (mergedRepaintRects[i].isZero()) {
  35709. mergedRepaintRects.splice(i, 1);
  35710. continue;
  35711. }
  35712. for (var j = i + 1; j < mergedRepaintRects.length;) {
  35713. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  35714. hasIntersections = true;
  35715. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  35716. mergedRepaintRects.splice(j, 1);
  35717. }
  35718. else {
  35719. j++;
  35720. }
  35721. }
  35722. i++;
  35723. }
  35724. } while (hasIntersections);
  35725. this._paintRects = mergedRepaintRects;
  35726. return mergedRepaintRects;
  35727. };
  35728. Layer.prototype.debugGetPaintRects = function () {
  35729. return (this._paintRects || []).slice();
  35730. };
  35731. Layer.prototype.resize = function (width, height) {
  35732. var dpr = this.dpr;
  35733. var dom = this.dom;
  35734. var domStyle = dom.style;
  35735. var domBack = this.domBack;
  35736. if (domStyle) {
  35737. domStyle.width = width + 'px';
  35738. domStyle.height = height + 'px';
  35739. }
  35740. dom.width = width * dpr;
  35741. dom.height = height * dpr;
  35742. if (domBack) {
  35743. domBack.width = width * dpr;
  35744. domBack.height = height * dpr;
  35745. if (dpr !== 1) {
  35746. this.ctxBack.scale(dpr, dpr);
  35747. }
  35748. }
  35749. };
  35750. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  35751. var dom = this.dom;
  35752. var ctx = this.ctx;
  35753. var width = dom.width;
  35754. var height = dom.height;
  35755. clearColor = clearColor || this.clearColor;
  35756. var haveMotionBLur = this.motionBlur && !clearAll;
  35757. var lastFrameAlpha = this.lastFrameAlpha;
  35758. var dpr = this.dpr;
  35759. var self = this;
  35760. if (haveMotionBLur) {
  35761. if (!this.domBack) {
  35762. this.createBackBuffer();
  35763. }
  35764. this.ctxBack.globalCompositeOperation = 'copy';
  35765. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  35766. }
  35767. var domBack = this.domBack;
  35768. function doClear(x, y, width, height) {
  35769. ctx.clearRect(x, y, width, height);
  35770. if (clearColor && clearColor !== 'transparent') {
  35771. var clearColorGradientOrPattern = void 0;
  35772. if (isGradientObject(clearColor)) {
  35773. var shouldCache = clearColor.global || (clearColor.__width === width
  35774. && clearColor.__height === height);
  35775. clearColorGradientOrPattern = shouldCache
  35776. && clearColor.__canvasGradient
  35777. || getCanvasGradient(ctx, clearColor, {
  35778. x: 0,
  35779. y: 0,
  35780. width: width,
  35781. height: height
  35782. });
  35783. clearColor.__canvasGradient = clearColorGradientOrPattern;
  35784. clearColor.__width = width;
  35785. clearColor.__height = height;
  35786. }
  35787. else if (isImagePatternObject(clearColor)) {
  35788. clearColor.scaleX = clearColor.scaleX || dpr;
  35789. clearColor.scaleY = clearColor.scaleY || dpr;
  35790. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  35791. dirty: function () {
  35792. self.setUnpainted();
  35793. self.painter.refresh();
  35794. }
  35795. });
  35796. }
  35797. ctx.save();
  35798. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  35799. ctx.fillRect(x, y, width, height);
  35800. ctx.restore();
  35801. }
  35802. if (haveMotionBLur) {
  35803. ctx.save();
  35804. ctx.globalAlpha = lastFrameAlpha;
  35805. ctx.drawImage(domBack, x, y, width, height);
  35806. ctx.restore();
  35807. }
  35808. }
  35809. if (!repaintRects || haveMotionBLur) {
  35810. doClear(0, 0, width, height);
  35811. }
  35812. else if (repaintRects.length) {
  35813. each(repaintRects, function (rect) {
  35814. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35815. });
  35816. }
  35817. };
  35818. return Layer;
  35819. }(Eventful));
  35820. var HOVER_LAYER_ZLEVEL = 1e5;
  35821. var CANVAS_ZLEVEL = 314159;
  35822. var EL_AFTER_INCREMENTAL_INC = 0.01;
  35823. var INCREMENTAL_INC = 0.001;
  35824. function isLayerValid(layer) {
  35825. if (!layer) {
  35826. return false;
  35827. }
  35828. if (layer.__builtin__) {
  35829. return true;
  35830. }
  35831. if (typeof (layer.resize) !== 'function'
  35832. || typeof (layer.refresh) !== 'function') {
  35833. return false;
  35834. }
  35835. return true;
  35836. }
  35837. function createRoot(width, height) {
  35838. var domRoot = document.createElement('div');
  35839. domRoot.style.cssText = [
  35840. 'position:relative',
  35841. 'width:' + width + 'px',
  35842. 'height:' + height + 'px',
  35843. 'padding:0',
  35844. 'margin:0',
  35845. 'border-width:0'
  35846. ].join(';') + ';';
  35847. return domRoot;
  35848. }
  35849. var CanvasPainter = (function () {
  35850. function CanvasPainter(root, storage, opts, id) {
  35851. this.type = 'canvas';
  35852. this._zlevelList = [];
  35853. this._prevDisplayList = [];
  35854. this._layers = {};
  35855. this._layerConfig = {};
  35856. this._needsManuallyCompositing = false;
  35857. this.type = 'canvas';
  35858. var singleCanvas = !root.nodeName
  35859. || root.nodeName.toUpperCase() === 'CANVAS';
  35860. this._opts = opts = extend({}, opts || {});
  35861. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  35862. this._singleCanvas = singleCanvas;
  35863. this.root = root;
  35864. var rootStyle = root.style;
  35865. if (rootStyle) {
  35866. disableUserSelect(root);
  35867. root.innerHTML = '';
  35868. }
  35869. this.storage = storage;
  35870. var zlevelList = this._zlevelList;
  35871. this._prevDisplayList = [];
  35872. var layers = this._layers;
  35873. if (!singleCanvas) {
  35874. this._width = getSize(root, 0, opts);
  35875. this._height = getSize(root, 1, opts);
  35876. var domRoot = this._domRoot = createRoot(this._width, this._height);
  35877. root.appendChild(domRoot);
  35878. }
  35879. else {
  35880. var rootCanvas = root;
  35881. var width = rootCanvas.width;
  35882. var height = rootCanvas.height;
  35883. if (opts.width != null) {
  35884. width = opts.width;
  35885. }
  35886. if (opts.height != null) {
  35887. height = opts.height;
  35888. }
  35889. this.dpr = opts.devicePixelRatio || 1;
  35890. rootCanvas.width = width * this.dpr;
  35891. rootCanvas.height = height * this.dpr;
  35892. this._width = width;
  35893. this._height = height;
  35894. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  35895. mainLayer.__builtin__ = true;
  35896. mainLayer.initContext();
  35897. layers[CANVAS_ZLEVEL] = mainLayer;
  35898. mainLayer.zlevel = CANVAS_ZLEVEL;
  35899. zlevelList.push(CANVAS_ZLEVEL);
  35900. this._domRoot = root;
  35901. }
  35902. }
  35903. CanvasPainter.prototype.getType = function () {
  35904. return 'canvas';
  35905. };
  35906. CanvasPainter.prototype.isSingleCanvas = function () {
  35907. return this._singleCanvas;
  35908. };
  35909. CanvasPainter.prototype.getViewportRoot = function () {
  35910. return this._domRoot;
  35911. };
  35912. CanvasPainter.prototype.getViewportRootOffset = function () {
  35913. var viewportRoot = this.getViewportRoot();
  35914. if (viewportRoot) {
  35915. return {
  35916. offsetLeft: viewportRoot.offsetLeft || 0,
  35917. offsetTop: viewportRoot.offsetTop || 0
  35918. };
  35919. }
  35920. };
  35921. CanvasPainter.prototype.refresh = function (paintAll) {
  35922. var list = this.storage.getDisplayList(true);
  35923. var prevList = this._prevDisplayList;
  35924. var zlevelList = this._zlevelList;
  35925. this._redrawId = Math.random();
  35926. this._paintList(list, prevList, paintAll, this._redrawId);
  35927. for (var i = 0; i < zlevelList.length; i++) {
  35928. var z = zlevelList[i];
  35929. var layer = this._layers[z];
  35930. if (!layer.__builtin__ && layer.refresh) {
  35931. var clearColor = i === 0 ? this._backgroundColor : null;
  35932. layer.refresh(clearColor);
  35933. }
  35934. }
  35935. if (this._opts.useDirtyRect) {
  35936. this._prevDisplayList = list.slice();
  35937. }
  35938. return this;
  35939. };
  35940. CanvasPainter.prototype.refreshHover = function () {
  35941. this._paintHoverList(this.storage.getDisplayList(false));
  35942. };
  35943. CanvasPainter.prototype._paintHoverList = function (list) {
  35944. var len = list.length;
  35945. var hoverLayer = this._hoverlayer;
  35946. hoverLayer && hoverLayer.clear();
  35947. if (!len) {
  35948. return;
  35949. }
  35950. var scope = {
  35951. inHover: true,
  35952. viewWidth: this._width,
  35953. viewHeight: this._height
  35954. };
  35955. var ctx;
  35956. for (var i = 0; i < len; i++) {
  35957. var el = list[i];
  35958. if (el.__inHover) {
  35959. if (!hoverLayer) {
  35960. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  35961. }
  35962. if (!ctx) {
  35963. ctx = hoverLayer.ctx;
  35964. ctx.save();
  35965. }
  35966. brush(ctx, el, scope, i === len - 1);
  35967. }
  35968. }
  35969. if (ctx) {
  35970. ctx.restore();
  35971. }
  35972. };
  35973. CanvasPainter.prototype.getHoverLayer = function () {
  35974. return this.getLayer(HOVER_LAYER_ZLEVEL);
  35975. };
  35976. CanvasPainter.prototype.paintOne = function (ctx, el) {
  35977. brushSingle(ctx, el);
  35978. };
  35979. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  35980. if (this._redrawId !== redrawId) {
  35981. return;
  35982. }
  35983. paintAll = paintAll || false;
  35984. this._updateLayerStatus(list);
  35985. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  35986. if (this._needsManuallyCompositing) {
  35987. this._compositeManually();
  35988. }
  35989. if (needsRefreshHover) {
  35990. this._paintHoverList(list);
  35991. }
  35992. if (!finished) {
  35993. var self_1 = this;
  35994. requestAnimationFrame$1(function () {
  35995. self_1._paintList(list, prevList, paintAll, redrawId);
  35996. });
  35997. }
  35998. else {
  35999. this.eachLayer(function (layer) {
  36000. layer.afterBrush && layer.afterBrush();
  36001. });
  36002. }
  36003. };
  36004. CanvasPainter.prototype._compositeManually = function () {
  36005. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  36006. var width = this._domRoot.width;
  36007. var height = this._domRoot.height;
  36008. ctx.clearRect(0, 0, width, height);
  36009. this.eachBuiltinLayer(function (layer) {
  36010. if (layer.virtual) {
  36011. ctx.drawImage(layer.dom, 0, 0, width, height);
  36012. }
  36013. });
  36014. };
  36015. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  36016. var _this = this;
  36017. var layerList = [];
  36018. var useDirtyRect = this._opts.useDirtyRect;
  36019. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  36020. var zlevel = this._zlevelList[zi];
  36021. var layer = this._layers[zlevel];
  36022. if (layer.__builtin__
  36023. && layer !== this._hoverlayer
  36024. && (layer.__dirty || paintAll)) {
  36025. layerList.push(layer);
  36026. }
  36027. }
  36028. var finished = true;
  36029. var needsRefreshHover = false;
  36030. var _loop_1 = function (k) {
  36031. var layer = layerList[k];
  36032. var ctx = layer.ctx;
  36033. var repaintRects = useDirtyRect
  36034. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  36035. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  36036. var useTimer = !paintAll && layer.incremental && Date.now;
  36037. var startTime = useTimer && Date.now();
  36038. var clearColor = layer.zlevel === this_1._zlevelList[0]
  36039. ? this_1._backgroundColor : null;
  36040. if (layer.__startIndex === layer.__endIndex) {
  36041. layer.clear(false, clearColor, repaintRects);
  36042. }
  36043. else if (start === layer.__startIndex) {
  36044. var firstEl = list[start];
  36045. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  36046. layer.clear(false, clearColor, repaintRects);
  36047. }
  36048. }
  36049. if (start === -1) {
  36050. console.error('For some unknown reason. drawIndex is -1');
  36051. start = layer.__startIndex;
  36052. }
  36053. var i;
  36054. var repaint = function (repaintRect) {
  36055. var scope = {
  36056. inHover: false,
  36057. allClipped: false,
  36058. prevEl: null,
  36059. viewWidth: _this._width,
  36060. viewHeight: _this._height
  36061. };
  36062. for (i = start; i < layer.__endIndex; i++) {
  36063. var el = list[i];
  36064. if (el.__inHover) {
  36065. needsRefreshHover = true;
  36066. }
  36067. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  36068. if (useTimer) {
  36069. var dTime = Date.now() - startTime;
  36070. if (dTime > 15) {
  36071. break;
  36072. }
  36073. }
  36074. }
  36075. if (scope.prevElClipPaths) {
  36076. ctx.restore();
  36077. }
  36078. };
  36079. if (repaintRects) {
  36080. if (repaintRects.length === 0) {
  36081. i = layer.__endIndex;
  36082. }
  36083. else {
  36084. var dpr = this_1.dpr;
  36085. for (var r = 0; r < repaintRects.length; ++r) {
  36086. var rect = repaintRects[r];
  36087. ctx.save();
  36088. ctx.beginPath();
  36089. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36090. ctx.clip();
  36091. repaint(rect);
  36092. ctx.restore();
  36093. }
  36094. }
  36095. }
  36096. else {
  36097. ctx.save();
  36098. repaint();
  36099. ctx.restore();
  36100. }
  36101. layer.__drawIndex = i;
  36102. if (layer.__drawIndex < layer.__endIndex) {
  36103. finished = false;
  36104. }
  36105. };
  36106. var this_1 = this;
  36107. for (var k = 0; k < layerList.length; k++) {
  36108. _loop_1(k);
  36109. }
  36110. if (env.wxa) {
  36111. each(this._layers, function (layer) {
  36112. if (layer && layer.ctx && layer.ctx.draw) {
  36113. layer.ctx.draw();
  36114. }
  36115. });
  36116. }
  36117. return {
  36118. finished: finished,
  36119. needsRefreshHover: needsRefreshHover
  36120. };
  36121. };
  36122. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36123. var ctx = currentLayer.ctx;
  36124. if (useDirtyRect) {
  36125. var paintRect = el.getPaintRect();
  36126. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36127. brush(ctx, el, scope, isLast);
  36128. el.setPrevPaintRect(paintRect);
  36129. }
  36130. }
  36131. else {
  36132. brush(ctx, el, scope, isLast);
  36133. }
  36134. };
  36135. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36136. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36137. zlevel = CANVAS_ZLEVEL;
  36138. }
  36139. var layer = this._layers[zlevel];
  36140. if (!layer) {
  36141. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36142. layer.zlevel = zlevel;
  36143. layer.__builtin__ = true;
  36144. if (this._layerConfig[zlevel]) {
  36145. merge(layer, this._layerConfig[zlevel], true);
  36146. }
  36147. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36148. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36149. }
  36150. if (virtual) {
  36151. layer.virtual = virtual;
  36152. }
  36153. this.insertLayer(zlevel, layer);
  36154. layer.initContext();
  36155. }
  36156. return layer;
  36157. };
  36158. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36159. var layersMap = this._layers;
  36160. var zlevelList = this._zlevelList;
  36161. var len = zlevelList.length;
  36162. var domRoot = this._domRoot;
  36163. var prevLayer = null;
  36164. var i = -1;
  36165. if (layersMap[zlevel]) {
  36166. if ("development" !== 'production') {
  36167. logError('ZLevel ' + zlevel + ' has been used already');
  36168. }
  36169. return;
  36170. }
  36171. if (!isLayerValid(layer)) {
  36172. if ("development" !== 'production') {
  36173. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36174. }
  36175. return;
  36176. }
  36177. if (len > 0 && zlevel > zlevelList[0]) {
  36178. for (i = 0; i < len - 1; i++) {
  36179. if (zlevelList[i] < zlevel
  36180. && zlevelList[i + 1] > zlevel) {
  36181. break;
  36182. }
  36183. }
  36184. prevLayer = layersMap[zlevelList[i]];
  36185. }
  36186. zlevelList.splice(i + 1, 0, zlevel);
  36187. layersMap[zlevel] = layer;
  36188. if (!layer.virtual) {
  36189. if (prevLayer) {
  36190. var prevDom = prevLayer.dom;
  36191. if (prevDom.nextSibling) {
  36192. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36193. }
  36194. else {
  36195. domRoot.appendChild(layer.dom);
  36196. }
  36197. }
  36198. else {
  36199. if (domRoot.firstChild) {
  36200. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36201. }
  36202. else {
  36203. domRoot.appendChild(layer.dom);
  36204. }
  36205. }
  36206. }
  36207. layer.painter || (layer.painter = this);
  36208. };
  36209. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36210. var zlevelList = this._zlevelList;
  36211. for (var i = 0; i < zlevelList.length; i++) {
  36212. var z = zlevelList[i];
  36213. cb.call(context, this._layers[z], z);
  36214. }
  36215. };
  36216. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36217. var zlevelList = this._zlevelList;
  36218. for (var i = 0; i < zlevelList.length; i++) {
  36219. var z = zlevelList[i];
  36220. var layer = this._layers[z];
  36221. if (layer.__builtin__) {
  36222. cb.call(context, layer, z);
  36223. }
  36224. }
  36225. };
  36226. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36227. var zlevelList = this._zlevelList;
  36228. for (var i = 0; i < zlevelList.length; i++) {
  36229. var z = zlevelList[i];
  36230. var layer = this._layers[z];
  36231. if (!layer.__builtin__) {
  36232. cb.call(context, layer, z);
  36233. }
  36234. }
  36235. };
  36236. CanvasPainter.prototype.getLayers = function () {
  36237. return this._layers;
  36238. };
  36239. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36240. this.eachBuiltinLayer(function (layer, z) {
  36241. layer.__dirty = layer.__used = false;
  36242. });
  36243. function updatePrevLayer(idx) {
  36244. if (prevLayer) {
  36245. if (prevLayer.__endIndex !== idx) {
  36246. prevLayer.__dirty = true;
  36247. }
  36248. prevLayer.__endIndex = idx;
  36249. }
  36250. }
  36251. if (this._singleCanvas) {
  36252. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36253. var el = list[i_1];
  36254. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36255. this._needsManuallyCompositing = true;
  36256. break;
  36257. }
  36258. }
  36259. }
  36260. var prevLayer = null;
  36261. var incrementalLayerCount = 0;
  36262. var prevZlevel;
  36263. var i;
  36264. for (i = 0; i < list.length; i++) {
  36265. var el = list[i];
  36266. var zlevel = el.zlevel;
  36267. var layer = void 0;
  36268. if (prevZlevel !== zlevel) {
  36269. prevZlevel = zlevel;
  36270. incrementalLayerCount = 0;
  36271. }
  36272. if (el.incremental) {
  36273. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36274. layer.incremental = true;
  36275. incrementalLayerCount = 1;
  36276. }
  36277. else {
  36278. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36279. }
  36280. if (!layer.__builtin__) {
  36281. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36282. }
  36283. if (layer !== prevLayer) {
  36284. layer.__used = true;
  36285. if (layer.__startIndex !== i) {
  36286. layer.__dirty = true;
  36287. }
  36288. layer.__startIndex = i;
  36289. if (!layer.incremental) {
  36290. layer.__drawIndex = i;
  36291. }
  36292. else {
  36293. layer.__drawIndex = -1;
  36294. }
  36295. updatePrevLayer(i);
  36296. prevLayer = layer;
  36297. }
  36298. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  36299. layer.__dirty = true;
  36300. if (layer.incremental && layer.__drawIndex < 0) {
  36301. layer.__drawIndex = i;
  36302. }
  36303. }
  36304. }
  36305. updatePrevLayer(i);
  36306. this.eachBuiltinLayer(function (layer, z) {
  36307. if (!layer.__used && layer.getElementCount() > 0) {
  36308. layer.__dirty = true;
  36309. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36310. }
  36311. if (layer.__dirty && layer.__drawIndex < 0) {
  36312. layer.__drawIndex = layer.__startIndex;
  36313. }
  36314. });
  36315. };
  36316. CanvasPainter.prototype.clear = function () {
  36317. this.eachBuiltinLayer(this._clearLayer);
  36318. return this;
  36319. };
  36320. CanvasPainter.prototype._clearLayer = function (layer) {
  36321. layer.clear();
  36322. };
  36323. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36324. this._backgroundColor = backgroundColor;
  36325. each(this._layers, function (layer) {
  36326. layer.setUnpainted();
  36327. });
  36328. };
  36329. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36330. if (config) {
  36331. var layerConfig = this._layerConfig;
  36332. if (!layerConfig[zlevel]) {
  36333. layerConfig[zlevel] = config;
  36334. }
  36335. else {
  36336. merge(layerConfig[zlevel], config, true);
  36337. }
  36338. for (var i = 0; i < this._zlevelList.length; i++) {
  36339. var _zlevel = this._zlevelList[i];
  36340. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36341. var layer = this._layers[_zlevel];
  36342. merge(layer, layerConfig[zlevel], true);
  36343. }
  36344. }
  36345. }
  36346. };
  36347. CanvasPainter.prototype.delLayer = function (zlevel) {
  36348. var layers = this._layers;
  36349. var zlevelList = this._zlevelList;
  36350. var layer = layers[zlevel];
  36351. if (!layer) {
  36352. return;
  36353. }
  36354. layer.dom.parentNode.removeChild(layer.dom);
  36355. delete layers[zlevel];
  36356. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36357. };
  36358. CanvasPainter.prototype.resize = function (width, height) {
  36359. if (!this._domRoot.style) {
  36360. if (width == null || height == null) {
  36361. return;
  36362. }
  36363. this._width = width;
  36364. this._height = height;
  36365. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36366. }
  36367. else {
  36368. var domRoot = this._domRoot;
  36369. domRoot.style.display = 'none';
  36370. var opts = this._opts;
  36371. var root = this.root;
  36372. width != null && (opts.width = width);
  36373. height != null && (opts.height = height);
  36374. width = getSize(root, 0, opts);
  36375. height = getSize(root, 1, opts);
  36376. domRoot.style.display = '';
  36377. if (this._width !== width || height !== this._height) {
  36378. domRoot.style.width = width + 'px';
  36379. domRoot.style.height = height + 'px';
  36380. for (var id in this._layers) {
  36381. if (this._layers.hasOwnProperty(id)) {
  36382. this._layers[id].resize(width, height);
  36383. }
  36384. }
  36385. this.refresh(true);
  36386. }
  36387. this._width = width;
  36388. this._height = height;
  36389. }
  36390. return this;
  36391. };
  36392. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36393. var layer = this._layers[zlevel];
  36394. if (layer) {
  36395. layer.clear();
  36396. }
  36397. };
  36398. CanvasPainter.prototype.dispose = function () {
  36399. this.root.innerHTML = '';
  36400. this.root =
  36401. this.storage =
  36402. this._domRoot =
  36403. this._layers = null;
  36404. };
  36405. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36406. opts = opts || {};
  36407. if (this._singleCanvas && !this._compositeManually) {
  36408. return this._layers[CANVAS_ZLEVEL].dom;
  36409. }
  36410. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36411. imageLayer.initContext();
  36412. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36413. var ctx = imageLayer.ctx;
  36414. if (opts.pixelRatio <= this.dpr) {
  36415. this.refresh();
  36416. var width_1 = imageLayer.dom.width;
  36417. var height_1 = imageLayer.dom.height;
  36418. this.eachLayer(function (layer) {
  36419. if (layer.__builtin__) {
  36420. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36421. }
  36422. else if (layer.renderToCanvas) {
  36423. ctx.save();
  36424. layer.renderToCanvas(ctx);
  36425. ctx.restore();
  36426. }
  36427. });
  36428. }
  36429. else {
  36430. var scope = {
  36431. inHover: false,
  36432. viewWidth: this._width,
  36433. viewHeight: this._height
  36434. };
  36435. var displayList = this.storage.getDisplayList(true);
  36436. for (var i = 0, len = displayList.length; i < len; i++) {
  36437. var el = displayList[i];
  36438. brush(ctx, el, scope, i === len - 1);
  36439. }
  36440. }
  36441. return imageLayer.dom;
  36442. };
  36443. CanvasPainter.prototype.getWidth = function () {
  36444. return this._width;
  36445. };
  36446. CanvasPainter.prototype.getHeight = function () {
  36447. return this._height;
  36448. };
  36449. return CanvasPainter;
  36450. }());
  36451. function install$1(registers) {
  36452. registers.registerPainter('canvas', CanvasPainter);
  36453. }
  36454. var LineSeriesModel = /** @class */function (_super) {
  36455. __extends(LineSeriesModel, _super);
  36456. function LineSeriesModel() {
  36457. var _this = _super !== null && _super.apply(this, arguments) || this;
  36458. _this.type = LineSeriesModel.type;
  36459. _this.hasSymbolVisual = true;
  36460. return _this;
  36461. }
  36462. LineSeriesModel.prototype.getInitialData = function (option) {
  36463. if ("development" !== 'production') {
  36464. var coordSys = option.coordinateSystem;
  36465. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  36466. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  36467. }
  36468. }
  36469. return createSeriesData(null, this, {
  36470. useEncodeDefaulter: true
  36471. });
  36472. };
  36473. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  36474. var group = new Group();
  36475. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  36476. group.add(line);
  36477. line.setStyle(opt.lineStyle);
  36478. var visualType = this.getData().getVisual('symbol');
  36479. var visualRotate = this.getData().getVisual('symbolRotate');
  36480. var symbolType = visualType === 'none' ? 'circle' : visualType;
  36481. // Symbol size is 80% when there is a line
  36482. var size = opt.itemHeight * 0.8;
  36483. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  36484. group.add(symbol);
  36485. symbol.setStyle(opt.itemStyle);
  36486. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  36487. symbol.rotation = symbolRotate * Math.PI / 180;
  36488. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  36489. if (symbolType.indexOf('empty') > -1) {
  36490. symbol.style.stroke = symbol.style.fill;
  36491. symbol.style.fill = '#fff';
  36492. symbol.style.lineWidth = 2;
  36493. }
  36494. return group;
  36495. };
  36496. LineSeriesModel.type = 'series.line';
  36497. LineSeriesModel.dependencies = ['grid', 'polar'];
  36498. LineSeriesModel.defaultOption = {
  36499. // zlevel: 0,
  36500. z: 3,
  36501. coordinateSystem: 'cartesian2d',
  36502. legendHoverLink: true,
  36503. clip: true,
  36504. label: {
  36505. position: 'top'
  36506. },
  36507. // itemStyle: {
  36508. // },
  36509. endLabel: {
  36510. show: false,
  36511. valueAnimation: true,
  36512. distance: 8
  36513. },
  36514. lineStyle: {
  36515. width: 2,
  36516. type: 'solid'
  36517. },
  36518. emphasis: {
  36519. scale: true
  36520. },
  36521. // areaStyle: {
  36522. // origin of areaStyle. Valid values:
  36523. // `'auto'/null/undefined`: from axisLine to data
  36524. // `'start'`: from min to data
  36525. // `'end'`: from data to max
  36526. // origin: 'auto'
  36527. // },
  36528. // false, 'start', 'end', 'middle'
  36529. step: false,
  36530. // Disabled if step is true
  36531. smooth: false,
  36532. smoothMonotone: null,
  36533. symbol: 'emptyCircle',
  36534. symbolSize: 4,
  36535. symbolRotate: null,
  36536. showSymbol: true,
  36537. // `false`: follow the label interval strategy.
  36538. // `true`: show all symbols.
  36539. // `'auto'`: If possible, show all symbols, otherwise
  36540. // follow the label interval strategy.
  36541. showAllSymbol: 'auto',
  36542. // Whether to connect break point.
  36543. connectNulls: false,
  36544. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  36545. sampling: 'none',
  36546. animationEasing: 'linear',
  36547. // Disable progressive
  36548. progressive: 0,
  36549. hoverLayerThreshold: Infinity,
  36550. universalTransition: {
  36551. divideShape: 'clone'
  36552. },
  36553. triggerLineEvent: false
  36554. };
  36555. return LineSeriesModel;
  36556. }(SeriesModel);
  36557. /**
  36558. * @return label string. Not null/undefined
  36559. */
  36560. function getDefaultLabel(data, dataIndex) {
  36561. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36562. var len = labelDims.length;
  36563. // Simple optimization (in lots of cases, label dims length is 1)
  36564. if (len === 1) {
  36565. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  36566. return rawVal != null ? rawVal + '' : null;
  36567. } else if (len) {
  36568. var vals = [];
  36569. for (var i = 0; i < labelDims.length; i++) {
  36570. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  36571. }
  36572. return vals.join(' ');
  36573. }
  36574. }
  36575. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  36576. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36577. if (!isArray(interpolatedValue)) {
  36578. return interpolatedValue + '';
  36579. }
  36580. var vals = [];
  36581. for (var i = 0; i < labelDims.length; i++) {
  36582. var dimIndex = data.getDimensionIndex(labelDims[i]);
  36583. if (dimIndex >= 0) {
  36584. vals.push(interpolatedValue[dimIndex]);
  36585. }
  36586. }
  36587. return vals.join(' ');
  36588. }
  36589. var Symbol = /** @class */function (_super) {
  36590. __extends(Symbol, _super);
  36591. function Symbol(data, idx, seriesScope, opts) {
  36592. var _this = _super.call(this) || this;
  36593. _this.updateData(data, idx, seriesScope, opts);
  36594. return _this;
  36595. }
  36596. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  36597. // Remove paths created before
  36598. this.removeAll();
  36599. // let symbolPath = createSymbol(
  36600. // symbolType, -0.5, -0.5, 1, 1, color
  36601. // );
  36602. // If width/height are set too small (e.g., set to 1) on ios10
  36603. // and macOS Sierra, a circle stroke become a rect, no matter what
  36604. // the scale is set. So we set width/height as 2. See #4150.
  36605. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  36606. symbolPath.attr({
  36607. z2: 100,
  36608. culling: true,
  36609. scaleX: symbolSize[0] / 2,
  36610. scaleY: symbolSize[1] / 2
  36611. });
  36612. // Rewrite drift method
  36613. symbolPath.drift = driftSymbol;
  36614. this._symbolType = symbolType;
  36615. this.add(symbolPath);
  36616. };
  36617. /**
  36618. * Stop animation
  36619. * @param {boolean} toLastFrame
  36620. */
  36621. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  36622. this.childAt(0).stopAnimation(null, toLastFrame);
  36623. };
  36624. Symbol.prototype.getSymbolType = function () {
  36625. return this._symbolType;
  36626. };
  36627. /**
  36628. * FIXME:
  36629. * Caution: This method breaks the encapsulation of this module,
  36630. * but it indeed brings convenience. So do not use the method
  36631. * unless you detailedly know all the implements of `Symbol`,
  36632. * especially animation.
  36633. *
  36634. * Get symbol path element.
  36635. */
  36636. Symbol.prototype.getSymbolPath = function () {
  36637. return this.childAt(0);
  36638. };
  36639. /**
  36640. * Highlight symbol
  36641. */
  36642. Symbol.prototype.highlight = function () {
  36643. enterEmphasis(this.childAt(0));
  36644. };
  36645. /**
  36646. * Downplay symbol
  36647. */
  36648. Symbol.prototype.downplay = function () {
  36649. leaveEmphasis(this.childAt(0));
  36650. };
  36651. /**
  36652. * @param {number} zlevel
  36653. * @param {number} z
  36654. */
  36655. Symbol.prototype.setZ = function (zlevel, z) {
  36656. var symbolPath = this.childAt(0);
  36657. symbolPath.zlevel = zlevel;
  36658. symbolPath.z = z;
  36659. };
  36660. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  36661. var symbolPath = this.childAt(0);
  36662. symbolPath.draggable = draggable;
  36663. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  36664. };
  36665. /**
  36666. * Update symbol properties
  36667. */
  36668. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  36669. this.silent = false;
  36670. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36671. var seriesModel = data.hostModel;
  36672. var symbolSize = Symbol.getSymbolSize(data, idx);
  36673. var isInit = symbolType !== this._symbolType;
  36674. var disableAnimation = opts && opts.disableAnimation;
  36675. if (isInit) {
  36676. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  36677. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  36678. } else {
  36679. var symbolPath = this.childAt(0);
  36680. symbolPath.silent = false;
  36681. var target = {
  36682. scaleX: symbolSize[0] / 2,
  36683. scaleY: symbolSize[1] / 2
  36684. };
  36685. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  36686. saveOldStyle(symbolPath);
  36687. }
  36688. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  36689. if (isInit) {
  36690. var symbolPath = this.childAt(0);
  36691. if (!disableAnimation) {
  36692. var target = {
  36693. scaleX: this._sizeX,
  36694. scaleY: this._sizeY,
  36695. style: {
  36696. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  36697. opacity: symbolPath.style.opacity
  36698. }
  36699. };
  36700. symbolPath.scaleX = symbolPath.scaleY = 0;
  36701. symbolPath.style.opacity = 0;
  36702. initProps(symbolPath, target, seriesModel, idx);
  36703. }
  36704. }
  36705. if (disableAnimation) {
  36706. // Must stop leave transition manually if don't call initProps or updateProps.
  36707. this.childAt(0).stopAnimation('leave');
  36708. }
  36709. };
  36710. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  36711. var symbolPath = this.childAt(0);
  36712. var seriesModel = data.hostModel;
  36713. var emphasisItemStyle;
  36714. var blurItemStyle;
  36715. var selectItemStyle;
  36716. var focus;
  36717. var blurScope;
  36718. var emphasisDisabled;
  36719. var labelStatesModels;
  36720. var hoverScale;
  36721. var cursorStyle;
  36722. if (seriesScope) {
  36723. emphasisItemStyle = seriesScope.emphasisItemStyle;
  36724. blurItemStyle = seriesScope.blurItemStyle;
  36725. selectItemStyle = seriesScope.selectItemStyle;
  36726. focus = seriesScope.focus;
  36727. blurScope = seriesScope.blurScope;
  36728. labelStatesModels = seriesScope.labelStatesModels;
  36729. hoverScale = seriesScope.hoverScale;
  36730. cursorStyle = seriesScope.cursorStyle;
  36731. emphasisDisabled = seriesScope.emphasisDisabled;
  36732. }
  36733. if (!seriesScope || data.hasItemOption) {
  36734. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  36735. var emphasisModel = itemModel.getModel('emphasis');
  36736. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  36737. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  36738. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  36739. focus = emphasisModel.get('focus');
  36740. blurScope = emphasisModel.get('blurScope');
  36741. emphasisDisabled = emphasisModel.get('disabled');
  36742. labelStatesModels = getLabelStatesModels(itemModel);
  36743. hoverScale = emphasisModel.getShallow('scale');
  36744. cursorStyle = itemModel.getShallow('cursor');
  36745. }
  36746. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  36747. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  36748. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  36749. if (symbolOffset) {
  36750. symbolPath.x = symbolOffset[0];
  36751. symbolPath.y = symbolOffset[1];
  36752. }
  36753. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  36754. var symbolStyle = data.getItemVisual(idx, 'style');
  36755. var visualColor = symbolStyle.fill;
  36756. if (symbolPath instanceof ZRImage) {
  36757. var pathStyle = symbolPath.style;
  36758. symbolPath.useStyle(extend({
  36759. // TODO other properties like x, y ?
  36760. image: pathStyle.image,
  36761. x: pathStyle.x,
  36762. y: pathStyle.y,
  36763. width: pathStyle.width,
  36764. height: pathStyle.height
  36765. }, symbolStyle));
  36766. } else {
  36767. if (symbolPath.__isEmptyBrush) {
  36768. // fill and stroke will be swapped if it's empty.
  36769. // So we cloned a new style to avoid it affecting the original style in visual storage.
  36770. // TODO Better implementation. No empty logic!
  36771. symbolPath.useStyle(extend({}, symbolStyle));
  36772. } else {
  36773. symbolPath.useStyle(symbolStyle);
  36774. }
  36775. // Disable decal because symbol scale will been applied on the decal.
  36776. symbolPath.style.decal = null;
  36777. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  36778. symbolPath.style.strokeNoScale = true;
  36779. }
  36780. var liftZ = data.getItemVisual(idx, 'liftZ');
  36781. var z2Origin = this._z2;
  36782. if (liftZ != null) {
  36783. if (z2Origin == null) {
  36784. this._z2 = symbolPath.z2;
  36785. symbolPath.z2 += liftZ;
  36786. }
  36787. } else if (z2Origin != null) {
  36788. symbolPath.z2 = z2Origin;
  36789. this._z2 = null;
  36790. }
  36791. var useNameLabel = opts && opts.useNameLabel;
  36792. setLabelStyle(symbolPath, labelStatesModels, {
  36793. labelFetcher: seriesModel,
  36794. labelDataIndex: idx,
  36795. defaultText: getLabelDefaultText,
  36796. inheritColor: visualColor,
  36797. defaultOpacity: symbolStyle.opacity
  36798. });
  36799. // Do not execute util needed.
  36800. function getLabelDefaultText(idx) {
  36801. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  36802. }
  36803. this._sizeX = symbolSize[0] / 2;
  36804. this._sizeY = symbolSize[1] / 2;
  36805. var emphasisState = symbolPath.ensureState('emphasis');
  36806. emphasisState.style = emphasisItemStyle;
  36807. symbolPath.ensureState('select').style = selectItemStyle;
  36808. symbolPath.ensureState('blur').style = blurItemStyle;
  36809. // null / undefined / true means to use default strategy.
  36810. // 0 / false / negative number / NaN / Infinity means no scale.
  36811. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY)
  36812. // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  36813. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1;
  36814. // always set scale to allow resetting
  36815. emphasisState.scaleX = this._sizeX * scaleRatio;
  36816. emphasisState.scaleY = this._sizeY * scaleRatio;
  36817. this.setSymbolScale(1);
  36818. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  36819. };
  36820. Symbol.prototype.setSymbolScale = function (scale) {
  36821. this.scaleX = this.scaleY = scale;
  36822. };
  36823. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  36824. var symbolPath = this.childAt(0);
  36825. var dataIndex = getECData(this).dataIndex;
  36826. var animationOpt = opt && opt.animation;
  36827. // Avoid mistaken hover when fading out
  36828. this.silent = symbolPath.silent = true;
  36829. // Not show text when animating
  36830. if (opt && opt.fadeLabel) {
  36831. var textContent = symbolPath.getTextContent();
  36832. if (textContent) {
  36833. removeElement(textContent, {
  36834. style: {
  36835. opacity: 0
  36836. }
  36837. }, seriesModel, {
  36838. dataIndex: dataIndex,
  36839. removeOpt: animationOpt,
  36840. cb: function () {
  36841. symbolPath.removeTextContent();
  36842. }
  36843. });
  36844. }
  36845. } else {
  36846. symbolPath.removeTextContent();
  36847. }
  36848. removeElement(symbolPath, {
  36849. style: {
  36850. opacity: 0
  36851. },
  36852. scaleX: 0,
  36853. scaleY: 0
  36854. }, seriesModel, {
  36855. dataIndex: dataIndex,
  36856. cb: cb,
  36857. removeOpt: animationOpt
  36858. });
  36859. };
  36860. Symbol.getSymbolSize = function (data, idx) {
  36861. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  36862. };
  36863. return Symbol;
  36864. }(Group);
  36865. function driftSymbol(dx, dy) {
  36866. this.parent.drift(dx, dy);
  36867. }
  36868. function symbolNeedsDraw(data, point, idx, opt) {
  36869. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx))
  36870. // We do not set clipShape on group, because it will cut part of
  36871. // the symbol element shape. We use the same clip shape here as
  36872. // the line clip.
  36873. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  36874. }
  36875. function normalizeUpdateOpt(opt) {
  36876. if (opt != null && !isObject(opt)) {
  36877. opt = {
  36878. isIgnore: opt
  36879. };
  36880. }
  36881. return opt || {};
  36882. }
  36883. function makeSeriesScope(data) {
  36884. var seriesModel = data.hostModel;
  36885. var emphasisModel = seriesModel.getModel('emphasis');
  36886. return {
  36887. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  36888. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  36889. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  36890. focus: emphasisModel.get('focus'),
  36891. blurScope: emphasisModel.get('blurScope'),
  36892. emphasisDisabled: emphasisModel.get('disabled'),
  36893. hoverScale: emphasisModel.get('scale'),
  36894. labelStatesModels: getLabelStatesModels(seriesModel),
  36895. cursorStyle: seriesModel.get('cursor')
  36896. };
  36897. }
  36898. var SymbolDraw = /** @class */function () {
  36899. function SymbolDraw(SymbolCtor) {
  36900. this.group = new Group();
  36901. this._SymbolCtor = SymbolCtor || Symbol;
  36902. }
  36903. /**
  36904. * Update symbols draw by new data
  36905. */
  36906. SymbolDraw.prototype.updateData = function (data, opt) {
  36907. // Remove progressive els.
  36908. this._progressiveEls = null;
  36909. opt = normalizeUpdateOpt(opt);
  36910. var group = this.group;
  36911. var seriesModel = data.hostModel;
  36912. var oldData = this._data;
  36913. var SymbolCtor = this._SymbolCtor;
  36914. var disableAnimation = opt.disableAnimation;
  36915. var seriesScope = makeSeriesScope(data);
  36916. var symbolUpdateOpt = {
  36917. disableAnimation: disableAnimation
  36918. };
  36919. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  36920. return data.getItemLayout(idx);
  36921. };
  36922. // There is no oldLineData only when first rendering or switching from
  36923. // stream mode to normal mode, where previous elements should be removed.
  36924. if (!oldData) {
  36925. group.removeAll();
  36926. }
  36927. data.diff(oldData).add(function (newIdx) {
  36928. var point = getSymbolPoint(newIdx);
  36929. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  36930. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36931. symbolEl.setPosition(point);
  36932. data.setItemGraphicEl(newIdx, symbolEl);
  36933. group.add(symbolEl);
  36934. }
  36935. }).update(function (newIdx, oldIdx) {
  36936. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36937. var point = getSymbolPoint(newIdx);
  36938. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  36939. group.remove(symbolEl);
  36940. return;
  36941. }
  36942. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  36943. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  36944. if (!symbolEl
  36945. // Create a new if symbol type changed.
  36946. || oldSymbolType && oldSymbolType !== newSymbolType) {
  36947. group.remove(symbolEl);
  36948. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36949. symbolEl.setPosition(point);
  36950. } else {
  36951. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  36952. var target = {
  36953. x: point[0],
  36954. y: point[1]
  36955. };
  36956. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  36957. }
  36958. // Add back
  36959. group.add(symbolEl);
  36960. data.setItemGraphicEl(newIdx, symbolEl);
  36961. }).remove(function (oldIdx) {
  36962. var el = oldData.getItemGraphicEl(oldIdx);
  36963. el && el.fadeOut(function () {
  36964. group.remove(el);
  36965. }, seriesModel);
  36966. }).execute();
  36967. this._getSymbolPoint = getSymbolPoint;
  36968. this._data = data;
  36969. };
  36970. SymbolDraw.prototype.updateLayout = function () {
  36971. var _this = this;
  36972. var data = this._data;
  36973. if (data) {
  36974. // Not use animation
  36975. data.eachItemGraphicEl(function (el, idx) {
  36976. var point = _this._getSymbolPoint(idx);
  36977. el.setPosition(point);
  36978. el.markRedraw();
  36979. });
  36980. }
  36981. };
  36982. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  36983. this._seriesScope = makeSeriesScope(data);
  36984. this._data = null;
  36985. this.group.removeAll();
  36986. };
  36987. /**
  36988. * Update symbols draw by new data
  36989. */
  36990. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  36991. // Clear
  36992. this._progressiveEls = [];
  36993. opt = normalizeUpdateOpt(opt);
  36994. function updateIncrementalAndHover(el) {
  36995. if (!el.isGroup) {
  36996. el.incremental = true;
  36997. el.ensureState('emphasis').hoverLayer = true;
  36998. }
  36999. }
  37000. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  37001. var point = data.getItemLayout(idx);
  37002. if (symbolNeedsDraw(data, point, idx, opt)) {
  37003. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  37004. el.traverse(updateIncrementalAndHover);
  37005. el.setPosition(point);
  37006. this.group.add(el);
  37007. data.setItemGraphicEl(idx, el);
  37008. this._progressiveEls.push(el);
  37009. }
  37010. }
  37011. };
  37012. SymbolDraw.prototype.eachRendered = function (cb) {
  37013. traverseElements(this._progressiveEls || this.group, cb);
  37014. };
  37015. SymbolDraw.prototype.remove = function (enableAnimation) {
  37016. var group = this.group;
  37017. var data = this._data;
  37018. // Incremental model do not have this._data.
  37019. if (data && enableAnimation) {
  37020. data.eachItemGraphicEl(function (el) {
  37021. el.fadeOut(function () {
  37022. group.remove(el);
  37023. }, data.hostModel);
  37024. });
  37025. } else {
  37026. group.removeAll();
  37027. }
  37028. };
  37029. return SymbolDraw;
  37030. }();
  37031. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  37032. var baseAxis = coordSys.getBaseAxis();
  37033. var valueAxis = coordSys.getOtherAxis(baseAxis);
  37034. var valueStart = getValueStart(valueAxis, valueOrigin);
  37035. var baseAxisDim = baseAxis.dim;
  37036. var valueAxisDim = valueAxis.dim;
  37037. var valueDim = data.mapDimension(valueAxisDim);
  37038. var baseDim = data.mapDimension(baseAxisDim);
  37039. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  37040. var dims = map(coordSys.dimensions, function (coordDim) {
  37041. return data.mapDimension(coordDim);
  37042. });
  37043. var stacked = false;
  37044. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  37045. if (isDimensionStacked(data, dims[0] /* , dims[1] */)) {
  37046. // jshint ignore:line
  37047. stacked = true;
  37048. dims[0] = stackResultDim;
  37049. }
  37050. if (isDimensionStacked(data, dims[1] /* , dims[0] */)) {
  37051. // jshint ignore:line
  37052. stacked = true;
  37053. dims[1] = stackResultDim;
  37054. }
  37055. return {
  37056. dataDimsForPoint: dims,
  37057. valueStart: valueStart,
  37058. valueAxisDim: valueAxisDim,
  37059. baseAxisDim: baseAxisDim,
  37060. stacked: !!stacked,
  37061. valueDim: valueDim,
  37062. baseDim: baseDim,
  37063. baseDataOffset: baseDataOffset,
  37064. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  37065. };
  37066. }
  37067. function getValueStart(valueAxis, valueOrigin) {
  37068. var valueStart = 0;
  37069. var extent = valueAxis.scale.getExtent();
  37070. if (valueOrigin === 'start') {
  37071. valueStart = extent[0];
  37072. } else if (valueOrigin === 'end') {
  37073. valueStart = extent[1];
  37074. }
  37075. // If origin is specified as a number, use it as
  37076. // valueStart directly
  37077. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  37078. valueStart = valueOrigin;
  37079. }
  37080. // auto
  37081. else {
  37082. // Both positive
  37083. if (extent[0] > 0) {
  37084. valueStart = extent[0];
  37085. }
  37086. // Both negative
  37087. else if (extent[1] < 0) {
  37088. valueStart = extent[1];
  37089. }
  37090. // If is one positive, and one negative, onZero shall be true
  37091. }
  37092. return valueStart;
  37093. }
  37094. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  37095. var value = NaN;
  37096. if (dataCoordInfo.stacked) {
  37097. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  37098. }
  37099. if (isNaN(value)) {
  37100. value = dataCoordInfo.valueStart;
  37101. }
  37102. var baseDataOffset = dataCoordInfo.baseDataOffset;
  37103. var stackedData = [];
  37104. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  37105. stackedData[1 - baseDataOffset] = value;
  37106. return coordSys.dataToPoint(stackedData);
  37107. }
  37108. function diffData(oldData, newData) {
  37109. var diffResult = [];
  37110. newData.diff(oldData).add(function (idx) {
  37111. diffResult.push({
  37112. cmd: '+',
  37113. idx: idx
  37114. });
  37115. }).update(function (newIdx, oldIdx) {
  37116. diffResult.push({
  37117. cmd: '=',
  37118. idx: oldIdx,
  37119. idx1: newIdx
  37120. });
  37121. }).remove(function (idx) {
  37122. diffResult.push({
  37123. cmd: '-',
  37124. idx: idx
  37125. });
  37126. }).execute();
  37127. return diffResult;
  37128. }
  37129. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37130. var diff = diffData(oldData, newData);
  37131. // let newIdList = newData.mapArray(newData.getId);
  37132. // let oldIdList = oldData.mapArray(oldData.getId);
  37133. // convertToIntId(newIdList, oldIdList);
  37134. // // FIXME One data ?
  37135. // diff = arrayDiff(oldIdList, newIdList);
  37136. var currPoints = [];
  37137. var nextPoints = [];
  37138. // Points for stacking base line
  37139. var currStackedPoints = [];
  37140. var nextStackedPoints = [];
  37141. var status = [];
  37142. var sortedIndices = [];
  37143. var rawIndices = [];
  37144. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  37145. // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37146. var oldPoints = oldData.getLayout('points') || [];
  37147. var newPoints = newData.getLayout('points') || [];
  37148. for (var i = 0; i < diff.length; i++) {
  37149. var diffItem = diff[i];
  37150. var pointAdded = true;
  37151. var oldIdx2 = void 0;
  37152. var newIdx2 = void 0;
  37153. // FIXME, animation is not so perfect when dataZoom window moves fast
  37154. // Which is in case remvoing or add more than one data in the tail or head
  37155. switch (diffItem.cmd) {
  37156. case '=':
  37157. oldIdx2 = diffItem.idx * 2;
  37158. newIdx2 = diffItem.idx1 * 2;
  37159. var currentX = oldPoints[oldIdx2];
  37160. var currentY = oldPoints[oldIdx2 + 1];
  37161. var nextX = newPoints[newIdx2];
  37162. var nextY = newPoints[newIdx2 + 1];
  37163. // If previous data is NaN, use next point directly
  37164. if (isNaN(currentX) || isNaN(currentY)) {
  37165. currentX = nextX;
  37166. currentY = nextY;
  37167. }
  37168. currPoints.push(currentX, currentY);
  37169. nextPoints.push(nextX, nextY);
  37170. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37171. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37172. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37173. break;
  37174. case '+':
  37175. var newIdx = diffItem.idx;
  37176. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37177. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37178. newIdx2 = newIdx * 2;
  37179. currPoints.push(oldPt[0], oldPt[1]);
  37180. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37181. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37182. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37183. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37184. rawIndices.push(newData.getRawIndex(newIdx));
  37185. break;
  37186. case '-':
  37187. pointAdded = false;
  37188. }
  37189. // Original indices
  37190. if (pointAdded) {
  37191. status.push(diffItem);
  37192. sortedIndices.push(sortedIndices.length);
  37193. }
  37194. }
  37195. // Diff result may be crossed if all items are changed
  37196. // Sort by data index
  37197. sortedIndices.sort(function (a, b) {
  37198. return rawIndices[a] - rawIndices[b];
  37199. });
  37200. var len = currPoints.length;
  37201. var sortedCurrPoints = createFloat32Array(len);
  37202. var sortedNextPoints = createFloat32Array(len);
  37203. var sortedCurrStackedPoints = createFloat32Array(len);
  37204. var sortedNextStackedPoints = createFloat32Array(len);
  37205. var sortedStatus = [];
  37206. for (var i = 0; i < sortedIndices.length; i++) {
  37207. var idx = sortedIndices[i];
  37208. var i2 = i * 2;
  37209. var idx2 = idx * 2;
  37210. sortedCurrPoints[i2] = currPoints[idx2];
  37211. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37212. sortedNextPoints[i2] = nextPoints[idx2];
  37213. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37214. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37215. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37216. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37217. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37218. sortedStatus[i] = status[idx];
  37219. }
  37220. return {
  37221. current: sortedCurrPoints,
  37222. next: sortedNextPoints,
  37223. stackedOnCurrent: sortedCurrStackedPoints,
  37224. stackedOnNext: sortedNextStackedPoints,
  37225. status: sortedStatus
  37226. };
  37227. }
  37228. var mathMin$5 = Math.min;
  37229. var mathMax$5 = Math.max;
  37230. function isPointNull(x, y) {
  37231. return isNaN(x) || isNaN(y);
  37232. }
  37233. /**
  37234. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37235. * situations. This should be used when points are non-monotone neither in x or
  37236. * y dimension.
  37237. */
  37238. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37239. var prevX;
  37240. var prevY;
  37241. var cpx0;
  37242. var cpy0;
  37243. var cpx1;
  37244. var cpy1;
  37245. var idx = start;
  37246. var k = 0;
  37247. for (; k < segLen; k++) {
  37248. var x = points[idx * 2];
  37249. var y = points[idx * 2 + 1];
  37250. if (idx >= allLen || idx < 0) {
  37251. break;
  37252. }
  37253. if (isPointNull(x, y)) {
  37254. if (connectNulls) {
  37255. idx += dir;
  37256. continue;
  37257. }
  37258. break;
  37259. }
  37260. if (idx === start) {
  37261. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37262. cpx0 = x;
  37263. cpy0 = y;
  37264. } else {
  37265. var dx = x - prevX;
  37266. var dy = y - prevY;
  37267. // Ignore tiny segment.
  37268. if (dx * dx + dy * dy < 0.5) {
  37269. idx += dir;
  37270. continue;
  37271. }
  37272. if (smooth > 0) {
  37273. var nextIdx = idx + dir;
  37274. var nextX = points[nextIdx * 2];
  37275. var nextY = points[nextIdx * 2 + 1];
  37276. // Ignore duplicate point
  37277. while (nextX === x && nextY === y && k < segLen) {
  37278. k++;
  37279. nextIdx += dir;
  37280. idx += dir;
  37281. nextX = points[nextIdx * 2];
  37282. nextY = points[nextIdx * 2 + 1];
  37283. x = points[idx * 2];
  37284. y = points[idx * 2 + 1];
  37285. dx = x - prevX;
  37286. dy = y - prevY;
  37287. }
  37288. var tmpK = k + 1;
  37289. if (connectNulls) {
  37290. // Find next point not null
  37291. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37292. tmpK++;
  37293. nextIdx += dir;
  37294. nextX = points[nextIdx * 2];
  37295. nextY = points[nextIdx * 2 + 1];
  37296. }
  37297. }
  37298. var ratioNextSeg = 0.5;
  37299. var vx = 0;
  37300. var vy = 0;
  37301. var nextCpx0 = void 0;
  37302. var nextCpy0 = void 0;
  37303. // Is last point
  37304. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37305. cpx1 = x;
  37306. cpy1 = y;
  37307. } else {
  37308. vx = nextX - prevX;
  37309. vy = nextY - prevY;
  37310. var dx0 = x - prevX;
  37311. var dx1 = nextX - x;
  37312. var dy0 = y - prevY;
  37313. var dy1 = nextY - y;
  37314. var lenPrevSeg = void 0;
  37315. var lenNextSeg = void 0;
  37316. if (smoothMonotone === 'x') {
  37317. lenPrevSeg = Math.abs(dx0);
  37318. lenNextSeg = Math.abs(dx1);
  37319. var dir_1 = vx > 0 ? 1 : -1;
  37320. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  37321. cpy1 = y;
  37322. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  37323. nextCpy0 = y;
  37324. } else if (smoothMonotone === 'y') {
  37325. lenPrevSeg = Math.abs(dy0);
  37326. lenNextSeg = Math.abs(dy1);
  37327. var dir_2 = vy > 0 ? 1 : -1;
  37328. cpx1 = x;
  37329. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  37330. nextCpx0 = x;
  37331. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  37332. } else {
  37333. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37334. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  37335. // Use ratio of seg length
  37336. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37337. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37338. cpy1 = y - vy * smooth * (1 - ratioNextSeg);
  37339. // cp0 of next segment
  37340. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37341. nextCpy0 = y + vy * smooth * ratioNextSeg;
  37342. // Smooth constraint between point and next point.
  37343. // Avoid exceeding extreme after smoothing.
  37344. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37345. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37346. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37347. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y));
  37348. // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37349. vx = nextCpx0 - x;
  37350. vy = nextCpy0 - y;
  37351. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37352. cpy1 = y - vy * lenPrevSeg / lenNextSeg;
  37353. // Smooth constraint between point and prev point.
  37354. // Avoid exceeding extreme after smoothing.
  37355. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37356. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37357. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37358. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y));
  37359. // Adjust next cp0 again.
  37360. vx = x - cpx1;
  37361. vy = y - cpy1;
  37362. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37363. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37364. }
  37365. }
  37366. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37367. cpx0 = nextCpx0;
  37368. cpy0 = nextCpy0;
  37369. } else {
  37370. ctx.lineTo(x, y);
  37371. }
  37372. }
  37373. prevX = x;
  37374. prevY = y;
  37375. idx += dir;
  37376. }
  37377. return k;
  37378. }
  37379. var ECPolylineShape = /** @class */function () {
  37380. function ECPolylineShape() {
  37381. this.smooth = 0;
  37382. this.smoothConstraint = true;
  37383. }
  37384. return ECPolylineShape;
  37385. }();
  37386. var ECPolyline = /** @class */function (_super) {
  37387. __extends(ECPolyline, _super);
  37388. function ECPolyline(opts) {
  37389. var _this = _super.call(this, opts) || this;
  37390. _this.type = 'ec-polyline';
  37391. return _this;
  37392. }
  37393. ECPolyline.prototype.getDefaultStyle = function () {
  37394. return {
  37395. stroke: '#000',
  37396. fill: null
  37397. };
  37398. };
  37399. ECPolyline.prototype.getDefaultShape = function () {
  37400. return new ECPolylineShape();
  37401. };
  37402. ECPolyline.prototype.buildPath = function (ctx, shape) {
  37403. var points = shape.points;
  37404. var i = 0;
  37405. var len = points.length / 2;
  37406. // const result = getBoundingBox(points, shape.smoothConstraint);
  37407. if (shape.connectNulls) {
  37408. // Must remove first and last null values avoid draw error in polygon
  37409. for (; len > 0; len--) {
  37410. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37411. break;
  37412. }
  37413. }
  37414. for (; i < len; i++) {
  37415. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37416. break;
  37417. }
  37418. }
  37419. }
  37420. while (i < len) {
  37421. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  37422. }
  37423. };
  37424. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  37425. if (!this.path) {
  37426. this.createPathProxy();
  37427. this.buildPath(this.path, this.shape);
  37428. }
  37429. var path = this.path;
  37430. var data = path.data;
  37431. var CMD = PathProxy.CMD;
  37432. var x0;
  37433. var y0;
  37434. var isDimX = dim === 'x';
  37435. var roots = [];
  37436. for (var i = 0; i < data.length;) {
  37437. var cmd = data[i++];
  37438. var x = void 0;
  37439. var y = void 0;
  37440. var x2 = void 0;
  37441. var y2 = void 0;
  37442. var x3 = void 0;
  37443. var y3 = void 0;
  37444. var t = void 0;
  37445. switch (cmd) {
  37446. case CMD.M:
  37447. x0 = data[i++];
  37448. y0 = data[i++];
  37449. break;
  37450. case CMD.L:
  37451. x = data[i++];
  37452. y = data[i++];
  37453. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  37454. if (t <= 1 && t >= 0) {
  37455. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  37456. return isDimX ? [xOrY, val] : [val, xOrY];
  37457. }
  37458. x0 = x;
  37459. y0 = y;
  37460. break;
  37461. case CMD.C:
  37462. x = data[i++];
  37463. y = data[i++];
  37464. x2 = data[i++];
  37465. y2 = data[i++];
  37466. x3 = data[i++];
  37467. y3 = data[i++];
  37468. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  37469. if (nRoot > 0) {
  37470. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  37471. var t_1 = roots[i_1];
  37472. if (t_1 <= 1 && t_1 >= 0) {
  37473. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  37474. return isDimX ? [xOrY, val] : [val, xOrY];
  37475. }
  37476. }
  37477. }
  37478. x0 = x3;
  37479. y0 = y3;
  37480. break;
  37481. }
  37482. }
  37483. };
  37484. return ECPolyline;
  37485. }(Path);
  37486. var ECPolygonShape = /** @class */function (_super) {
  37487. __extends(ECPolygonShape, _super);
  37488. function ECPolygonShape() {
  37489. return _super !== null && _super.apply(this, arguments) || this;
  37490. }
  37491. return ECPolygonShape;
  37492. }(ECPolylineShape);
  37493. var ECPolygon = /** @class */function (_super) {
  37494. __extends(ECPolygon, _super);
  37495. function ECPolygon(opts) {
  37496. var _this = _super.call(this, opts) || this;
  37497. _this.type = 'ec-polygon';
  37498. return _this;
  37499. }
  37500. ECPolygon.prototype.getDefaultShape = function () {
  37501. return new ECPolygonShape();
  37502. };
  37503. ECPolygon.prototype.buildPath = function (ctx, shape) {
  37504. var points = shape.points;
  37505. var stackedOnPoints = shape.stackedOnPoints;
  37506. var i = 0;
  37507. var len = points.length / 2;
  37508. var smoothMonotone = shape.smoothMonotone;
  37509. if (shape.connectNulls) {
  37510. // Must remove first and last null values avoid draw error in polygon
  37511. for (; len > 0; len--) {
  37512. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37513. break;
  37514. }
  37515. }
  37516. for (; i < len; i++) {
  37517. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37518. break;
  37519. }
  37520. }
  37521. }
  37522. while (i < len) {
  37523. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  37524. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  37525. i += k + 1;
  37526. ctx.closePath();
  37527. }
  37528. };
  37529. return ECPolygon;
  37530. }(Path);
  37531. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  37532. var rect = cartesian.getArea();
  37533. var x = rect.x;
  37534. var y = rect.y;
  37535. var width = rect.width;
  37536. var height = rect.height;
  37537. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 0;
  37538. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  37539. x -= lineWidth / 2;
  37540. y -= lineWidth / 2;
  37541. width += lineWidth;
  37542. height += lineWidth;
  37543. // fix: https://github.com/apache/incubator-echarts/issues/11369
  37544. width = Math.ceil(width);
  37545. if (x !== Math.floor(x)) {
  37546. x = Math.floor(x);
  37547. // if no extra 1px on `width`, it will still be clipped since `x` is floored
  37548. width++;
  37549. }
  37550. var clipPath = new Rect({
  37551. shape: {
  37552. x: x,
  37553. y: y,
  37554. width: width,
  37555. height: height
  37556. }
  37557. });
  37558. if (hasAnimation) {
  37559. var baseAxis = cartesian.getBaseAxis();
  37560. var isHorizontal = baseAxis.isHorizontal();
  37561. var isAxisInversed = baseAxis.inverse;
  37562. if (isHorizontal) {
  37563. if (isAxisInversed) {
  37564. clipPath.shape.x += width;
  37565. }
  37566. clipPath.shape.width = 0;
  37567. } else {
  37568. if (!isAxisInversed) {
  37569. clipPath.shape.y += height;
  37570. }
  37571. clipPath.shape.height = 0;
  37572. }
  37573. var duringCb = isFunction(during) ? function (percent) {
  37574. during(percent, clipPath);
  37575. } : null;
  37576. initProps(clipPath, {
  37577. shape: {
  37578. width: width,
  37579. height: height,
  37580. x: x,
  37581. y: y
  37582. }
  37583. }, seriesModel, null, done, duringCb);
  37584. }
  37585. return clipPath;
  37586. }
  37587. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  37588. var sectorArea = polar.getArea();
  37589. // Avoid float number rounding error for symbol on the edge of axis extent.
  37590. var r0 = round(sectorArea.r0, 1);
  37591. var r = round(sectorArea.r, 1);
  37592. var clipPath = new Sector({
  37593. shape: {
  37594. cx: round(polar.cx, 1),
  37595. cy: round(polar.cy, 1),
  37596. r0: r0,
  37597. r: r,
  37598. startAngle: sectorArea.startAngle,
  37599. endAngle: sectorArea.endAngle,
  37600. clockwise: sectorArea.clockwise
  37601. }
  37602. });
  37603. if (hasAnimation) {
  37604. var isRadial = polar.getBaseAxis().dim === 'angle';
  37605. if (isRadial) {
  37606. clipPath.shape.endAngle = sectorArea.startAngle;
  37607. } else {
  37608. clipPath.shape.r = r0;
  37609. }
  37610. initProps(clipPath, {
  37611. shape: {
  37612. endAngle: sectorArea.endAngle,
  37613. r: r
  37614. }
  37615. }, seriesModel);
  37616. }
  37617. return clipPath;
  37618. }
  37619. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  37620. if (!coordSys) {
  37621. return null;
  37622. } else if (coordSys.type === 'polar') {
  37623. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37624. } else if (coordSys.type === 'cartesian2d') {
  37625. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  37626. }
  37627. return null;
  37628. }
  37629. /*
  37630. * Licensed to the Apache Software Foundation (ASF) under one
  37631. * or more contributor license agreements. See the NOTICE file
  37632. * distributed with this work for additional information
  37633. * regarding copyright ownership. The ASF licenses this file
  37634. * to you under the Apache License, Version 2.0 (the
  37635. * "License"); you may not use this file except in compliance
  37636. * with the License. You may obtain a copy of the License at
  37637. *
  37638. * http://www.apache.org/licenses/LICENSE-2.0
  37639. *
  37640. * Unless required by applicable law or agreed to in writing,
  37641. * software distributed under the License is distributed on an
  37642. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37643. * KIND, either express or implied. See the License for the
  37644. * specific language governing permissions and limitations
  37645. * under the License.
  37646. */
  37647. /**
  37648. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37649. */
  37650. /*
  37651. * Licensed to the Apache Software Foundation (ASF) under one
  37652. * or more contributor license agreements. See the NOTICE file
  37653. * distributed with this work for additional information
  37654. * regarding copyright ownership. The ASF licenses this file
  37655. * to you under the Apache License, Version 2.0 (the
  37656. * "License"); you may not use this file except in compliance
  37657. * with the License. You may obtain a copy of the License at
  37658. *
  37659. * http://www.apache.org/licenses/LICENSE-2.0
  37660. *
  37661. * Unless required by applicable law or agreed to in writing,
  37662. * software distributed under the License is distributed on an
  37663. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37664. * KIND, either express or implied. See the License for the
  37665. * specific language governing permissions and limitations
  37666. * under the License.
  37667. */
  37668. function isCoordinateSystemType(coordSys, type) {
  37669. return coordSys.type === type;
  37670. }
  37671. function isPointsSame(points1, points2) {
  37672. if (points1.length !== points2.length) {
  37673. return;
  37674. }
  37675. for (var i = 0; i < points1.length; i++) {
  37676. if (points1[i] !== points2[i]) {
  37677. return;
  37678. }
  37679. }
  37680. return true;
  37681. }
  37682. function bboxFromPoints(points) {
  37683. var minX = Infinity;
  37684. var minY = Infinity;
  37685. var maxX = -Infinity;
  37686. var maxY = -Infinity;
  37687. for (var i = 0; i < points.length;) {
  37688. var x = points[i++];
  37689. var y = points[i++];
  37690. if (!isNaN(x)) {
  37691. minX = Math.min(x, minX);
  37692. maxX = Math.max(x, maxX);
  37693. }
  37694. if (!isNaN(y)) {
  37695. minY = Math.min(y, minY);
  37696. maxY = Math.max(y, maxY);
  37697. }
  37698. }
  37699. return [[minX, minY], [maxX, maxY]];
  37700. }
  37701. function getBoundingDiff(points1, points2) {
  37702. var _a = bboxFromPoints(points1),
  37703. min1 = _a[0],
  37704. max1 = _a[1];
  37705. var _b = bboxFromPoints(points2),
  37706. min2 = _b[0],
  37707. max2 = _b[1];
  37708. // Get a max value from each corner of two boundings.
  37709. return Math.max(Math.abs(min1[0] - min2[0]), Math.abs(min1[1] - min2[1]), Math.abs(max1[0] - max2[0]), Math.abs(max1[1] - max2[1]));
  37710. }
  37711. function getSmooth(smooth) {
  37712. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  37713. }
  37714. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  37715. if (!dataCoordInfo.valueDim) {
  37716. return [];
  37717. }
  37718. var len = data.count();
  37719. var points = createFloat32Array(len * 2);
  37720. for (var idx = 0; idx < len; idx++) {
  37721. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  37722. points[idx * 2] = pt[0];
  37723. points[idx * 2 + 1] = pt[1];
  37724. }
  37725. return points;
  37726. }
  37727. /**
  37728. * Filter the null data and extend data for step considering `stepTurnAt`
  37729. *
  37730. * @param points data to convert, that may containing null
  37731. * @param basePoints base data to reference, used only for areaStyle points
  37732. * @param coordSys coordinate system
  37733. * @param stepTurnAt 'start' | 'end' | 'middle' | true
  37734. * @param connectNulls whether to connect nulls
  37735. * @returns converted point positions
  37736. */
  37737. function turnPointsIntoStep(points, basePoints, coordSys, stepTurnAt, connectNulls) {
  37738. var baseAxis = coordSys.getBaseAxis();
  37739. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  37740. var stepPoints = [];
  37741. var i = 0;
  37742. var stepPt = [];
  37743. var pt = [];
  37744. var nextPt = [];
  37745. var filteredPoints = [];
  37746. if (connectNulls) {
  37747. for (i = 0; i < points.length; i += 2) {
  37748. /**
  37749. * For areaStyle of stepped lines, `stackedOnPoints` should be
  37750. * filtered the same as `points` so that the base axis values
  37751. * should stay the same as the lines above. See #20021
  37752. */
  37753. var reference = basePoints || points;
  37754. if (!isNaN(reference[i]) && !isNaN(reference[i + 1])) {
  37755. filteredPoints.push(points[i], points[i + 1]);
  37756. }
  37757. }
  37758. points = filteredPoints;
  37759. }
  37760. for (i = 0; i < points.length - 2; i += 2) {
  37761. nextPt[0] = points[i + 2];
  37762. nextPt[1] = points[i + 3];
  37763. pt[0] = points[i];
  37764. pt[1] = points[i + 1];
  37765. stepPoints.push(pt[0], pt[1]);
  37766. switch (stepTurnAt) {
  37767. case 'end':
  37768. stepPt[baseIndex] = nextPt[baseIndex];
  37769. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37770. stepPoints.push(stepPt[0], stepPt[1]);
  37771. break;
  37772. case 'middle':
  37773. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  37774. var stepPt2 = [];
  37775. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  37776. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37777. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  37778. stepPoints.push(stepPt[0], stepPt[1]);
  37779. stepPoints.push(stepPt2[0], stepPt2[1]);
  37780. break;
  37781. default:
  37782. // default is start
  37783. stepPt[baseIndex] = pt[baseIndex];
  37784. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  37785. stepPoints.push(stepPt[0], stepPt[1]);
  37786. }
  37787. }
  37788. // Last points
  37789. stepPoints.push(points[i++], points[i++]);
  37790. return stepPoints;
  37791. }
  37792. /**
  37793. * Clip color stops to edge. Avoid creating too large gradients.
  37794. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  37795. *
  37796. * The stops has been sorted from small to large.
  37797. */
  37798. function clipColorStops(colorStops, maxSize) {
  37799. var newColorStops = [];
  37800. var len = colorStops.length;
  37801. // coord will always < 0 in prevOutOfRangeColorStop.
  37802. var prevOutOfRangeColorStop;
  37803. var prevInRangeColorStop;
  37804. function lerpStop(stop0, stop1, clippedCoord) {
  37805. var coord0 = stop0.coord;
  37806. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  37807. var color = lerp$1(p, [stop0.color, stop1.color]);
  37808. return {
  37809. coord: clippedCoord,
  37810. color: color
  37811. };
  37812. }
  37813. for (var i = 0; i < len; i++) {
  37814. var stop_1 = colorStops[i];
  37815. var coord = stop_1.coord;
  37816. if (coord < 0) {
  37817. prevOutOfRangeColorStop = stop_1;
  37818. } else if (coord > maxSize) {
  37819. if (prevInRangeColorStop) {
  37820. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  37821. } else if (prevOutOfRangeColorStop) {
  37822. // If there are two stops and coord range is between these two stops
  37823. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  37824. }
  37825. // All following stop will be out of range. So just ignore them.
  37826. break;
  37827. } else {
  37828. if (prevOutOfRangeColorStop) {
  37829. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0));
  37830. // Reset
  37831. prevOutOfRangeColorStop = null;
  37832. }
  37833. newColorStops.push(stop_1);
  37834. prevInRangeColorStop = stop_1;
  37835. }
  37836. }
  37837. return newColorStops;
  37838. }
  37839. function getVisualGradient(data, coordSys, api) {
  37840. var visualMetaList = data.getVisual('visualMeta');
  37841. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  37842. // When data.count() is 0, gradient range can not be calculated.
  37843. return;
  37844. }
  37845. if (coordSys.type !== 'cartesian2d') {
  37846. if ("development" !== 'production') {
  37847. console.warn('Visual map on line style is only supported on cartesian2d.');
  37848. }
  37849. return;
  37850. }
  37851. var coordDim;
  37852. var visualMeta;
  37853. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  37854. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  37855. coordDim = dimInfo && dimInfo.coordDim;
  37856. // Can only be x or y
  37857. if (coordDim === 'x' || coordDim === 'y') {
  37858. visualMeta = visualMetaList[i];
  37859. break;
  37860. }
  37861. }
  37862. if (!visualMeta) {
  37863. if ("development" !== 'production') {
  37864. console.warn('Visual map on line style only support x or y dimension.');
  37865. }
  37866. return;
  37867. }
  37868. // If the area to be rendered is bigger than area defined by LinearGradient,
  37869. // the canvas spec prescribes that the color of the first stop and the last
  37870. // stop should be used. But if two stops are added at offset 0, in effect
  37871. // browsers use the color of the second stop to render area outside
  37872. // LinearGradient. So we can only infinitesimally extend area defined in
  37873. // LinearGradient to render `outerColors`.
  37874. var axis = coordSys.getAxis(coordDim);
  37875. // dataToCoord mapping may not be linear, but must be monotonic.
  37876. var colorStops = map(visualMeta.stops, function (stop) {
  37877. // offset will be calculated later.
  37878. return {
  37879. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  37880. color: stop.color
  37881. };
  37882. });
  37883. var stopLen = colorStops.length;
  37884. var outerColors = visualMeta.outerColors.slice();
  37885. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  37886. colorStops.reverse();
  37887. outerColors.reverse();
  37888. }
  37889. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  37890. var inRangeStopLen = colorStopsInRange.length;
  37891. if (!inRangeStopLen && stopLen) {
  37892. // All stops are out of range. All will be the same color.
  37893. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  37894. }
  37895. var tinyExtent = 10; // Arbitrary value: 10px
  37896. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  37897. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  37898. var coordSpan = maxCoord - minCoord;
  37899. if (coordSpan < 1e-3) {
  37900. return 'transparent';
  37901. }
  37902. each(colorStopsInRange, function (stop) {
  37903. stop.offset = (stop.coord - minCoord) / coordSpan;
  37904. });
  37905. colorStopsInRange.push({
  37906. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  37907. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  37908. color: outerColors[1] || 'transparent'
  37909. });
  37910. colorStopsInRange.unshift({
  37911. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  37912. color: outerColors[0] || 'transparent'
  37913. });
  37914. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  37915. gradient[coordDim] = minCoord;
  37916. gradient[coordDim + '2'] = maxCoord;
  37917. return gradient;
  37918. }
  37919. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  37920. var showAllSymbol = seriesModel.get('showAllSymbol');
  37921. var isAuto = showAllSymbol === 'auto';
  37922. if (showAllSymbol && !isAuto) {
  37923. return;
  37924. }
  37925. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  37926. if (!categoryAxis) {
  37927. return;
  37928. }
  37929. // Note that category label interval strategy might bring some weird effect
  37930. // in some scenario: users may wonder why some of the symbols are not
  37931. // displayed. So we show all symbols as possible as we can.
  37932. if (isAuto
  37933. // Simplify the logic, do not determine label overlap here.
  37934. && canShowAllSymbolForCategory(categoryAxis, data)) {
  37935. return;
  37936. }
  37937. // Otherwise follow the label interval strategy on category axis.
  37938. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  37939. var labelMap = {};
  37940. each(categoryAxis.getViewLabels(), function (labelItem) {
  37941. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  37942. labelMap[ordinalNumber] = 1;
  37943. });
  37944. return function (dataIndex) {
  37945. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  37946. };
  37947. }
  37948. function canShowAllSymbolForCategory(categoryAxis, data) {
  37949. // In most cases, line is monotonous on category axis, and the label size
  37950. // is close with each other. So we check the symbol size and some of the
  37951. // label size alone with the category axis to estimate whether all symbol
  37952. // can be shown without overlap.
  37953. var axisExtent = categoryAxis.getExtent();
  37954. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  37955. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  37956. // Sampling some points, max 5.
  37957. var dataLen = data.count();
  37958. var step = Math.max(1, Math.round(dataLen / 5));
  37959. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  37960. if (Symbol.getSymbolSize(data, dataIndex
  37961. // Only for cartesian, where `isHorizontal` exists.
  37962. )[categoryAxis.isHorizontal() ? 1 : 0]
  37963. // Empirical number
  37964. * 1.5 > availSize) {
  37965. return false;
  37966. }
  37967. }
  37968. return true;
  37969. }
  37970. function isPointNull$1(x, y) {
  37971. return isNaN(x) || isNaN(y);
  37972. }
  37973. function getLastIndexNotNull(points) {
  37974. var len = points.length / 2;
  37975. for (; len > 0; len--) {
  37976. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  37977. break;
  37978. }
  37979. }
  37980. return len - 1;
  37981. }
  37982. function getPointAtIndex(points, idx) {
  37983. return [points[idx * 2], points[idx * 2 + 1]];
  37984. }
  37985. function getIndexRange(points, xOrY, dim) {
  37986. var len = points.length / 2;
  37987. var dimIdx = dim === 'x' ? 0 : 1;
  37988. var a;
  37989. var b;
  37990. var prevIndex = 0;
  37991. var nextIndex = -1;
  37992. for (var i = 0; i < len; i++) {
  37993. b = points[i * 2 + dimIdx];
  37994. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  37995. continue;
  37996. }
  37997. if (i === 0) {
  37998. a = b;
  37999. continue;
  38000. }
  38001. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  38002. nextIndex = i;
  38003. break;
  38004. }
  38005. prevIndex = i;
  38006. a = b;
  38007. }
  38008. return {
  38009. range: [prevIndex, nextIndex],
  38010. t: (xOrY - a) / (b - a)
  38011. };
  38012. }
  38013. function anyStateShowEndLabel(seriesModel) {
  38014. if (seriesModel.get(['endLabel', 'show'])) {
  38015. return true;
  38016. }
  38017. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  38018. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  38019. return true;
  38020. }
  38021. }
  38022. return false;
  38023. }
  38024. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  38025. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  38026. var endLabelModel_1 = seriesModel.getModel('endLabel');
  38027. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  38028. var data_1 = seriesModel.getData();
  38029. var labelAnimationRecord_1 = {
  38030. lastFrameIndex: 0
  38031. };
  38032. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  38033. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  38034. } : null;
  38035. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  38036. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  38037. var endLabel = lineView._endLabel;
  38038. if (endLabel && hasAnimation) {
  38039. if (labelAnimationRecord_1.originalX != null) {
  38040. endLabel.attr({
  38041. x: labelAnimationRecord_1.originalX,
  38042. y: labelAnimationRecord_1.originalY
  38043. });
  38044. }
  38045. }
  38046. }, during);
  38047. // Expand clip shape to avoid clipping when line value exceeds axis
  38048. if (!seriesModel.get('clip', true)) {
  38049. var rectShape = clipPath.shape;
  38050. var expandSize = Math.max(rectShape.width, rectShape.height);
  38051. if (isHorizontal) {
  38052. rectShape.y -= expandSize;
  38053. rectShape.height += expandSize * 2;
  38054. } else {
  38055. rectShape.x -= expandSize;
  38056. rectShape.width += expandSize * 2;
  38057. }
  38058. }
  38059. // Set to the final frame. To make sure label layout is right.
  38060. if (during) {
  38061. during(1, clipPath);
  38062. }
  38063. return clipPath;
  38064. } else {
  38065. if ("development" !== 'production') {
  38066. if (seriesModel.get(['endLabel', 'show'])) {
  38067. console.warn('endLabel is not supported for lines in polar systems.');
  38068. }
  38069. }
  38070. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  38071. }
  38072. }
  38073. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  38074. var baseAxis = coordSys.getBaseAxis();
  38075. var isHorizontal = baseAxis.isHorizontal();
  38076. var isBaseInversed = baseAxis.inverse;
  38077. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  38078. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  38079. return {
  38080. normal: {
  38081. align: endLabelModel.get('align') || align,
  38082. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  38083. }
  38084. };
  38085. }
  38086. var LineView = /** @class */function (_super) {
  38087. __extends(LineView, _super);
  38088. function LineView() {
  38089. return _super !== null && _super.apply(this, arguments) || this;
  38090. }
  38091. LineView.prototype.init = function () {
  38092. var lineGroup = new Group();
  38093. var symbolDraw = new SymbolDraw();
  38094. this.group.add(symbolDraw.group);
  38095. this._symbolDraw = symbolDraw;
  38096. this._lineGroup = lineGroup;
  38097. this._changePolyState = bind(this._changePolyState, this);
  38098. };
  38099. LineView.prototype.render = function (seriesModel, ecModel, api) {
  38100. var coordSys = seriesModel.coordinateSystem;
  38101. var group = this.group;
  38102. var data = seriesModel.getData();
  38103. var lineStyleModel = seriesModel.getModel('lineStyle');
  38104. var areaStyleModel = seriesModel.getModel('areaStyle');
  38105. var points = data.getLayout('points') || [];
  38106. var isCoordSysPolar = coordSys.type === 'polar';
  38107. var prevCoordSys = this._coordSys;
  38108. var symbolDraw = this._symbolDraw;
  38109. var polyline = this._polyline;
  38110. var polygon = this._polygon;
  38111. var lineGroup = this._lineGroup;
  38112. var hasAnimation = !ecModel.ssr && seriesModel.get('animation');
  38113. var isAreaChart = !areaStyleModel.isEmpty();
  38114. var valueOrigin = areaStyleModel.get('origin');
  38115. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  38116. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  38117. var showSymbol = seriesModel.get('showSymbol');
  38118. var connectNulls = seriesModel.get('connectNulls');
  38119. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys);
  38120. // Remove temporary symbols
  38121. var oldData = this._data;
  38122. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38123. if (el.__temp) {
  38124. group.remove(el);
  38125. oldData.setItemGraphicEl(idx, null);
  38126. }
  38127. });
  38128. // Remove previous created symbols if showSymbol changed to false
  38129. if (!showSymbol) {
  38130. symbolDraw.remove();
  38131. }
  38132. group.add(lineGroup);
  38133. // FIXME step not support polar
  38134. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38135. var clipShapeForSymbol;
  38136. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38137. clipShapeForSymbol = coordSys.getArea();
  38138. // Avoid float number rounding error for symbol on the edge of axis extent.
  38139. // See #7913 and `test/dataZoom-clip.html`.
  38140. if (clipShapeForSymbol.width != null) {
  38141. clipShapeForSymbol.x -= 0.1;
  38142. clipShapeForSymbol.y -= 0.1;
  38143. clipShapeForSymbol.width += 0.2;
  38144. clipShapeForSymbol.height += 0.2;
  38145. } else if (clipShapeForSymbol.r0) {
  38146. clipShapeForSymbol.r0 -= 0.5;
  38147. clipShapeForSymbol.r += 0.5;
  38148. }
  38149. }
  38150. this._clipShapeForSymbol = clipShapeForSymbol;
  38151. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')];
  38152. // Initialization animation or coordinate system changed
  38153. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38154. showSymbol && symbolDraw.updateData(data, {
  38155. isIgnore: isIgnoreFunc,
  38156. clipShape: clipShapeForSymbol,
  38157. disableAnimation: true,
  38158. getSymbolPoint: function (idx) {
  38159. return [points[idx * 2], points[idx * 2 + 1]];
  38160. }
  38161. });
  38162. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38163. if (step) {
  38164. if (stackedOnPoints) {
  38165. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
  38166. }
  38167. // TODO If stacked series is not step
  38168. points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
  38169. }
  38170. polyline = this._newPolyline(points);
  38171. if (isAreaChart) {
  38172. polygon = this._newPolygon(points, stackedOnPoints);
  38173. } // If areaStyle is removed
  38174. else if (polygon) {
  38175. lineGroup.remove(polygon);
  38176. polygon = this._polygon = null;
  38177. }
  38178. // NOTE: Must update _endLabel before setClipPath.
  38179. if (!isCoordSysPolar) {
  38180. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38181. }
  38182. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38183. } else {
  38184. if (isAreaChart && !polygon) {
  38185. // If areaStyle is added
  38186. polygon = this._newPolygon(points, stackedOnPoints);
  38187. } else if (polygon && !isAreaChart) {
  38188. // If areaStyle is removed
  38189. lineGroup.remove(polygon);
  38190. polygon = this._polygon = null;
  38191. }
  38192. // NOTE: Must update _endLabel before setClipPath.
  38193. if (!isCoordSysPolar) {
  38194. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38195. }
  38196. // Update clipPath
  38197. var oldClipPath = lineGroup.getClipPath();
  38198. if (oldClipPath) {
  38199. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  38200. initProps(oldClipPath, {
  38201. shape: newClipPath.shape
  38202. }, seriesModel);
  38203. } else {
  38204. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38205. }
  38206. // Always update, or it is wrong in the case turning on legend
  38207. // because points are not changed.
  38208. showSymbol && symbolDraw.updateData(data, {
  38209. isIgnore: isIgnoreFunc,
  38210. clipShape: clipShapeForSymbol,
  38211. disableAnimation: true,
  38212. getSymbolPoint: function (idx) {
  38213. return [points[idx * 2], points[idx * 2 + 1]];
  38214. }
  38215. });
  38216. // In the case data zoom triggered refreshing frequently
  38217. // Data may not change if line has a category axis. So it should animate nothing.
  38218. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38219. if (hasAnimation) {
  38220. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  38221. } else {
  38222. // Not do it in update with animation
  38223. if (step) {
  38224. if (stackedOnPoints) {
  38225. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
  38226. }
  38227. // TODO If stacked series is not step
  38228. points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
  38229. }
  38230. polyline.setShape({
  38231. points: points
  38232. });
  38233. polygon && polygon.setShape({
  38234. points: points,
  38235. stackedOnPoints: stackedOnPoints
  38236. });
  38237. }
  38238. }
  38239. }
  38240. var emphasisModel = seriesModel.getModel('emphasis');
  38241. var focus = emphasisModel.get('focus');
  38242. var blurScope = emphasisModel.get('blurScope');
  38243. var emphasisDisabled = emphasisModel.get('disabled');
  38244. polyline.useStyle(defaults(
  38245. // Use color in lineStyle first
  38246. lineStyleModel.getLineStyle(), {
  38247. fill: 'none',
  38248. stroke: visualColor,
  38249. lineJoin: 'bevel'
  38250. }));
  38251. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38252. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38253. var emphasisLineStyle = polyline.getState('emphasis').style;
  38254. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38255. }
  38256. // Needs seriesIndex for focus
  38257. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38258. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  38259. var smooth = getSmooth(seriesModel.get('smooth'));
  38260. var smoothMonotone = seriesModel.get('smoothMonotone');
  38261. polyline.setShape({
  38262. smooth: smooth,
  38263. smoothMonotone: smoothMonotone,
  38264. connectNulls: connectNulls
  38265. });
  38266. if (polygon) {
  38267. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38268. var stackedOnSmooth = 0;
  38269. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38270. fill: visualColor,
  38271. opacity: 0.7,
  38272. lineJoin: 'bevel',
  38273. decal: data.getVisual('style').decal
  38274. }));
  38275. if (stackedOnSeries) {
  38276. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38277. }
  38278. polygon.setShape({
  38279. smooth: smooth,
  38280. stackedOnSmooth: stackedOnSmooth,
  38281. smoothMonotone: smoothMonotone,
  38282. connectNulls: connectNulls
  38283. });
  38284. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle');
  38285. // Needs seriesIndex for focus
  38286. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38287. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  38288. }
  38289. var changePolyState = this._changePolyState;
  38290. data.eachItemGraphicEl(function (el) {
  38291. // Switch polyline / polygon state if element changed its state.
  38292. el && (el.onHoverStateChange = changePolyState);
  38293. });
  38294. this._polyline.onHoverStateChange = changePolyState;
  38295. this._data = data;
  38296. // Save the coordinate system for transition animation when data changed
  38297. this._coordSys = coordSys;
  38298. this._stackedOnPoints = stackedOnPoints;
  38299. this._points = points;
  38300. this._step = step;
  38301. this._valueOrigin = valueOrigin;
  38302. if (seriesModel.get('triggerLineEvent')) {
  38303. this.packEventData(seriesModel, polyline);
  38304. polygon && this.packEventData(seriesModel, polygon);
  38305. }
  38306. };
  38307. LineView.prototype.packEventData = function (seriesModel, el) {
  38308. getECData(el).eventData = {
  38309. componentType: 'series',
  38310. componentSubType: 'line',
  38311. componentIndex: seriesModel.componentIndex,
  38312. seriesIndex: seriesModel.seriesIndex,
  38313. seriesName: seriesModel.name,
  38314. seriesType: 'line'
  38315. };
  38316. };
  38317. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38318. var data = seriesModel.getData();
  38319. var dataIndex = queryDataIndex(data, payload);
  38320. this._changePolyState('emphasis');
  38321. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38322. var points = data.getLayout('points');
  38323. var symbol = data.getItemGraphicEl(dataIndex);
  38324. if (!symbol) {
  38325. // Create a temporary symbol if it is not exists
  38326. var x = points[dataIndex * 2];
  38327. var y = points[dataIndex * 2 + 1];
  38328. if (isNaN(x) || isNaN(y)) {
  38329. // Null data
  38330. return;
  38331. }
  38332. // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  38333. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38334. return;
  38335. }
  38336. var zlevel = seriesModel.get('zlevel') || 0;
  38337. var z = seriesModel.get('z') || 0;
  38338. symbol = new Symbol(data, dataIndex);
  38339. symbol.x = x;
  38340. symbol.y = y;
  38341. symbol.setZ(zlevel, z);
  38342. // ensure label text of the temporary symbol is in front of line and area polygon
  38343. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38344. if (symbolLabel) {
  38345. symbolLabel.zlevel = zlevel;
  38346. symbolLabel.z = z;
  38347. symbolLabel.z2 = this._polyline.z2 + 1;
  38348. }
  38349. symbol.__temp = true;
  38350. data.setItemGraphicEl(dataIndex, symbol);
  38351. // Stop scale animation
  38352. symbol.stopSymbolAnimation(true);
  38353. this.group.add(symbol);
  38354. }
  38355. symbol.highlight();
  38356. } else {
  38357. // Highlight whole series
  38358. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38359. }
  38360. };
  38361. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38362. var data = seriesModel.getData();
  38363. var dataIndex = queryDataIndex(data, payload);
  38364. this._changePolyState('normal');
  38365. if (dataIndex != null && dataIndex >= 0) {
  38366. var symbol = data.getItemGraphicEl(dataIndex);
  38367. if (symbol) {
  38368. if (symbol.__temp) {
  38369. data.setItemGraphicEl(dataIndex, null);
  38370. this.group.remove(symbol);
  38371. } else {
  38372. symbol.downplay();
  38373. }
  38374. }
  38375. } else {
  38376. // FIXME
  38377. // can not downplay completely.
  38378. // Downplay whole series
  38379. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38380. }
  38381. };
  38382. LineView.prototype._changePolyState = function (toState) {
  38383. var polygon = this._polygon;
  38384. setStatesFlag(this._polyline, toState);
  38385. polygon && setStatesFlag(polygon, toState);
  38386. };
  38387. LineView.prototype._newPolyline = function (points) {
  38388. var polyline = this._polyline;
  38389. // Remove previous created polyline
  38390. if (polyline) {
  38391. this._lineGroup.remove(polyline);
  38392. }
  38393. polyline = new ECPolyline({
  38394. shape: {
  38395. points: points
  38396. },
  38397. segmentIgnoreThreshold: 2,
  38398. z2: 10
  38399. });
  38400. this._lineGroup.add(polyline);
  38401. this._polyline = polyline;
  38402. return polyline;
  38403. };
  38404. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38405. var polygon = this._polygon;
  38406. // Remove previous created polygon
  38407. if (polygon) {
  38408. this._lineGroup.remove(polygon);
  38409. }
  38410. polygon = new ECPolygon({
  38411. shape: {
  38412. points: points,
  38413. stackedOnPoints: stackedOnPoints
  38414. },
  38415. segmentIgnoreThreshold: 2
  38416. });
  38417. this._lineGroup.add(polygon);
  38418. this._polygon = polygon;
  38419. return polygon;
  38420. };
  38421. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38422. var isHorizontalOrRadial;
  38423. var isCoordSysPolar;
  38424. var baseAxis = coordSys.getBaseAxis();
  38425. var isAxisInverse = baseAxis.inverse;
  38426. if (coordSys.type === 'cartesian2d') {
  38427. isHorizontalOrRadial = baseAxis.isHorizontal();
  38428. isCoordSysPolar = false;
  38429. } else if (coordSys.type === 'polar') {
  38430. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38431. isCoordSysPolar = true;
  38432. }
  38433. var seriesModel = data.hostModel;
  38434. var seriesDuration = seriesModel.get('animationDuration');
  38435. if (isFunction(seriesDuration)) {
  38436. seriesDuration = seriesDuration(null);
  38437. }
  38438. var seriesDelay = seriesModel.get('animationDelay') || 0;
  38439. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  38440. data.eachItemGraphicEl(function (symbol, idx) {
  38441. var el = symbol;
  38442. if (el) {
  38443. var point = [symbol.x, symbol.y];
  38444. var start = void 0;
  38445. var end = void 0;
  38446. var current = void 0;
  38447. if (clipShape) {
  38448. if (isCoordSysPolar) {
  38449. var polarClip = clipShape;
  38450. var coord = coordSys.pointToCoord(point);
  38451. if (isHorizontalOrRadial) {
  38452. start = polarClip.startAngle;
  38453. end = polarClip.endAngle;
  38454. current = -coord[1] / 180 * Math.PI;
  38455. } else {
  38456. start = polarClip.r0;
  38457. end = polarClip.r;
  38458. current = coord[0];
  38459. }
  38460. } else {
  38461. var gridClip = clipShape;
  38462. if (isHorizontalOrRadial) {
  38463. start = gridClip.x;
  38464. end = gridClip.x + gridClip.width;
  38465. current = symbol.x;
  38466. } else {
  38467. start = gridClip.y + gridClip.height;
  38468. end = gridClip.y;
  38469. current = symbol.y;
  38470. }
  38471. }
  38472. }
  38473. var ratio = end === start ? 0 : (current - start) / (end - start);
  38474. if (isAxisInverse) {
  38475. ratio = 1 - ratio;
  38476. }
  38477. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  38478. var symbolPath = el.getSymbolPath();
  38479. var text = symbolPath.getTextContent();
  38480. el.attr({
  38481. scaleX: 0,
  38482. scaleY: 0
  38483. });
  38484. el.animateTo({
  38485. scaleX: 1,
  38486. scaleY: 1
  38487. }, {
  38488. duration: 200,
  38489. setToFinal: true,
  38490. delay: delay
  38491. });
  38492. if (text) {
  38493. text.animateFrom({
  38494. style: {
  38495. opacity: 0
  38496. }
  38497. }, {
  38498. duration: 300,
  38499. delay: delay
  38500. });
  38501. }
  38502. symbolPath.disableLabelAnimation = true;
  38503. }
  38504. });
  38505. };
  38506. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38507. var endLabelModel = seriesModel.getModel('endLabel');
  38508. if (anyStateShowEndLabel(seriesModel)) {
  38509. var data_2 = seriesModel.getData();
  38510. var polyline = this._polyline;
  38511. // series may be filtered.
  38512. var points = data_2.getLayout('points');
  38513. if (!points) {
  38514. polyline.removeTextContent();
  38515. this._endLabel = null;
  38516. return;
  38517. }
  38518. var endLabel = this._endLabel;
  38519. if (!endLabel) {
  38520. endLabel = this._endLabel = new ZRText({
  38521. z2: 200 // should be higher than item symbol
  38522. });
  38523. endLabel.ignoreClip = true;
  38524. polyline.setTextContent(this._endLabel);
  38525. polyline.disableLabelAnimation = true;
  38526. }
  38527. // Find last non-NaN data to display data
  38528. var dataIndex = getLastIndexNotNull(points);
  38529. if (dataIndex >= 0) {
  38530. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  38531. inheritColor: inheritColor,
  38532. labelFetcher: seriesModel,
  38533. labelDataIndex: dataIndex,
  38534. defaultText: function (dataIndex, opt, interpolatedValue) {
  38535. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  38536. },
  38537. enableTextSetter: true
  38538. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  38539. polyline.textConfig.position = null;
  38540. }
  38541. } else if (this._endLabel) {
  38542. this._polyline.removeTextContent();
  38543. this._endLabel = null;
  38544. }
  38545. };
  38546. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  38547. var endLabel = this._endLabel;
  38548. var polyline = this._polyline;
  38549. if (endLabel) {
  38550. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  38551. // The label is not prepared at this time.
  38552. if (percent < 1 && animationRecord.originalX == null) {
  38553. animationRecord.originalX = endLabel.x;
  38554. animationRecord.originalY = endLabel.y;
  38555. }
  38556. var points = data.getLayout('points');
  38557. var seriesModel = data.hostModel;
  38558. var connectNulls = seriesModel.get('connectNulls');
  38559. var precision = endLabelModel.get('precision');
  38560. var distance = endLabelModel.get('distance') || 0;
  38561. var baseAxis = coordSys.getBaseAxis();
  38562. var isHorizontal = baseAxis.isHorizontal();
  38563. var isBaseInversed = baseAxis.inverse;
  38564. var clipShape = clipRect.shape;
  38565. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  38566. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  38567. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  38568. var dim = isHorizontal ? 'x' : 'y';
  38569. var dataIndexRange = getIndexRange(points, xOrY, dim);
  38570. var indices = dataIndexRange.range;
  38571. var diff = indices[1] - indices[0];
  38572. var value = void 0;
  38573. if (diff >= 1) {
  38574. // diff > 1 && connectNulls, which is on the null data.
  38575. if (diff > 1 && !connectNulls) {
  38576. var pt = getPointAtIndex(points, indices[0]);
  38577. endLabel.attr({
  38578. x: pt[0] + distanceX,
  38579. y: pt[1] + distanceY
  38580. });
  38581. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  38582. } else {
  38583. var pt = polyline.getPointOn(xOrY, dim);
  38584. pt && endLabel.attr({
  38585. x: pt[0] + distanceX,
  38586. y: pt[1] + distanceY
  38587. });
  38588. var startValue = seriesModel.getRawValue(indices[0]);
  38589. var endValue = seriesModel.getRawValue(indices[1]);
  38590. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  38591. }
  38592. animationRecord.lastFrameIndex = indices[0];
  38593. } else {
  38594. // If diff <= 0, which is the range is not found(Include NaN)
  38595. // Choose the first point or last point.
  38596. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  38597. var pt = getPointAtIndex(points, idx);
  38598. valueAnimation && (value = seriesModel.getRawValue(idx));
  38599. endLabel.attr({
  38600. x: pt[0] + distanceX,
  38601. y: pt[1] + distanceY
  38602. });
  38603. }
  38604. if (valueAnimation) {
  38605. var inner = labelInner(endLabel);
  38606. if (typeof inner.setLabelText === 'function') {
  38607. inner.setLabelText(value);
  38608. }
  38609. }
  38610. }
  38611. };
  38612. /**
  38613. * @private
  38614. */
  38615. // FIXME Two value axis
  38616. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  38617. var polyline = this._polyline;
  38618. var polygon = this._polygon;
  38619. var seriesModel = data.hostModel;
  38620. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  38621. var current = diff.current;
  38622. var stackedOnCurrent = diff.stackedOnCurrent;
  38623. var next = diff.next;
  38624. var stackedOnNext = diff.stackedOnNext;
  38625. if (step) {
  38626. // TODO If stacked series is not step
  38627. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, diff.current, coordSys, step, connectNulls);
  38628. current = turnPointsIntoStep(diff.current, null, coordSys, step, connectNulls);
  38629. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, diff.next, coordSys, step, connectNulls);
  38630. next = turnPointsIntoStep(diff.next, null, coordSys, step, connectNulls);
  38631. }
  38632. // Don't apply animation if diff is large.
  38633. // For better result and avoid memory explosion problems like
  38634. // https://github.com/apache/incubator-echarts/issues/12229
  38635. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  38636. polyline.stopAnimation();
  38637. polyline.setShape({
  38638. points: next
  38639. });
  38640. if (polygon) {
  38641. polygon.stopAnimation();
  38642. polygon.setShape({
  38643. points: next,
  38644. stackedOnPoints: stackedOnNext
  38645. });
  38646. }
  38647. return;
  38648. }
  38649. polyline.shape.__points = diff.current;
  38650. polyline.shape.points = current;
  38651. var target = {
  38652. shape: {
  38653. points: next
  38654. }
  38655. };
  38656. // Also animate the original points.
  38657. // If points reference is changed when turning into step line.
  38658. if (diff.current !== current) {
  38659. target.shape.__points = diff.next;
  38660. }
  38661. // Stop previous animation.
  38662. polyline.stopAnimation();
  38663. updateProps(polyline, target, seriesModel);
  38664. if (polygon) {
  38665. polygon.setShape({
  38666. // Reuse the points with polyline.
  38667. points: current,
  38668. stackedOnPoints: stackedOnCurrent
  38669. });
  38670. polygon.stopAnimation();
  38671. updateProps(polygon, {
  38672. shape: {
  38673. stackedOnPoints: stackedOnNext
  38674. }
  38675. }, seriesModel);
  38676. // If use attr directly in updateProps.
  38677. if (polyline.shape.points !== polygon.shape.points) {
  38678. polygon.shape.points = polyline.shape.points;
  38679. }
  38680. }
  38681. var updatedDataInfo = [];
  38682. var diffStatus = diff.status;
  38683. for (var i = 0; i < diffStatus.length; i++) {
  38684. var cmd = diffStatus[i].cmd;
  38685. if (cmd === '=') {
  38686. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  38687. if (el) {
  38688. updatedDataInfo.push({
  38689. el: el,
  38690. ptIdx: i // Index of points
  38691. });
  38692. }
  38693. }
  38694. }
  38695. if (polyline.animators && polyline.animators.length) {
  38696. polyline.animators[0].during(function () {
  38697. polygon && polygon.dirtyShape();
  38698. var points = polyline.shape.__points;
  38699. for (var i = 0; i < updatedDataInfo.length; i++) {
  38700. var el = updatedDataInfo[i].el;
  38701. var offset = updatedDataInfo[i].ptIdx * 2;
  38702. el.x = points[offset];
  38703. el.y = points[offset + 1];
  38704. el.markRedraw();
  38705. }
  38706. });
  38707. }
  38708. };
  38709. LineView.prototype.remove = function (ecModel) {
  38710. var group = this.group;
  38711. var oldData = this._data;
  38712. this._lineGroup.removeAll();
  38713. this._symbolDraw.remove(true);
  38714. // Remove temporary created elements when highlighting
  38715. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38716. if (el.__temp) {
  38717. group.remove(el);
  38718. oldData.setItemGraphicEl(idx, null);
  38719. }
  38720. });
  38721. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  38722. };
  38723. LineView.type = 'line';
  38724. return LineView;
  38725. }(ChartView);
  38726. function pointsLayout(seriesType, forceStoreInTypedArray) {
  38727. return {
  38728. seriesType: seriesType,
  38729. plan: createRenderPlanner(),
  38730. reset: function (seriesModel) {
  38731. var data = seriesModel.getData();
  38732. var coordSys = seriesModel.coordinateSystem;
  38733. var pipelineContext = seriesModel.pipelineContext;
  38734. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  38735. if (!coordSys) {
  38736. return;
  38737. }
  38738. var dims = map(coordSys.dimensions, function (dim) {
  38739. return data.mapDimension(dim);
  38740. }).slice(0, 2);
  38741. var dimLen = dims.length;
  38742. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38743. if (isDimensionStacked(data, dims[0])) {
  38744. dims[0] = stackResultDim;
  38745. }
  38746. if (isDimensionStacked(data, dims[1])) {
  38747. dims[1] = stackResultDim;
  38748. }
  38749. var store = data.getStore();
  38750. var dimIdx0 = data.getDimensionIndex(dims[0]);
  38751. var dimIdx1 = data.getDimensionIndex(dims[1]);
  38752. return dimLen && {
  38753. progress: function (params, data) {
  38754. var segCount = params.end - params.start;
  38755. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  38756. var tmpIn = [];
  38757. var tmpOut = [];
  38758. for (var i = params.start, offset = 0; i < params.end; i++) {
  38759. var point = void 0;
  38760. if (dimLen === 1) {
  38761. var x = store.get(dimIdx0, i);
  38762. // NOTE: Make sure the second parameter is null to use default strategy.
  38763. point = coordSys.dataToPoint(x, null, tmpOut);
  38764. } else {
  38765. tmpIn[0] = store.get(dimIdx0, i);
  38766. tmpIn[1] = store.get(dimIdx1, i);
  38767. // Let coordinate system to handle the NaN data.
  38768. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  38769. }
  38770. if (useTypedArray) {
  38771. points[offset++] = point[0];
  38772. points[offset++] = point[1];
  38773. } else {
  38774. data.setItemLayout(i, point.slice());
  38775. }
  38776. }
  38777. useTypedArray && data.setLayout('points', points);
  38778. }
  38779. };
  38780. }
  38781. };
  38782. }
  38783. var samplers = {
  38784. average: function (frame) {
  38785. var sum = 0;
  38786. var count = 0;
  38787. for (var i = 0; i < frame.length; i++) {
  38788. if (!isNaN(frame[i])) {
  38789. sum += frame[i];
  38790. count++;
  38791. }
  38792. }
  38793. // Return NaN if count is 0
  38794. return count === 0 ? NaN : sum / count;
  38795. },
  38796. sum: function (frame) {
  38797. var sum = 0;
  38798. for (var i = 0; i < frame.length; i++) {
  38799. // Ignore NaN
  38800. sum += frame[i] || 0;
  38801. }
  38802. return sum;
  38803. },
  38804. max: function (frame) {
  38805. var max = -Infinity;
  38806. for (var i = 0; i < frame.length; i++) {
  38807. frame[i] > max && (max = frame[i]);
  38808. }
  38809. // NaN will cause illegal axis extent.
  38810. return isFinite(max) ? max : NaN;
  38811. },
  38812. min: function (frame) {
  38813. var min = Infinity;
  38814. for (var i = 0; i < frame.length; i++) {
  38815. frame[i] < min && (min = frame[i]);
  38816. }
  38817. // NaN will cause illegal axis extent.
  38818. return isFinite(min) ? min : NaN;
  38819. },
  38820. // TODO
  38821. // Median
  38822. nearest: function (frame) {
  38823. return frame[0];
  38824. }
  38825. };
  38826. var indexSampler = function (frame) {
  38827. return Math.round(frame.length / 2);
  38828. };
  38829. function dataSample(seriesType) {
  38830. return {
  38831. seriesType: seriesType,
  38832. // FIXME:TS never used, so comment it
  38833. // modifyOutputEnd: true,
  38834. reset: function (seriesModel, ecModel, api) {
  38835. var data = seriesModel.getData();
  38836. var sampling = seriesModel.get('sampling');
  38837. var coordSys = seriesModel.coordinateSystem;
  38838. var count = data.count();
  38839. // Only cartesian2d support down sampling. Disable it when there is few data.
  38840. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  38841. var baseAxis = coordSys.getBaseAxis();
  38842. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38843. var extent = baseAxis.getExtent();
  38844. var dpr = api.getDevicePixelRatio();
  38845. // Coordinste system has been resized
  38846. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  38847. var rate = Math.round(count / size);
  38848. if (isFinite(rate) && rate > 1) {
  38849. if (sampling === 'lttb') {
  38850. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38851. } else if (sampling === 'minmax') {
  38852. seriesModel.setData(data.minmaxDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38853. }
  38854. var sampler = void 0;
  38855. if (isString(sampling)) {
  38856. sampler = samplers[sampling];
  38857. } else if (isFunction(sampling)) {
  38858. sampler = sampling;
  38859. }
  38860. if (sampler) {
  38861. // Only support sample the first dim mapped from value axis.
  38862. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  38863. }
  38864. }
  38865. }
  38866. }
  38867. };
  38868. }
  38869. function install$2(registers) {
  38870. registers.registerChartView(LineView);
  38871. registers.registerSeriesModel(LineSeriesModel);
  38872. registers.registerLayout(pointsLayout('line', true));
  38873. registers.registerVisual({
  38874. seriesType: 'line',
  38875. reset: function (seriesModel) {
  38876. var data = seriesModel.getData();
  38877. // Visual coding for legend
  38878. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  38879. if (lineStyle && !lineStyle.stroke) {
  38880. // Fill in visual should be palette color if
  38881. // has color callback
  38882. lineStyle.stroke = data.getVisual('style').fill;
  38883. }
  38884. data.setVisual('legendLineStyle', lineStyle);
  38885. }
  38886. });
  38887. // Down sample after filter
  38888. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  38889. }
  38890. var BaseBarSeriesModel = /** @class */function (_super) {
  38891. __extends(BaseBarSeriesModel, _super);
  38892. function BaseBarSeriesModel() {
  38893. var _this = _super !== null && _super.apply(this, arguments) || this;
  38894. _this.type = BaseBarSeriesModel.type;
  38895. return _this;
  38896. }
  38897. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38898. return createSeriesData(null, this, {
  38899. useEncodeDefaulter: true
  38900. });
  38901. };
  38902. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  38903. var coordSys = this.coordinateSystem;
  38904. if (coordSys && coordSys.clampData) {
  38905. // PENDING if clamp ?
  38906. var clampData_1 = coordSys.clampData(value);
  38907. var pt_1 = coordSys.dataToPoint(clampData_1);
  38908. if (startingAtTick) {
  38909. each(coordSys.getAxes(), function (axis, idx) {
  38910. // If axis type is category, use tick coords instead
  38911. if (axis.type === 'category' && dims != null) {
  38912. var tickCoords = axis.getTicksCoords();
  38913. var alignTicksWithLabel = axis.getTickModel().get('alignWithLabel');
  38914. var targetTickId = clampData_1[idx];
  38915. // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  38916. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  38917. if (isEnd && !alignTicksWithLabel) {
  38918. targetTickId += 1;
  38919. }
  38920. // The only contains one tick, tickCoords is
  38921. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  38922. // to the length should always be larger than 1
  38923. if (tickCoords.length < 2) {
  38924. return;
  38925. } else if (tickCoords.length === 2) {
  38926. // The left value and right value of the axis are
  38927. // the same. coord is 0 in both items. Use the max
  38928. // value of the axis as the coord
  38929. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  38930. return;
  38931. }
  38932. var leftCoord = void 0;
  38933. var coord = void 0;
  38934. var stepTickValue = 1;
  38935. for (var i = 0; i < tickCoords.length; i++) {
  38936. var tickCoord = tickCoords[i].coord;
  38937. // The last item of tickCoords doesn't contain
  38938. // tickValue
  38939. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  38940. if (tickValue === targetTickId) {
  38941. coord = tickCoord;
  38942. break;
  38943. } else if (tickValue < targetTickId) {
  38944. leftCoord = tickCoord;
  38945. } else if (leftCoord != null && tickValue > targetTickId) {
  38946. coord = (tickCoord + leftCoord) / 2;
  38947. break;
  38948. }
  38949. if (i === 1) {
  38950. // Here we assume the step of category axes is
  38951. // the same
  38952. stepTickValue = tickValue - tickCoords[0].tickValue;
  38953. }
  38954. }
  38955. if (coord == null) {
  38956. if (!leftCoord) {
  38957. // targetTickId is smaller than all tick ids in the
  38958. // visible area, use the leftmost tick coord
  38959. coord = tickCoords[0].coord;
  38960. } else if (leftCoord) {
  38961. // targetTickId is larger than all tick ids in the
  38962. // visible area, use the rightmost tick coord
  38963. coord = tickCoords[tickCoords.length - 1].coord;
  38964. }
  38965. }
  38966. pt_1[idx] = axis.toGlobalCoord(coord);
  38967. }
  38968. });
  38969. } else {
  38970. var data = this.getData();
  38971. var offset = data.getLayout('offset');
  38972. var size = data.getLayout('size');
  38973. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  38974. pt_1[offsetIndex] += offset + size / 2;
  38975. }
  38976. return pt_1;
  38977. }
  38978. return [NaN, NaN];
  38979. };
  38980. BaseBarSeriesModel.type = 'series.__base_bar__';
  38981. BaseBarSeriesModel.defaultOption = {
  38982. // zlevel: 0,
  38983. z: 2,
  38984. coordinateSystem: 'cartesian2d',
  38985. legendHoverLink: true,
  38986. // stack: null
  38987. // Cartesian coordinate system
  38988. // xAxisIndex: 0,
  38989. // yAxisIndex: 0,
  38990. barMinHeight: 0,
  38991. barMinAngle: 0,
  38992. // cursor: null,
  38993. large: false,
  38994. largeThreshold: 400,
  38995. progressive: 3e3,
  38996. progressiveChunkMode: 'mod'
  38997. };
  38998. return BaseBarSeriesModel;
  38999. }(SeriesModel);
  39000. SeriesModel.registerClass(BaseBarSeriesModel);
  39001. var BarSeriesModel = /** @class */function (_super) {
  39002. __extends(BarSeriesModel, _super);
  39003. function BarSeriesModel() {
  39004. var _this = _super !== null && _super.apply(this, arguments) || this;
  39005. _this.type = BarSeriesModel.type;
  39006. return _this;
  39007. }
  39008. BarSeriesModel.prototype.getInitialData = function () {
  39009. return createSeriesData(null, this, {
  39010. useEncodeDefaulter: true,
  39011. createInvertedIndices: !!this.get('realtimeSort', true) || null
  39012. });
  39013. };
  39014. /**
  39015. * @override
  39016. */
  39017. BarSeriesModel.prototype.getProgressive = function () {
  39018. // Do not support progressive in normal mode.
  39019. return this.get('large') ? this.get('progressive') : false;
  39020. };
  39021. /**
  39022. * @override
  39023. */
  39024. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  39025. // Do not support progressive in normal mode.
  39026. var progressiveThreshold = this.get('progressiveThreshold');
  39027. var largeThreshold = this.get('largeThreshold');
  39028. if (largeThreshold > progressiveThreshold) {
  39029. progressiveThreshold = largeThreshold;
  39030. }
  39031. return progressiveThreshold;
  39032. };
  39033. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  39034. return selectors.rect(data.getItemLayout(dataIndex));
  39035. };
  39036. BarSeriesModel.type = 'series.bar';
  39037. BarSeriesModel.dependencies = ['grid', 'polar'];
  39038. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  39039. // If clipped
  39040. // Only available on cartesian2d
  39041. clip: true,
  39042. roundCap: false,
  39043. showBackground: false,
  39044. backgroundStyle: {
  39045. color: 'rgba(180, 180, 180, 0.2)',
  39046. borderColor: null,
  39047. borderWidth: 0,
  39048. borderType: 'solid',
  39049. borderRadius: 0,
  39050. shadowBlur: 0,
  39051. shadowColor: null,
  39052. shadowOffsetX: 0,
  39053. shadowOffsetY: 0,
  39054. opacity: 1
  39055. },
  39056. select: {
  39057. itemStyle: {
  39058. borderColor: '#212121'
  39059. }
  39060. },
  39061. realtimeSort: false
  39062. });
  39063. return BarSeriesModel;
  39064. }(BaseBarSeriesModel);
  39065. /**
  39066. * Sausage: similar to sector, but have half circle on both sides
  39067. */
  39068. var SausageShape = /** @class */function () {
  39069. function SausageShape() {
  39070. this.cx = 0;
  39071. this.cy = 0;
  39072. this.r0 = 0;
  39073. this.r = 0;
  39074. this.startAngle = 0;
  39075. this.endAngle = Math.PI * 2;
  39076. this.clockwise = true;
  39077. }
  39078. return SausageShape;
  39079. }();
  39080. var SausagePath = /** @class */function (_super) {
  39081. __extends(SausagePath, _super);
  39082. function SausagePath(opts) {
  39083. var _this = _super.call(this, opts) || this;
  39084. _this.type = 'sausage';
  39085. return _this;
  39086. }
  39087. SausagePath.prototype.getDefaultShape = function () {
  39088. return new SausageShape();
  39089. };
  39090. SausagePath.prototype.buildPath = function (ctx, shape) {
  39091. var cx = shape.cx;
  39092. var cy = shape.cy;
  39093. var r0 = Math.max(shape.r0 || 0, 0);
  39094. var r = Math.max(shape.r, 0);
  39095. var dr = (r - r0) * 0.5;
  39096. var rCenter = r0 + dr;
  39097. var startAngle = shape.startAngle;
  39098. var endAngle = shape.endAngle;
  39099. var clockwise = shape.clockwise;
  39100. var PI2 = Math.PI * 2;
  39101. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  39102. if (!lessThanCircle) {
  39103. // Normalize angles
  39104. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  39105. }
  39106. var unitStartX = Math.cos(startAngle);
  39107. var unitStartY = Math.sin(startAngle);
  39108. var unitEndX = Math.cos(endAngle);
  39109. var unitEndY = Math.sin(endAngle);
  39110. if (lessThanCircle) {
  39111. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  39112. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  39113. } else {
  39114. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  39115. }
  39116. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  39117. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  39118. if (r0 !== 0) {
  39119. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  39120. }
  39121. // ctx.closePath();
  39122. };
  39123. return SausagePath;
  39124. }(Path);
  39125. function createSectorCalculateTextPosition(positionMapping, opts) {
  39126. opts = opts || {};
  39127. var isRoundCap = opts.isRoundCap;
  39128. return function (out, opts, boundingRect) {
  39129. var textPosition = opts.position;
  39130. if (!textPosition || textPosition instanceof Array) {
  39131. return calculateTextPosition(out, opts, boundingRect);
  39132. }
  39133. var mappedSectorPosition = positionMapping(textPosition);
  39134. var distance = opts.distance != null ? opts.distance : 5;
  39135. var sector = this.shape;
  39136. var cx = sector.cx;
  39137. var cy = sector.cy;
  39138. var r = sector.r;
  39139. var r0 = sector.r0;
  39140. var middleR = (r + r0) / 2;
  39141. var startAngle = sector.startAngle;
  39142. var endAngle = sector.endAngle;
  39143. var middleAngle = (startAngle + endAngle) / 2;
  39144. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39145. var mathCos = Math.cos;
  39146. var mathSin = Math.sin;
  39147. // base position: top-left
  39148. var x = cx + r * mathCos(startAngle);
  39149. var y = cy + r * mathSin(startAngle);
  39150. var textAlign = 'left';
  39151. var textVerticalAlign = 'top';
  39152. switch (mappedSectorPosition) {
  39153. case 'startArc':
  39154. x = cx + (r0 - distance) * mathCos(middleAngle);
  39155. y = cy + (r0 - distance) * mathSin(middleAngle);
  39156. textAlign = 'center';
  39157. textVerticalAlign = 'top';
  39158. break;
  39159. case 'insideStartArc':
  39160. x = cx + (r0 + distance) * mathCos(middleAngle);
  39161. y = cy + (r0 + distance) * mathSin(middleAngle);
  39162. textAlign = 'center';
  39163. textVerticalAlign = 'bottom';
  39164. break;
  39165. case 'startAngle':
  39166. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39167. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39168. textAlign = 'right';
  39169. textVerticalAlign = 'middle';
  39170. break;
  39171. case 'insideStartAngle':
  39172. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39173. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39174. textAlign = 'left';
  39175. textVerticalAlign = 'middle';
  39176. break;
  39177. case 'middle':
  39178. x = cx + middleR * mathCos(middleAngle);
  39179. y = cy + middleR * mathSin(middleAngle);
  39180. textAlign = 'center';
  39181. textVerticalAlign = 'middle';
  39182. break;
  39183. case 'endArc':
  39184. x = cx + (r + distance) * mathCos(middleAngle);
  39185. y = cy + (r + distance) * mathSin(middleAngle);
  39186. textAlign = 'center';
  39187. textVerticalAlign = 'bottom';
  39188. break;
  39189. case 'insideEndArc':
  39190. x = cx + (r - distance) * mathCos(middleAngle);
  39191. y = cy + (r - distance) * mathSin(middleAngle);
  39192. textAlign = 'center';
  39193. textVerticalAlign = 'top';
  39194. break;
  39195. case 'endAngle':
  39196. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39197. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39198. textAlign = 'left';
  39199. textVerticalAlign = 'middle';
  39200. break;
  39201. case 'insideEndAngle':
  39202. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39203. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39204. textAlign = 'right';
  39205. textVerticalAlign = 'middle';
  39206. break;
  39207. default:
  39208. return calculateTextPosition(out, opts, boundingRect);
  39209. }
  39210. out = out || {};
  39211. out.x = x;
  39212. out.y = y;
  39213. out.align = textAlign;
  39214. out.verticalAlign = textVerticalAlign;
  39215. return out;
  39216. };
  39217. }
  39218. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39219. if (isNumber(rotateType)) {
  39220. // user-set rotation
  39221. sector.setTextConfig({
  39222. rotation: rotateType
  39223. });
  39224. return;
  39225. } else if (isArray(textPosition)) {
  39226. // user-set position, use 0 as auto rotation
  39227. sector.setTextConfig({
  39228. rotation: 0
  39229. });
  39230. return;
  39231. }
  39232. var shape = sector.shape;
  39233. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39234. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39235. var middleAngle = (startAngle + endAngle) / 2;
  39236. var anchorAngle;
  39237. var mappedSectorPosition = positionMapping(textPosition);
  39238. switch (mappedSectorPosition) {
  39239. case 'startArc':
  39240. case 'insideStartArc':
  39241. case 'middle':
  39242. case 'insideEndArc':
  39243. case 'endArc':
  39244. anchorAngle = middleAngle;
  39245. break;
  39246. case 'startAngle':
  39247. case 'insideStartAngle':
  39248. anchorAngle = startAngle;
  39249. break;
  39250. case 'endAngle':
  39251. case 'insideEndAngle':
  39252. anchorAngle = endAngle;
  39253. break;
  39254. default:
  39255. sector.setTextConfig({
  39256. rotation: 0
  39257. });
  39258. return;
  39259. }
  39260. var rotate = Math.PI * 1.5 - anchorAngle;
  39261. /**
  39262. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39263. * half round flipped to increase readability. However, only middle
  39264. * position supports this for now, because in other positions, the
  39265. * anchor point is not at the center of the text, so the positions
  39266. * after rotating is not as expected.
  39267. */
  39268. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39269. rotate -= Math.PI;
  39270. }
  39271. sector.setTextConfig({
  39272. rotation: rotate
  39273. });
  39274. }
  39275. function adjustAngleDistanceX(angle, distance, isEnd) {
  39276. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39277. }
  39278. function adjustAngleDistanceY(angle, distance, isEnd) {
  39279. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39280. }
  39281. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39282. var cornerRadius = model.get('borderRadius');
  39283. if (cornerRadius == null) {
  39284. return zeroIfNull ? {
  39285. cornerRadius: 0
  39286. } : null;
  39287. }
  39288. if (!isArray(cornerRadius)) {
  39289. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39290. }
  39291. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39292. return {
  39293. cornerRadius: map(cornerRadius, function (cr) {
  39294. return parsePercent(cr, dr);
  39295. })
  39296. };
  39297. }
  39298. var mathMax$6 = Math.max;
  39299. var mathMin$6 = Math.min;
  39300. function getClipArea(coord, data) {
  39301. var coordSysClipArea = coord.getArea && coord.getArea();
  39302. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39303. var baseAxis = coord.getBaseAxis();
  39304. // When boundaryGap is false or using time axis. bar may exceed the grid.
  39305. // We should not clip this part.
  39306. // See test/bar2.html
  39307. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39308. var expandWidth = data.getLayout('bandWidth');
  39309. if (baseAxis.isHorizontal()) {
  39310. coordSysClipArea.x -= expandWidth;
  39311. coordSysClipArea.width += expandWidth * 2;
  39312. } else {
  39313. coordSysClipArea.y -= expandWidth;
  39314. coordSysClipArea.height += expandWidth * 2;
  39315. }
  39316. }
  39317. }
  39318. return coordSysClipArea;
  39319. }
  39320. var BarView = /** @class */function (_super) {
  39321. __extends(BarView, _super);
  39322. function BarView() {
  39323. var _this = _super.call(this) || this;
  39324. _this.type = BarView.type;
  39325. _this._isFirstFrame = true;
  39326. return _this;
  39327. }
  39328. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39329. this._model = seriesModel;
  39330. this._removeOnRenderedListener(api);
  39331. this._updateDrawMode(seriesModel);
  39332. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39333. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39334. // Clear previously rendered progressive elements.
  39335. this._progressiveEls = null;
  39336. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39337. } else if ("development" !== 'production') {
  39338. warn('Only cartesian2d and polar supported for bar.');
  39339. }
  39340. };
  39341. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39342. this._clear();
  39343. this._updateDrawMode(seriesModel);
  39344. // incremental also need to clip, otherwise might be overlow.
  39345. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39346. this._updateLargeClip(seriesModel);
  39347. };
  39348. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39349. // Reset
  39350. this._progressiveEls = [];
  39351. // Do not support progressive in normal mode.
  39352. this._incrementalRenderLarge(params, seriesModel);
  39353. };
  39354. BarView.prototype.eachRendered = function (cb) {
  39355. traverseElements(this._progressiveEls || this.group, cb);
  39356. };
  39357. BarView.prototype._updateDrawMode = function (seriesModel) {
  39358. var isLargeDraw = seriesModel.pipelineContext.large;
  39359. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39360. this._isLargeDraw = isLargeDraw;
  39361. this._clear();
  39362. }
  39363. };
  39364. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39365. var group = this.group;
  39366. var data = seriesModel.getData();
  39367. var oldData = this._data;
  39368. var coord = seriesModel.coordinateSystem;
  39369. var baseAxis = coord.getBaseAxis();
  39370. var isHorizontalOrRadial;
  39371. if (coord.type === 'cartesian2d') {
  39372. isHorizontalOrRadial = baseAxis.isHorizontal();
  39373. } else if (coord.type === 'polar') {
  39374. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39375. }
  39376. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39377. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39378. if (realtimeSortCfg) {
  39379. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39380. }
  39381. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39382. var coordSysClipArea = getClipArea(coord, data);
  39383. // If there is clipPath created in large mode. Remove it.
  39384. group.removeClipPath();
  39385. // We don't use clipPath in normal mode because we needs a perfect animation
  39386. // And don't want the label are clipped.
  39387. var roundCap = seriesModel.get('roundCap', true);
  39388. var drawBackground = seriesModel.get('showBackground', true);
  39389. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39390. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39391. var bgEls = [];
  39392. var oldBgEls = this._backgroundEls;
  39393. var isInitSort = payload && payload.isInitSort;
  39394. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39395. function createBackground(dataIndex) {
  39396. var bgLayout = getLayout[coord.type](data, dataIndex);
  39397. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39398. bgEl.useStyle(backgroundModel.getItemStyle());
  39399. // Only cartesian2d support borderRadius.
  39400. if (coord.type === 'cartesian2d') {
  39401. bgEl.setShape('r', barBorderRadius);
  39402. } else {
  39403. bgEl.setShape('cornerRadius', barBorderRadius);
  39404. }
  39405. bgEls[dataIndex] = bgEl;
  39406. return bgEl;
  39407. }
  39408. data.diff(oldData).add(function (dataIndex) {
  39409. var itemModel = data.getItemModel(dataIndex);
  39410. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39411. if (drawBackground) {
  39412. createBackground(dataIndex);
  39413. }
  39414. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39415. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39416. return;
  39417. }
  39418. var isClipped = false;
  39419. if (needsClip) {
  39420. // Clip will modify the layout params.
  39421. // And return a boolean to determine if the shape are fully clipped.
  39422. isClipped = clip[coord.type](coordSysClipArea, layout);
  39423. }
  39424. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39425. if (realtimeSortCfg) {
  39426. /**
  39427. * Force label animation because even if the element is
  39428. * ignored because it's clipped, it may not be clipped after
  39429. * changing order. Then, if not using forceLabelAnimation,
  39430. * the label animation was never started, in which case,
  39431. * the label will be the final value and doesn't have label
  39432. * animation.
  39433. */
  39434. el.forceLabelAnimation = true;
  39435. }
  39436. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39437. if (isInitSort) {
  39438. el.attr({
  39439. shape: layout
  39440. });
  39441. } else if (realtimeSortCfg) {
  39442. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39443. } else {
  39444. initProps(el, {
  39445. shape: layout
  39446. }, seriesModel, dataIndex);
  39447. }
  39448. data.setItemGraphicEl(dataIndex, el);
  39449. group.add(el);
  39450. el.ignore = isClipped;
  39451. }).update(function (newIndex, oldIndex) {
  39452. var itemModel = data.getItemModel(newIndex);
  39453. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39454. if (drawBackground) {
  39455. var bgEl = void 0;
  39456. if (oldBgEls.length === 0) {
  39457. bgEl = createBackground(oldIndex);
  39458. } else {
  39459. bgEl = oldBgEls[oldIndex];
  39460. bgEl.useStyle(backgroundModel.getItemStyle());
  39461. // Only cartesian2d support borderRadius.
  39462. if (coord.type === 'cartesian2d') {
  39463. bgEl.setShape('r', barBorderRadius);
  39464. } else {
  39465. bgEl.setShape('cornerRadius', barBorderRadius);
  39466. }
  39467. bgEls[newIndex] = bgEl;
  39468. }
  39469. var bgLayout = getLayout[coord.type](data, newIndex);
  39470. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39471. updateProps(bgEl, {
  39472. shape: shape
  39473. }, animationModel, newIndex);
  39474. }
  39475. var el = oldData.getItemGraphicEl(oldIndex);
  39476. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39477. group.remove(el);
  39478. return;
  39479. }
  39480. var isClipped = false;
  39481. if (needsClip) {
  39482. isClipped = clip[coord.type](coordSysClipArea, layout);
  39483. if (isClipped) {
  39484. group.remove(el);
  39485. }
  39486. }
  39487. if (!el) {
  39488. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39489. } else {
  39490. saveOldStyle(el);
  39491. }
  39492. if (realtimeSortCfg) {
  39493. el.forceLabelAnimation = true;
  39494. }
  39495. if (isChangeOrder) {
  39496. var textEl = el.getTextContent();
  39497. if (textEl) {
  39498. var labelInnerStore = labelInner(textEl);
  39499. if (labelInnerStore.prevValue != null) {
  39500. /**
  39501. * Set preValue to be value so that no new label
  39502. * should be started, otherwise, it will take a full
  39503. * `animationDurationUpdate` time to finish the
  39504. * animation, which is not expected.
  39505. */
  39506. labelInnerStore.prevValue = labelInnerStore.value;
  39507. }
  39508. }
  39509. }
  39510. // Not change anything if only order changed.
  39511. // Especially not change label.
  39512. else {
  39513. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39514. }
  39515. if (isInitSort) {
  39516. el.attr({
  39517. shape: layout
  39518. });
  39519. } else if (realtimeSortCfg) {
  39520. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39521. } else {
  39522. updateProps(el, {
  39523. shape: layout
  39524. }, seriesModel, newIndex, null);
  39525. }
  39526. data.setItemGraphicEl(newIndex, el);
  39527. el.ignore = isClipped;
  39528. group.add(el);
  39529. }).remove(function (dataIndex) {
  39530. var el = oldData.getItemGraphicEl(dataIndex);
  39531. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39532. }).execute();
  39533. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39534. bgGroup.removeAll();
  39535. for (var i = 0; i < bgEls.length; ++i) {
  39536. bgGroup.add(bgEls[i]);
  39537. }
  39538. group.add(bgGroup);
  39539. this._backgroundEls = bgEls;
  39540. this._data = data;
  39541. };
  39542. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39543. this._clear();
  39544. createLarge(seriesModel, this.group);
  39545. this._updateLargeClip(seriesModel);
  39546. };
  39547. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39548. this._removeBackground();
  39549. createLarge(seriesModel, this.group, this._progressiveEls, true);
  39550. };
  39551. BarView.prototype._updateLargeClip = function (seriesModel) {
  39552. // Use clipPath in large mode.
  39553. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  39554. var group = this.group;
  39555. if (clipPath) {
  39556. group.setClipPath(clipPath);
  39557. } else {
  39558. group.removeClipPath();
  39559. }
  39560. };
  39561. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39562. var _this = this;
  39563. // If no data in the first frame, wait for data to initSort
  39564. if (!data.count()) {
  39565. return;
  39566. }
  39567. var baseAxis = realtimeSortCfg.baseAxis;
  39568. if (this._isFirstFrame) {
  39569. this._dispatchInitSort(data, realtimeSortCfg, api);
  39570. this._isFirstFrame = false;
  39571. } else {
  39572. var orderMapping_1 = function (idx) {
  39573. var el = data.getItemGraphicEl(idx);
  39574. var shape = el && el.shape;
  39575. return shape &&
  39576. // The result should be consistent with the initial sort by data value.
  39577. // Do not support the case that both positive and negative exist.
  39578. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width)
  39579. // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39580. || 0;
  39581. };
  39582. this._onRendered = function () {
  39583. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39584. };
  39585. api.getZr().on('rendered', this._onRendered);
  39586. }
  39587. };
  39588. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39589. var info = [];
  39590. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39591. var mappedValue = orderMapping(dataIdx);
  39592. mappedValue = mappedValue == null ? NaN : mappedValue;
  39593. info.push({
  39594. dataIndex: dataIdx,
  39595. mappedValue: mappedValue,
  39596. ordinalNumber: ordinalNumber
  39597. });
  39598. });
  39599. info.sort(function (a, b) {
  39600. // If NaN, it will be treated as min val.
  39601. return b.mappedValue - a.mappedValue;
  39602. });
  39603. return {
  39604. ordinalNumbers: map(info, function (item) {
  39605. return item.ordinalNumber;
  39606. })
  39607. };
  39608. };
  39609. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39610. var scale = baseAxis.scale;
  39611. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39612. var lastValue = Number.MAX_VALUE;
  39613. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39614. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39615. var value = rawIdx < 0
  39616. // If some tick have no bar, the tick will be treated as min.
  39617. ? Number.MIN_VALUE
  39618. // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39619. : orderMapping(data.indexOfRawIndex(rawIdx));
  39620. if (value > lastValue) {
  39621. return true;
  39622. }
  39623. lastValue = value;
  39624. }
  39625. return false;
  39626. };
  39627. /*
  39628. * Consider the case when A and B changed order, whose representing
  39629. * bars are both out of sight, we don't wish to trigger reorder action
  39630. * as long as the order in the view doesn't change.
  39631. */
  39632. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  39633. var scale = baseAxis.scale;
  39634. var extent = scale.getExtent();
  39635. var tickNum = Math.max(0, extent[0]);
  39636. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  39637. for (; tickNum <= tickMax; ++tickNum) {
  39638. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  39639. return true;
  39640. }
  39641. }
  39642. };
  39643. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  39644. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  39645. return;
  39646. }
  39647. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  39648. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  39649. this._removeOnRenderedListener(api);
  39650. api.dispatchAction({
  39651. type: 'changeAxisOrder',
  39652. componentType: baseAxis.dim + 'Axis',
  39653. axisId: baseAxis.index,
  39654. sortInfo: sortInfo
  39655. });
  39656. }
  39657. };
  39658. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  39659. var baseAxis = realtimeSortCfg.baseAxis;
  39660. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  39661. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  39662. });
  39663. api.dispatchAction({
  39664. type: 'changeAxisOrder',
  39665. componentType: baseAxis.dim + 'Axis',
  39666. isInitSort: true,
  39667. axisId: baseAxis.index,
  39668. sortInfo: sortResult
  39669. });
  39670. };
  39671. BarView.prototype.remove = function (ecModel, api) {
  39672. this._clear(this._model);
  39673. this._removeOnRenderedListener(api);
  39674. };
  39675. BarView.prototype.dispose = function (ecModel, api) {
  39676. this._removeOnRenderedListener(api);
  39677. };
  39678. BarView.prototype._removeOnRenderedListener = function (api) {
  39679. if (this._onRendered) {
  39680. api.getZr().off('rendered', this._onRendered);
  39681. this._onRendered = null;
  39682. }
  39683. };
  39684. BarView.prototype._clear = function (model) {
  39685. var group = this.group;
  39686. var data = this._data;
  39687. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  39688. this._removeBackground();
  39689. this._backgroundEls = [];
  39690. data.eachItemGraphicEl(function (el) {
  39691. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  39692. });
  39693. } else {
  39694. group.removeAll();
  39695. }
  39696. this._data = null;
  39697. this._isFirstFrame = true;
  39698. };
  39699. BarView.prototype._removeBackground = function () {
  39700. this.group.remove(this._backgroundGroup);
  39701. this._backgroundGroup = null;
  39702. };
  39703. BarView.type = 'bar';
  39704. return BarView;
  39705. }(ChartView);
  39706. var clip = {
  39707. cartesian2d: function (coordSysBoundingRect, layout) {
  39708. var signWidth = layout.width < 0 ? -1 : 1;
  39709. var signHeight = layout.height < 0 ? -1 : 1;
  39710. // Needs positive width and height
  39711. if (signWidth < 0) {
  39712. layout.x += layout.width;
  39713. layout.width = -layout.width;
  39714. }
  39715. if (signHeight < 0) {
  39716. layout.y += layout.height;
  39717. layout.height = -layout.height;
  39718. }
  39719. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  39720. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  39721. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  39722. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  39723. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  39724. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  39725. var xClipped = x2 < x;
  39726. var yClipped = y2 < y;
  39727. // When xClipped or yClipped, the element will be marked as `ignore`.
  39728. // But we should also place the element at the edge of the coord sys bounding rect.
  39729. // Because if data changed and the bar shows again, its transition animation
  39730. // will begin at this place.
  39731. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  39732. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  39733. layout.width = xClipped ? 0 : x2 - x;
  39734. layout.height = yClipped ? 0 : y2 - y;
  39735. // Reverse back
  39736. if (signWidth < 0) {
  39737. layout.x += layout.width;
  39738. layout.width = -layout.width;
  39739. }
  39740. if (signHeight < 0) {
  39741. layout.y += layout.height;
  39742. layout.height = -layout.height;
  39743. }
  39744. return xClipped || yClipped;
  39745. },
  39746. polar: function (coordSysClipArea, layout) {
  39747. var signR = layout.r0 <= layout.r ? 1 : -1;
  39748. // Make sure r is larger than r0
  39749. if (signR < 0) {
  39750. var tmp = layout.r;
  39751. layout.r = layout.r0;
  39752. layout.r0 = tmp;
  39753. }
  39754. var r = mathMin$6(layout.r, coordSysClipArea.r);
  39755. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  39756. layout.r = r;
  39757. layout.r0 = r0;
  39758. var clipped = r - r0 < 0;
  39759. // Reverse back
  39760. if (signR < 0) {
  39761. var tmp = layout.r;
  39762. layout.r = layout.r0;
  39763. layout.r0 = tmp;
  39764. }
  39765. return clipped;
  39766. }
  39767. };
  39768. var elementCreator = {
  39769. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  39770. var rect = new Rect({
  39771. shape: extend({}, layout),
  39772. z2: 1
  39773. });
  39774. rect.__dataIndex = newIndex;
  39775. rect.name = 'item';
  39776. if (animationModel) {
  39777. var rectShape = rect.shape;
  39778. var animateProperty = isHorizontal ? 'height' : 'width';
  39779. rectShape[animateProperty] = 0;
  39780. }
  39781. return rect;
  39782. },
  39783. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  39784. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  39785. var sector = new ShapeClass({
  39786. shape: layout,
  39787. z2: 1
  39788. });
  39789. sector.name = 'item';
  39790. var positionMap = createPolarPositionMapping(isRadial);
  39791. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  39792. isRoundCap: ShapeClass === SausagePath
  39793. });
  39794. // Animation
  39795. if (animationModel) {
  39796. var sectorShape = sector.shape;
  39797. var animateProperty = isRadial ? 'r' : 'endAngle';
  39798. var animateTarget = {};
  39799. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  39800. animateTarget[animateProperty] = layout[animateProperty];
  39801. (isUpdate ? updateProps : initProps)(sector, {
  39802. shape: animateTarget
  39803. // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  39804. }, animationModel);
  39805. }
  39806. return sector;
  39807. }
  39808. };
  39809. function shouldRealtimeSort(seriesModel, coordSys) {
  39810. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  39811. var baseAxis = coordSys.getBaseAxis();
  39812. if ("development" !== 'production') {
  39813. if (realtimeSortOption) {
  39814. if (baseAxis.type !== 'category') {
  39815. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  39816. }
  39817. if (coordSys.type !== 'cartesian2d') {
  39818. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  39819. }
  39820. }
  39821. }
  39822. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  39823. return {
  39824. baseAxis: baseAxis,
  39825. otherAxis: coordSys.getOtherAxis(baseAxis)
  39826. };
  39827. }
  39828. }
  39829. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  39830. var seriesTarget;
  39831. var axisTarget;
  39832. if (isHorizontal) {
  39833. axisTarget = {
  39834. x: layout.x,
  39835. width: layout.width
  39836. };
  39837. seriesTarget = {
  39838. y: layout.y,
  39839. height: layout.height
  39840. };
  39841. } else {
  39842. axisTarget = {
  39843. y: layout.y,
  39844. height: layout.height
  39845. };
  39846. seriesTarget = {
  39847. x: layout.x,
  39848. width: layout.width
  39849. };
  39850. }
  39851. if (!isChangeOrder) {
  39852. // Keep the original growth animation if only axis order changed.
  39853. // Not start a new animation.
  39854. (isUpdate ? updateProps : initProps)(el, {
  39855. shape: seriesTarget
  39856. }, seriesAnimationModel, newIndex, null);
  39857. }
  39858. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  39859. (isUpdate ? updateProps : initProps)(el, {
  39860. shape: axisTarget
  39861. }, axisAnimationModel, newIndex);
  39862. }
  39863. function checkPropertiesNotValid(obj, props) {
  39864. for (var i = 0; i < props.length; i++) {
  39865. if (!isFinite(obj[props[i]])) {
  39866. return true;
  39867. }
  39868. }
  39869. return false;
  39870. }
  39871. var rectPropties = ['x', 'y', 'width', 'height'];
  39872. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  39873. var isValidLayout = {
  39874. cartesian2d: function (layout) {
  39875. return !checkPropertiesNotValid(layout, rectPropties);
  39876. },
  39877. polar: function (layout) {
  39878. return !checkPropertiesNotValid(layout, polarPropties);
  39879. }
  39880. };
  39881. var getLayout = {
  39882. // itemModel is only used to get borderWidth, which is not needed
  39883. // when calculating bar background layout.
  39884. cartesian2d: function (data, dataIndex, itemModel) {
  39885. var layout = data.getItemLayout(dataIndex);
  39886. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  39887. // fix layout with lineWidth
  39888. var signX = layout.width > 0 ? 1 : -1;
  39889. var signY = layout.height > 0 ? 1 : -1;
  39890. return {
  39891. x: layout.x + signX * fixedLineWidth / 2,
  39892. y: layout.y + signY * fixedLineWidth / 2,
  39893. width: layout.width - signX * fixedLineWidth,
  39894. height: layout.height - signY * fixedLineWidth
  39895. };
  39896. },
  39897. polar: function (data, dataIndex, itemModel) {
  39898. var layout = data.getItemLayout(dataIndex);
  39899. return {
  39900. cx: layout.cx,
  39901. cy: layout.cy,
  39902. r0: layout.r0,
  39903. r: layout.r,
  39904. startAngle: layout.startAngle,
  39905. endAngle: layout.endAngle,
  39906. clockwise: layout.clockwise
  39907. };
  39908. }
  39909. };
  39910. function isZeroOnPolar(layout) {
  39911. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  39912. }
  39913. function createPolarPositionMapping(isRadial) {
  39914. return function (isRadial) {
  39915. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  39916. return function (position) {
  39917. switch (position) {
  39918. case 'start':
  39919. case 'insideStart':
  39920. case 'end':
  39921. case 'insideEnd':
  39922. return position + arcOrAngle;
  39923. default:
  39924. return position;
  39925. }
  39926. };
  39927. }(isRadial);
  39928. }
  39929. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  39930. var style = data.getItemVisual(dataIndex, 'style');
  39931. if (!isPolar) {
  39932. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  39933. el.setShape('r', borderRadius);
  39934. } else if (!seriesModel.get('roundCap')) {
  39935. var sectorShape = el.shape;
  39936. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  39937. extend(sectorShape, cornerRadius);
  39938. el.setShape(sectorShape);
  39939. }
  39940. el.useStyle(style);
  39941. var cursorStyle = itemModel.getShallow('cursor');
  39942. cursorStyle && el.attr('cursor', cursorStyle);
  39943. var labelPositionOutside = isPolar ? isHorizontalOrRadial ? layout.r >= layout.r0 ? 'endArc' : 'startArc' : layout.endAngle >= layout.startAngle ? 'endAngle' : 'startAngle' : isHorizontalOrRadial ? layout.height >= 0 ? 'bottom' : 'top' : layout.width >= 0 ? 'right' : 'left';
  39944. var labelStatesModels = getLabelStatesModels(itemModel);
  39945. setLabelStyle(el, labelStatesModels, {
  39946. labelFetcher: seriesModel,
  39947. labelDataIndex: dataIndex,
  39948. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  39949. inheritColor: style.fill,
  39950. defaultOpacity: style.opacity,
  39951. defaultOutsidePosition: labelPositionOutside
  39952. });
  39953. var label = el.getTextContent();
  39954. if (isPolar && label) {
  39955. var position = itemModel.get(['label', 'position']);
  39956. el.textConfig.inside = position === 'middle' ? true : null;
  39957. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  39958. }
  39959. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  39960. return getDefaultInterpolatedLabel(data, value);
  39961. });
  39962. var emphasisModel = itemModel.getModel(['emphasis']);
  39963. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39964. setStatesStylesFromModel(el, itemModel);
  39965. if (isZeroOnPolar(layout)) {
  39966. el.style.fill = 'none';
  39967. el.style.stroke = 'none';
  39968. each(el.states, function (state) {
  39969. if (state.style) {
  39970. state.style.fill = state.style.stroke = 'none';
  39971. }
  39972. });
  39973. }
  39974. }
  39975. // In case width or height are too small.
  39976. function getLineWidth(itemModel, rawLayout) {
  39977. // Has no border.
  39978. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  39979. if (!borderColor || borderColor === 'none') {
  39980. return 0;
  39981. }
  39982. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0;
  39983. // width or height may be NaN for empty data
  39984. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  39985. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  39986. return Math.min(lineWidth, width, height);
  39987. }
  39988. var LagePathShape = /** @class */function () {
  39989. function LagePathShape() {}
  39990. return LagePathShape;
  39991. }();
  39992. var LargePath = /** @class */function (_super) {
  39993. __extends(LargePath, _super);
  39994. function LargePath(opts) {
  39995. var _this = _super.call(this, opts) || this;
  39996. _this.type = 'largeBar';
  39997. return _this;
  39998. }
  39999. LargePath.prototype.getDefaultShape = function () {
  40000. return new LagePathShape();
  40001. };
  40002. LargePath.prototype.buildPath = function (ctx, shape) {
  40003. // Drawing lines is more efficient than drawing
  40004. // a whole line or drawing rects.
  40005. var points = shape.points;
  40006. var baseDimIdx = this.baseDimIdx;
  40007. var valueDimIdx = 1 - this.baseDimIdx;
  40008. var startPoint = [];
  40009. var size = [];
  40010. var barWidth = this.barWidth;
  40011. for (var i = 0; i < points.length; i += 3) {
  40012. size[baseDimIdx] = barWidth;
  40013. size[valueDimIdx] = points[i + 2];
  40014. startPoint[baseDimIdx] = points[i + baseDimIdx];
  40015. startPoint[valueDimIdx] = points[i + valueDimIdx];
  40016. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  40017. }
  40018. };
  40019. return LargePath;
  40020. }(Path);
  40021. function createLarge(seriesModel, group, progressiveEls, incremental) {
  40022. // TODO support polar
  40023. var data = seriesModel.getData();
  40024. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  40025. var largeDataIndices = data.getLayout('largeDataIndices');
  40026. var barWidth = data.getLayout('size');
  40027. var backgroundModel = seriesModel.getModel('backgroundStyle');
  40028. var bgPoints = data.getLayout('largeBackgroundPoints');
  40029. if (bgPoints) {
  40030. var bgEl = new LargePath({
  40031. shape: {
  40032. points: bgPoints
  40033. },
  40034. incremental: !!incremental,
  40035. silent: true,
  40036. z2: 0
  40037. });
  40038. bgEl.baseDimIdx = baseDimIdx;
  40039. bgEl.largeDataIndices = largeDataIndices;
  40040. bgEl.barWidth = barWidth;
  40041. bgEl.useStyle(backgroundModel.getItemStyle());
  40042. group.add(bgEl);
  40043. progressiveEls && progressiveEls.push(bgEl);
  40044. }
  40045. var el = new LargePath({
  40046. shape: {
  40047. points: data.getLayout('largePoints')
  40048. },
  40049. incremental: !!incremental,
  40050. ignoreCoarsePointer: true,
  40051. z2: 1
  40052. });
  40053. el.baseDimIdx = baseDimIdx;
  40054. el.largeDataIndices = largeDataIndices;
  40055. el.barWidth = barWidth;
  40056. group.add(el);
  40057. el.useStyle(data.getVisual('style'));
  40058. // Stroke is rendered first to avoid overlapping with fill
  40059. el.style.stroke = null;
  40060. // Enable tooltip and user mouse/touch event handlers.
  40061. getECData(el).seriesIndex = seriesModel.seriesIndex;
  40062. if (!seriesModel.get('silent')) {
  40063. el.on('mousedown', largePathUpdateDataIndex);
  40064. el.on('mousemove', largePathUpdateDataIndex);
  40065. }
  40066. progressiveEls && progressiveEls.push(el);
  40067. }
  40068. // Use throttle to avoid frequently traverse to find dataIndex.
  40069. var largePathUpdateDataIndex = throttle(function (event) {
  40070. var largePath = this;
  40071. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  40072. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  40073. }, 30, false);
  40074. function largePathFindDataIndex(largePath, x, y) {
  40075. var baseDimIdx = largePath.baseDimIdx;
  40076. var valueDimIdx = 1 - baseDimIdx;
  40077. var points = largePath.shape.points;
  40078. var largeDataIndices = largePath.largeDataIndices;
  40079. var startPoint = [];
  40080. var size = [];
  40081. var barWidth = largePath.barWidth;
  40082. for (var i = 0, len = points.length / 3; i < len; i++) {
  40083. var ii = i * 3;
  40084. size[baseDimIdx] = barWidth;
  40085. size[valueDimIdx] = points[ii + 2];
  40086. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  40087. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  40088. if (size[valueDimIdx] < 0) {
  40089. startPoint[valueDimIdx] += size[valueDimIdx];
  40090. size[valueDimIdx] = -size[valueDimIdx];
  40091. }
  40092. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  40093. return largeDataIndices[i];
  40094. }
  40095. }
  40096. return -1;
  40097. }
  40098. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  40099. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  40100. var rectShape = layout;
  40101. var coordLayout = coord.getArea();
  40102. return {
  40103. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  40104. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  40105. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  40106. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  40107. };
  40108. } else {
  40109. var coordLayout = coord.getArea();
  40110. var sectorShape = layout;
  40111. return {
  40112. cx: coordLayout.cx,
  40113. cy: coordLayout.cy,
  40114. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  40115. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  40116. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  40117. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  40118. };
  40119. }
  40120. }
  40121. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  40122. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  40123. return new ElementClz({
  40124. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  40125. silent: true,
  40126. z2: 0
  40127. });
  40128. }
  40129. function install$3(registers) {
  40130. registers.registerChartView(BarView);
  40131. registers.registerSeriesModel(BarSeriesModel);
  40132. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  40133. // Do layout after other overall layout, which can prepare some information.
  40134. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar'));
  40135. // Down sample after filter
  40136. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  40137. /**
  40138. * @payload
  40139. * @property {string} [componentType=series]
  40140. * @property {number} [dx]
  40141. * @property {number} [dy]
  40142. * @property {number} [zoom]
  40143. * @property {number} [originX]
  40144. * @property {number} [originY]
  40145. */
  40146. registers.registerAction({
  40147. type: 'changeAxisOrder',
  40148. event: 'changeAxisOrder',
  40149. update: 'update'
  40150. }, function (payload, ecModel) {
  40151. var componentType = payload.componentType || 'series';
  40152. ecModel.eachComponent({
  40153. mainType: componentType,
  40154. query: payload
  40155. }, function (componentModel) {
  40156. if (payload.sortInfo) {
  40157. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40158. }
  40159. });
  40160. });
  40161. }
  40162. var PI2$7 = Math.PI * 2;
  40163. var RADIAN = Math.PI / 180;
  40164. function getViewRect(seriesModel, api) {
  40165. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40166. width: api.getWidth(),
  40167. height: api.getHeight()
  40168. });
  40169. }
  40170. function getBasicPieLayout(seriesModel, api) {
  40171. var viewRect = getViewRect(seriesModel, api);
  40172. // center can be string or number when coordinateSystem is specified
  40173. var center = seriesModel.get('center');
  40174. var radius = seriesModel.get('radius');
  40175. if (!isArray(radius)) {
  40176. radius = [0, radius];
  40177. }
  40178. var width = parsePercent$1(viewRect.width, api.getWidth());
  40179. var height = parsePercent$1(viewRect.height, api.getHeight());
  40180. var size = Math.min(width, height);
  40181. var r0 = parsePercent$1(radius[0], size / 2);
  40182. var r = parsePercent$1(radius[1], size / 2);
  40183. var cx;
  40184. var cy;
  40185. var coordSys = seriesModel.coordinateSystem;
  40186. if (coordSys) {
  40187. // percentage is not allowed when coordinate system is specified
  40188. var point = coordSys.dataToPoint(center);
  40189. cx = point[0] || 0;
  40190. cy = point[1] || 0;
  40191. } else {
  40192. if (!isArray(center)) {
  40193. center = [center, center];
  40194. }
  40195. cx = parsePercent$1(center[0], width) + viewRect.x;
  40196. cy = parsePercent$1(center[1], height) + viewRect.y;
  40197. }
  40198. return {
  40199. cx: cx,
  40200. cy: cy,
  40201. r0: r0,
  40202. r: r
  40203. };
  40204. }
  40205. function pieLayout(seriesType, ecModel, api) {
  40206. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40207. var data = seriesModel.getData();
  40208. var valueDim = data.mapDimension('value');
  40209. var viewRect = getViewRect(seriesModel, api);
  40210. var _a = getBasicPieLayout(seriesModel, api),
  40211. cx = _a.cx,
  40212. cy = _a.cy,
  40213. r = _a.r,
  40214. r0 = _a.r0;
  40215. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40216. var endAngle = seriesModel.get('endAngle');
  40217. var padAngle = seriesModel.get('padAngle') * RADIAN;
  40218. endAngle = endAngle === 'auto' ? startAngle - PI2$7 : -endAngle * RADIAN;
  40219. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40220. var minAndPadAngle = minAngle + padAngle;
  40221. var validDataCount = 0;
  40222. data.each(valueDim, function (value) {
  40223. !isNaN(value) && validDataCount++;
  40224. });
  40225. var sum = data.getSum(valueDim);
  40226. // Sum may be 0
  40227. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40228. var clockwise = seriesModel.get('clockwise');
  40229. var roseType = seriesModel.get('roseType');
  40230. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  40231. // [0...max]
  40232. var extent = data.getDataExtent(valueDim);
  40233. extent[0] = 0;
  40234. var dir = clockwise ? 1 : -1;
  40235. var angles = [startAngle, endAngle];
  40236. var halfPadAngle = dir * padAngle / 2;
  40237. normalizeArcAngles(angles, !clockwise);
  40238. startAngle = angles[0], endAngle = angles[1];
  40239. var layoutData = getSeriesLayoutData(seriesModel);
  40240. layoutData.startAngle = startAngle;
  40241. layoutData.endAngle = endAngle;
  40242. layoutData.clockwise = clockwise;
  40243. var angleRange = Math.abs(endAngle - startAngle);
  40244. // In the case some sector angle is smaller than minAngle
  40245. var restAngle = angleRange;
  40246. var valueSumLargerThanMinAngle = 0;
  40247. var currentAngle = startAngle;
  40248. data.setLayout({
  40249. viewRect: viewRect,
  40250. r: r
  40251. });
  40252. data.each(valueDim, function (value, idx) {
  40253. var angle;
  40254. if (isNaN(value)) {
  40255. data.setItemLayout(idx, {
  40256. angle: NaN,
  40257. startAngle: NaN,
  40258. endAngle: NaN,
  40259. clockwise: clockwise,
  40260. cx: cx,
  40261. cy: cy,
  40262. r0: r0,
  40263. r: roseType ? NaN : r
  40264. });
  40265. return;
  40266. }
  40267. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40268. if (roseType !== 'area') {
  40269. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40270. } else {
  40271. angle = angleRange / validDataCount;
  40272. }
  40273. if (angle < minAndPadAngle) {
  40274. angle = minAndPadAngle;
  40275. restAngle -= minAndPadAngle;
  40276. } else {
  40277. valueSumLargerThanMinAngle += value;
  40278. }
  40279. var endAngle = currentAngle + dir * angle;
  40280. // calculate display angle
  40281. var actualStartAngle = 0;
  40282. var actualEndAngle = 0;
  40283. if (padAngle > angle) {
  40284. actualStartAngle = currentAngle + dir * angle / 2;
  40285. actualEndAngle = actualStartAngle;
  40286. } else {
  40287. actualStartAngle = currentAngle + halfPadAngle;
  40288. actualEndAngle = endAngle - halfPadAngle;
  40289. }
  40290. data.setItemLayout(idx, {
  40291. angle: angle,
  40292. startAngle: actualStartAngle,
  40293. endAngle: actualEndAngle,
  40294. clockwise: clockwise,
  40295. cx: cx,
  40296. cy: cy,
  40297. r0: r0,
  40298. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40299. });
  40300. currentAngle = endAngle;
  40301. });
  40302. // Some sector is constrained by minAngle and padAngle
  40303. // Rest sectors needs recalculate angle
  40304. if (restAngle < PI2$7 && validDataCount) {
  40305. // Average the angle if rest angle is not enough after all angles is
  40306. // Constrained by minAngle and padAngle
  40307. if (restAngle <= 1e-3) {
  40308. var angle_1 = angleRange / validDataCount;
  40309. data.each(valueDim, function (value, idx) {
  40310. if (!isNaN(value)) {
  40311. var layout_1 = data.getItemLayout(idx);
  40312. layout_1.angle = angle_1;
  40313. var actualStartAngle = 0;
  40314. var actualEndAngle = 0;
  40315. if (angle_1 < padAngle) {
  40316. actualStartAngle = startAngle + dir * (idx + 1 / 2) * angle_1;
  40317. actualEndAngle = actualStartAngle;
  40318. } else {
  40319. actualStartAngle = startAngle + dir * idx * angle_1 + halfPadAngle;
  40320. actualEndAngle = startAngle + dir * (idx + 1) * angle_1 - halfPadAngle;
  40321. }
  40322. layout_1.startAngle = actualStartAngle;
  40323. layout_1.endAngle = actualEndAngle;
  40324. }
  40325. });
  40326. } else {
  40327. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40328. currentAngle = startAngle;
  40329. data.each(valueDim, function (value, idx) {
  40330. if (!isNaN(value)) {
  40331. var layout_2 = data.getItemLayout(idx);
  40332. var angle = layout_2.angle === minAndPadAngle ? minAndPadAngle : value * unitRadian;
  40333. var actualStartAngle = 0;
  40334. var actualEndAngle = 0;
  40335. if (angle < padAngle) {
  40336. actualStartAngle = currentAngle + dir * angle / 2;
  40337. actualEndAngle = actualStartAngle;
  40338. } else {
  40339. actualStartAngle = currentAngle + halfPadAngle;
  40340. actualEndAngle = currentAngle + dir * angle - halfPadAngle;
  40341. }
  40342. layout_2.startAngle = actualStartAngle;
  40343. layout_2.endAngle = actualEndAngle;
  40344. currentAngle += dir * angle;
  40345. }
  40346. });
  40347. }
  40348. }
  40349. });
  40350. }
  40351. var getSeriesLayoutData = makeInner();
  40352. /*
  40353. * Licensed to the Apache Software Foundation (ASF) under one
  40354. * or more contributor license agreements. See the NOTICE file
  40355. * distributed with this work for additional information
  40356. * regarding copyright ownership. The ASF licenses this file
  40357. * to you under the Apache License, Version 2.0 (the
  40358. * "License"); you may not use this file except in compliance
  40359. * with the License. You may obtain a copy of the License at
  40360. *
  40361. * http://www.apache.org/licenses/LICENSE-2.0
  40362. *
  40363. * Unless required by applicable law or agreed to in writing,
  40364. * software distributed under the License is distributed on an
  40365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40366. * KIND, either express or implied. See the License for the
  40367. * specific language governing permissions and limitations
  40368. * under the License.
  40369. */
  40370. /**
  40371. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40372. */
  40373. /*
  40374. * Licensed to the Apache Software Foundation (ASF) under one
  40375. * or more contributor license agreements. See the NOTICE file
  40376. * distributed with this work for additional information
  40377. * regarding copyright ownership. The ASF licenses this file
  40378. * to you under the Apache License, Version 2.0 (the
  40379. * "License"); you may not use this file except in compliance
  40380. * with the License. You may obtain a copy of the License at
  40381. *
  40382. * http://www.apache.org/licenses/LICENSE-2.0
  40383. *
  40384. * Unless required by applicable law or agreed to in writing,
  40385. * software distributed under the License is distributed on an
  40386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40387. * KIND, either express or implied. See the License for the
  40388. * specific language governing permissions and limitations
  40389. * under the License.
  40390. */
  40391. function dataFilter(seriesType) {
  40392. return {
  40393. seriesType: seriesType,
  40394. reset: function (seriesModel, ecModel) {
  40395. var legendModels = ecModel.findComponents({
  40396. mainType: 'legend'
  40397. });
  40398. if (!legendModels || !legendModels.length) {
  40399. return;
  40400. }
  40401. var data = seriesModel.getData();
  40402. data.filterSelf(function (idx) {
  40403. var name = data.getName(idx);
  40404. // If in any legend component the status is not selected.
  40405. for (var i = 0; i < legendModels.length; i++) {
  40406. // @ts-ignore FIXME: LegendModel
  40407. if (!legendModels[i].isSelected(name)) {
  40408. return false;
  40409. }
  40410. }
  40411. return true;
  40412. });
  40413. }
  40414. };
  40415. }
  40416. var RADIAN$1 = Math.PI / 180;
  40417. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40418. if (list.length < 2) {
  40419. return;
  40420. }
  40421. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40422. var rB = semi.rB;
  40423. var rB2 = rB * rB;
  40424. for (var i = 0; i < semi.list.length; i++) {
  40425. var item = semi.list[i];
  40426. var dy = Math.abs(item.label.y - cy);
  40427. // horizontal r is always same with original r because x is not changed.
  40428. var rA = r + item.len;
  40429. var rA2 = rA * rA;
  40430. // Use ellipse implicit function to calculate x
  40431. var dx = Math.sqrt(Math.abs((1 - dy * dy / rB2) * rA2));
  40432. var newX = cx + (dx + item.len2) * dir;
  40433. var deltaX = newX - item.label.x;
  40434. var newTargetWidth = item.targetTextWidth - deltaX * dir;
  40435. // text x is changed, so need to recalculate width.
  40436. constrainTextWidth(item, newTargetWidth, true);
  40437. item.label.x = newX;
  40438. }
  40439. }
  40440. // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40441. function recalculateX(items) {
  40442. // Extremes of
  40443. var topSemi = {
  40444. list: [],
  40445. maxY: 0
  40446. };
  40447. var bottomSemi = {
  40448. list: [],
  40449. maxY: 0
  40450. };
  40451. for (var i = 0; i < items.length; i++) {
  40452. if (items[i].labelAlignTo !== 'none') {
  40453. continue;
  40454. }
  40455. var item = items[i];
  40456. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40457. var dy = Math.abs(item.label.y - cy);
  40458. if (dy >= semi.maxY) {
  40459. var dx = item.label.x - cx - item.len2 * dir;
  40460. // horizontal r is always same with original r because x is not changed.
  40461. var rA = r + item.len;
  40462. // Canculate rB based on the topest / bottemest label.
  40463. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40464. semi.rB = rB;
  40465. semi.maxY = dy;
  40466. }
  40467. semi.list.push(item);
  40468. }
  40469. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40470. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40471. }
  40472. var len = list.length;
  40473. for (var i = 0; i < len; i++) {
  40474. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40475. var dx = list[i].label.x - farthestX;
  40476. list[i].linePoints[1][0] += dx;
  40477. list[i].label.x = farthestX;
  40478. }
  40479. }
  40480. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40481. recalculateX(list);
  40482. }
  40483. }
  40484. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40485. var leftList = [];
  40486. var rightList = [];
  40487. var leftmostX = Number.MAX_VALUE;
  40488. var rightmostX = -Number.MAX_VALUE;
  40489. for (var i = 0; i < labelLayoutList.length; i++) {
  40490. var label = labelLayoutList[i].label;
  40491. if (isPositionCenter(labelLayoutList[i])) {
  40492. continue;
  40493. }
  40494. if (label.x < cx) {
  40495. leftmostX = Math.min(leftmostX, label.x);
  40496. leftList.push(labelLayoutList[i]);
  40497. } else {
  40498. rightmostX = Math.max(rightmostX, label.x);
  40499. rightList.push(labelLayoutList[i]);
  40500. }
  40501. }
  40502. for (var i = 0; i < labelLayoutList.length; i++) {
  40503. var layout = labelLayoutList[i];
  40504. if (!isPositionCenter(layout) && layout.linePoints) {
  40505. if (layout.labelStyleWidth != null) {
  40506. continue;
  40507. }
  40508. var label = layout.label;
  40509. var linePoints = layout.linePoints;
  40510. var targetTextWidth = void 0;
  40511. if (layout.labelAlignTo === 'edge') {
  40512. if (label.x < cx) {
  40513. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40514. } else {
  40515. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40516. }
  40517. } else if (layout.labelAlignTo === 'labelLine') {
  40518. if (label.x < cx) {
  40519. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  40520. } else {
  40521. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  40522. }
  40523. } else {
  40524. if (label.x < cx) {
  40525. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40526. } else {
  40527. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40528. }
  40529. }
  40530. layout.targetTextWidth = targetTextWidth;
  40531. constrainTextWidth(layout, targetTextWidth);
  40532. }
  40533. }
  40534. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40535. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40536. for (var i = 0; i < labelLayoutList.length; i++) {
  40537. var layout = labelLayoutList[i];
  40538. if (!isPositionCenter(layout) && layout.linePoints) {
  40539. var label = layout.label;
  40540. var linePoints = layout.linePoints;
  40541. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40542. var padding = label.style.padding;
  40543. var paddingH = padding ? padding[1] + padding[3] : 0;
  40544. // textRect.width already contains paddingH if bgColor is set
  40545. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  40546. var realTextWidth = layout.rect.width + extraPaddingH;
  40547. var dist = linePoints[1][0] - linePoints[2][0];
  40548. if (isAlignToEdge) {
  40549. if (label.x < cx) {
  40550. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40551. } else {
  40552. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40553. }
  40554. } else {
  40555. if (label.x < cx) {
  40556. linePoints[2][0] = label.x + layout.labelDistance;
  40557. } else {
  40558. linePoints[2][0] = label.x - layout.labelDistance;
  40559. }
  40560. linePoints[1][0] = linePoints[2][0] + dist;
  40561. }
  40562. linePoints[1][1] = linePoints[2][1] = label.y;
  40563. }
  40564. }
  40565. }
  40566. /**
  40567. * Set max width of each label, and then wrap each label to the max width.
  40568. *
  40569. * @param layout label layout
  40570. * @param availableWidth max width for the label to display
  40571. * @param forceRecalculate recaculate the text layout even if the current width
  40572. * is smaller than `availableWidth`. This is useful when the text was previously
  40573. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  40574. * which case, previous wrapping should be redo.
  40575. */
  40576. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  40577. if (forceRecalculate === void 0) {
  40578. forceRecalculate = false;
  40579. }
  40580. if (layout.labelStyleWidth != null) {
  40581. // User-defined style.width has the highest priority.
  40582. return;
  40583. }
  40584. var label = layout.label;
  40585. var style = label.style;
  40586. var textRect = layout.rect;
  40587. var bgColor = style.backgroundColor;
  40588. var padding = style.padding;
  40589. var paddingH = padding ? padding[1] + padding[3] : 0;
  40590. var overflow = style.overflow;
  40591. // textRect.width already contains paddingH if bgColor is set
  40592. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  40593. if (availableWidth < oldOuterWidth || forceRecalculate) {
  40594. var oldHeight = textRect.height;
  40595. if (overflow && overflow.match('break')) {
  40596. // Temporarily set background to be null to calculate
  40597. // the bounding box without background.
  40598. label.setStyle('backgroundColor', null);
  40599. // Set constraining width
  40600. label.setStyle('width', availableWidth - paddingH);
  40601. // This is the real bounding box of the text without padding.
  40602. var innerRect = label.getBoundingRect();
  40603. label.setStyle('width', Math.ceil(innerRect.width));
  40604. label.setStyle('backgroundColor', bgColor);
  40605. } else {
  40606. var availableInnerWidth = availableWidth - paddingH;
  40607. var newWidth = availableWidth < oldOuterWidth
  40608. // Current text is too wide, use `availableWidth` as max width.
  40609. ? availableInnerWidth :
  40610. // Current available width is enough, but the text may have
  40611. // already been wrapped with a smaller available width.
  40612. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth
  40613. // Current available is larger than text width,
  40614. // so don't constrain width (otherwise it may have
  40615. // empty space in the background).
  40616. ? null
  40617. // Current available is smaller than text width, so
  40618. // use the current available width as constraining
  40619. // width.
  40620. : availableInnerWidth
  40621. // Current available width is enough, so no need to
  40622. // constrain.
  40623. : null;
  40624. label.setStyle('width', newWidth);
  40625. }
  40626. var newRect = label.getBoundingRect();
  40627. textRect.width = newRect.width;
  40628. var margin = (label.style.margin || 0) + 2.1;
  40629. textRect.height = newRect.height + margin;
  40630. textRect.y -= (textRect.height - oldHeight) / 2;
  40631. }
  40632. }
  40633. function isPositionCenter(sectorShape) {
  40634. // Not change x for center label
  40635. return sectorShape.position === 'center';
  40636. }
  40637. function pieLabelLayout(seriesModel) {
  40638. var data = seriesModel.getData();
  40639. var labelLayoutList = [];
  40640. var cx;
  40641. var cy;
  40642. var hasLabelRotate = false;
  40643. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40644. var viewRect = data.getLayout('viewRect');
  40645. var r = data.getLayout('r');
  40646. var viewWidth = viewRect.width;
  40647. var viewLeft = viewRect.x;
  40648. var viewTop = viewRect.y;
  40649. var viewHeight = viewRect.height;
  40650. function setNotShow(el) {
  40651. el.ignore = true;
  40652. }
  40653. function isLabelShown(label) {
  40654. if (!label.ignore) {
  40655. return true;
  40656. }
  40657. for (var key in label.states) {
  40658. if (label.states[key].ignore === false) {
  40659. return true;
  40660. }
  40661. }
  40662. return false;
  40663. }
  40664. data.each(function (idx) {
  40665. var sector = data.getItemGraphicEl(idx);
  40666. var sectorShape = sector.shape;
  40667. var label = sector.getTextContent();
  40668. var labelLine = sector.getTextGuideLine();
  40669. var itemModel = data.getItemModel(idx);
  40670. var labelModel = itemModel.getModel('label');
  40671. // Use position in normal or emphasis
  40672. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40673. var labelDistance = labelModel.get('distanceToLabelLine');
  40674. var labelAlignTo = labelModel.get('alignTo');
  40675. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40676. var bleedMargin = labelModel.get('bleedMargin');
  40677. var labelLineModel = itemModel.getModel('labelLine');
  40678. var labelLineLen = labelLineModel.get('length');
  40679. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40680. var labelLineLen2 = labelLineModel.get('length2');
  40681. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40682. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40683. each(label.states, setNotShow);
  40684. label.ignore = true;
  40685. if (labelLine) {
  40686. each(labelLine.states, setNotShow);
  40687. labelLine.ignore = true;
  40688. }
  40689. return;
  40690. }
  40691. if (!isLabelShown(label)) {
  40692. return;
  40693. }
  40694. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40695. var nx = Math.cos(midAngle);
  40696. var ny = Math.sin(midAngle);
  40697. var textX;
  40698. var textY;
  40699. var linePoints;
  40700. var textAlign;
  40701. cx = sectorShape.cx;
  40702. cy = sectorShape.cy;
  40703. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40704. if (labelPosition === 'center') {
  40705. textX = sectorShape.cx;
  40706. textY = sectorShape.cy;
  40707. textAlign = 'center';
  40708. } else {
  40709. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40710. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40711. textX = x1 + nx * 3;
  40712. textY = y1 + ny * 3;
  40713. if (!isLabelInside) {
  40714. // For roseType
  40715. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40716. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40717. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40718. var y3 = y2;
  40719. if (labelAlignTo === 'edge') {
  40720. // Adjust textX because text align of edge is opposite
  40721. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40722. } else {
  40723. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40724. }
  40725. textY = y3;
  40726. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40727. }
  40728. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40729. }
  40730. var PI = Math.PI;
  40731. var labelRotate = 0;
  40732. var rotate = labelModel.get('rotate');
  40733. if (isNumber(rotate)) {
  40734. labelRotate = rotate * (PI / 180);
  40735. } else if (labelPosition === 'center') {
  40736. labelRotate = 0;
  40737. } else if (rotate === 'radial' || rotate === true) {
  40738. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  40739. labelRotate = radialAngle;
  40740. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40741. var rad = Math.atan2(nx, ny);
  40742. if (rad < 0) {
  40743. rad = PI * 2 + rad;
  40744. }
  40745. var isDown = ny > 0;
  40746. if (isDown) {
  40747. rad = PI + rad;
  40748. }
  40749. labelRotate = rad - PI;
  40750. }
  40751. hasLabelRotate = !!labelRotate;
  40752. label.x = textX;
  40753. label.y = textY;
  40754. label.rotation = labelRotate;
  40755. label.setStyle({
  40756. verticalAlign: 'middle'
  40757. });
  40758. // Not sectorShape the inside label
  40759. if (!isLabelInside) {
  40760. var textRect = label.getBoundingRect().clone();
  40761. textRect.applyTransform(label.getComputedTransform());
  40762. // Text has a default 1px stroke. Exclude this.
  40763. var margin = (label.style.margin || 0) + 2.1;
  40764. textRect.y -= margin / 2;
  40765. textRect.height += margin;
  40766. labelLayoutList.push({
  40767. label: label,
  40768. labelLine: labelLine,
  40769. position: labelPosition,
  40770. len: labelLineLen,
  40771. len2: labelLineLen2,
  40772. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40773. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40774. surfaceNormal: new Point(nx, ny),
  40775. linePoints: linePoints,
  40776. textAlign: textAlign,
  40777. labelDistance: labelDistance,
  40778. labelAlignTo: labelAlignTo,
  40779. edgeDistance: edgeDistance,
  40780. bleedMargin: bleedMargin,
  40781. rect: textRect,
  40782. unconstrainedWidth: textRect.width,
  40783. labelStyleWidth: label.style.width
  40784. });
  40785. } else {
  40786. label.setStyle({
  40787. align: textAlign
  40788. });
  40789. var selectState = label.states.select;
  40790. if (selectState) {
  40791. selectState.x += label.x;
  40792. selectState.y += label.y;
  40793. }
  40794. }
  40795. sector.setTextConfig({
  40796. inside: isLabelInside
  40797. });
  40798. });
  40799. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  40800. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  40801. }
  40802. for (var i = 0; i < labelLayoutList.length; i++) {
  40803. var layout = labelLayoutList[i];
  40804. var label = layout.label;
  40805. var labelLine = layout.labelLine;
  40806. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  40807. if (label) {
  40808. label.setStyle({
  40809. align: layout.textAlign
  40810. });
  40811. if (notShowLabel) {
  40812. each(label.states, setNotShow);
  40813. label.ignore = true;
  40814. }
  40815. var selectState = label.states.select;
  40816. if (selectState) {
  40817. selectState.x += label.x;
  40818. selectState.y += label.y;
  40819. }
  40820. }
  40821. if (labelLine) {
  40822. var linePoints = layout.linePoints;
  40823. if (notShowLabel || !linePoints) {
  40824. each(labelLine.states, setNotShow);
  40825. labelLine.ignore = true;
  40826. } else {
  40827. limitTurnAngle(linePoints, layout.minTurnAngle);
  40828. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  40829. labelLine.setShape({
  40830. points: linePoints
  40831. });
  40832. // Set the anchor to the midpoint of sector
  40833. label.__hostTarget.textGuideLineConfig = {
  40834. anchor: new Point(linePoints[0][0], linePoints[0][1])
  40835. };
  40836. }
  40837. }
  40838. }
  40839. }
  40840. /**
  40841. * Piece of pie including Sector, Label, LabelLine
  40842. */
  40843. var PiePiece = /** @class */function (_super) {
  40844. __extends(PiePiece, _super);
  40845. function PiePiece(data, idx, startAngle) {
  40846. var _this = _super.call(this) || this;
  40847. _this.z2 = 2;
  40848. var text = new ZRText();
  40849. _this.setTextContent(text);
  40850. _this.updateData(data, idx, startAngle, true);
  40851. return _this;
  40852. }
  40853. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  40854. var sector = this;
  40855. var seriesModel = data.hostModel;
  40856. var itemModel = data.getItemModel(idx);
  40857. var emphasisModel = itemModel.getModel('emphasis');
  40858. var layout = data.getItemLayout(idx);
  40859. // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  40860. // see `setItemLayout` in `pieLayout.ts`.
  40861. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout);
  40862. // Ignore NaN data.
  40863. if (isNaN(sectorShape.startAngle)) {
  40864. // Use NaN shape to avoid drawing shape.
  40865. sector.setShape(sectorShape);
  40866. return;
  40867. }
  40868. if (firstCreate) {
  40869. sector.setShape(sectorShape);
  40870. var animationType = seriesModel.getShallow('animationType');
  40871. if (seriesModel.ecModel.ssr) {
  40872. // Use scale animation in SSR mode(opacity?)
  40873. // Because CSS SVG animation doesn't support very customized shape animation.
  40874. initProps(sector, {
  40875. scaleX: 0,
  40876. scaleY: 0
  40877. }, seriesModel, {
  40878. dataIndex: idx,
  40879. isFrom: true
  40880. });
  40881. sector.originX = sectorShape.cx;
  40882. sector.originY = sectorShape.cy;
  40883. } else if (animationType === 'scale') {
  40884. sector.shape.r = layout.r0;
  40885. initProps(sector, {
  40886. shape: {
  40887. r: layout.r
  40888. }
  40889. }, seriesModel, idx);
  40890. }
  40891. // Expansion
  40892. else {
  40893. if (startAngle != null) {
  40894. sector.setShape({
  40895. startAngle: startAngle,
  40896. endAngle: startAngle
  40897. });
  40898. initProps(sector, {
  40899. shape: {
  40900. startAngle: layout.startAngle,
  40901. endAngle: layout.endAngle
  40902. }
  40903. }, seriesModel, idx);
  40904. } else {
  40905. sector.shape.endAngle = layout.startAngle;
  40906. updateProps(sector, {
  40907. shape: {
  40908. endAngle: layout.endAngle
  40909. }
  40910. }, seriesModel, idx);
  40911. }
  40912. }
  40913. } else {
  40914. saveOldStyle(sector);
  40915. // Transition animation from the old shape
  40916. updateProps(sector, {
  40917. shape: sectorShape
  40918. }, seriesModel, idx);
  40919. }
  40920. sector.useStyle(data.getItemVisual(idx, 'style'));
  40921. setStatesStylesFromModel(sector, itemModel);
  40922. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  40923. var offset = seriesModel.get('selectedOffset');
  40924. var dx = Math.cos(midAngle) * offset;
  40925. var dy = Math.sin(midAngle) * offset;
  40926. var cursorStyle = itemModel.getShallow('cursor');
  40927. cursorStyle && sector.attr('cursor', cursorStyle);
  40928. this._updateLabel(seriesModel, data, idx);
  40929. sector.ensureState('emphasis').shape = extend({
  40930. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  40931. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  40932. extend(sector.ensureState('select'), {
  40933. x: dx,
  40934. y: dy,
  40935. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  40936. });
  40937. extend(sector.ensureState('blur'), {
  40938. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  40939. });
  40940. var labelLine = sector.getTextGuideLine();
  40941. var labelText = sector.getTextContent();
  40942. labelLine && extend(labelLine.ensureState('select'), {
  40943. x: dx,
  40944. y: dy
  40945. });
  40946. // TODO: needs dx, dy in zrender?
  40947. extend(labelText.ensureState('select'), {
  40948. x: dx,
  40949. y: dy
  40950. });
  40951. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  40952. };
  40953. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  40954. var sector = this;
  40955. var itemModel = data.getItemModel(idx);
  40956. var labelLineModel = itemModel.getModel('labelLine');
  40957. var style = data.getItemVisual(idx, 'style');
  40958. var visualColor = style && style.fill;
  40959. var visualOpacity = style && style.opacity;
  40960. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  40961. labelFetcher: data.hostModel,
  40962. labelDataIndex: idx,
  40963. inheritColor: visualColor,
  40964. defaultOpacity: visualOpacity,
  40965. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  40966. });
  40967. var labelText = sector.getTextContent();
  40968. // Set textConfig on sector.
  40969. sector.setTextConfig({
  40970. // reset position, rotation
  40971. position: null,
  40972. rotation: null
  40973. });
  40974. // Make sure update style on labelText after setLabelStyle.
  40975. // Because setLabelStyle will replace a new style on it.
  40976. labelText.attr({
  40977. z2: 10
  40978. });
  40979. var labelPosition = seriesModel.get(['label', 'position']);
  40980. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  40981. sector.removeTextGuideLine();
  40982. } else {
  40983. var polyline = this.getTextGuideLine();
  40984. if (!polyline) {
  40985. polyline = new Polyline();
  40986. this.setTextGuideLine(polyline);
  40987. }
  40988. // Default use item visual color
  40989. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  40990. stroke: visualColor,
  40991. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  40992. });
  40993. }
  40994. };
  40995. return PiePiece;
  40996. }(Sector);
  40997. // Pie view
  40998. var PieView = /** @class */function (_super) {
  40999. __extends(PieView, _super);
  41000. function PieView() {
  41001. var _this = _super !== null && _super.apply(this, arguments) || this;
  41002. _this.ignoreLabelLineUpdate = true;
  41003. return _this;
  41004. }
  41005. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  41006. var data = seriesModel.getData();
  41007. var oldData = this._data;
  41008. var group = this.group;
  41009. var startAngle;
  41010. // First render
  41011. if (!oldData && data.count() > 0) {
  41012. var shape = data.getItemLayout(0);
  41013. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  41014. shape = data.getItemLayout(s);
  41015. }
  41016. if (shape) {
  41017. startAngle = shape.startAngle;
  41018. }
  41019. }
  41020. // remove empty-circle if it exists
  41021. if (this._emptyCircleSector) {
  41022. group.remove(this._emptyCircleSector);
  41023. }
  41024. // when all data are filtered, show lightgray empty circle
  41025. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  41026. var layoutData = getSeriesLayoutData(seriesModel);
  41027. var sector = new Sector({
  41028. shape: extend(getBasicPieLayout(seriesModel, api), layoutData)
  41029. });
  41030. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  41031. this._emptyCircleSector = sector;
  41032. group.add(sector);
  41033. }
  41034. data.diff(oldData).add(function (idx) {
  41035. var piePiece = new PiePiece(data, idx, startAngle);
  41036. data.setItemGraphicEl(idx, piePiece);
  41037. group.add(piePiece);
  41038. }).update(function (newIdx, oldIdx) {
  41039. var piePiece = oldData.getItemGraphicEl(oldIdx);
  41040. piePiece.updateData(data, newIdx, startAngle);
  41041. piePiece.off('click');
  41042. group.add(piePiece);
  41043. data.setItemGraphicEl(newIdx, piePiece);
  41044. }).remove(function (idx) {
  41045. var piePiece = oldData.getItemGraphicEl(idx);
  41046. removeElementWithFadeOut(piePiece, seriesModel, idx);
  41047. }).execute();
  41048. pieLabelLayout(seriesModel);
  41049. // Always use initial animation.
  41050. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  41051. this._data = data;
  41052. }
  41053. };
  41054. PieView.prototype.dispose = function () {};
  41055. PieView.prototype.containPoint = function (point, seriesModel) {
  41056. var data = seriesModel.getData();
  41057. var itemLayout = data.getItemLayout(0);
  41058. if (itemLayout) {
  41059. var dx = point[0] - itemLayout.cx;
  41060. var dy = point[1] - itemLayout.cy;
  41061. var radius = Math.sqrt(dx * dx + dy * dy);
  41062. return radius <= itemLayout.r && radius >= itemLayout.r0;
  41063. }
  41064. };
  41065. PieView.type = 'pie';
  41066. return PieView;
  41067. }(ChartView);
  41068. /**
  41069. * [Usage]:
  41070. * (1)
  41071. * createListSimply(seriesModel, ['value']);
  41072. * (2)
  41073. * createListSimply(seriesModel, {
  41074. * coordDimensions: ['value'],
  41075. * dimensionsCount: 5
  41076. * });
  41077. */
  41078. function createSeriesDataSimply(seriesModel, opt, nameList) {
  41079. opt = isArray(opt) && {
  41080. coordDimensions: opt
  41081. } || extend({
  41082. encodeDefine: seriesModel.getEncode()
  41083. }, opt);
  41084. var source = seriesModel.getSource();
  41085. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  41086. var list = new SeriesData(dimensions, seriesModel);
  41087. list.initData(source, nameList);
  41088. return list;
  41089. }
  41090. /*
  41091. * Licensed to the Apache Software Foundation (ASF) under one
  41092. * or more contributor license agreements. See the NOTICE file
  41093. * distributed with this work for additional information
  41094. * regarding copyright ownership. The ASF licenses this file
  41095. * to you under the Apache License, Version 2.0 (the
  41096. * "License"); you may not use this file except in compliance
  41097. * with the License. You may obtain a copy of the License at
  41098. *
  41099. * http://www.apache.org/licenses/LICENSE-2.0
  41100. *
  41101. * Unless required by applicable law or agreed to in writing,
  41102. * software distributed under the License is distributed on an
  41103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41104. * KIND, either express or implied. See the License for the
  41105. * specific language governing permissions and limitations
  41106. * under the License.
  41107. */
  41108. /**
  41109. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41110. */
  41111. /*
  41112. * Licensed to the Apache Software Foundation (ASF) under one
  41113. * or more contributor license agreements. See the NOTICE file
  41114. * distributed with this work for additional information
  41115. * regarding copyright ownership. The ASF licenses this file
  41116. * to you under the Apache License, Version 2.0 (the
  41117. * "License"); you may not use this file except in compliance
  41118. * with the License. You may obtain a copy of the License at
  41119. *
  41120. * http://www.apache.org/licenses/LICENSE-2.0
  41121. *
  41122. * Unless required by applicable law or agreed to in writing,
  41123. * software distributed under the License is distributed on an
  41124. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41125. * KIND, either express or implied. See the License for the
  41126. * specific language governing permissions and limitations
  41127. * under the License.
  41128. */
  41129. /**
  41130. * LegendVisualProvider is an bridge that pick encoded color from data and
  41131. * provide to the legend component.
  41132. */
  41133. var LegendVisualProvider = /** @class */function () {
  41134. function LegendVisualProvider(
  41135. // Function to get data after filtered. It stores all the encoding info
  41136. getDataWithEncodedVisual,
  41137. // Function to get raw data before filtered.
  41138. getRawData) {
  41139. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  41140. this._getRawData = getRawData;
  41141. }
  41142. LegendVisualProvider.prototype.getAllNames = function () {
  41143. var rawData = this._getRawData();
  41144. // We find the name from the raw data. In case it's filtered by the legend component.
  41145. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  41146. return rawData.mapArray(rawData.getName);
  41147. };
  41148. LegendVisualProvider.prototype.containName = function (name) {
  41149. var rawData = this._getRawData();
  41150. return rawData.indexOfName(name) >= 0;
  41151. };
  41152. LegendVisualProvider.prototype.indexOfName = function (name) {
  41153. // Only get data when necessary.
  41154. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  41155. // Invoking Series#getData immediately will throw an error.
  41156. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41157. return dataWithEncodedVisual.indexOfName(name);
  41158. };
  41159. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  41160. // Get encoded visual properties from final filtered data.
  41161. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41162. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  41163. };
  41164. return LegendVisualProvider;
  41165. }();
  41166. var innerData = makeInner();
  41167. var PieSeriesModel = /** @class */function (_super) {
  41168. __extends(PieSeriesModel, _super);
  41169. function PieSeriesModel() {
  41170. return _super !== null && _super.apply(this, arguments) || this;
  41171. }
  41172. /**
  41173. * @overwrite
  41174. */
  41175. PieSeriesModel.prototype.init = function (option) {
  41176. _super.prototype.init.apply(this, arguments);
  41177. // Enable legend selection for each data item
  41178. // Use a function instead of direct access because data reference may changed
  41179. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  41180. this._defaultLabelLine(option);
  41181. };
  41182. /**
  41183. * @overwrite
  41184. */
  41185. PieSeriesModel.prototype.mergeOption = function () {
  41186. _super.prototype.mergeOption.apply(this, arguments);
  41187. };
  41188. /**
  41189. * @overwrite
  41190. */
  41191. PieSeriesModel.prototype.getInitialData = function () {
  41192. return createSeriesDataSimply(this, {
  41193. coordDimensions: ['value'],
  41194. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41195. });
  41196. };
  41197. /**
  41198. * @overwrite
  41199. */
  41200. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  41201. var data = this.getData();
  41202. // update seats when data is changed
  41203. var dataInner = innerData(data);
  41204. var seats = dataInner.seats;
  41205. if (!seats) {
  41206. var valueList_1 = [];
  41207. data.each(data.mapDimension('value'), function (value) {
  41208. valueList_1.push(value);
  41209. });
  41210. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  41211. }
  41212. var params = _super.prototype.getDataParams.call(this, dataIndex);
  41213. // seats may be empty when sum is 0
  41214. params.percent = seats[dataIndex] || 0;
  41215. params.$vars.push('percent');
  41216. return params;
  41217. };
  41218. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  41219. // Extend labelLine emphasis
  41220. defaultEmphasis(option, 'labelLine', ['show']);
  41221. var labelLineNormalOpt = option.labelLine;
  41222. var labelLineEmphasisOpt = option.emphasis.labelLine;
  41223. // Not show label line if `label.normal.show = false`
  41224. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  41225. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  41226. };
  41227. PieSeriesModel.type = 'series.pie';
  41228. PieSeriesModel.defaultOption = {
  41229. // zlevel: 0,
  41230. z: 2,
  41231. legendHoverLink: true,
  41232. colorBy: 'data',
  41233. // 默认全局居中
  41234. center: ['50%', '50%'],
  41235. radius: [0, '75%'],
  41236. // 默认顺时针
  41237. clockwise: true,
  41238. startAngle: 90,
  41239. endAngle: 'auto',
  41240. padAngle: 0,
  41241. // 最小角度改为0
  41242. minAngle: 0,
  41243. // If the angle of a sector less than `minShowLabelAngle`,
  41244. // the label will not be displayed.
  41245. minShowLabelAngle: 0,
  41246. // 选中时扇区偏移量
  41247. selectedOffset: 10,
  41248. // 选择模式,默认关闭,可选single,multiple
  41249. // selectedMode: false,
  41250. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41251. // roseType: null,
  41252. percentPrecision: 2,
  41253. // If still show when all data zero.
  41254. stillShowZeroSum: true,
  41255. // cursor: null,
  41256. left: 0,
  41257. top: 0,
  41258. right: 0,
  41259. bottom: 0,
  41260. width: null,
  41261. height: null,
  41262. label: {
  41263. // color: 'inherit',
  41264. // If rotate around circle
  41265. rotate: 0,
  41266. show: true,
  41267. overflow: 'truncate',
  41268. // 'outer', 'inside', 'center'
  41269. position: 'outer',
  41270. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41271. alignTo: 'none',
  41272. // Closest distance between label and chart edge.
  41273. // Works only position is 'outer' and alignTo is 'edge'.
  41274. edgeDistance: '25%',
  41275. // Works only position is 'outer' and alignTo is not 'edge'.
  41276. bleedMargin: 10,
  41277. // Distance between text and label line.
  41278. distanceToLabelLine: 5
  41279. // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  41280. // 默认使用全局文本样式,详见 textStyle
  41281. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41282. },
  41283. // Enabled when label.normal.position is 'outer'
  41284. labelLine: {
  41285. show: true,
  41286. // 引导线两段中的第一段长度
  41287. length: 15,
  41288. // 引导线两段中的第二段长度
  41289. length2: 15,
  41290. smooth: false,
  41291. minTurnAngle: 90,
  41292. maxSurfaceAngle: 90,
  41293. lineStyle: {
  41294. // color: 各异,
  41295. width: 1,
  41296. type: 'solid'
  41297. }
  41298. },
  41299. itemStyle: {
  41300. borderWidth: 1,
  41301. borderJoin: 'round'
  41302. },
  41303. showEmptyCircle: true,
  41304. emptyCircleStyle: {
  41305. color: 'lightgray',
  41306. opacity: 1
  41307. },
  41308. labelLayout: {
  41309. // Hide the overlapped label.
  41310. hideOverlap: true
  41311. },
  41312. emphasis: {
  41313. scale: true,
  41314. scaleSize: 5
  41315. },
  41316. // If use strategy to avoid label overlapping
  41317. avoidLabelOverlap: true,
  41318. // Animation type. Valid values: expansion, scale
  41319. animationType: 'expansion',
  41320. animationDuration: 1000,
  41321. // Animation type when update. Valid values: transition, expansion
  41322. animationTypeUpdate: 'transition',
  41323. animationEasingUpdate: 'cubicInOut',
  41324. animationDurationUpdate: 500,
  41325. animationEasing: 'cubicInOut'
  41326. };
  41327. return PieSeriesModel;
  41328. }(SeriesModel);
  41329. function negativeDataFilter(seriesType) {
  41330. return {
  41331. seriesType: seriesType,
  41332. reset: function (seriesModel, ecModel) {
  41333. var data = seriesModel.getData();
  41334. data.filterSelf(function (idx) {
  41335. // handle negative value condition
  41336. var valueDim = data.mapDimension('value');
  41337. var curValue = data.get(valueDim, idx);
  41338. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  41339. return false;
  41340. }
  41341. return true;
  41342. });
  41343. }
  41344. };
  41345. }
  41346. function install$4(registers) {
  41347. registers.registerChartView(PieView);
  41348. registers.registerSeriesModel(PieSeriesModel);
  41349. createLegacyDataSelectAction('pie', registers.registerAction);
  41350. registers.registerLayout(curry(pieLayout, 'pie'));
  41351. registers.registerProcessor(dataFilter('pie'));
  41352. registers.registerProcessor(negativeDataFilter('pie'));
  41353. }
  41354. var ScatterSeriesModel = /** @class */function (_super) {
  41355. __extends(ScatterSeriesModel, _super);
  41356. function ScatterSeriesModel() {
  41357. var _this = _super !== null && _super.apply(this, arguments) || this;
  41358. _this.type = ScatterSeriesModel.type;
  41359. _this.hasSymbolVisual = true;
  41360. return _this;
  41361. }
  41362. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41363. return createSeriesData(null, this, {
  41364. useEncodeDefaulter: true
  41365. });
  41366. };
  41367. ScatterSeriesModel.prototype.getProgressive = function () {
  41368. var progressive = this.option.progressive;
  41369. if (progressive == null) {
  41370. // PENDING
  41371. return this.option.large ? 5e3 : this.get('progressive');
  41372. }
  41373. return progressive;
  41374. };
  41375. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41376. var progressiveThreshold = this.option.progressiveThreshold;
  41377. if (progressiveThreshold == null) {
  41378. // PENDING
  41379. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41380. }
  41381. return progressiveThreshold;
  41382. };
  41383. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41384. return selectors.point(data.getItemLayout(dataIndex));
  41385. };
  41386. ScatterSeriesModel.prototype.getZLevelKey = function () {
  41387. // Each progressive series has individual key.
  41388. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  41389. };
  41390. ScatterSeriesModel.type = 'series.scatter';
  41391. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41392. ScatterSeriesModel.defaultOption = {
  41393. coordinateSystem: 'cartesian2d',
  41394. // zlevel: 0,
  41395. z: 2,
  41396. legendHoverLink: true,
  41397. symbolSize: 10,
  41398. // symbolRotate: null, // 图形旋转控制
  41399. large: false,
  41400. // Available when large is true
  41401. largeThreshold: 2000,
  41402. // cursor: null,
  41403. itemStyle: {
  41404. opacity: 0.8
  41405. // color: 各异
  41406. },
  41407. emphasis: {
  41408. scale: true
  41409. },
  41410. // If clip the overflow graphics
  41411. // Works on cartesian / polar series
  41412. clip: true,
  41413. select: {
  41414. itemStyle: {
  41415. borderColor: '#212121'
  41416. }
  41417. },
  41418. universalTransition: {
  41419. divideShape: 'clone'
  41420. }
  41421. // progressive: null
  41422. };
  41423. return ScatterSeriesModel;
  41424. }(SeriesModel);
  41425. var BOOST_SIZE_THRESHOLD = 4;
  41426. var LargeSymbolPathShape = /** @class */function () {
  41427. function LargeSymbolPathShape() {}
  41428. return LargeSymbolPathShape;
  41429. }();
  41430. var LargeSymbolPath = /** @class */function (_super) {
  41431. __extends(LargeSymbolPath, _super);
  41432. function LargeSymbolPath(opts) {
  41433. var _this = _super.call(this, opts) || this;
  41434. _this._off = 0;
  41435. _this.hoverDataIdx = -1;
  41436. return _this;
  41437. }
  41438. LargeSymbolPath.prototype.getDefaultShape = function () {
  41439. return new LargeSymbolPathShape();
  41440. };
  41441. LargeSymbolPath.prototype.reset = function () {
  41442. this.notClear = false;
  41443. this._off = 0;
  41444. };
  41445. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41446. var points = shape.points;
  41447. var size = shape.size;
  41448. var symbolProxy = this.symbolProxy;
  41449. var symbolProxyShape = symbolProxy.shape;
  41450. var ctx = path.getContext ? path.getContext() : path;
  41451. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  41452. var softClipShape = this.softClipShape;
  41453. var i;
  41454. // Do draw in afterBrush.
  41455. if (canBoost) {
  41456. this._ctx = ctx;
  41457. return;
  41458. }
  41459. this._ctx = null;
  41460. for (i = this._off; i < points.length;) {
  41461. var x = points[i++];
  41462. var y = points[i++];
  41463. if (isNaN(x) || isNaN(y)) {
  41464. continue;
  41465. }
  41466. if (softClipShape && !softClipShape.contain(x, y)) {
  41467. continue;
  41468. }
  41469. symbolProxyShape.x = x - size[0] / 2;
  41470. symbolProxyShape.y = y - size[1] / 2;
  41471. symbolProxyShape.width = size[0];
  41472. symbolProxyShape.height = size[1];
  41473. symbolProxy.buildPath(path, symbolProxyShape, true);
  41474. }
  41475. if (this.incremental) {
  41476. this._off = i;
  41477. this.notClear = true;
  41478. }
  41479. };
  41480. LargeSymbolPath.prototype.afterBrush = function () {
  41481. var shape = this.shape;
  41482. var points = shape.points;
  41483. var size = shape.size;
  41484. var ctx = this._ctx;
  41485. var softClipShape = this.softClipShape;
  41486. var i;
  41487. if (!ctx) {
  41488. return;
  41489. }
  41490. // PENDING If style or other canvas status changed?
  41491. for (i = this._off; i < points.length;) {
  41492. var x = points[i++];
  41493. var y = points[i++];
  41494. if (isNaN(x) || isNaN(y)) {
  41495. continue;
  41496. }
  41497. if (softClipShape && !softClipShape.contain(x, y)) {
  41498. continue;
  41499. }
  41500. // fillRect is faster than building a rect path and draw.
  41501. // And it support light globalCompositeOperation.
  41502. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41503. }
  41504. if (this.incremental) {
  41505. this._off = i;
  41506. this.notClear = true;
  41507. }
  41508. };
  41509. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41510. // TODO ???
  41511. // Consider transform
  41512. var shape = this.shape;
  41513. var points = shape.points;
  41514. var size = shape.size;
  41515. var w = Math.max(size[0], 4);
  41516. var h = Math.max(size[1], 4);
  41517. // Not consider transform
  41518. // Treat each element as a rect
  41519. // top down traverse
  41520. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41521. var i = idx * 2;
  41522. var x0 = points[i] - w / 2;
  41523. var y0 = points[i + 1] - h / 2;
  41524. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41525. return idx;
  41526. }
  41527. }
  41528. return -1;
  41529. };
  41530. LargeSymbolPath.prototype.contain = function (x, y) {
  41531. var localPos = this.transformCoordToLocal(x, y);
  41532. var rect = this.getBoundingRect();
  41533. x = localPos[0];
  41534. y = localPos[1];
  41535. if (rect.contain(x, y)) {
  41536. // Cache found data index.
  41537. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  41538. return dataIdx >= 0;
  41539. }
  41540. this.hoverDataIdx = -1;
  41541. return false;
  41542. };
  41543. LargeSymbolPath.prototype.getBoundingRect = function () {
  41544. // Ignore stroke for large symbol draw.
  41545. var rect = this._rect;
  41546. if (!rect) {
  41547. var shape = this.shape;
  41548. var points = shape.points;
  41549. var size = shape.size;
  41550. var w = size[0];
  41551. var h = size[1];
  41552. var minX = Infinity;
  41553. var minY = Infinity;
  41554. var maxX = -Infinity;
  41555. var maxY = -Infinity;
  41556. for (var i = 0; i < points.length;) {
  41557. var x = points[i++];
  41558. var y = points[i++];
  41559. minX = Math.min(x, minX);
  41560. maxX = Math.max(x, maxX);
  41561. minY = Math.min(y, minY);
  41562. maxY = Math.max(y, maxY);
  41563. }
  41564. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  41565. }
  41566. return rect;
  41567. };
  41568. return LargeSymbolPath;
  41569. }(Path);
  41570. var LargeSymbolDraw = /** @class */function () {
  41571. function LargeSymbolDraw() {
  41572. this.group = new Group();
  41573. }
  41574. /**
  41575. * Update symbols draw by new data
  41576. */
  41577. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41578. this._clear();
  41579. var symbolEl = this._create();
  41580. symbolEl.setShape({
  41581. points: data.getLayout('points')
  41582. });
  41583. this._setCommon(symbolEl, data, opt);
  41584. };
  41585. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41586. var points = data.getLayout('points');
  41587. this.group.eachChild(function (child) {
  41588. if (child.startIndex != null) {
  41589. var len = (child.endIndex - child.startIndex) * 2;
  41590. var byteOffset = child.startIndex * 4 * 2;
  41591. points = new Float32Array(points.buffer, byteOffset, len);
  41592. }
  41593. child.setShape('points', points);
  41594. // Reset draw cursor.
  41595. child.reset();
  41596. });
  41597. };
  41598. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41599. this._clear();
  41600. };
  41601. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41602. var lastAdded = this._newAdded[0];
  41603. var points = data.getLayout('points');
  41604. var oldPoints = lastAdded && lastAdded.shape.points;
  41605. // Merging the exists. Each element has 1e4 points.
  41606. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  41607. if (oldPoints && oldPoints.length < 2e4) {
  41608. var oldLen = oldPoints.length;
  41609. var newPoints = new Float32Array(oldLen + points.length);
  41610. // Concat two array
  41611. newPoints.set(oldPoints);
  41612. newPoints.set(points, oldLen);
  41613. // Update endIndex
  41614. lastAdded.endIndex = taskParams.end;
  41615. lastAdded.setShape({
  41616. points: newPoints
  41617. });
  41618. } else {
  41619. // Clear
  41620. this._newAdded = [];
  41621. var symbolEl = this._create();
  41622. symbolEl.startIndex = taskParams.start;
  41623. symbolEl.endIndex = taskParams.end;
  41624. symbolEl.incremental = true;
  41625. symbolEl.setShape({
  41626. points: points
  41627. });
  41628. this._setCommon(symbolEl, data, opt);
  41629. }
  41630. };
  41631. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  41632. this._newAdded[0] && cb(this._newAdded[0]);
  41633. };
  41634. LargeSymbolDraw.prototype._create = function () {
  41635. var symbolEl = new LargeSymbolPath({
  41636. cursor: 'default'
  41637. });
  41638. symbolEl.ignoreCoarsePointer = true;
  41639. this.group.add(symbolEl);
  41640. this._newAdded.push(symbolEl);
  41641. return symbolEl;
  41642. };
  41643. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  41644. var hostModel = data.hostModel;
  41645. opt = opt || {};
  41646. var size = data.getVisual('symbolSize');
  41647. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41648. symbolEl.softClipShape = opt.clipShape || null;
  41649. // Create symbolProxy to build path for each data
  41650. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0);
  41651. // Use symbolProxy setColor method
  41652. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41653. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41654. symbolEl.useStyle(
  41655. // Draw shadow when doing fillRect is extremely slow.
  41656. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41657. var globalStyle = data.getVisual('style');
  41658. var visualColor = globalStyle && globalStyle.fill;
  41659. if (visualColor) {
  41660. symbolEl.setColor(visualColor);
  41661. }
  41662. var ecData = getECData(symbolEl);
  41663. // Enable tooltip
  41664. // PENDING May have performance issue when path is extremely large
  41665. ecData.seriesIndex = hostModel.seriesIndex;
  41666. symbolEl.on('mousemove', function (e) {
  41667. ecData.dataIndex = null;
  41668. var dataIndex = symbolEl.hoverDataIdx;
  41669. if (dataIndex >= 0) {
  41670. // Provide dataIndex for tooltip
  41671. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41672. }
  41673. });
  41674. };
  41675. LargeSymbolDraw.prototype.remove = function () {
  41676. this._clear();
  41677. };
  41678. LargeSymbolDraw.prototype._clear = function () {
  41679. this._newAdded = [];
  41680. this.group.removeAll();
  41681. };
  41682. return LargeSymbolDraw;
  41683. }();
  41684. var ScatterView = /** @class */function (_super) {
  41685. __extends(ScatterView, _super);
  41686. function ScatterView() {
  41687. var _this = _super !== null && _super.apply(this, arguments) || this;
  41688. _this.type = ScatterView.type;
  41689. return _this;
  41690. }
  41691. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41692. var data = seriesModel.getData();
  41693. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41694. symbolDraw.updateData(data, {
  41695. // TODO
  41696. // If this parameter should be a shape or a bounding volume
  41697. // shape will be more general.
  41698. // But bounding volume like bounding rect will be much faster in the contain calculation
  41699. clipShape: this._getClipShape(seriesModel)
  41700. });
  41701. this._finished = true;
  41702. };
  41703. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41704. var data = seriesModel.getData();
  41705. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41706. symbolDraw.incrementalPrepareUpdate(data);
  41707. this._finished = false;
  41708. };
  41709. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41710. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41711. clipShape: this._getClipShape(seriesModel)
  41712. });
  41713. this._finished = taskParams.end === seriesModel.getData().count();
  41714. };
  41715. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41716. var data = seriesModel.getData();
  41717. // Must mark group dirty and make sure the incremental layer will be cleared
  41718. // PENDING
  41719. this.group.dirty();
  41720. if (!this._finished || data.count() > 1e4) {
  41721. return {
  41722. update: true
  41723. };
  41724. } else {
  41725. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41726. if (res.progress) {
  41727. res.progress({
  41728. start: 0,
  41729. end: data.count(),
  41730. count: data.count()
  41731. }, data);
  41732. }
  41733. this._symbolDraw.updateLayout(data);
  41734. }
  41735. };
  41736. ScatterView.prototype.eachRendered = function (cb) {
  41737. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  41738. };
  41739. ScatterView.prototype._getClipShape = function (seriesModel) {
  41740. if (!seriesModel.get('clip', true)) {
  41741. return;
  41742. }
  41743. var coordSys = seriesModel.coordinateSystem;
  41744. // PENDING make `0.1` configurable, for example, `clipTolerance`?
  41745. return coordSys && coordSys.getArea && coordSys.getArea(.1);
  41746. };
  41747. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41748. var symbolDraw = this._symbolDraw;
  41749. var pipelineContext = seriesModel.pipelineContext;
  41750. var isLargeDraw = pipelineContext.large;
  41751. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41752. symbolDraw && symbolDraw.remove();
  41753. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41754. this._isLargeDraw = isLargeDraw;
  41755. this.group.removeAll();
  41756. }
  41757. this.group.add(symbolDraw.group);
  41758. return symbolDraw;
  41759. };
  41760. ScatterView.prototype.remove = function (ecModel, api) {
  41761. this._symbolDraw && this._symbolDraw.remove(true);
  41762. this._symbolDraw = null;
  41763. };
  41764. ScatterView.prototype.dispose = function () {};
  41765. ScatterView.type = 'scatter';
  41766. return ScatterView;
  41767. }(ChartView);
  41768. var GridModel = /** @class */function (_super) {
  41769. __extends(GridModel, _super);
  41770. function GridModel() {
  41771. return _super !== null && _super.apply(this, arguments) || this;
  41772. }
  41773. GridModel.type = 'grid';
  41774. GridModel.dependencies = ['xAxis', 'yAxis'];
  41775. GridModel.layoutMode = 'box';
  41776. GridModel.defaultOption = {
  41777. show: false,
  41778. // zlevel: 0,
  41779. z: 0,
  41780. left: '10%',
  41781. top: 60,
  41782. right: '10%',
  41783. bottom: 70,
  41784. // If grid size contain label
  41785. containLabel: false,
  41786. // width: {totalWidth} - left - right,
  41787. // height: {totalHeight} - top - bottom,
  41788. backgroundColor: 'rgba(0,0,0,0)',
  41789. borderWidth: 1,
  41790. borderColor: '#ccc'
  41791. };
  41792. return GridModel;
  41793. }(ComponentModel);
  41794. var CartesianAxisModel = /** @class */function (_super) {
  41795. __extends(CartesianAxisModel, _super);
  41796. function CartesianAxisModel() {
  41797. return _super !== null && _super.apply(this, arguments) || this;
  41798. }
  41799. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41800. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41801. };
  41802. CartesianAxisModel.type = 'cartesian2dAxis';
  41803. return CartesianAxisModel;
  41804. }(ComponentModel);
  41805. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41806. var defaultOption = {
  41807. show: true,
  41808. // zlevel: 0,
  41809. z: 0,
  41810. // Inverse the axis.
  41811. inverse: false,
  41812. // Axis name displayed.
  41813. name: '',
  41814. // 'start' | 'middle' | 'end'
  41815. nameLocation: 'end',
  41816. // By degree. By default auto rotate by nameLocation.
  41817. nameRotate: null,
  41818. nameTruncate: {
  41819. maxWidth: null,
  41820. ellipsis: '...',
  41821. placeholder: '.'
  41822. },
  41823. // Use global text style by default.
  41824. nameTextStyle: {},
  41825. // The gap between axisName and axisLine.
  41826. nameGap: 15,
  41827. // Default `false` to support tooltip.
  41828. silent: false,
  41829. // Default `false` to avoid legacy user event listener fail.
  41830. triggerEvent: false,
  41831. tooltip: {
  41832. show: false
  41833. },
  41834. axisPointer: {},
  41835. axisLine: {
  41836. show: true,
  41837. onZero: true,
  41838. onZeroAxisIndex: null,
  41839. lineStyle: {
  41840. color: '#6E7079',
  41841. width: 1,
  41842. type: 'solid'
  41843. },
  41844. // The arrow at both ends the the axis.
  41845. symbol: ['none', 'none'],
  41846. symbolSize: [10, 15]
  41847. },
  41848. axisTick: {
  41849. show: true,
  41850. // Whether axisTick is inside the grid or outside the grid.
  41851. inside: false,
  41852. // The length of axisTick.
  41853. length: 5,
  41854. lineStyle: {
  41855. width: 1
  41856. }
  41857. },
  41858. axisLabel: {
  41859. show: true,
  41860. // Whether axisLabel is inside the grid or outside the grid.
  41861. inside: false,
  41862. rotate: 0,
  41863. // true | false | null/undefined (auto)
  41864. showMinLabel: null,
  41865. // true | false | null/undefined (auto)
  41866. showMaxLabel: null,
  41867. margin: 8,
  41868. // formatter: null,
  41869. fontSize: 12
  41870. },
  41871. splitLine: {
  41872. show: true,
  41873. showMinLine: true,
  41874. showMaxLine: true,
  41875. lineStyle: {
  41876. color: ['#E0E6F1'],
  41877. width: 1,
  41878. type: 'solid'
  41879. }
  41880. },
  41881. splitArea: {
  41882. show: false,
  41883. areaStyle: {
  41884. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  41885. }
  41886. }
  41887. };
  41888. var categoryAxis = merge({
  41889. // The gap at both ends of the axis. For categoryAxis, boolean.
  41890. boundaryGap: true,
  41891. // Set false to faster category collection.
  41892. deduplication: null,
  41893. // splitArea: {
  41894. // show: false
  41895. // },
  41896. splitLine: {
  41897. show: false
  41898. },
  41899. axisTick: {
  41900. // If tick is align with label when boundaryGap is true
  41901. alignWithLabel: false,
  41902. interval: 'auto'
  41903. },
  41904. axisLabel: {
  41905. interval: 'auto'
  41906. }
  41907. }, defaultOption);
  41908. var valueAxis = merge({
  41909. boundaryGap: [0, 0],
  41910. axisLine: {
  41911. // Not shown when other axis is categoryAxis in cartesian
  41912. show: 'auto'
  41913. },
  41914. axisTick: {
  41915. // Not shown when other axis is categoryAxis in cartesian
  41916. show: 'auto'
  41917. },
  41918. // TODO
  41919. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  41920. splitNumber: 5,
  41921. minorTick: {
  41922. // Minor tick, not available for cateogry axis.
  41923. show: false,
  41924. // Split number of minor ticks. The value should be in range of (0, 100)
  41925. splitNumber: 5,
  41926. // Length of minor tick
  41927. length: 3,
  41928. // Line style
  41929. lineStyle: {
  41930. // Default to be same with axisTick
  41931. }
  41932. },
  41933. minorSplitLine: {
  41934. show: false,
  41935. lineStyle: {
  41936. color: '#F4F7FD',
  41937. width: 1
  41938. }
  41939. }
  41940. }, defaultOption);
  41941. var timeAxis = merge({
  41942. splitNumber: 6,
  41943. axisLabel: {
  41944. // To eliminate labels that are not nice
  41945. showMinLabel: false,
  41946. showMaxLabel: false,
  41947. rich: {
  41948. primary: {
  41949. fontWeight: 'bold'
  41950. }
  41951. }
  41952. },
  41953. splitLine: {
  41954. show: false
  41955. }
  41956. }, valueAxis);
  41957. var logAxis = defaults({
  41958. logBase: 10
  41959. }, valueAxis);
  41960. var axisDefault = {
  41961. category: categoryAxis,
  41962. value: valueAxis,
  41963. time: timeAxis,
  41964. log: logAxis
  41965. };
  41966. /*
  41967. * Licensed to the Apache Software Foundation (ASF) under one
  41968. * or more contributor license agreements. See the NOTICE file
  41969. * distributed with this work for additional information
  41970. * regarding copyright ownership. The ASF licenses this file
  41971. * to you under the Apache License, Version 2.0 (the
  41972. * "License"); you may not use this file except in compliance
  41973. * with the License. You may obtain a copy of the License at
  41974. *
  41975. * http://www.apache.org/licenses/LICENSE-2.0
  41976. *
  41977. * Unless required by applicable law or agreed to in writing,
  41978. * software distributed under the License is distributed on an
  41979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41980. * KIND, either express or implied. See the License for the
  41981. * specific language governing permissions and limitations
  41982. * under the License.
  41983. */
  41984. /**
  41985. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41986. */
  41987. /*
  41988. * Licensed to the Apache Software Foundation (ASF) under one
  41989. * or more contributor license agreements. See the NOTICE file
  41990. * distributed with this work for additional information
  41991. * regarding copyright ownership. The ASF licenses this file
  41992. * to you under the Apache License, Version 2.0 (the
  41993. * "License"); you may not use this file except in compliance
  41994. * with the License. You may obtain a copy of the License at
  41995. *
  41996. * http://www.apache.org/licenses/LICENSE-2.0
  41997. *
  41998. * Unless required by applicable law or agreed to in writing,
  41999. * software distributed under the License is distributed on an
  42000. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42001. * KIND, either express or implied. See the License for the
  42002. * specific language governing permissions and limitations
  42003. * under the License.
  42004. */
  42005. var AXIS_TYPES = {
  42006. value: 1,
  42007. category: 1,
  42008. time: 1,
  42009. log: 1
  42010. };
  42011. /**
  42012. * Generate sub axis model class
  42013. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  42014. */
  42015. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  42016. each(AXIS_TYPES, function (v, axisType) {
  42017. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  42018. var AxisModel = /** @class */function (_super) {
  42019. __extends(AxisModel, _super);
  42020. function AxisModel() {
  42021. var _this = _super !== null && _super.apply(this, arguments) || this;
  42022. _this.type = axisName + 'Axis.' + axisType;
  42023. return _this;
  42024. }
  42025. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  42026. var layoutMode = fetchLayoutMode(this);
  42027. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  42028. var themeModel = ecModel.getTheme();
  42029. merge(option, themeModel.get(axisType + 'Axis'));
  42030. merge(option, this.getDefaultOption());
  42031. option.type = getAxisType(option);
  42032. if (layoutMode) {
  42033. mergeLayoutParam(option, inputPositionParams, layoutMode);
  42034. }
  42035. };
  42036. AxisModel.prototype.optionUpdated = function () {
  42037. var thisOption = this.option;
  42038. if (thisOption.type === 'category') {
  42039. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  42040. }
  42041. };
  42042. /**
  42043. * Should not be called before all of 'getInitailData' finished.
  42044. * Because categories are collected during initializing data.
  42045. */
  42046. AxisModel.prototype.getCategories = function (rawData) {
  42047. var option = this.option;
  42048. // FIXME
  42049. // warning if called before all of 'getInitailData' finished.
  42050. if (option.type === 'category') {
  42051. if (rawData) {
  42052. return option.data;
  42053. }
  42054. return this.__ordinalMeta.categories;
  42055. }
  42056. };
  42057. AxisModel.prototype.getOrdinalMeta = function () {
  42058. return this.__ordinalMeta;
  42059. };
  42060. AxisModel.type = axisName + 'Axis.' + axisType;
  42061. AxisModel.defaultOption = defaultOption;
  42062. return AxisModel;
  42063. }(BaseAxisModelClass);
  42064. registers.registerComponentModel(AxisModel);
  42065. });
  42066. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  42067. }
  42068. function getAxisType(option) {
  42069. // Default axis with data is category axis
  42070. return option.type || (option.data ? 'category' : 'value');
  42071. }
  42072. var Cartesian = /** @class */function () {
  42073. function Cartesian(name) {
  42074. this.type = 'cartesian';
  42075. this._dimList = [];
  42076. this._axes = {};
  42077. this.name = name || '';
  42078. }
  42079. Cartesian.prototype.getAxis = function (dim) {
  42080. return this._axes[dim];
  42081. };
  42082. Cartesian.prototype.getAxes = function () {
  42083. return map(this._dimList, function (dim) {
  42084. return this._axes[dim];
  42085. }, this);
  42086. };
  42087. Cartesian.prototype.getAxesByScale = function (scaleType) {
  42088. scaleType = scaleType.toLowerCase();
  42089. return filter(this.getAxes(), function (axis) {
  42090. return axis.scale.type === scaleType;
  42091. });
  42092. };
  42093. Cartesian.prototype.addAxis = function (axis) {
  42094. var dim = axis.dim;
  42095. this._axes[dim] = axis;
  42096. this._dimList.push(dim);
  42097. };
  42098. return Cartesian;
  42099. }();
  42100. var cartesian2DDimensions = ['x', 'y'];
  42101. function canCalculateAffineTransform(scale) {
  42102. return scale.type === 'interval' || scale.type === 'time';
  42103. }
  42104. var Cartesian2D = /** @class */function (_super) {
  42105. __extends(Cartesian2D, _super);
  42106. function Cartesian2D() {
  42107. var _this = _super !== null && _super.apply(this, arguments) || this;
  42108. _this.type = 'cartesian2d';
  42109. _this.dimensions = cartesian2DDimensions;
  42110. return _this;
  42111. }
  42112. /**
  42113. * Calculate an affine transform matrix if two axes are time or value.
  42114. * It's mainly for accelartion on the large time series data.
  42115. */
  42116. Cartesian2D.prototype.calcAffineTransform = function () {
  42117. this._transform = this._invTransform = null;
  42118. var xAxisScale = this.getAxis('x').scale;
  42119. var yAxisScale = this.getAxis('y').scale;
  42120. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  42121. return;
  42122. }
  42123. var xScaleExtent = xAxisScale.getExtent();
  42124. var yScaleExtent = yAxisScale.getExtent();
  42125. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  42126. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  42127. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  42128. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  42129. if (!xScaleSpan || !yScaleSpan) {
  42130. return;
  42131. }
  42132. // Accelerate data to point calculation on the special large time series data.
  42133. var scaleX = (end[0] - start[0]) / xScaleSpan;
  42134. var scaleY = (end[1] - start[1]) / yScaleSpan;
  42135. var translateX = start[0] - xScaleExtent[0] * scaleX;
  42136. var translateY = start[1] - yScaleExtent[0] * scaleY;
  42137. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  42138. this._invTransform = invert([], m);
  42139. };
  42140. /**
  42141. * Base axis will be used on stacking.
  42142. */
  42143. Cartesian2D.prototype.getBaseAxis = function () {
  42144. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  42145. };
  42146. Cartesian2D.prototype.containPoint = function (point) {
  42147. var axisX = this.getAxis('x');
  42148. var axisY = this.getAxis('y');
  42149. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  42150. };
  42151. Cartesian2D.prototype.containData = function (data) {
  42152. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  42153. };
  42154. Cartesian2D.prototype.containZone = function (data1, data2) {
  42155. var zoneDiag1 = this.dataToPoint(data1);
  42156. var zoneDiag2 = this.dataToPoint(data2);
  42157. var area = this.getArea();
  42158. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  42159. return area.intersect(zone);
  42160. };
  42161. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  42162. out = out || [];
  42163. var xVal = data[0];
  42164. var yVal = data[1];
  42165. // Fast path
  42166. if (this._transform
  42167. // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  42168. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  42169. return applyTransform(out, data, this._transform);
  42170. }
  42171. var xAxis = this.getAxis('x');
  42172. var yAxis = this.getAxis('y');
  42173. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  42174. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  42175. return out;
  42176. };
  42177. Cartesian2D.prototype.clampData = function (data, out) {
  42178. var xScale = this.getAxis('x').scale;
  42179. var yScale = this.getAxis('y').scale;
  42180. var xAxisExtent = xScale.getExtent();
  42181. var yAxisExtent = yScale.getExtent();
  42182. var x = xScale.parse(data[0]);
  42183. var y = yScale.parse(data[1]);
  42184. out = out || [];
  42185. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  42186. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  42187. return out;
  42188. };
  42189. Cartesian2D.prototype.pointToData = function (point, clamp) {
  42190. var out = [];
  42191. if (this._invTransform) {
  42192. return applyTransform(out, point, this._invTransform);
  42193. }
  42194. var xAxis = this.getAxis('x');
  42195. var yAxis = this.getAxis('y');
  42196. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  42197. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  42198. return out;
  42199. };
  42200. Cartesian2D.prototype.getOtherAxis = function (axis) {
  42201. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  42202. };
  42203. /**
  42204. * Get rect area of cartesian.
  42205. * Area will have a contain function to determine if a point is in the coordinate system.
  42206. */
  42207. Cartesian2D.prototype.getArea = function (tolerance) {
  42208. tolerance = tolerance || 0;
  42209. var xExtent = this.getAxis('x').getGlobalExtent();
  42210. var yExtent = this.getAxis('y').getGlobalExtent();
  42211. var x = Math.min(xExtent[0], xExtent[1]) - tolerance;
  42212. var y = Math.min(yExtent[0], yExtent[1]) - tolerance;
  42213. var width = Math.max(xExtent[0], xExtent[1]) - x + tolerance;
  42214. var height = Math.max(yExtent[0], yExtent[1]) - y + tolerance;
  42215. return new BoundingRect(x, y, width, height);
  42216. };
  42217. return Cartesian2D;
  42218. }(Cartesian);
  42219. var Axis2D = /** @class */function (_super) {
  42220. __extends(Axis2D, _super);
  42221. function Axis2D(dim, scale, coordExtent, axisType, position) {
  42222. var _this = _super.call(this, dim, scale, coordExtent) || this;
  42223. /**
  42224. * Index of axis, can be used as key
  42225. * Injected outside.
  42226. */
  42227. _this.index = 0;
  42228. _this.type = axisType || 'value';
  42229. _this.position = position || 'bottom';
  42230. return _this;
  42231. }
  42232. Axis2D.prototype.isHorizontal = function () {
  42233. var position = this.position;
  42234. return position === 'top' || position === 'bottom';
  42235. };
  42236. /**
  42237. * Each item cooresponds to this.getExtent(), which
  42238. * means globalExtent[0] may greater than globalExtent[1],
  42239. * unless `asc` is input.
  42240. *
  42241. * @param {boolean} [asc]
  42242. * @return {Array.<number>}
  42243. */
  42244. Axis2D.prototype.getGlobalExtent = function (asc) {
  42245. var ret = this.getExtent();
  42246. ret[0] = this.toGlobalCoord(ret[0]);
  42247. ret[1] = this.toGlobalCoord(ret[1]);
  42248. asc && ret[0] > ret[1] && ret.reverse();
  42249. return ret;
  42250. };
  42251. Axis2D.prototype.pointToData = function (point, clamp) {
  42252. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42253. };
  42254. /**
  42255. * Set ordinalSortInfo
  42256. * @param info new OrdinalSortInfo
  42257. */
  42258. Axis2D.prototype.setCategorySortInfo = function (info) {
  42259. if (this.type !== 'category') {
  42260. return false;
  42261. }
  42262. this.model.option.categorySortInfo = info;
  42263. this.scale.setSortInfo(info);
  42264. };
  42265. return Axis2D;
  42266. }(Axis);
  42267. /**
  42268. * Can only be called after coordinate system creation stage.
  42269. * (Can be called before coordinate system update stage).
  42270. */
  42271. function layout$1(gridModel, axisModel, opt) {
  42272. opt = opt || {};
  42273. var grid = gridModel.coordinateSystem;
  42274. var axis = axisModel.axis;
  42275. var layout = {};
  42276. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42277. var rawAxisPosition = axis.position;
  42278. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42279. var axisDim = axis.dim;
  42280. var rect = grid.getRect();
  42281. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42282. var idx = {
  42283. left: 0,
  42284. right: 1,
  42285. top: 0,
  42286. bottom: 1,
  42287. onZero: 2
  42288. };
  42289. var axisOffset = axisModel.get('offset') || 0;
  42290. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42291. if (otherAxisOnZeroOf) {
  42292. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42293. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42294. }
  42295. // Axis position
  42296. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]];
  42297. // Axis rotation
  42298. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  42299. // Tick and label direction, x y is axisDim
  42300. var dirMap = {
  42301. top: -1,
  42302. bottom: 1,
  42303. left: -1,
  42304. right: 1
  42305. };
  42306. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42307. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42308. if (axisModel.get(['axisTick', 'inside'])) {
  42309. layout.tickDirection = -layout.tickDirection;
  42310. }
  42311. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42312. layout.labelDirection = -layout.labelDirection;
  42313. }
  42314. // Special label rotation
  42315. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42316. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  42317. // Over splitLine and splitArea
  42318. layout.z2 = 1;
  42319. return layout;
  42320. }
  42321. function isCartesian2DSeries(seriesModel) {
  42322. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42323. }
  42324. function findAxisModels(seriesModel) {
  42325. var axisModelMap = {
  42326. xAxisModel: null,
  42327. yAxisModel: null
  42328. };
  42329. each(axisModelMap, function (v, key) {
  42330. var axisType = key.replace(/Model$/, '');
  42331. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42332. if ("development" !== 'production') {
  42333. if (!axisModel) {
  42334. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42335. }
  42336. }
  42337. axisModelMap[key] = axisModel;
  42338. });
  42339. return axisModelMap;
  42340. }
  42341. var mathLog$1 = Math.log;
  42342. function alignScaleTicks(scale, axisModel, alignToScale) {
  42343. var intervalScaleProto = IntervalScale.prototype;
  42344. // NOTE: There is a precondition for log scale here:
  42345. // In log scale we store _interval and _extent of exponent value.
  42346. // So if we use the method of InternalScale to set/get these data.
  42347. // It process the exponent value, which is linear and what we want here.
  42348. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  42349. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  42350. var alignToSplitNumber = alignToTicks.length - 1;
  42351. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  42352. var scaleExtent = getScaleExtent(scale, axisModel);
  42353. var rawExtent = scaleExtent.extent;
  42354. var isMinFixed = scaleExtent.fixMin;
  42355. var isMaxFixed = scaleExtent.fixMax;
  42356. if (scale.type === 'log') {
  42357. var logBase = mathLog$1(scale.base);
  42358. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  42359. }
  42360. scale.setExtent(rawExtent[0], rawExtent[1]);
  42361. scale.calcNiceExtent({
  42362. splitNumber: alignToSplitNumber,
  42363. fixMin: isMinFixed,
  42364. fixMax: isMaxFixed
  42365. });
  42366. var extent = intervalScaleProto.getExtent.call(scale);
  42367. // Need to update the rawExtent.
  42368. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  42369. if (isMinFixed) {
  42370. rawExtent[0] = extent[0];
  42371. }
  42372. if (isMaxFixed) {
  42373. rawExtent[1] = extent[1];
  42374. }
  42375. var interval = intervalScaleProto.getInterval.call(scale);
  42376. var min = rawExtent[0];
  42377. var max = rawExtent[1];
  42378. if (isMinFixed && isMaxFixed) {
  42379. // User set min, max, divide to get new interval
  42380. interval = (max - min) / alignToSplitNumber;
  42381. } else if (isMinFixed) {
  42382. max = rawExtent[0] + interval * alignToSplitNumber;
  42383. // User set min, expand extent on the other side
  42384. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  42385. interval = increaseInterval(interval);
  42386. max = rawExtent[0] + interval * alignToSplitNumber;
  42387. }
  42388. } else if (isMaxFixed) {
  42389. // User set max, expand extent on the other side
  42390. min = rawExtent[1] - interval * alignToSplitNumber;
  42391. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  42392. interval = increaseInterval(interval);
  42393. min = rawExtent[1] - interval * alignToSplitNumber;
  42394. }
  42395. } else {
  42396. var nicedSplitNumber = scale.getTicks().length - 1;
  42397. if (nicedSplitNumber > alignToSplitNumber) {
  42398. interval = increaseInterval(interval);
  42399. }
  42400. var range = interval * alignToSplitNumber;
  42401. max = Math.ceil(rawExtent[1] / interval) * interval;
  42402. min = round(max - range);
  42403. // Not change the result that crossing zero.
  42404. if (min < 0 && rawExtent[0] >= 0) {
  42405. min = 0;
  42406. max = round(range);
  42407. } else if (max > 0 && rawExtent[1] <= 0) {
  42408. max = 0;
  42409. min = -round(range);
  42410. }
  42411. }
  42412. // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  42413. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  42414. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval;
  42415. // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  42416. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  42417. intervalScaleProto.setInterval.call(scale, interval);
  42418. if (t0 || t1) {
  42419. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  42420. }
  42421. if ("development" !== 'production') {
  42422. var ticks = intervalScaleProto.getTicks.call(scale);
  42423. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  42424. warn(
  42425. // eslint-disable-next-line
  42426. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  42427. }
  42428. }
  42429. }
  42430. var Grid = /** @class */function () {
  42431. function Grid(gridModel, ecModel, api) {
  42432. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42433. this.type = 'grid';
  42434. this._coordsMap = {};
  42435. this._coordsList = [];
  42436. this._axesMap = {};
  42437. this._axesList = [];
  42438. this.axisPointerEnabled = true;
  42439. this.dimensions = cartesian2DDimensions;
  42440. this._initCartesian(gridModel, ecModel, api);
  42441. this.model = gridModel;
  42442. }
  42443. Grid.prototype.getRect = function () {
  42444. return this._rect;
  42445. };
  42446. Grid.prototype.update = function (ecModel, api) {
  42447. var axesMap = this._axesMap;
  42448. this._updateScale(ecModel, this.model);
  42449. function updateAxisTicks(axes) {
  42450. var alignTo;
  42451. // Axis is added in order of axisIndex.
  42452. var axesIndices = keys(axes);
  42453. var len = axesIndices.length;
  42454. if (!len) {
  42455. return;
  42456. }
  42457. var axisNeedsAlign = [];
  42458. // Process once and calculate the ticks for those don't use alignTicks.
  42459. for (var i = len - 1; i >= 0; i--) {
  42460. var idx = +axesIndices[i]; // Convert to number.
  42461. var axis = axes[idx];
  42462. var model = axis.model;
  42463. var scale = axis.scale;
  42464. if (
  42465. // Only value and log axis without interval support alignTicks.
  42466. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  42467. axisNeedsAlign.push(axis);
  42468. } else {
  42469. niceScaleExtent(scale, model);
  42470. if (isIntervalOrLogScale(scale)) {
  42471. // Can only align to interval or log axis.
  42472. alignTo = axis;
  42473. }
  42474. }
  42475. }
  42476. // All axes has set alignTicks. Pick the first one.
  42477. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  42478. if (axisNeedsAlign.length) {
  42479. if (!alignTo) {
  42480. alignTo = axisNeedsAlign.pop();
  42481. niceScaleExtent(alignTo.scale, alignTo.model);
  42482. }
  42483. each(axisNeedsAlign, function (axis) {
  42484. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  42485. });
  42486. }
  42487. }
  42488. updateAxisTicks(axesMap.x);
  42489. updateAxisTicks(axesMap.y);
  42490. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42491. var onZeroRecords = {};
  42492. each(axesMap.x, function (xAxis) {
  42493. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42494. });
  42495. each(axesMap.y, function (yAxis) {
  42496. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42497. });
  42498. // Resize again if containLabel is enabled
  42499. // FIXME It may cause getting wrong grid size in data processing stage
  42500. this.resize(this.model, api);
  42501. };
  42502. /**
  42503. * Resize the grid
  42504. */
  42505. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42506. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42507. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42508. var gridRect = getLayoutRect(boxLayoutParams, {
  42509. width: api.getWidth(),
  42510. height: api.getHeight()
  42511. });
  42512. this._rect = gridRect;
  42513. var axesList = this._axesList;
  42514. adjustAxes();
  42515. // Minus label size
  42516. if (isContainLabel) {
  42517. each(axesList, function (axis) {
  42518. if (!axis.model.get(['axisLabel', 'inside'])) {
  42519. var labelUnionRect = estimateLabelUnionRect(axis);
  42520. if (labelUnionRect) {
  42521. var dim = axis.isHorizontal() ? 'height' : 'width';
  42522. var margin = axis.model.get(['axisLabel', 'margin']);
  42523. gridRect[dim] -= labelUnionRect[dim] + margin;
  42524. if (axis.position === 'top') {
  42525. gridRect.y += labelUnionRect.height + margin;
  42526. } else if (axis.position === 'left') {
  42527. gridRect.x += labelUnionRect.width + margin;
  42528. }
  42529. }
  42530. }
  42531. });
  42532. adjustAxes();
  42533. }
  42534. each(this._coordsList, function (coord) {
  42535. // Calculate affine matrix to accelerate the data to point transform.
  42536. // If all the axes scales are time or value.
  42537. coord.calcAffineTransform();
  42538. });
  42539. function adjustAxes() {
  42540. each(axesList, function (axis) {
  42541. var isHorizontal = axis.isHorizontal();
  42542. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42543. var idx = axis.inverse ? 1 : 0;
  42544. axis.setExtent(extent[idx], extent[1 - idx]);
  42545. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42546. });
  42547. }
  42548. };
  42549. Grid.prototype.getAxis = function (dim, axisIndex) {
  42550. var axesMapOnDim = this._axesMap[dim];
  42551. if (axesMapOnDim != null) {
  42552. return axesMapOnDim[axisIndex || 0];
  42553. }
  42554. };
  42555. Grid.prototype.getAxes = function () {
  42556. return this._axesList.slice();
  42557. };
  42558. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42559. if (xAxisIndex != null && yAxisIndex != null) {
  42560. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42561. return this._coordsMap[key];
  42562. }
  42563. if (isObject(xAxisIndex)) {
  42564. yAxisIndex = xAxisIndex.yAxisIndex;
  42565. xAxisIndex = xAxisIndex.xAxisIndex;
  42566. }
  42567. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42568. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42569. return coordList[i];
  42570. }
  42571. }
  42572. };
  42573. Grid.prototype.getCartesians = function () {
  42574. return this._coordsList.slice();
  42575. };
  42576. /**
  42577. * @implements
  42578. */
  42579. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42580. var target = this._findConvertTarget(finder);
  42581. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42582. };
  42583. /**
  42584. * @implements
  42585. */
  42586. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42587. var target = this._findConvertTarget(finder);
  42588. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42589. };
  42590. Grid.prototype._findConvertTarget = function (finder) {
  42591. var seriesModel = finder.seriesModel;
  42592. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42593. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42594. var gridModel = finder.gridModel;
  42595. var coordsList = this._coordsList;
  42596. var cartesian;
  42597. var axis;
  42598. if (seriesModel) {
  42599. cartesian = seriesModel.coordinateSystem;
  42600. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42601. } else if (xAxisModel && yAxisModel) {
  42602. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42603. } else if (xAxisModel) {
  42604. axis = this.getAxis('x', xAxisModel.componentIndex);
  42605. } else if (yAxisModel) {
  42606. axis = this.getAxis('y', yAxisModel.componentIndex);
  42607. }
  42608. // Lowest priority.
  42609. else if (gridModel) {
  42610. var grid = gridModel.coordinateSystem;
  42611. if (grid === this) {
  42612. cartesian = this._coordsList[0];
  42613. }
  42614. }
  42615. return {
  42616. cartesian: cartesian,
  42617. axis: axis
  42618. };
  42619. };
  42620. /**
  42621. * @implements
  42622. */
  42623. Grid.prototype.containPoint = function (point) {
  42624. var coord = this._coordsList[0];
  42625. if (coord) {
  42626. return coord.containPoint(point);
  42627. }
  42628. };
  42629. /**
  42630. * Initialize cartesian coordinate systems
  42631. */
  42632. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42633. var _this = this;
  42634. var grid = this;
  42635. var axisPositionUsed = {
  42636. left: false,
  42637. right: false,
  42638. top: false,
  42639. bottom: false
  42640. };
  42641. var axesMap = {
  42642. x: {},
  42643. y: {}
  42644. };
  42645. var axesCount = {
  42646. x: 0,
  42647. y: 0
  42648. };
  42649. // Create axis
  42650. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42651. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42652. if (!axesCount.x || !axesCount.y) {
  42653. // Roll back when there no either x or y axis
  42654. this._axesMap = {};
  42655. this._axesList = [];
  42656. return;
  42657. }
  42658. this._axesMap = axesMap;
  42659. // Create cartesian2d
  42660. each(axesMap.x, function (xAxis, xAxisIndex) {
  42661. each(axesMap.y, function (yAxis, yAxisIndex) {
  42662. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42663. var cartesian = new Cartesian2D(key);
  42664. cartesian.master = _this;
  42665. cartesian.model = gridModel;
  42666. _this._coordsMap[key] = cartesian;
  42667. _this._coordsList.push(cartesian);
  42668. cartesian.addAxis(xAxis);
  42669. cartesian.addAxis(yAxis);
  42670. });
  42671. });
  42672. function createAxisCreator(dimName) {
  42673. return function (axisModel, idx) {
  42674. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42675. return;
  42676. }
  42677. var axisPosition = axisModel.get('position');
  42678. if (dimName === 'x') {
  42679. // Fix position
  42680. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42681. // Default bottom of X
  42682. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42683. }
  42684. } else {
  42685. // Fix position
  42686. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42687. // Default left of Y
  42688. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42689. }
  42690. }
  42691. axisPositionUsed[axisPosition] = true;
  42692. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42693. var isCategory = axis.type === 'category';
  42694. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42695. axis.inverse = axisModel.get('inverse');
  42696. // Inject axis into axisModel
  42697. axisModel.axis = axis;
  42698. // Inject axisModel into axis
  42699. axis.model = axisModel;
  42700. // Inject grid info axis
  42701. axis.grid = grid;
  42702. // Index of axis, can be used as key
  42703. axis.index = idx;
  42704. grid._axesList.push(axis);
  42705. axesMap[dimName][idx] = axis;
  42706. axesCount[dimName]++;
  42707. };
  42708. }
  42709. };
  42710. /**
  42711. * Update cartesian properties from series.
  42712. */
  42713. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42714. // Reset scale
  42715. each(this._axesList, function (axis) {
  42716. axis.scale.setExtent(Infinity, -Infinity);
  42717. if (axis.type === 'category') {
  42718. var categorySortInfo = axis.model.get('categorySortInfo');
  42719. axis.scale.setSortInfo(categorySortInfo);
  42720. }
  42721. });
  42722. ecModel.eachSeries(function (seriesModel) {
  42723. if (isCartesian2DSeries(seriesModel)) {
  42724. var axesModelMap = findAxisModels(seriesModel);
  42725. var xAxisModel = axesModelMap.xAxisModel;
  42726. var yAxisModel = axesModelMap.yAxisModel;
  42727. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42728. return;
  42729. }
  42730. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42731. var data = seriesModel.getData();
  42732. var xAxis = cartesian.getAxis('x');
  42733. var yAxis = cartesian.getAxis('y');
  42734. unionExtent(data, xAxis);
  42735. unionExtent(data, yAxis);
  42736. }
  42737. }, this);
  42738. function unionExtent(data, axis) {
  42739. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42740. axis.scale.unionExtentFromData(data, dim);
  42741. });
  42742. }
  42743. };
  42744. /**
  42745. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42746. */
  42747. Grid.prototype.getTooltipAxes = function (dim) {
  42748. var baseAxes = [];
  42749. var otherAxes = [];
  42750. each(this.getCartesians(), function (cartesian) {
  42751. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42752. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42753. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42754. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42755. });
  42756. return {
  42757. baseAxes: baseAxes,
  42758. otherAxes: otherAxes
  42759. };
  42760. };
  42761. Grid.create = function (ecModel, api) {
  42762. var grids = [];
  42763. ecModel.eachComponent('grid', function (gridModel, idx) {
  42764. var grid = new Grid(gridModel, ecModel, api);
  42765. grid.name = 'grid_' + idx;
  42766. // dataSampling requires axis extent, so resize
  42767. // should be performed in create stage.
  42768. grid.resize(gridModel, api, true);
  42769. gridModel.coordinateSystem = grid;
  42770. grids.push(grid);
  42771. });
  42772. // Inject the coordinateSystems into seriesModel
  42773. ecModel.eachSeries(function (seriesModel) {
  42774. if (!isCartesian2DSeries(seriesModel)) {
  42775. return;
  42776. }
  42777. var axesModelMap = findAxisModels(seriesModel);
  42778. var xAxisModel = axesModelMap.xAxisModel;
  42779. var yAxisModel = axesModelMap.yAxisModel;
  42780. var gridModel = xAxisModel.getCoordSysModel();
  42781. if ("development" !== 'production') {
  42782. if (!gridModel) {
  42783. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42784. }
  42785. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42786. throw new Error('xAxis and yAxis must use the same grid');
  42787. }
  42788. }
  42789. var grid = gridModel.coordinateSystem;
  42790. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42791. });
  42792. return grids;
  42793. };
  42794. // For deciding which dimensions to use when creating list data
  42795. Grid.dimensions = cartesian2DDimensions;
  42796. return Grid;
  42797. }();
  42798. /**
  42799. * Check if the axis is used in the specified grid.
  42800. */
  42801. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42802. return axisModel.getCoordSysModel() === gridModel;
  42803. }
  42804. function fixAxisOnZero(axesMap, otherAxisDim, axis,
  42805. // Key: see `getOnZeroRecordKey`
  42806. onZeroRecords) {
  42807. axis.getAxesOnZeroOf = function () {
  42808. // TODO: onZero of multiple axes.
  42809. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42810. };
  42811. // onZero can not be enabled in these two situations:
  42812. // 1. When any other axis is a category axis.
  42813. // 2. When no axis is cross 0 point.
  42814. var otherAxes = axesMap[otherAxisDim];
  42815. var otherAxisOnZeroOf;
  42816. var axisModel = axis.model;
  42817. var onZero = axisModel.get(['axisLine', 'onZero']);
  42818. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42819. if (!onZero) {
  42820. return;
  42821. }
  42822. // If target axis is specified.
  42823. if (onZeroAxisIndex != null) {
  42824. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42825. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42826. }
  42827. } else {
  42828. // Find the first available other axis.
  42829. for (var idx in otherAxes) {
  42830. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])
  42831. // Consider that two Y axes on one value axis,
  42832. // if both onZero, the two Y axes overlap.
  42833. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42834. otherAxisOnZeroOf = otherAxes[idx];
  42835. break;
  42836. }
  42837. }
  42838. }
  42839. if (otherAxisOnZeroOf) {
  42840. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42841. }
  42842. function getOnZeroRecordKey(axis) {
  42843. return axis.dim + '_' + axis.index;
  42844. }
  42845. }
  42846. function canOnZeroToAxis(axis) {
  42847. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42848. }
  42849. function updateAxisTransform(axis, coordBase) {
  42850. var axisExtent = axis.getExtent();
  42851. var axisExtentSum = axisExtent[0] + axisExtent[1];
  42852. // Fast transform
  42853. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42854. return coord + coordBase;
  42855. } : function (coord) {
  42856. return axisExtentSum - coord + coordBase;
  42857. };
  42858. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42859. return coord - coordBase;
  42860. } : function (coord) {
  42861. return axisExtentSum - coord + coordBase;
  42862. };
  42863. }
  42864. var PI$5 = Math.PI;
  42865. /**
  42866. * A final axis is translated and rotated from a "standard axis".
  42867. * So opt.position and opt.rotation is required.
  42868. *
  42869. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42870. * for example: (0, 0) ------------> (0, 50)
  42871. *
  42872. * nameDirection or tickDirection or labelDirection is 1 means tick
  42873. * or label is below the standard axis, whereas is -1 means above
  42874. * the standard axis. labelOffset means offset between label and axis,
  42875. * which is useful when 'onZero', where axisLabel is in the grid and
  42876. * label in outside grid.
  42877. *
  42878. * Tips: like always,
  42879. * positive rotation represents anticlockwise, and negative rotation
  42880. * represents clockwise.
  42881. * The direction of position coordinate is the same as the direction
  42882. * of screen coordinate.
  42883. *
  42884. * Do not need to consider axis 'inverse', which is auto processed by
  42885. * axis extent.
  42886. */
  42887. var AxisBuilder = /** @class */function () {
  42888. function AxisBuilder(axisModel, opt) {
  42889. this.group = new Group();
  42890. this.opt = opt;
  42891. this.axisModel = axisModel;
  42892. // Default value
  42893. defaults(opt, {
  42894. labelOffset: 0,
  42895. nameDirection: 1,
  42896. tickDirection: 1,
  42897. labelDirection: 1,
  42898. silent: true,
  42899. handleAutoShown: function () {
  42900. return true;
  42901. }
  42902. });
  42903. // FIXME Not use a separate text group?
  42904. var transformGroup = new Group({
  42905. x: opt.position[0],
  42906. y: opt.position[1],
  42907. rotation: opt.rotation
  42908. });
  42909. // this.group.add(transformGroup);
  42910. // this._transformGroup = transformGroup;
  42911. transformGroup.updateTransform();
  42912. this._transformGroup = transformGroup;
  42913. }
  42914. AxisBuilder.prototype.hasBuilder = function (name) {
  42915. return !!builders[name];
  42916. };
  42917. AxisBuilder.prototype.add = function (name) {
  42918. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42919. };
  42920. AxisBuilder.prototype.getGroup = function () {
  42921. return this.group;
  42922. };
  42923. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42924. var rotationDiff = remRadian(textRotation - axisRotation);
  42925. var textAlign;
  42926. var textVerticalAlign;
  42927. if (isRadianAroundZero(rotationDiff)) {
  42928. // Label is parallel with axis line.
  42929. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42930. textAlign = 'center';
  42931. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42932. // Label is inverse parallel with axis line.
  42933. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42934. textAlign = 'center';
  42935. } else {
  42936. textVerticalAlign = 'middle';
  42937. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42938. textAlign = direction > 0 ? 'right' : 'left';
  42939. } else {
  42940. textAlign = direction > 0 ? 'left' : 'right';
  42941. }
  42942. }
  42943. return {
  42944. rotation: rotationDiff,
  42945. textAlign: textAlign,
  42946. textVerticalAlign: textVerticalAlign
  42947. };
  42948. };
  42949. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42950. var eventData = {
  42951. componentType: axisModel.mainType,
  42952. componentIndex: axisModel.componentIndex
  42953. };
  42954. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42955. return eventData;
  42956. };
  42957. AxisBuilder.isLabelSilent = function (axisModel) {
  42958. var tooltipOpt = axisModel.get('tooltip');
  42959. return axisModel.get('silent')
  42960. // Consider mouse cursor, add these restrictions.
  42961. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42962. };
  42963. return AxisBuilder;
  42964. }();
  42965. var builders = {
  42966. axisLine: function (opt, axisModel, group, transformGroup) {
  42967. var shown = axisModel.get(['axisLine', 'show']);
  42968. if (shown === 'auto' && opt.handleAutoShown) {
  42969. shown = opt.handleAutoShown('axisLine');
  42970. }
  42971. if (!shown) {
  42972. return;
  42973. }
  42974. var extent = axisModel.axis.getExtent();
  42975. var matrix = transformGroup.transform;
  42976. var pt1 = [extent[0], 0];
  42977. var pt2 = [extent[1], 0];
  42978. var inverse = pt1[0] > pt2[0];
  42979. if (matrix) {
  42980. applyTransform(pt1, pt1, matrix);
  42981. applyTransform(pt2, pt2, matrix);
  42982. }
  42983. var lineStyle = extend({
  42984. lineCap: 'round'
  42985. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  42986. var line = new Line({
  42987. shape: {
  42988. x1: pt1[0],
  42989. y1: pt1[1],
  42990. x2: pt2[0],
  42991. y2: pt2[1]
  42992. },
  42993. style: lineStyle,
  42994. strokeContainThreshold: opt.strokeContainThreshold || 5,
  42995. silent: true,
  42996. z2: 1
  42997. });
  42998. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  42999. line.anid = 'line';
  43000. group.add(line);
  43001. var arrows = axisModel.get(['axisLine', 'symbol']);
  43002. if (arrows != null) {
  43003. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  43004. if (isString(arrows)) {
  43005. // Use the same arrow for start and end point
  43006. arrows = [arrows, arrows];
  43007. }
  43008. if (isString(arrowSize) || isNumber(arrowSize)) {
  43009. // Use the same size for width and height
  43010. arrowSize = [arrowSize, arrowSize];
  43011. }
  43012. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  43013. var symbolWidth_1 = arrowSize[0];
  43014. var symbolHeight_1 = arrowSize[1];
  43015. each([{
  43016. rotate: opt.rotation + Math.PI / 2,
  43017. offset: arrowOffset[0],
  43018. r: 0
  43019. }, {
  43020. rotate: opt.rotation - Math.PI / 2,
  43021. offset: arrowOffset[1],
  43022. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  43023. }], function (point, index) {
  43024. if (arrows[index] !== 'none' && arrows[index] != null) {
  43025. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true);
  43026. // Calculate arrow position with offset
  43027. var r = point.r + point.offset;
  43028. var pt = inverse ? pt2 : pt1;
  43029. symbol.attr({
  43030. rotation: point.rotate,
  43031. x: pt[0] + r * Math.cos(opt.rotation),
  43032. y: pt[1] - r * Math.sin(opt.rotation),
  43033. silent: true,
  43034. z2: 11
  43035. });
  43036. group.add(symbol);
  43037. }
  43038. });
  43039. }
  43040. },
  43041. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  43042. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  43043. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  43044. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  43045. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  43046. // This bit fixes the label overlap issue for the time chart.
  43047. // See https://github.com/apache/echarts/issues/14266 for more.
  43048. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  43049. var labelList = prepareLayoutList(map(labelEls, function (label) {
  43050. return {
  43051. label: label,
  43052. priority: label.z2,
  43053. defaultAttr: {
  43054. ignore: label.ignore
  43055. }
  43056. };
  43057. }));
  43058. hideOverlap(labelList);
  43059. }
  43060. },
  43061. axisName: function (opt, axisModel, group, transformGroup) {
  43062. var name = retrieve(opt.axisName, axisModel.get('name'));
  43063. if (!name) {
  43064. return;
  43065. }
  43066. var nameLocation = axisModel.get('nameLocation');
  43067. var nameDirection = opt.nameDirection;
  43068. var textStyleModel = axisModel.getModel('nameTextStyle');
  43069. var gap = axisModel.get('nameGap') || 0;
  43070. var extent = axisModel.axis.getExtent();
  43071. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  43072. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2,
  43073. // Reuse labelOffset.
  43074. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  43075. var labelLayout;
  43076. var nameRotation = axisModel.get('nameRotate');
  43077. if (nameRotation != null) {
  43078. nameRotation = nameRotation * PI$5 / 180; // To radian.
  43079. }
  43080. var axisNameAvailableWidth;
  43081. if (isNameLocationCenter(nameLocation)) {
  43082. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation,
  43083. // Adapt to axis.
  43084. nameDirection);
  43085. } else {
  43086. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  43087. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  43088. if (axisNameAvailableWidth != null) {
  43089. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  43090. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  43091. }
  43092. }
  43093. var textFont = textStyleModel.getFont();
  43094. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  43095. var ellipsis = truncateOpt.ellipsis;
  43096. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  43097. var textEl = new ZRText({
  43098. x: pos[0],
  43099. y: pos[1],
  43100. rotation: labelLayout.rotation,
  43101. silent: AxisBuilder.isLabelSilent(axisModel),
  43102. style: createTextStyle(textStyleModel, {
  43103. text: name,
  43104. font: textFont,
  43105. overflow: 'truncate',
  43106. width: maxWidth,
  43107. ellipsis: ellipsis,
  43108. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  43109. align: textStyleModel.get('align') || labelLayout.textAlign,
  43110. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  43111. }),
  43112. z2: 1
  43113. });
  43114. setTooltipConfig({
  43115. el: textEl,
  43116. componentModel: axisModel,
  43117. itemName: name
  43118. });
  43119. textEl.__fullText = name;
  43120. // Id for animation
  43121. textEl.anid = 'name';
  43122. if (axisModel.get('triggerEvent')) {
  43123. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43124. eventData.targetType = 'axisName';
  43125. eventData.name = name;
  43126. getECData(textEl).eventData = eventData;
  43127. }
  43128. // FIXME
  43129. transformGroup.add(textEl);
  43130. textEl.updateTransform();
  43131. group.add(textEl);
  43132. textEl.decomposeTransform();
  43133. }
  43134. };
  43135. function endTextLayout(rotation, textPosition, textRotate, extent) {
  43136. var rotationDiff = remRadian(textRotate - rotation);
  43137. var textAlign;
  43138. var textVerticalAlign;
  43139. var inverse = extent[0] > extent[1];
  43140. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  43141. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  43142. textVerticalAlign = onLeft ? 'bottom' : 'top';
  43143. textAlign = 'center';
  43144. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  43145. textVerticalAlign = onLeft ? 'top' : 'bottom';
  43146. textAlign = 'center';
  43147. } else {
  43148. textVerticalAlign = 'middle';
  43149. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  43150. textAlign = onLeft ? 'left' : 'right';
  43151. } else {
  43152. textAlign = onLeft ? 'right' : 'left';
  43153. }
  43154. }
  43155. return {
  43156. rotation: rotationDiff,
  43157. textAlign: textAlign,
  43158. textVerticalAlign: textVerticalAlign
  43159. };
  43160. }
  43161. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  43162. if (shouldShowAllLabels(axisModel.axis)) {
  43163. return;
  43164. }
  43165. // If min or max are user set, we need to check
  43166. // If the tick on min(max) are overlap on their neighbour tick
  43167. // If they are overlapped, we need to hide the min(max) tick label
  43168. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  43169. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']);
  43170. // FIXME
  43171. // Have not consider onBand yet, where tick els is more than label els.
  43172. labelEls = labelEls || [];
  43173. tickEls = tickEls || [];
  43174. var firstLabel = labelEls[0];
  43175. var nextLabel = labelEls[1];
  43176. var lastLabel = labelEls[labelEls.length - 1];
  43177. var prevLabel = labelEls[labelEls.length - 2];
  43178. var firstTick = tickEls[0];
  43179. var nextTick = tickEls[1];
  43180. var lastTick = tickEls[tickEls.length - 1];
  43181. var prevTick = tickEls[tickEls.length - 2];
  43182. if (showMinLabel === false) {
  43183. ignoreEl(firstLabel);
  43184. ignoreEl(firstTick);
  43185. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  43186. if (showMinLabel) {
  43187. ignoreEl(nextLabel);
  43188. ignoreEl(nextTick);
  43189. } else {
  43190. ignoreEl(firstLabel);
  43191. ignoreEl(firstTick);
  43192. }
  43193. }
  43194. if (showMaxLabel === false) {
  43195. ignoreEl(lastLabel);
  43196. ignoreEl(lastTick);
  43197. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  43198. if (showMaxLabel) {
  43199. ignoreEl(prevLabel);
  43200. ignoreEl(prevTick);
  43201. } else {
  43202. ignoreEl(lastLabel);
  43203. ignoreEl(lastTick);
  43204. }
  43205. }
  43206. }
  43207. function ignoreEl(el) {
  43208. el && (el.ignore = true);
  43209. }
  43210. function isTwoLabelOverlapped(current, next) {
  43211. // current and next has the same rotation.
  43212. var firstRect = current && current.getBoundingRect().clone();
  43213. var nextRect = next && next.getBoundingRect().clone();
  43214. if (!firstRect || !nextRect) {
  43215. return;
  43216. }
  43217. // When checking intersect of two rotated labels, we use mRotationBack
  43218. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  43219. var mRotationBack = identity([]);
  43220. rotate(mRotationBack, mRotationBack, -current.rotation);
  43221. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  43222. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  43223. return firstRect.intersect(nextRect);
  43224. }
  43225. function isNameLocationCenter(nameLocation) {
  43226. return nameLocation === 'middle' || nameLocation === 'center';
  43227. }
  43228. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  43229. var tickEls = [];
  43230. var pt1 = [];
  43231. var pt2 = [];
  43232. for (var i = 0; i < ticksCoords.length; i++) {
  43233. var tickCoord = ticksCoords[i].coord;
  43234. pt1[0] = tickCoord;
  43235. pt1[1] = 0;
  43236. pt2[0] = tickCoord;
  43237. pt2[1] = tickEndCoord;
  43238. if (tickTransform) {
  43239. applyTransform(pt1, pt1, tickTransform);
  43240. applyTransform(pt2, pt2, tickTransform);
  43241. }
  43242. // Tick line, Not use group transform to have better line draw
  43243. var tickEl = new Line({
  43244. shape: {
  43245. x1: pt1[0],
  43246. y1: pt1[1],
  43247. x2: pt2[0],
  43248. y2: pt2[1]
  43249. },
  43250. style: tickLineStyle,
  43251. z2: 2,
  43252. autoBatch: true,
  43253. silent: true
  43254. });
  43255. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  43256. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  43257. tickEls.push(tickEl);
  43258. }
  43259. return tickEls;
  43260. }
  43261. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  43262. var axis = axisModel.axis;
  43263. var tickModel = axisModel.getModel('axisTick');
  43264. var shown = tickModel.get('show');
  43265. if (shown === 'auto' && opt.handleAutoShown) {
  43266. shown = opt.handleAutoShown('axisTick');
  43267. }
  43268. if (!shown || axis.scale.isBlank()) {
  43269. return;
  43270. }
  43271. var lineStyleModel = tickModel.getModel('lineStyle');
  43272. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  43273. var ticksCoords = axis.getTicksCoords();
  43274. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  43275. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43276. }), 'ticks');
  43277. for (var i = 0; i < ticksEls.length; i++) {
  43278. group.add(ticksEls[i]);
  43279. }
  43280. return ticksEls;
  43281. }
  43282. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  43283. var axis = axisModel.axis;
  43284. var minorTickModel = axisModel.getModel('minorTick');
  43285. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  43286. return;
  43287. }
  43288. var minorTicksCoords = axis.getMinorTicksCoords();
  43289. if (!minorTicksCoords.length) {
  43290. return;
  43291. }
  43292. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43293. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43294. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43295. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43296. }));
  43297. for (var i = 0; i < minorTicksCoords.length; i++) {
  43298. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43299. for (var k = 0; k < minorTicksEls.length; k++) {
  43300. group.add(minorTicksEls[k]);
  43301. }
  43302. }
  43303. }
  43304. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43305. var axis = axisModel.axis;
  43306. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43307. if (!show || axis.scale.isBlank()) {
  43308. return;
  43309. }
  43310. var labelModel = axisModel.getModel('axisLabel');
  43311. var labelMargin = labelModel.get('margin');
  43312. var labels = axis.getViewLabels();
  43313. // Special label rotate.
  43314. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43315. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43316. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43317. var labelEls = [];
  43318. var silent = AxisBuilder.isLabelSilent(axisModel);
  43319. var triggerEvent = axisModel.get('triggerEvent');
  43320. each(labels, function (labelItem, index) {
  43321. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43322. var formattedLabel = labelItem.formattedLabel;
  43323. var rawLabel = labelItem.rawLabel;
  43324. var itemLabelModel = labelModel;
  43325. if (rawCategoryData && rawCategoryData[tickValue]) {
  43326. var rawCategoryItem = rawCategoryData[tickValue];
  43327. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43328. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43329. }
  43330. }
  43331. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43332. var tickCoord = axis.dataToCoord(tickValue);
  43333. var align = itemLabelModel.getShallow('align', true) || labelLayout.textAlign;
  43334. var alignMin = retrieve2(itemLabelModel.getShallow('alignMinLabel', true), align);
  43335. var alignMax = retrieve2(itemLabelModel.getShallow('alignMaxLabel', true), align);
  43336. var verticalAlign = itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign;
  43337. var verticalAlignMin = retrieve2(itemLabelModel.getShallow('verticalAlignMinLabel', true), verticalAlign);
  43338. var verticalAlignMax = retrieve2(itemLabelModel.getShallow('verticalAlignMaxLabel', true), verticalAlign);
  43339. var textEl = new ZRText({
  43340. x: tickCoord,
  43341. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43342. rotation: labelLayout.rotation,
  43343. silent: silent,
  43344. z2: 10 + (labelItem.level || 0),
  43345. style: createTextStyle(itemLabelModel, {
  43346. text: formattedLabel,
  43347. align: index === 0 ? alignMin : index === labels.length - 1 ? alignMax : align,
  43348. verticalAlign: index === 0 ? verticalAlignMin : index === labels.length - 1 ? verticalAlignMax : verticalAlign,
  43349. fill: isFunction(textColor) ? textColor(
  43350. // (1) In category axis with data zoom, tick is not the original
  43351. // index of axis.data. So tick should not be exposed to user
  43352. // in category axis.
  43353. // (2) Compatible with previous version, which always use formatted label as
  43354. // input. But in interval scale the formatted label is like '223,445', which
  43355. // maked user replace ','. So we modify it to return original val but remain
  43356. // it as 'string' to avoid error in replacing.
  43357. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43358. })
  43359. });
  43360. textEl.anid = 'label_' + tickValue;
  43361. setTooltipConfig({
  43362. el: textEl,
  43363. componentModel: axisModel,
  43364. itemName: formattedLabel,
  43365. formatterParamsExtra: {
  43366. isTruncated: function () {
  43367. return textEl.isTruncated;
  43368. },
  43369. value: rawLabel,
  43370. tickIndex: index
  43371. }
  43372. });
  43373. // Pack data for mouse event
  43374. if (triggerEvent) {
  43375. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43376. eventData.targetType = 'axisLabel';
  43377. eventData.value = rawLabel;
  43378. eventData.tickIndex = index;
  43379. if (axis.type === 'category') {
  43380. eventData.dataIndex = tickValue;
  43381. }
  43382. getECData(textEl).eventData = eventData;
  43383. }
  43384. // FIXME
  43385. transformGroup.add(textEl);
  43386. textEl.updateTransform();
  43387. labelEls.push(textEl);
  43388. group.add(textEl);
  43389. textEl.decomposeTransform();
  43390. });
  43391. return labelEls;
  43392. }
  43393. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  43394. // allAxesInfo should be updated when setOption performed.
  43395. function collect(ecModel, api) {
  43396. var result = {
  43397. /**
  43398. * key: makeKey(axis.model)
  43399. * value: {
  43400. * axis,
  43401. * coordSys,
  43402. * axisPointerModel,
  43403. * triggerTooltip,
  43404. * triggerEmphasis,
  43405. * involveSeries,
  43406. * snap,
  43407. * seriesModels,
  43408. * seriesDataCount
  43409. * }
  43410. */
  43411. axesInfo: {},
  43412. seriesInvolved: false,
  43413. /**
  43414. * key: makeKey(coordSys.model)
  43415. * value: Object: key makeKey(axis.model), value: axisInfo
  43416. */
  43417. coordSysAxesInfo: {},
  43418. coordSysMap: {}
  43419. };
  43420. collectAxesInfo(result, ecModel, api);
  43421. // Check seriesInvolved for performance, in case too many series in some chart.
  43422. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43423. return result;
  43424. }
  43425. function collectAxesInfo(result, ecModel, api) {
  43426. var globalTooltipModel = ecModel.getComponent('tooltip');
  43427. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  43428. // links can only be set on global.
  43429. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43430. var linkGroups = [];
  43431. // Collect axes info.
  43432. each(api.getCoordinateSystems(), function (coordSys) {
  43433. // Some coordinate system do not support axes, like geo.
  43434. if (!coordSys.axisPointerEnabled) {
  43435. return;
  43436. }
  43437. var coordSysKey = makeKey(coordSys.model);
  43438. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43439. result.coordSysMap[coordSysKey] = coordSys;
  43440. // Set tooltip (like 'cross') is a convenient way to show axisPointer
  43441. // for user. So we enable setting tooltip on coordSys model.
  43442. var coordSysModel = coordSys.model;
  43443. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43444. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null));
  43445. // If axis tooltip used, choose tooltip axis for each coordSys.
  43446. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43447. if (coordSys.getTooltipAxes && globalTooltipModel
  43448. // If tooltip.showContent is set as false, tooltip will not
  43449. // show but axisPointer will show as normal.
  43450. && baseTooltipModel.get('show')) {
  43451. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43452. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43453. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43454. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43455. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43456. if (triggerAxis || cross) {
  43457. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43458. }
  43459. if (cross) {
  43460. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43461. }
  43462. }
  43463. // fromTooltip: true | false | 'cross'
  43464. // triggerTooltip: true | false | null
  43465. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43466. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43467. var axisPointerShow = axisPointerModel.get('show');
  43468. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43469. return;
  43470. }
  43471. if (triggerTooltip == null) {
  43472. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43473. }
  43474. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43475. var snap = axisPointerModel.get('snap');
  43476. var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
  43477. var axisKey = makeKey(axis.model);
  43478. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  43479. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43480. var axisInfo = result.axesInfo[axisKey] = {
  43481. key: axisKey,
  43482. axis: axis,
  43483. coordSys: coordSys,
  43484. axisPointerModel: axisPointerModel,
  43485. triggerTooltip: triggerTooltip,
  43486. triggerEmphasis: triggerEmphasis,
  43487. involveSeries: involveSeries,
  43488. snap: snap,
  43489. useHandle: isHandleTrigger(axisPointerModel),
  43490. seriesModels: [],
  43491. linkGroup: null
  43492. };
  43493. axesInfoInCoordSys[axisKey] = axisInfo;
  43494. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43495. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43496. if (groupIndex != null) {
  43497. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43498. axesInfo: {}
  43499. });
  43500. linkGroup.axesInfo[axisKey] = axisInfo;
  43501. linkGroup.mapper = linksOption[groupIndex].mapper;
  43502. axisInfo.linkGroup = linkGroup;
  43503. }
  43504. }
  43505. });
  43506. }
  43507. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43508. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43509. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43510. var volatileOption = {};
  43511. each(fields, function (field) {
  43512. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43513. });
  43514. // category axis do not auto snap, otherwise some tick that do not
  43515. // has value can not be hovered. value/time/log axis default snap if
  43516. // triggered from tooltip and trigger tooltip.
  43517. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  43518. // Compatible with previous behavior, tooltip axis does not show label by default.
  43519. // Only these properties can be overridden from tooltip to axisPointer.
  43520. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43521. volatileOption.type = 'line';
  43522. }
  43523. var labelOption = volatileOption.label || (volatileOption.label = {});
  43524. // Follow the convention, do not show label when triggered by tooltip by default.
  43525. labelOption.show == null && (labelOption.show = false);
  43526. if (fromTooltip === 'cross') {
  43527. // When 'cross', both axes show labels.
  43528. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43529. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  43530. // If triggerTooltip, this is a base axis, which should better not use cross style
  43531. // (cross style is dashed by default)
  43532. if (!triggerTooltip) {
  43533. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43534. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43535. }
  43536. }
  43537. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43538. }
  43539. function collectSeriesInfo(result, ecModel) {
  43540. // Prepare data for axis trigger
  43541. ecModel.eachSeries(function (seriesModel) {
  43542. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43543. var coordSys = seriesModel.coordinateSystem;
  43544. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43545. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43546. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43547. return;
  43548. }
  43549. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43550. var axis = axisInfo.axis;
  43551. if (coordSys.getAxis(axis.dim) === axis) {
  43552. axisInfo.seriesModels.push(seriesModel);
  43553. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43554. axisInfo.seriesDataCount += seriesModel.getData().count();
  43555. }
  43556. });
  43557. });
  43558. }
  43559. /**
  43560. * For example:
  43561. * {
  43562. * axisPointer: {
  43563. * links: [{
  43564. * xAxisIndex: [2, 4],
  43565. * yAxisIndex: 'all'
  43566. * }, {
  43567. * xAxisId: ['a5', 'a7'],
  43568. * xAxisName: 'xxx'
  43569. * }]
  43570. * }
  43571. * }
  43572. */
  43573. function getLinkGroupIndex(linksOption, axis) {
  43574. var axisModel = axis.model;
  43575. var dim = axis.dim;
  43576. for (var i = 0; i < linksOption.length; i++) {
  43577. var linkOption = linksOption[i] || {};
  43578. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43579. return i;
  43580. }
  43581. }
  43582. }
  43583. function checkPropInLink(linkPropValue, axisPropValue) {
  43584. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43585. }
  43586. function fixValue(axisModel) {
  43587. var axisInfo = getAxisInfo(axisModel);
  43588. if (!axisInfo) {
  43589. return;
  43590. }
  43591. var axisPointerModel = axisInfo.axisPointerModel;
  43592. var scale = axisInfo.axis.scale;
  43593. var option = axisPointerModel.option;
  43594. var status = axisPointerModel.get('status');
  43595. var value = axisPointerModel.get('value');
  43596. // Parse init value for category and time axis.
  43597. if (value != null) {
  43598. value = scale.parse(value);
  43599. }
  43600. var useHandle = isHandleTrigger(axisPointerModel);
  43601. // If `handle` used, `axisPointer` will always be displayed, so value
  43602. // and status should be initialized.
  43603. if (status == null) {
  43604. option.status = useHandle ? 'show' : 'hide';
  43605. }
  43606. var extent = scale.getExtent().slice();
  43607. extent[0] > extent[1] && extent.reverse();
  43608. if (
  43609. // Pick a value on axis when initializing.
  43610. value == null
  43611. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43612. // where we should re-pick a value to keep `handle` displaying normally.
  43613. || value > extent[1]) {
  43614. // Make handle displayed on the end of the axis when init, which looks better.
  43615. value = extent[1];
  43616. }
  43617. if (value < extent[0]) {
  43618. value = extent[0];
  43619. }
  43620. option.value = value;
  43621. if (useHandle) {
  43622. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43623. }
  43624. }
  43625. function getAxisInfo(axisModel) {
  43626. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43627. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43628. }
  43629. function getAxisPointerModel(axisModel) {
  43630. var axisInfo = getAxisInfo(axisModel);
  43631. return axisInfo && axisInfo.axisPointerModel;
  43632. }
  43633. function isHandleTrigger(axisPointerModel) {
  43634. return !!axisPointerModel.get(['handle', 'show']);
  43635. }
  43636. /**
  43637. * @param {module:echarts/model/Model} model
  43638. * @return {string} unique key
  43639. */
  43640. function makeKey(model) {
  43641. return model.type + '||' + model.id;
  43642. }
  43643. var axisPointerClazz = {};
  43644. /**
  43645. * Base class of AxisView.
  43646. */
  43647. var AxisView = /** @class */function (_super) {
  43648. __extends(AxisView, _super);
  43649. function AxisView() {
  43650. var _this = _super !== null && _super.apply(this, arguments) || this;
  43651. _this.type = AxisView.type;
  43652. return _this;
  43653. }
  43654. /**
  43655. * @override
  43656. */
  43657. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43658. // FIXME
  43659. // This process should proformed after coordinate systems updated
  43660. // (axis scale updated), and should be performed each time update.
  43661. // So put it here temporarily, although it is not appropriate to
  43662. // put a model-writing procedure in `view`.
  43663. this.axisPointerClass && fixValue(axisModel);
  43664. _super.prototype.render.apply(this, arguments);
  43665. this._doUpdateAxisPointerClass(axisModel, api, true);
  43666. };
  43667. /**
  43668. * Action handler.
  43669. */
  43670. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43671. this._doUpdateAxisPointerClass(axisModel, api, false);
  43672. };
  43673. /**
  43674. * @override
  43675. */
  43676. AxisView.prototype.remove = function (ecModel, api) {
  43677. var axisPointer = this._axisPointer;
  43678. axisPointer && axisPointer.remove(api);
  43679. };
  43680. /**
  43681. * @override
  43682. */
  43683. AxisView.prototype.dispose = function (ecModel, api) {
  43684. this._disposeAxisPointer(api);
  43685. _super.prototype.dispose.apply(this, arguments);
  43686. };
  43687. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43688. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43689. if (!Clazz) {
  43690. return;
  43691. }
  43692. var axisPointerModel = getAxisPointerModel(axisModel);
  43693. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43694. };
  43695. AxisView.prototype._disposeAxisPointer = function (api) {
  43696. this._axisPointer && this._axisPointer.dispose(api);
  43697. this._axisPointer = null;
  43698. };
  43699. AxisView.registerAxisPointerClass = function (type, clazz) {
  43700. if ("development" !== 'production') {
  43701. if (axisPointerClazz[type]) {
  43702. throw new Error('axisPointer ' + type + ' exists');
  43703. }
  43704. }
  43705. axisPointerClazz[type] = clazz;
  43706. };
  43707. AxisView.getAxisPointerClass = function (type) {
  43708. return type && axisPointerClazz[type];
  43709. };
  43710. AxisView.type = 'axis';
  43711. return AxisView;
  43712. }(ComponentView);
  43713. var inner$6 = makeInner();
  43714. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43715. var axis = axisModel.axis;
  43716. if (axis.scale.isBlank()) {
  43717. return;
  43718. }
  43719. // TODO: TYPE
  43720. var splitAreaModel = axisModel.getModel('splitArea');
  43721. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43722. var areaColors = areaStyleModel.get('color');
  43723. var gridRect = gridModel.coordinateSystem.getRect();
  43724. var ticksCoords = axis.getTicksCoords({
  43725. tickModel: splitAreaModel,
  43726. clamp: true
  43727. });
  43728. if (!ticksCoords.length) {
  43729. return;
  43730. }
  43731. // For Making appropriate splitArea animation, the color and anid
  43732. // should be corresponding to previous one if possible.
  43733. var areaColorsLen = areaColors.length;
  43734. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43735. var newSplitAreaColors = createHashMap();
  43736. var colorIndex = 0;
  43737. if (lastSplitAreaColors) {
  43738. for (var i = 0; i < ticksCoords.length; i++) {
  43739. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43740. if (cIndex != null) {
  43741. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43742. break;
  43743. }
  43744. }
  43745. }
  43746. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43747. var areaStyle = areaStyleModel.getAreaStyle();
  43748. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43749. for (var i = 1; i < ticksCoords.length; i++) {
  43750. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43751. var x = void 0;
  43752. var y = void 0;
  43753. var width = void 0;
  43754. var height = void 0;
  43755. if (axis.isHorizontal()) {
  43756. x = prev;
  43757. y = gridRect.y;
  43758. width = tickCoord - x;
  43759. height = gridRect.height;
  43760. prev = x + width;
  43761. } else {
  43762. x = gridRect.x;
  43763. y = prev;
  43764. width = gridRect.width;
  43765. height = tickCoord - y;
  43766. prev = y + height;
  43767. }
  43768. var tickValue = ticksCoords[i - 1].tickValue;
  43769. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43770. axisGroup.add(new Rect({
  43771. anid: tickValue != null ? 'area_' + tickValue : null,
  43772. shape: {
  43773. x: x,
  43774. y: y,
  43775. width: width,
  43776. height: height
  43777. },
  43778. style: defaults({
  43779. fill: areaColors[colorIndex]
  43780. }, areaStyle),
  43781. autoBatch: true,
  43782. silent: true
  43783. }));
  43784. colorIndex = (colorIndex + 1) % areaColorsLen;
  43785. }
  43786. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43787. }
  43788. function rectCoordAxisHandleRemove(axisView) {
  43789. inner$6(axisView).splitAreaColors = null;
  43790. }
  43791. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43792. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43793. var CartesianAxisView = /** @class */function (_super) {
  43794. __extends(CartesianAxisView, _super);
  43795. function CartesianAxisView() {
  43796. var _this = _super !== null && _super.apply(this, arguments) || this;
  43797. _this.type = CartesianAxisView.type;
  43798. _this.axisPointerClass = 'CartesianAxisPointer';
  43799. return _this;
  43800. }
  43801. /**
  43802. * @override
  43803. */
  43804. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43805. this.group.removeAll();
  43806. var oldAxisGroup = this._axisGroup;
  43807. this._axisGroup = new Group();
  43808. this.group.add(this._axisGroup);
  43809. if (!axisModel.get('show')) {
  43810. return;
  43811. }
  43812. var gridModel = axisModel.getCoordSysModel();
  43813. var layout = layout$1(gridModel, axisModel);
  43814. var axisBuilder = new AxisBuilder(axisModel, extend({
  43815. handleAutoShown: function (elementType) {
  43816. var cartesians = gridModel.coordinateSystem.getCartesians();
  43817. for (var i = 0; i < cartesians.length; i++) {
  43818. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  43819. // Still show axis tick or axisLine if other axis is value / log
  43820. return true;
  43821. }
  43822. }
  43823. // Not show axisTick or axisLine if other axis is category / time
  43824. return false;
  43825. }
  43826. }, layout));
  43827. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43828. this._axisGroup.add(axisBuilder.getGroup());
  43829. each(selfBuilderAttrs, function (name) {
  43830. if (axisModel.get([name, 'show'])) {
  43831. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43832. }
  43833. }, this);
  43834. // THIS is a special case for bar racing chart.
  43835. // Update the axis label from the natural initial layout to
  43836. // sorted layout should has no animation.
  43837. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43838. if (!isInitialSortFromBarRacing) {
  43839. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43840. }
  43841. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43842. };
  43843. CartesianAxisView.prototype.remove = function () {
  43844. rectCoordAxisHandleRemove(this);
  43845. };
  43846. CartesianAxisView.type = 'cartesianAxis';
  43847. return CartesianAxisView;
  43848. }(AxisView);
  43849. var axisElementBuilders = {
  43850. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43851. var axis = axisModel.axis;
  43852. if (axis.scale.isBlank()) {
  43853. return;
  43854. }
  43855. var splitLineModel = axisModel.getModel('splitLine');
  43856. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43857. var lineColors = lineStyleModel.get('color');
  43858. var showMinLine = splitLineModel.get('showMinLine') !== false;
  43859. var showMaxLine = splitLineModel.get('showMaxLine') !== false;
  43860. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43861. var gridRect = gridModel.coordinateSystem.getRect();
  43862. var isHorizontal = axis.isHorizontal();
  43863. var lineCount = 0;
  43864. var ticksCoords = axis.getTicksCoords({
  43865. tickModel: splitLineModel
  43866. });
  43867. var p1 = [];
  43868. var p2 = [];
  43869. var lineStyle = lineStyleModel.getLineStyle();
  43870. for (var i = 0; i < ticksCoords.length; i++) {
  43871. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43872. if (i === 0 && !showMinLine || i === ticksCoords.length - 1 && !showMaxLine) {
  43873. continue;
  43874. }
  43875. var tickValue = ticksCoords[i].tickValue;
  43876. if (isHorizontal) {
  43877. p1[0] = tickCoord;
  43878. p1[1] = gridRect.y;
  43879. p2[0] = tickCoord;
  43880. p2[1] = gridRect.y + gridRect.height;
  43881. } else {
  43882. p1[0] = gridRect.x;
  43883. p1[1] = tickCoord;
  43884. p2[0] = gridRect.x + gridRect.width;
  43885. p2[1] = tickCoord;
  43886. }
  43887. var colorIndex = lineCount++ % lineColors.length;
  43888. var line = new Line({
  43889. anid: tickValue != null ? 'line_' + tickValue : null,
  43890. autoBatch: true,
  43891. shape: {
  43892. x1: p1[0],
  43893. y1: p1[1],
  43894. x2: p2[0],
  43895. y2: p2[1]
  43896. },
  43897. style: defaults({
  43898. stroke: lineColors[colorIndex]
  43899. }, lineStyle),
  43900. silent: true
  43901. });
  43902. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43903. axisGroup.add(line);
  43904. }
  43905. },
  43906. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43907. var axis = axisModel.axis;
  43908. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43909. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43910. var gridRect = gridModel.coordinateSystem.getRect();
  43911. var isHorizontal = axis.isHorizontal();
  43912. var minorTicksCoords = axis.getMinorTicksCoords();
  43913. if (!minorTicksCoords.length) {
  43914. return;
  43915. }
  43916. var p1 = [];
  43917. var p2 = [];
  43918. var lineStyle = lineStyleModel.getLineStyle();
  43919. for (var i = 0; i < minorTicksCoords.length; i++) {
  43920. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43921. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43922. if (isHorizontal) {
  43923. p1[0] = tickCoord;
  43924. p1[1] = gridRect.y;
  43925. p2[0] = tickCoord;
  43926. p2[1] = gridRect.y + gridRect.height;
  43927. } else {
  43928. p1[0] = gridRect.x;
  43929. p1[1] = tickCoord;
  43930. p2[0] = gridRect.x + gridRect.width;
  43931. p2[1] = tickCoord;
  43932. }
  43933. var line = new Line({
  43934. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43935. autoBatch: true,
  43936. shape: {
  43937. x1: p1[0],
  43938. y1: p1[1],
  43939. x2: p2[0],
  43940. y2: p2[1]
  43941. },
  43942. style: lineStyle,
  43943. silent: true
  43944. });
  43945. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43946. axisGroup.add(line);
  43947. }
  43948. }
  43949. },
  43950. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43951. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43952. }
  43953. };
  43954. var CartesianXAxisView = /** @class */function (_super) {
  43955. __extends(CartesianXAxisView, _super);
  43956. function CartesianXAxisView() {
  43957. var _this = _super !== null && _super.apply(this, arguments) || this;
  43958. _this.type = CartesianXAxisView.type;
  43959. return _this;
  43960. }
  43961. CartesianXAxisView.type = 'xAxis';
  43962. return CartesianXAxisView;
  43963. }(CartesianAxisView);
  43964. var CartesianYAxisView = /** @class */function (_super) {
  43965. __extends(CartesianYAxisView, _super);
  43966. function CartesianYAxisView() {
  43967. var _this = _super !== null && _super.apply(this, arguments) || this;
  43968. _this.type = CartesianXAxisView.type;
  43969. return _this;
  43970. }
  43971. CartesianYAxisView.type = 'yAxis';
  43972. return CartesianYAxisView;
  43973. }(CartesianAxisView);
  43974. // Grid view
  43975. var GridView = /** @class */function (_super) {
  43976. __extends(GridView, _super);
  43977. function GridView() {
  43978. var _this = _super !== null && _super.apply(this, arguments) || this;
  43979. _this.type = 'grid';
  43980. return _this;
  43981. }
  43982. GridView.prototype.render = function (gridModel, ecModel) {
  43983. this.group.removeAll();
  43984. if (gridModel.get('show')) {
  43985. this.group.add(new Rect({
  43986. shape: gridModel.coordinateSystem.getRect(),
  43987. style: defaults({
  43988. fill: gridModel.get('backgroundColor')
  43989. }, gridModel.getItemStyle()),
  43990. silent: true,
  43991. z2: -1
  43992. }));
  43993. }
  43994. };
  43995. GridView.type = 'grid';
  43996. return GridView;
  43997. }(ComponentView);
  43998. var extraOption = {
  43999. // gridIndex: 0,
  44000. // gridId: '',
  44001. offset: 0
  44002. };
  44003. function install$5(registers) {
  44004. registers.registerComponentView(GridView);
  44005. registers.registerComponentModel(GridModel);
  44006. registers.registerCoordinateSystem('cartesian2d', Grid);
  44007. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  44008. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  44009. registers.registerComponentView(CartesianXAxisView);
  44010. registers.registerComponentView(CartesianYAxisView);
  44011. registers.registerPreprocessor(function (option) {
  44012. // Only create grid when need
  44013. if (option.xAxis && option.yAxis && !option.grid) {
  44014. option.grid = {};
  44015. }
  44016. });
  44017. }
  44018. function install$6(registers) {
  44019. // In case developer forget to include grid component
  44020. use(install$5);
  44021. registers.registerSeriesModel(ScatterSeriesModel);
  44022. registers.registerChartView(ScatterView);
  44023. registers.registerLayout(pointsLayout('scatter'));
  44024. }
  44025. var inner$7 = makeInner();
  44026. var clone$3 = clone;
  44027. var bind$1 = bind;
  44028. /**
  44029. * Base axis pointer class in 2D.
  44030. */
  44031. var BaseAxisPointer = /** @class */function () {
  44032. function BaseAxisPointer() {
  44033. this._dragging = false;
  44034. /**
  44035. * In px, arbitrary value. Do not set too small,
  44036. * no animation is ok for most cases.
  44037. */
  44038. this.animationThreshold = 15;
  44039. }
  44040. /**
  44041. * @implement
  44042. */
  44043. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  44044. var value = axisPointerModel.get('value');
  44045. var status = axisPointerModel.get('status');
  44046. // Bind them to `this`, not in closure, otherwise they will not
  44047. // be replaced when user calling setOption in not merge mode.
  44048. this._axisModel = axisModel;
  44049. this._axisPointerModel = axisPointerModel;
  44050. this._api = api;
  44051. // Optimize: `render` will be called repeatedly during mouse move.
  44052. // So it is power consuming if performing `render` each time,
  44053. // especially on mobile device.
  44054. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  44055. return;
  44056. }
  44057. this._lastValue = value;
  44058. this._lastStatus = status;
  44059. var group = this._group;
  44060. var handle = this._handle;
  44061. if (!status || status === 'hide') {
  44062. // Do not clear here, for animation better.
  44063. group && group.hide();
  44064. handle && handle.hide();
  44065. return;
  44066. }
  44067. group && group.show();
  44068. handle && handle.show();
  44069. // Otherwise status is 'show'
  44070. var elOption = {};
  44071. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  44072. // Enable change axis pointer type.
  44073. var graphicKey = elOption.graphicKey;
  44074. if (graphicKey !== this._lastGraphicKey) {
  44075. this.clear(api);
  44076. }
  44077. this._lastGraphicKey = graphicKey;
  44078. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  44079. if (!group) {
  44080. group = this._group = new Group();
  44081. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  44082. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  44083. api.getZr().add(group);
  44084. } else {
  44085. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  44086. this.updatePointerEl(group, elOption, doUpdateProps);
  44087. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  44088. }
  44089. updateMandatoryProps(group, axisPointerModel, true);
  44090. this._renderHandle(value);
  44091. };
  44092. /**
  44093. * @implement
  44094. */
  44095. BaseAxisPointer.prototype.remove = function (api) {
  44096. this.clear(api);
  44097. };
  44098. /**
  44099. * @implement
  44100. */
  44101. BaseAxisPointer.prototype.dispose = function (api) {
  44102. this.clear(api);
  44103. };
  44104. /**
  44105. * @protected
  44106. */
  44107. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  44108. var animation = axisPointerModel.get('animation');
  44109. var axis = axisModel.axis;
  44110. var isCategoryAxis = axis.type === 'category';
  44111. var useSnap = axisPointerModel.get('snap');
  44112. // Value axis without snap always do not snap.
  44113. if (!useSnap && !isCategoryAxis) {
  44114. return false;
  44115. }
  44116. if (animation === 'auto' || animation == null) {
  44117. var animationThreshold = this.animationThreshold;
  44118. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  44119. return true;
  44120. }
  44121. // It is important to auto animation when snap used. Consider if there is
  44122. // a dataZoom, animation will be disabled when too many points exist, while
  44123. // it will be enabled for better visual effect when little points exist.
  44124. if (useSnap) {
  44125. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  44126. var axisExtent = axis.getExtent();
  44127. // Approximate band width
  44128. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  44129. }
  44130. return false;
  44131. }
  44132. return animation === true;
  44133. };
  44134. /**
  44135. * add {pointer, label, graphicKey} to elOption
  44136. * @protected
  44137. */
  44138. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  44139. // Should be implemenented by sub-class.
  44140. };
  44141. /**
  44142. * @protected
  44143. */
  44144. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  44145. var pointerOption = elOption.pointer;
  44146. if (pointerOption) {
  44147. var pointerEl = inner$7(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  44148. group.add(pointerEl);
  44149. }
  44150. };
  44151. /**
  44152. * @protected
  44153. */
  44154. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  44155. if (elOption.label) {
  44156. var labelEl = inner$7(group).labelEl = new ZRText(clone$3(elOption.label));
  44157. group.add(labelEl);
  44158. updateLabelShowHide(labelEl, axisPointerModel);
  44159. }
  44160. };
  44161. /**
  44162. * @protected
  44163. */
  44164. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  44165. var pointerEl = inner$7(group).pointerEl;
  44166. if (pointerEl && elOption.pointer) {
  44167. pointerEl.setStyle(elOption.pointer.style);
  44168. updateProps(pointerEl, {
  44169. shape: elOption.pointer.shape
  44170. });
  44171. }
  44172. };
  44173. /**
  44174. * @protected
  44175. */
  44176. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  44177. var labelEl = inner$7(group).labelEl;
  44178. if (labelEl) {
  44179. labelEl.setStyle(elOption.label.style);
  44180. updateProps(labelEl, {
  44181. // Consider text length change in vertical axis, animation should
  44182. // be used on shape, otherwise the effect will be weird.
  44183. // TODOTODO
  44184. // shape: elOption.label.shape,
  44185. x: elOption.label.x,
  44186. y: elOption.label.y
  44187. });
  44188. updateLabelShowHide(labelEl, axisPointerModel);
  44189. }
  44190. };
  44191. /**
  44192. * @private
  44193. */
  44194. BaseAxisPointer.prototype._renderHandle = function (value) {
  44195. if (this._dragging || !this.updateHandleTransform) {
  44196. return;
  44197. }
  44198. var axisPointerModel = this._axisPointerModel;
  44199. var zr = this._api.getZr();
  44200. var handle = this._handle;
  44201. var handleModel = axisPointerModel.getModel('handle');
  44202. var status = axisPointerModel.get('status');
  44203. if (!handleModel.get('show') || !status || status === 'hide') {
  44204. handle && zr.remove(handle);
  44205. this._handle = null;
  44206. return;
  44207. }
  44208. var isInit;
  44209. if (!this._handle) {
  44210. isInit = true;
  44211. handle = this._handle = createIcon(handleModel.get('icon'), {
  44212. cursor: 'move',
  44213. draggable: true,
  44214. onmousemove: function (e) {
  44215. // For mobile device, prevent screen slider on the button.
  44216. stop(e.event);
  44217. },
  44218. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  44219. drift: bind$1(this._onHandleDragMove, this),
  44220. ondragend: bind$1(this._onHandleDragEnd, this)
  44221. });
  44222. zr.add(handle);
  44223. }
  44224. updateMandatoryProps(handle, axisPointerModel, false);
  44225. // update style
  44226. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY']));
  44227. // update position
  44228. var handleSize = handleModel.get('size');
  44229. if (!isArray(handleSize)) {
  44230. handleSize = [handleSize, handleSize];
  44231. }
  44232. handle.scaleX = handleSize[0] / 2;
  44233. handle.scaleY = handleSize[1] / 2;
  44234. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  44235. this._moveHandleToValue(value, isInit);
  44236. };
  44237. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  44238. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  44239. };
  44240. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  44241. var handle = this._handle;
  44242. if (!handle) {
  44243. return;
  44244. }
  44245. this._dragging = true;
  44246. // Persistent for throttle.
  44247. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  44248. this._payloadInfo = trans;
  44249. handle.stopAnimation();
  44250. handle.attr(getHandleTransProps(trans));
  44251. inner$7(handle).lastProp = null;
  44252. this._doDispatchAxisPointer();
  44253. };
  44254. /**
  44255. * Throttled method.
  44256. */
  44257. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  44258. var handle = this._handle;
  44259. if (!handle) {
  44260. return;
  44261. }
  44262. var payloadInfo = this._payloadInfo;
  44263. var axisModel = this._axisModel;
  44264. this._api.dispatchAction({
  44265. type: 'updateAxisPointer',
  44266. x: payloadInfo.cursorPoint[0],
  44267. y: payloadInfo.cursorPoint[1],
  44268. tooltipOption: payloadInfo.tooltipOption,
  44269. axesInfo: [{
  44270. axisDim: axisModel.axis.dim,
  44271. axisIndex: axisModel.componentIndex
  44272. }]
  44273. });
  44274. };
  44275. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  44276. this._dragging = false;
  44277. var handle = this._handle;
  44278. if (!handle) {
  44279. return;
  44280. }
  44281. var value = this._axisPointerModel.get('value');
  44282. // Consider snap or categroy axis, handle may be not consistent with
  44283. // axisPointer. So move handle to align the exact value position when
  44284. // drag ended.
  44285. this._moveHandleToValue(value);
  44286. // For the effect: tooltip will be shown when finger holding on handle
  44287. // button, and will be hidden after finger left handle button.
  44288. this._api.dispatchAction({
  44289. type: 'hideTip'
  44290. });
  44291. };
  44292. /**
  44293. * @private
  44294. */
  44295. BaseAxisPointer.prototype.clear = function (api) {
  44296. this._lastValue = null;
  44297. this._lastStatus = null;
  44298. var zr = api.getZr();
  44299. var group = this._group;
  44300. var handle = this._handle;
  44301. if (zr && group) {
  44302. this._lastGraphicKey = null;
  44303. group && zr.remove(group);
  44304. handle && zr.remove(handle);
  44305. this._group = null;
  44306. this._handle = null;
  44307. this._payloadInfo = null;
  44308. }
  44309. clear(this, '_doDispatchAxisPointer');
  44310. };
  44311. /**
  44312. * @protected
  44313. */
  44314. BaseAxisPointer.prototype.doClear = function () {
  44315. // Implemented by sub-class if necessary.
  44316. };
  44317. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  44318. xDimIndex = xDimIndex || 0;
  44319. return {
  44320. x: xy[xDimIndex],
  44321. y: xy[1 - xDimIndex],
  44322. width: wh[xDimIndex],
  44323. height: wh[1 - xDimIndex]
  44324. };
  44325. };
  44326. return BaseAxisPointer;
  44327. }();
  44328. function updateProps$1(animationModel, moveAnimation, el, props) {
  44329. // Animation optimize.
  44330. if (!propsEqual(inner$7(el).lastProp, props)) {
  44331. inner$7(el).lastProp = props;
  44332. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  44333. }
  44334. }
  44335. function propsEqual(lastProps, newProps) {
  44336. if (isObject(lastProps) && isObject(newProps)) {
  44337. var equals_1 = true;
  44338. each(newProps, function (item, key) {
  44339. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  44340. });
  44341. return !!equals_1;
  44342. } else {
  44343. return lastProps === newProps;
  44344. }
  44345. }
  44346. function updateLabelShowHide(labelEl, axisPointerModel) {
  44347. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  44348. }
  44349. function getHandleTransProps(trans) {
  44350. return {
  44351. x: trans.x || 0,
  44352. y: trans.y || 0,
  44353. rotation: trans.rotation || 0
  44354. };
  44355. }
  44356. function updateMandatoryProps(group, axisPointerModel, silent) {
  44357. var z = axisPointerModel.get('z');
  44358. var zlevel = axisPointerModel.get('zlevel');
  44359. group && group.traverse(function (el) {
  44360. if (el.type !== 'group') {
  44361. z != null && (el.z = z);
  44362. zlevel != null && (el.zlevel = zlevel);
  44363. el.silent = silent;
  44364. }
  44365. });
  44366. }
  44367. function buildElStyle(axisPointerModel) {
  44368. var axisPointerType = axisPointerModel.get('type');
  44369. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  44370. var style;
  44371. if (axisPointerType === 'line') {
  44372. style = styleModel.getLineStyle();
  44373. style.fill = null;
  44374. } else if (axisPointerType === 'shadow') {
  44375. style = styleModel.getAreaStyle();
  44376. style.stroke = null;
  44377. }
  44378. return style;
  44379. }
  44380. /**
  44381. * @param {Function} labelPos {align, verticalAlign, position}
  44382. */
  44383. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  44384. var value = axisPointerModel.get('value');
  44385. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  44386. precision: axisPointerModel.get(['label', 'precision']),
  44387. formatter: axisPointerModel.get(['label', 'formatter'])
  44388. });
  44389. var labelModel = axisPointerModel.getModel('label');
  44390. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  44391. var font = labelModel.getFont();
  44392. var textRect = getBoundingRect(text, font);
  44393. var position = labelPos.position;
  44394. var width = textRect.width + paddings[1] + paddings[3];
  44395. var height = textRect.height + paddings[0] + paddings[2];
  44396. // Adjust by align.
  44397. var align = labelPos.align;
  44398. align === 'right' && (position[0] -= width);
  44399. align === 'center' && (position[0] -= width / 2);
  44400. var verticalAlign = labelPos.verticalAlign;
  44401. verticalAlign === 'bottom' && (position[1] -= height);
  44402. verticalAlign === 'middle' && (position[1] -= height / 2);
  44403. // Not overflow ec container
  44404. confineInContainer(position, width, height, api);
  44405. var bgColor = labelModel.get('backgroundColor');
  44406. if (!bgColor || bgColor === 'auto') {
  44407. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  44408. }
  44409. elOption.label = {
  44410. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  44411. x: position[0],
  44412. y: position[1],
  44413. style: createTextStyle(labelModel, {
  44414. text: text,
  44415. font: font,
  44416. fill: labelModel.getTextColor(),
  44417. padding: paddings,
  44418. backgroundColor: bgColor
  44419. }),
  44420. // Label should be over axisPointer.
  44421. z2: 10
  44422. };
  44423. }
  44424. // Do not overflow ec container
  44425. function confineInContainer(position, width, height, api) {
  44426. var viewWidth = api.getWidth();
  44427. var viewHeight = api.getHeight();
  44428. position[0] = Math.min(position[0] + width, viewWidth) - width;
  44429. position[1] = Math.min(position[1] + height, viewHeight) - height;
  44430. position[0] = Math.max(position[0], 0);
  44431. position[1] = Math.max(position[1], 0);
  44432. }
  44433. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  44434. value = axis.scale.parse(value);
  44435. var text = axis.scale.getLabel({
  44436. value: value
  44437. }, {
  44438. // If `precision` is set, width can be fixed (like '12.00500'), which
  44439. // helps to debounce when when moving label.
  44440. precision: opt.precision
  44441. });
  44442. var formatter = opt.formatter;
  44443. if (formatter) {
  44444. var params_1 = {
  44445. value: getAxisRawValue(axis, {
  44446. value: value
  44447. }),
  44448. axisDimension: axis.dim,
  44449. axisIndex: axis.index,
  44450. seriesData: []
  44451. };
  44452. each(seriesDataIndices, function (idxItem) {
  44453. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  44454. var dataIndex = idxItem.dataIndexInside;
  44455. var dataParams = series && series.getDataParams(dataIndex);
  44456. dataParams && params_1.seriesData.push(dataParams);
  44457. });
  44458. if (isString(formatter)) {
  44459. text = formatter.replace('{value}', text);
  44460. } else if (isFunction(formatter)) {
  44461. text = formatter(params_1);
  44462. }
  44463. }
  44464. return text;
  44465. }
  44466. function getTransformedPosition(axis, value, layoutInfo) {
  44467. var transform = create$1();
  44468. rotate(transform, transform, layoutInfo.rotation);
  44469. translate(transform, transform, layoutInfo.position);
  44470. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  44471. }
  44472. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  44473. // @ts-ignore
  44474. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  44475. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  44476. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  44477. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  44478. align: textLayout.textAlign,
  44479. verticalAlign: textLayout.textVerticalAlign
  44480. });
  44481. }
  44482. function makeLineShape(p1, p2, xDimIndex) {
  44483. xDimIndex = xDimIndex || 0;
  44484. return {
  44485. x1: p1[xDimIndex],
  44486. y1: p1[1 - xDimIndex],
  44487. x2: p2[xDimIndex],
  44488. y2: p2[1 - xDimIndex]
  44489. };
  44490. }
  44491. function makeRectShape(xy, wh, xDimIndex) {
  44492. xDimIndex = xDimIndex || 0;
  44493. return {
  44494. x: xy[xDimIndex],
  44495. y: xy[1 - xDimIndex],
  44496. width: wh[xDimIndex],
  44497. height: wh[1 - xDimIndex]
  44498. };
  44499. }
  44500. var CartesianAxisPointer = /** @class */function (_super) {
  44501. __extends(CartesianAxisPointer, _super);
  44502. function CartesianAxisPointer() {
  44503. return _super !== null && _super.apply(this, arguments) || this;
  44504. }
  44505. /**
  44506. * @override
  44507. */
  44508. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  44509. var axis = axisModel.axis;
  44510. var grid = axis.grid;
  44511. var axisPointerType = axisPointerModel.get('type');
  44512. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  44513. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  44514. if (axisPointerType && axisPointerType !== 'none') {
  44515. var elStyle = buildElStyle(axisPointerModel);
  44516. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  44517. pointerOption.style = elStyle;
  44518. elOption.graphicKey = pointerOption.type;
  44519. elOption.pointer = pointerOption;
  44520. }
  44521. var layoutInfo = layout$1(grid.model, axisModel);
  44522. buildCartesianSingleLabelElOption(
  44523. // @ts-ignore
  44524. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  44525. };
  44526. /**
  44527. * @override
  44528. */
  44529. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  44530. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  44531. labelInside: false
  44532. });
  44533. // @ts-ignore
  44534. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  44535. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  44536. return {
  44537. x: pos[0],
  44538. y: pos[1],
  44539. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  44540. };
  44541. };
  44542. /**
  44543. * @override
  44544. */
  44545. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  44546. var axis = axisModel.axis;
  44547. var grid = axis.grid;
  44548. var axisExtent = axis.getGlobalExtent(true);
  44549. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  44550. var dimIndex = axis.dim === 'x' ? 0 : 1;
  44551. var currPosition = [transform.x, transform.y];
  44552. currPosition[dimIndex] += delta[dimIndex];
  44553. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  44554. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  44555. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  44556. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  44557. cursorPoint[dimIndex] = currPosition[dimIndex];
  44558. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  44559. var tooltipOptions = [{
  44560. verticalAlign: 'middle'
  44561. }, {
  44562. align: 'center'
  44563. }];
  44564. return {
  44565. x: currPosition[0],
  44566. y: currPosition[1],
  44567. rotation: transform.rotation,
  44568. cursorPoint: cursorPoint,
  44569. tooltipOption: tooltipOptions[dimIndex]
  44570. };
  44571. };
  44572. return CartesianAxisPointer;
  44573. }(BaseAxisPointer);
  44574. function getCartesian(grid, axis) {
  44575. var opt = {};
  44576. opt[axis.dim + 'AxisIndex'] = axis.index;
  44577. return grid.getCartesian(opt);
  44578. }
  44579. var pointerShapeBuilder = {
  44580. line: function (axis, pixelValue, otherExtent) {
  44581. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  44582. return {
  44583. type: 'Line',
  44584. subPixelOptimize: true,
  44585. shape: targetShape
  44586. };
  44587. },
  44588. shadow: function (axis, pixelValue, otherExtent) {
  44589. var bandWidth = Math.max(1, axis.getBandWidth());
  44590. var span = otherExtent[1] - otherExtent[0];
  44591. return {
  44592. type: 'Rect',
  44593. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  44594. };
  44595. }
  44596. };
  44597. function getAxisDimIndex(axis) {
  44598. return axis.dim === 'x' ? 0 : 1;
  44599. }
  44600. var AxisPointerModel = /** @class */function (_super) {
  44601. __extends(AxisPointerModel, _super);
  44602. function AxisPointerModel() {
  44603. var _this = _super !== null && _super.apply(this, arguments) || this;
  44604. _this.type = AxisPointerModel.type;
  44605. return _this;
  44606. }
  44607. AxisPointerModel.type = 'axisPointer';
  44608. AxisPointerModel.defaultOption = {
  44609. // 'auto' means that show when triggered by tooltip or handle.
  44610. show: 'auto',
  44611. // zlevel: 0,
  44612. z: 50,
  44613. type: 'line',
  44614. // axispointer triggered by tootip determine snap automatically,
  44615. // see `modelHelper`.
  44616. snap: false,
  44617. triggerTooltip: true,
  44618. triggerEmphasis: true,
  44619. value: null,
  44620. status: null,
  44621. link: [],
  44622. // Do not set 'auto' here, otherwise global animation: false
  44623. // will not effect at this axispointer.
  44624. animation: null,
  44625. animationDurationUpdate: 200,
  44626. lineStyle: {
  44627. color: '#B9BEC9',
  44628. width: 1,
  44629. type: 'dashed'
  44630. },
  44631. shadowStyle: {
  44632. color: 'rgba(210,219,238,0.2)'
  44633. },
  44634. label: {
  44635. show: true,
  44636. formatter: null,
  44637. precision: 'auto',
  44638. margin: 3,
  44639. color: '#fff',
  44640. padding: [5, 7, 5, 7],
  44641. backgroundColor: 'auto',
  44642. borderColor: null,
  44643. borderWidth: 0,
  44644. borderRadius: 3
  44645. },
  44646. handle: {
  44647. show: false,
  44648. // eslint-disable-next-line
  44649. 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',
  44650. size: 45,
  44651. // handle margin is from symbol center to axis, which is stable when circular move.
  44652. margin: 50,
  44653. // color: '#1b8bbd'
  44654. // color: '#2f4554'
  44655. color: '#333',
  44656. shadowBlur: 3,
  44657. shadowColor: '#aaa',
  44658. shadowOffsetX: 0,
  44659. shadowOffsetY: 2,
  44660. // For mobile performance
  44661. throttle: 40
  44662. }
  44663. };
  44664. return AxisPointerModel;
  44665. }(ComponentModel);
  44666. var inner$8 = makeInner();
  44667. var each$3 = each;
  44668. /**
  44669. * @param {string} key
  44670. * @param {module:echarts/ExtensionAPI} api
  44671. * @param {Function} handler
  44672. * param: {string} currTrigger
  44673. * param: {Array.<number>} point
  44674. */
  44675. function register(key, api, handler) {
  44676. if (env.node) {
  44677. return;
  44678. }
  44679. var zr = api.getZr();
  44680. inner$8(zr).records || (inner$8(zr).records = {});
  44681. initGlobalListeners(zr, api);
  44682. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  44683. record.handler = handler;
  44684. }
  44685. function initGlobalListeners(zr, api) {
  44686. if (inner$8(zr).initialized) {
  44687. return;
  44688. }
  44689. inner$8(zr).initialized = true;
  44690. useHandler('click', curry(doEnter, 'click'));
  44691. useHandler('mousemove', curry(doEnter, 'mousemove'));
  44692. // useHandler('mouseout', onLeave);
  44693. useHandler('globalout', onLeave);
  44694. function useHandler(eventType, cb) {
  44695. zr.on(eventType, function (e) {
  44696. var dis = makeDispatchAction(api);
  44697. each$3(inner$8(zr).records, function (record) {
  44698. record && cb(record, e, dis.dispatchAction);
  44699. });
  44700. dispatchTooltipFinally(dis.pendings, api);
  44701. });
  44702. }
  44703. }
  44704. function dispatchTooltipFinally(pendings, api) {
  44705. var showLen = pendings.showTip.length;
  44706. var hideLen = pendings.hideTip.length;
  44707. var actuallyPayload;
  44708. if (showLen) {
  44709. actuallyPayload = pendings.showTip[showLen - 1];
  44710. } else if (hideLen) {
  44711. actuallyPayload = pendings.hideTip[hideLen - 1];
  44712. }
  44713. if (actuallyPayload) {
  44714. actuallyPayload.dispatchAction = null;
  44715. api.dispatchAction(actuallyPayload);
  44716. }
  44717. }
  44718. function onLeave(record, e, dispatchAction) {
  44719. record.handler('leave', null, dispatchAction);
  44720. }
  44721. function doEnter(currTrigger, record, e, dispatchAction) {
  44722. record.handler(currTrigger, e, dispatchAction);
  44723. }
  44724. function makeDispatchAction(api) {
  44725. var pendings = {
  44726. showTip: [],
  44727. hideTip: []
  44728. };
  44729. // FIXME
  44730. // better approach?
  44731. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  44732. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  44733. // So we have to add "final stage" to merge those dispatched actions.
  44734. var dispatchAction = function (payload) {
  44735. var pendingList = pendings[payload.type];
  44736. if (pendingList) {
  44737. pendingList.push(payload);
  44738. } else {
  44739. payload.dispatchAction = dispatchAction;
  44740. api.dispatchAction(payload);
  44741. }
  44742. };
  44743. return {
  44744. dispatchAction: dispatchAction,
  44745. pendings: pendings
  44746. };
  44747. }
  44748. function unregister(key, api) {
  44749. if (env.node) {
  44750. return;
  44751. }
  44752. var zr = api.getZr();
  44753. var record = (inner$8(zr).records || {})[key];
  44754. if (record) {
  44755. inner$8(zr).records[key] = null;
  44756. }
  44757. }
  44758. var AxisPointerView = /** @class */function (_super) {
  44759. __extends(AxisPointerView, _super);
  44760. function AxisPointerView() {
  44761. var _this = _super !== null && _super.apply(this, arguments) || this;
  44762. _this.type = AxisPointerView.type;
  44763. return _this;
  44764. }
  44765. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  44766. var globalTooltipModel = ecModel.getComponent('tooltip');
  44767. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click';
  44768. // Register global listener in AxisPointerView to enable
  44769. // AxisPointerView to be independent to Tooltip.
  44770. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  44771. // If 'none', it is not controlled by mouse totally.
  44772. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  44773. dispatchAction({
  44774. type: 'updateAxisPointer',
  44775. currTrigger: currTrigger,
  44776. x: e && e.offsetX,
  44777. y: e && e.offsetY
  44778. });
  44779. }
  44780. });
  44781. };
  44782. AxisPointerView.prototype.remove = function (ecModel, api) {
  44783. unregister('axisPointer', api);
  44784. };
  44785. AxisPointerView.prototype.dispose = function (ecModel, api) {
  44786. unregister('axisPointer', api);
  44787. };
  44788. AxisPointerView.type = 'axisPointer';
  44789. return AxisPointerView;
  44790. }(ComponentView);
  44791. /**
  44792. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  44793. * @param ecModel
  44794. * @return {point: [x, y], el: ...} point Will not be null.
  44795. */
  44796. function findPointFromSeries(finder, ecModel) {
  44797. var point = [];
  44798. var seriesIndex = finder.seriesIndex;
  44799. var seriesModel;
  44800. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  44801. return {
  44802. point: []
  44803. };
  44804. }
  44805. var data = seriesModel.getData();
  44806. var dataIndex = queryDataIndex(data, finder);
  44807. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  44808. return {
  44809. point: []
  44810. };
  44811. }
  44812. var el = data.getItemGraphicEl(dataIndex);
  44813. var coordSys = seriesModel.coordinateSystem;
  44814. if (seriesModel.getTooltipPosition) {
  44815. point = seriesModel.getTooltipPosition(dataIndex) || [];
  44816. } else if (coordSys && coordSys.dataToPoint) {
  44817. if (finder.isStacked) {
  44818. var baseAxis = coordSys.getBaseAxis();
  44819. var valueAxis = coordSys.getOtherAxis(baseAxis);
  44820. var valueAxisDim = valueAxis.dim;
  44821. var baseAxisDim = baseAxis.dim;
  44822. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  44823. var baseDim = data.mapDimension(baseAxisDim);
  44824. var stackedData = [];
  44825. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  44826. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  44827. point = coordSys.dataToPoint(stackedData) || [];
  44828. } else {
  44829. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  44830. return data.mapDimension(dim);
  44831. }), dataIndex)) || [];
  44832. }
  44833. } else if (el) {
  44834. // Use graphic bounding rect
  44835. var rect = el.getBoundingRect().clone();
  44836. rect.applyTransform(el.transform);
  44837. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  44838. }
  44839. return {
  44840. point: point,
  44841. el: el
  44842. };
  44843. }
  44844. var inner$9 = makeInner();
  44845. /**
  44846. * Basic logic: check all axis, if they do not demand show/highlight,
  44847. * then hide/downplay them.
  44848. *
  44849. * @return content of event obj for echarts.connect.
  44850. */
  44851. function axisTrigger(payload, ecModel, api) {
  44852. var currTrigger = payload.currTrigger;
  44853. var point = [payload.x, payload.y];
  44854. var finder = payload;
  44855. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  44856. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  44857. // Pending
  44858. // See #6121. But we are not able to reproduce it yet.
  44859. if (!coordSysAxesInfo) {
  44860. return;
  44861. }
  44862. if (illegalPoint(point)) {
  44863. // Used in the default behavior of `connection`: use the sample seriesIndex
  44864. // and dataIndex. And also used in the tooltipView trigger.
  44865. point = findPointFromSeries({
  44866. seriesIndex: finder.seriesIndex,
  44867. // Do not use dataIndexInside from other ec instance.
  44868. // FIXME: auto detect it?
  44869. dataIndex: finder.dataIndex
  44870. }, ecModel).point;
  44871. }
  44872. var isIllegalPoint = illegalPoint(point);
  44873. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  44874. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  44875. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  44876. // and dataIndex.
  44877. var inputAxesInfo = finder.axesInfo;
  44878. var axesInfo = coordSysAxesInfo.axesInfo;
  44879. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  44880. var outputPayload = {};
  44881. var showValueMap = {};
  44882. var dataByCoordSys = {
  44883. list: [],
  44884. map: {}
  44885. };
  44886. var updaters = {
  44887. showPointer: curry(showPointer, showValueMap),
  44888. showTooltip: curry(showTooltip, dataByCoordSys)
  44889. };
  44890. // Process for triggered axes.
  44891. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  44892. // If a point given, it must be contained by the coordinate system.
  44893. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  44894. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  44895. var axis = axisInfo.axis;
  44896. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  44897. // If no inputAxesInfo, no axis is restricted.
  44898. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  44899. var val = inputAxisInfo && inputAxisInfo.value;
  44900. if (val == null && !isIllegalPoint) {
  44901. val = axis.pointToData(point);
  44902. }
  44903. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  44904. }
  44905. });
  44906. });
  44907. // Process for linked axes.
  44908. var linkTriggers = {};
  44909. each(axesInfo, function (tarAxisInfo, tarKey) {
  44910. var linkGroup = tarAxisInfo.linkGroup;
  44911. // If axis has been triggered in the previous stage, it should not be triggered by link.
  44912. if (linkGroup && !showValueMap[tarKey]) {
  44913. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  44914. var srcValItem = showValueMap[srcKey];
  44915. // If srcValItem exist, source axis is triggered, so link to target axis.
  44916. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  44917. var val = srcValItem.value;
  44918. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  44919. linkTriggers[tarAxisInfo.key] = val;
  44920. }
  44921. });
  44922. }
  44923. });
  44924. each(linkTriggers, function (val, tarKey) {
  44925. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  44926. });
  44927. updateModelActually(showValueMap, axesInfo, outputPayload);
  44928. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  44929. dispatchHighDownActually(axesInfo, dispatchAction, api);
  44930. return outputPayload;
  44931. }
  44932. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  44933. var axis = axisInfo.axis;
  44934. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  44935. return;
  44936. }
  44937. if (!axisInfo.involveSeries) {
  44938. updaters.showPointer(axisInfo, newValue);
  44939. return;
  44940. }
  44941. // Heavy calculation. So put it after axis.containData checking.
  44942. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  44943. var payloadBatch = payloadInfo.payloadBatch;
  44944. var snapToValue = payloadInfo.snapToValue;
  44945. // Fill content of event obj for echarts.connect.
  44946. // By default use the first involved series data as a sample to connect.
  44947. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  44948. extend(outputFinder, payloadBatch[0]);
  44949. }
  44950. // If no linkSource input, this process is for collecting link
  44951. // target, where snap should not be accepted.
  44952. if (!noSnap && axisInfo.snap) {
  44953. if (axis.containData(snapToValue) && snapToValue != null) {
  44954. newValue = snapToValue;
  44955. }
  44956. }
  44957. updaters.showPointer(axisInfo, newValue, payloadBatch);
  44958. // Tooltip should always be snapToValue, otherwise there will be
  44959. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  44960. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  44961. }
  44962. function buildPayloadsBySeries(value, axisInfo) {
  44963. var axis = axisInfo.axis;
  44964. var dim = axis.dim;
  44965. var snapToValue = value;
  44966. var payloadBatch = [];
  44967. var minDist = Number.MAX_VALUE;
  44968. var minDiff = -1;
  44969. each(axisInfo.seriesModels, function (series, idx) {
  44970. var dataDim = series.getData().mapDimensionsAll(dim);
  44971. var seriesNestestValue;
  44972. var dataIndices;
  44973. if (series.getAxisTooltipData) {
  44974. var result = series.getAxisTooltipData(dataDim, value, axis);
  44975. dataIndices = result.dataIndices;
  44976. seriesNestestValue = result.nestestValue;
  44977. } else {
  44978. dataIndices = series.getData().indicesOfNearest(dataDim[0], value,
  44979. // Add a threshold to avoid find the wrong dataIndex
  44980. // when data length is not same.
  44981. // false,
  44982. axis.type === 'category' ? 0.5 : null);
  44983. if (!dataIndices.length) {
  44984. return;
  44985. }
  44986. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  44987. }
  44988. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  44989. return;
  44990. }
  44991. var diff = value - seriesNestestValue;
  44992. var dist = Math.abs(diff);
  44993. // Consider category case
  44994. if (dist <= minDist) {
  44995. if (dist < minDist || diff >= 0 && minDiff < 0) {
  44996. minDist = dist;
  44997. minDiff = diff;
  44998. snapToValue = seriesNestestValue;
  44999. payloadBatch.length = 0;
  45000. }
  45001. each(dataIndices, function (dataIndex) {
  45002. payloadBatch.push({
  45003. seriesIndex: series.seriesIndex,
  45004. dataIndexInside: dataIndex,
  45005. dataIndex: series.getData().getRawIndex(dataIndex)
  45006. });
  45007. });
  45008. }
  45009. });
  45010. return {
  45011. payloadBatch: payloadBatch,
  45012. snapToValue: snapToValue
  45013. };
  45014. }
  45015. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  45016. showValueMap[axisInfo.key] = {
  45017. value: value,
  45018. payloadBatch: payloadBatch
  45019. };
  45020. }
  45021. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  45022. var payloadBatch = payloadInfo.payloadBatch;
  45023. var axis = axisInfo.axis;
  45024. var axisModel = axis.model;
  45025. var axisPointerModel = axisInfo.axisPointerModel;
  45026. // If no data, do not create anything in dataByCoordSys,
  45027. // whose length will be used to judge whether dispatch action.
  45028. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  45029. return;
  45030. }
  45031. var coordSysModel = axisInfo.coordSys.model;
  45032. var coordSysKey = makeKey(coordSysModel);
  45033. var coordSysItem = dataByCoordSys.map[coordSysKey];
  45034. if (!coordSysItem) {
  45035. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  45036. coordSysId: coordSysModel.id,
  45037. coordSysIndex: coordSysModel.componentIndex,
  45038. coordSysType: coordSysModel.type,
  45039. coordSysMainType: coordSysModel.mainType,
  45040. dataByAxis: []
  45041. };
  45042. dataByCoordSys.list.push(coordSysItem);
  45043. }
  45044. coordSysItem.dataByAxis.push({
  45045. axisDim: axis.dim,
  45046. axisIndex: axisModel.componentIndex,
  45047. axisType: axisModel.type,
  45048. axisId: axisModel.id,
  45049. value: value,
  45050. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  45051. // depends that all models have been updated. So it should not be performed
  45052. // here. Considering axisPointerModel used here is volatile, which is hard
  45053. // to be retrieve in TooltipView, we prepare parameters here.
  45054. valueLabelOpt: {
  45055. precision: axisPointerModel.get(['label', 'precision']),
  45056. formatter: axisPointerModel.get(['label', 'formatter'])
  45057. },
  45058. seriesDataIndices: payloadBatch.slice()
  45059. });
  45060. }
  45061. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  45062. var outputAxesInfo = outputPayload.axesInfo = [];
  45063. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  45064. each(axesInfo, function (axisInfo, key) {
  45065. var option = axisInfo.axisPointerModel.option;
  45066. var valItem = showValueMap[key];
  45067. if (valItem) {
  45068. !axisInfo.useHandle && (option.status = 'show');
  45069. option.value = valItem.value;
  45070. // For label formatter param and highlight.
  45071. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  45072. }
  45073. // When always show (e.g., handle used), remain
  45074. // original value and status.
  45075. else {
  45076. // If hide, value still need to be set, consider
  45077. // click legend to toggle axis blank.
  45078. !axisInfo.useHandle && (option.status = 'hide');
  45079. }
  45080. // If status is 'hide', should be no info in payload.
  45081. option.status === 'show' && outputAxesInfo.push({
  45082. axisDim: axisInfo.axis.dim,
  45083. axisIndex: axisInfo.axis.model.componentIndex,
  45084. value: option.value
  45085. });
  45086. });
  45087. }
  45088. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  45089. // Basic logic: If no showTip required, hideTip will be dispatched.
  45090. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  45091. dispatchAction({
  45092. type: 'hideTip'
  45093. });
  45094. return;
  45095. }
  45096. // In most case only one axis (or event one series is used). It is
  45097. // convenient to fetch payload.seriesIndex and payload.dataIndex
  45098. // directly. So put the first seriesIndex and dataIndex of the first
  45099. // axis on the payload.
  45100. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  45101. dispatchAction({
  45102. type: 'showTip',
  45103. escapeConnect: true,
  45104. x: point[0],
  45105. y: point[1],
  45106. tooltipOption: payload.tooltipOption,
  45107. position: payload.position,
  45108. dataIndexInside: sampleItem.dataIndexInside,
  45109. dataIndex: sampleItem.dataIndex,
  45110. seriesIndex: sampleItem.seriesIndex,
  45111. dataByCoordSys: dataByCoordSys.list
  45112. });
  45113. }
  45114. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  45115. // FIXME
  45116. // highlight status modification should be a stage of main process?
  45117. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  45118. var zr = api.getZr();
  45119. var highDownKey = 'axisPointerLastHighlights';
  45120. var lastHighlights = inner$9(zr)[highDownKey] || {};
  45121. var newHighlights = inner$9(zr)[highDownKey] = {};
  45122. // Update highlight/downplay status according to axisPointer model.
  45123. // Build hash map and remove duplicate incidentally.
  45124. each(axesInfo, function (axisInfo, key) {
  45125. var option = axisInfo.axisPointerModel.option;
  45126. option.status === 'show' && axisInfo.triggerEmphasis && each(option.seriesDataIndices, function (batchItem) {
  45127. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  45128. newHighlights[key] = batchItem;
  45129. });
  45130. });
  45131. // Diff.
  45132. var toHighlight = [];
  45133. var toDownplay = [];
  45134. each(lastHighlights, function (batchItem, key) {
  45135. !newHighlights[key] && toDownplay.push(batchItem);
  45136. });
  45137. each(newHighlights, function (batchItem, key) {
  45138. !lastHighlights[key] && toHighlight.push(batchItem);
  45139. });
  45140. toDownplay.length && api.dispatchAction({
  45141. type: 'downplay',
  45142. escapeConnect: true,
  45143. // Not blur others when highlight in axisPointer.
  45144. notBlur: true,
  45145. batch: toDownplay
  45146. });
  45147. toHighlight.length && api.dispatchAction({
  45148. type: 'highlight',
  45149. escapeConnect: true,
  45150. // Not blur others when highlight in axisPointer.
  45151. notBlur: true,
  45152. batch: toHighlight
  45153. });
  45154. }
  45155. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  45156. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  45157. var inputAxisInfo = inputAxesInfo[i];
  45158. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  45159. return inputAxisInfo;
  45160. }
  45161. }
  45162. }
  45163. function makeMapperParam(axisInfo) {
  45164. var axisModel = axisInfo.axis.model;
  45165. var item = {};
  45166. var dim = item.axisDim = axisInfo.axis.dim;
  45167. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  45168. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  45169. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  45170. return item;
  45171. }
  45172. function illegalPoint(point) {
  45173. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  45174. }
  45175. function install$7(registers) {
  45176. // CartesianAxisPointer is not supposed to be required here. But consider
  45177. // echarts.simple.js and online build tooltip, which only require gridSimple,
  45178. // CartesianAxisPointer should be able to required somewhere.
  45179. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  45180. registers.registerComponentModel(AxisPointerModel);
  45181. registers.registerComponentView(AxisPointerView);
  45182. registers.registerPreprocessor(function (option) {
  45183. // Always has a global axisPointerModel for default setting.
  45184. if (option) {
  45185. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  45186. var link = option.axisPointer.link;
  45187. // Normalize to array to avoid object mergin. But if link
  45188. // is not set, remain null/undefined, otherwise it will
  45189. // override existent link setting.
  45190. if (link && !isArray(link)) {
  45191. option.axisPointer.link = [link];
  45192. }
  45193. }
  45194. });
  45195. // This process should proformed after coordinate systems created
  45196. // and series data processed. So put it on statistic processing stage.
  45197. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  45198. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  45199. // allAxesInfo should be updated when setOption performed.
  45200. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  45201. });
  45202. // Broadcast to all views.
  45203. registers.registerAction({
  45204. type: 'updateAxisPointer',
  45205. event: 'updateAxisPointer',
  45206. update: ':updateAxisPointer'
  45207. }, axisTrigger);
  45208. }
  45209. function install$8(registers) {
  45210. use(install$5);
  45211. use(install$7);
  45212. }
  45213. function setKeyInfoToNewElOption(resultItem, newElOption) {
  45214. var existElOption = resultItem.existing;
  45215. // Set id and type after id assigned.
  45216. newElOption.id = resultItem.keyInfo.id;
  45217. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  45218. // Set parent id if not specified
  45219. if (newElOption.parentId == null) {
  45220. var newElParentOption = newElOption.parentOption;
  45221. if (newElParentOption) {
  45222. newElOption.parentId = newElParentOption.id;
  45223. } else if (existElOption) {
  45224. newElOption.parentId = existElOption.parentId;
  45225. }
  45226. }
  45227. // Clear
  45228. newElOption.parentOption = null;
  45229. }
  45230. function isSetLoc(obj, props) {
  45231. var isSet;
  45232. each(props, function (prop) {
  45233. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  45234. });
  45235. return isSet;
  45236. }
  45237. function mergeNewElOptionToExist(existList, index, newElOption) {
  45238. // Update existing options, for `getOption` feature.
  45239. var newElOptCopy = extend({}, newElOption);
  45240. var existElOption = existList[index];
  45241. var $action = newElOption.$action || 'merge';
  45242. if ($action === 'merge') {
  45243. if (existElOption) {
  45244. if ("development" !== 'production') {
  45245. var newType = newElOption.type;
  45246. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  45247. }
  45248. // We can ensure that newElOptCopy and existElOption are not
  45249. // the same object, so `merge` will not change newElOptCopy.
  45250. merge(existElOption, newElOptCopy, true);
  45251. // Rigid body, use ignoreSize.
  45252. mergeLayoutParam(existElOption, newElOptCopy, {
  45253. ignoreSize: true
  45254. });
  45255. // Will be used in render.
  45256. copyLayoutParams(newElOption, existElOption);
  45257. // Copy transition info to new option so it can be used in the transition.
  45258. // DO IT AFTER merge
  45259. copyTransitionInfo(newElOption, existElOption);
  45260. copyTransitionInfo(newElOption, existElOption, 'shape');
  45261. copyTransitionInfo(newElOption, existElOption, 'style');
  45262. copyTransitionInfo(newElOption, existElOption, 'extra');
  45263. // Copy clipPath
  45264. newElOption.clipPath = existElOption.clipPath;
  45265. } else {
  45266. existList[index] = newElOptCopy;
  45267. }
  45268. } else if ($action === 'replace') {
  45269. existList[index] = newElOptCopy;
  45270. } else if ($action === 'remove') {
  45271. // null will be cleaned later.
  45272. existElOption && (existList[index] = null);
  45273. }
  45274. }
  45275. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  45276. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  45277. function copyTransitionInfo(target, source, targetProp) {
  45278. if (targetProp) {
  45279. if (!target[targetProp] && source[targetProp]) {
  45280. // TODO avoid creating this empty object when there is no transition configuration.
  45281. target[targetProp] = {};
  45282. }
  45283. target = target[targetProp];
  45284. source = source[targetProp];
  45285. }
  45286. if (!target || !source) {
  45287. return;
  45288. }
  45289. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  45290. for (var i = 0; i < props.length; i++) {
  45291. var prop = props[i];
  45292. if (target[prop] == null && source[prop] != null) {
  45293. target[prop] = source[prop];
  45294. }
  45295. }
  45296. }
  45297. function setLayoutInfoToExist(existItem, newElOption) {
  45298. if (!existItem) {
  45299. return;
  45300. }
  45301. existItem.hv = newElOption.hv = [
  45302. // Rigid body, don't care about `width`.
  45303. isSetLoc(newElOption, ['left', 'right']),
  45304. // Rigid body, don't care about `height`.
  45305. isSetLoc(newElOption, ['top', 'bottom'])];
  45306. // Give default group size. Otherwise layout error may occur.
  45307. if (existItem.type === 'group') {
  45308. var existingGroupOpt = existItem;
  45309. var newGroupOpt = newElOption;
  45310. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  45311. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  45312. }
  45313. }
  45314. var GraphicComponentModel = /** @class */function (_super) {
  45315. __extends(GraphicComponentModel, _super);
  45316. function GraphicComponentModel() {
  45317. var _this = _super !== null && _super.apply(this, arguments) || this;
  45318. _this.type = GraphicComponentModel.type;
  45319. _this.preventAutoZ = true;
  45320. return _this;
  45321. }
  45322. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  45323. // Prevent default merge to elements
  45324. var elements = this.option.elements;
  45325. this.option.elements = null;
  45326. _super.prototype.mergeOption.call(this, option, ecModel);
  45327. this.option.elements = elements;
  45328. };
  45329. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  45330. var thisOption = this.option;
  45331. var newList = (isInit ? thisOption : newOption).elements;
  45332. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  45333. var flattenedList = [];
  45334. this._flatten(newList, flattenedList, null);
  45335. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge');
  45336. // Clear elOptionsToUpdate
  45337. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  45338. each(mappingResult, function (resultItem, index) {
  45339. var newElOption = resultItem.newOption;
  45340. if ("development" !== 'production') {
  45341. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  45342. }
  45343. if (!newElOption) {
  45344. return;
  45345. }
  45346. elOptionsToUpdate.push(newElOption);
  45347. setKeyInfoToNewElOption(resultItem, newElOption);
  45348. mergeNewElOptionToExist(existList, index, newElOption);
  45349. setLayoutInfoToExist(existList[index], newElOption);
  45350. }, this);
  45351. // Clean
  45352. thisOption.elements = filter(existList, function (item) {
  45353. // $action should be volatile, otherwise option gotten from
  45354. // `getOption` will contain unexpected $action.
  45355. item && delete item.$action;
  45356. return item != null;
  45357. });
  45358. };
  45359. /**
  45360. * Convert
  45361. * [{
  45362. * type: 'group',
  45363. * id: 'xx',
  45364. * children: [{type: 'circle'}, {type: 'polygon'}]
  45365. * }]
  45366. * to
  45367. * [
  45368. * {type: 'group', id: 'xx'},
  45369. * {type: 'circle', parentId: 'xx'},
  45370. * {type: 'polygon', parentId: 'xx'}
  45371. * ]
  45372. */
  45373. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  45374. each(optionList, function (option) {
  45375. if (!option) {
  45376. return;
  45377. }
  45378. if (parentOption) {
  45379. option.parentOption = parentOption;
  45380. }
  45381. result.push(option);
  45382. var children = option.children;
  45383. // here we don't judge if option.type is `group`
  45384. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  45385. if (children && children.length) {
  45386. this._flatten(children, result, option);
  45387. }
  45388. // Deleting for JSON output, and for not affecting group creation.
  45389. delete option.children;
  45390. }, this);
  45391. };
  45392. // FIXME
  45393. // Pass to view using payload? setOption has a payload?
  45394. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  45395. var els = this._elOptionsToUpdate;
  45396. // Clear to avoid render duplicately when zooming.
  45397. this._elOptionsToUpdate = null;
  45398. return els;
  45399. };
  45400. GraphicComponentModel.type = 'graphic';
  45401. GraphicComponentModel.defaultOption = {
  45402. elements: []
  45403. // parentId: null
  45404. };
  45405. return GraphicComponentModel;
  45406. }(ComponentModel);
  45407. /**
  45408. * Whether need to call `convertEC4CompatibleStyle`.
  45409. */
  45410. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  45411. // Since echarts5, `RectText` is separated from its host element and style.text
  45412. // does not exist any more. The compat work brings some extra burden on performance.
  45413. // So we provide:
  45414. // `legacy: true` force make compat.
  45415. // `legacy: false`, force do not compat.
  45416. // `legacy` not set: auto detect whether legacy.
  45417. // But in this case we do not compat (difficult to detect and rare case):
  45418. // Becuse custom series and graphic component support "merge", users may firstly
  45419. // only set `textStrokeWidth` style or secondly only set `text`.
  45420. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan'
  45421. // Difficult to detect whether legacy for a "text" el.
  45422. && (elType === 'text' || hasOwn(style, 'text')));
  45423. }
  45424. /**
  45425. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  45426. * @param hostStyle The properties might be modified.
  45427. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  45428. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  45429. * retried from the `hostStyle`.
  45430. */
  45431. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  45432. var srcStyle = hostStyle;
  45433. var textConfig;
  45434. var textContent;
  45435. var textContentStyle;
  45436. if (elType === 'text') {
  45437. textContentStyle = srcStyle;
  45438. } else {
  45439. textContentStyle = {};
  45440. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  45441. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  45442. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  45443. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  45444. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  45445. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  45446. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  45447. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  45448. textContent = {
  45449. type: 'text',
  45450. style: textContentStyle,
  45451. // ec4 does not support rectText trigger.
  45452. // And when text position is different in normal and emphasis
  45453. // => hover text trigger emphasis;
  45454. // => text position changed, leave mouse pointer immediately;
  45455. // That might cause incorrect state.
  45456. silent: true
  45457. };
  45458. textConfig = {};
  45459. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  45460. if (isNormal) {
  45461. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  45462. } else {
  45463. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  45464. }
  45465. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  45466. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  45467. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  45468. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  45469. }
  45470. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  45471. each(textContentStyle.rich, function (richItem) {
  45472. convertEC4CompatibleRichItem(richItem, richItem);
  45473. });
  45474. return {
  45475. textConfig: textConfig,
  45476. textContent: textContent
  45477. };
  45478. }
  45479. /**
  45480. * The result will be set to `out`.
  45481. */
  45482. function convertEC4CompatibleRichItem(out, richItem) {
  45483. if (!richItem) {
  45484. return;
  45485. }
  45486. // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  45487. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  45488. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  45489. // richText in ec5.
  45490. // (2) `out === richItem` if and only if `out` is text el or rich item.
  45491. // So we can overwrite existing props in `out` since textXXX has higher priority.
  45492. richItem.font = richItem.textFont || richItem.font;
  45493. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  45494. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  45495. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  45496. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  45497. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  45498. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  45499. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  45500. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  45501. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  45502. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  45503. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  45504. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  45505. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  45506. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  45507. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  45508. }
  45509. var LEGACY_TRANSFORM_PROPS_MAP = {
  45510. position: ['x', 'y'],
  45511. scale: ['scaleX', 'scaleY'],
  45512. origin: ['originX', 'originY']
  45513. };
  45514. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  45515. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  45516. obj[key] = 1;
  45517. return obj;
  45518. }, {});
  45519. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', ');
  45520. // '' means root
  45521. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  45522. var transitionInnerStore = makeInner();
  45523. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  45524. var animationProp = animationType + "Animation";
  45525. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  45526. var userDuring = transitionInnerStore(el).userDuring;
  45527. // Only set when duration is > 0 and it's need to be animated.
  45528. if (config.duration > 0) {
  45529. // For simplicity, if during not specified, the previous during will not work any more.
  45530. config.during = userDuring ? bind(duringCall, {
  45531. el: el,
  45532. userDuring: userDuring
  45533. }) : null;
  45534. config.setToFinal = true;
  45535. config.scope = animationType;
  45536. }
  45537. extend(config, elOption[animationProp]);
  45538. return config;
  45539. }
  45540. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  45541. opts = opts || {};
  45542. var dataIndex = opts.dataIndex,
  45543. isInit = opts.isInit,
  45544. clearStyle = opts.clearStyle;
  45545. var hasAnimation = animatableModel.isAnimationEnabled();
  45546. // Save the meta info for further morphing. Like apply on the sub morphing elements.
  45547. var store = transitionInnerStore(el);
  45548. var styleOpt = elOption.style;
  45549. store.userDuring = elOption.during;
  45550. var transFromProps = {};
  45551. var propsToSet = {};
  45552. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  45553. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  45554. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  45555. if (!isInit && hasAnimation) {
  45556. prepareTransformTransitionFrom(el, elOption, transFromProps);
  45557. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  45558. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  45559. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  45560. }
  45561. propsToSet.style = styleOpt;
  45562. applyPropsDirectly(el, propsToSet, clearStyle);
  45563. applyMiscProps(el, elOption);
  45564. if (hasAnimation) {
  45565. if (isInit) {
  45566. var enterFromProps_1 = {};
  45567. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  45568. var prop = propName ? elOption[propName] : elOption;
  45569. if (prop && prop.enterFrom) {
  45570. if (propName) {
  45571. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  45572. }
  45573. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  45574. }
  45575. });
  45576. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  45577. if (config.duration > 0) {
  45578. el.animateFrom(enterFromProps_1, config);
  45579. }
  45580. } else {
  45581. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  45582. }
  45583. }
  45584. // Store leave to be used in leave transition.
  45585. updateLeaveTo(el, elOption);
  45586. styleOpt ? el.dirty() : el.markRedraw();
  45587. }
  45588. function updateLeaveTo(el, elOption) {
  45589. // Try merge to previous set leaveTo
  45590. var leaveToProps = transitionInnerStore(el).leaveToProps;
  45591. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  45592. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  45593. var prop = propName ? elOption[propName] : elOption;
  45594. if (prop && prop.leaveTo) {
  45595. if (!leaveToProps) {
  45596. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  45597. }
  45598. if (propName) {
  45599. leaveToProps[propName] = leaveToProps[propName] || {};
  45600. }
  45601. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  45602. }
  45603. }
  45604. }
  45605. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  45606. if (el) {
  45607. var parent_1 = el.parent;
  45608. var leaveToProps = transitionInnerStore(el).leaveToProps;
  45609. if (leaveToProps) {
  45610. // TODO TODO use leave after leaveAnimation in series is introduced
  45611. // TODO Data index?
  45612. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  45613. config.done = function () {
  45614. parent_1.remove(el);
  45615. onRemove && onRemove();
  45616. };
  45617. el.animateTo(leaveToProps, config);
  45618. } else {
  45619. parent_1.remove(el);
  45620. onRemove && onRemove();
  45621. }
  45622. }
  45623. }
  45624. function isTransitionAll(transition) {
  45625. return transition === 'all';
  45626. }
  45627. function applyPropsDirectly(el,
  45628. // Can be null/undefined
  45629. allPropsFinal, clearStyle) {
  45630. var styleOpt = allPropsFinal.style;
  45631. if (!el.isGroup && styleOpt) {
  45632. if (clearStyle) {
  45633. el.useStyle({});
  45634. // When style object changed, how to trade the existing animation?
  45635. // It is probably complicated and not needed to cover all the cases.
  45636. // But still need consider the case:
  45637. // (1) When using init animation on `style.opacity`, and before the animation
  45638. // ended users triggers an update by mousewhel. At that time the init
  45639. // animation should better be continued rather than terminated.
  45640. // So after `useStyle` called, we should change the animation target manually
  45641. // to continue the effect of the init animation.
  45642. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  45643. // to update the value to `val2` and no animation declared, should be terminate
  45644. // the previous animation or just modify the target of the animation?
  45645. // Therotically That will happen not only on `style` but also on `shape` and
  45646. // `transfrom` props. But we haven't handle this case at present yet.
  45647. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  45648. var animators = el.animators;
  45649. for (var i = 0; i < animators.length; i++) {
  45650. var animator = animators[i];
  45651. // targetName is the "topKey".
  45652. if (animator.targetName === 'style') {
  45653. animator.changeTarget(el.style);
  45654. }
  45655. }
  45656. }
  45657. el.setStyle(styleOpt);
  45658. }
  45659. if (allPropsFinal) {
  45660. // Not set style here.
  45661. allPropsFinal.style = null;
  45662. // Set el to the final state firstly.
  45663. allPropsFinal && el.attr(allPropsFinal);
  45664. allPropsFinal.style = styleOpt;
  45665. }
  45666. }
  45667. function applyPropsTransition(el, elOption, dataIndex, model,
  45668. // Can be null/undefined
  45669. transFromProps) {
  45670. if (transFromProps) {
  45671. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  45672. if (config.duration > 0) {
  45673. el.animateFrom(transFromProps, config);
  45674. }
  45675. }
  45676. }
  45677. function applyMiscProps(el, elOption) {
  45678. // Merge by default.
  45679. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  45680. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  45681. if (el instanceof Displayable) {
  45682. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  45683. }
  45684. if (el instanceof Path) {
  45685. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  45686. }
  45687. }
  45688. // Use it to avoid it be exposed to user.
  45689. var tmpDuringScope = {};
  45690. var transitionDuringAPI = {
  45691. // Usually other props do not need to be changed in animation during.
  45692. setTransform: function (key, val) {
  45693. if ("development" !== 'production') {
  45694. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  45695. }
  45696. tmpDuringScope.el[key] = val;
  45697. return this;
  45698. },
  45699. getTransform: function (key) {
  45700. if ("development" !== 'production') {
  45701. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  45702. }
  45703. return tmpDuringScope.el[key];
  45704. },
  45705. setShape: function (key, val) {
  45706. if ("development" !== 'production') {
  45707. assertNotReserved(key);
  45708. }
  45709. var el = tmpDuringScope.el;
  45710. var shape = el.shape || (el.shape = {});
  45711. shape[key] = val;
  45712. el.dirtyShape && el.dirtyShape();
  45713. return this;
  45714. },
  45715. getShape: function (key) {
  45716. if ("development" !== 'production') {
  45717. assertNotReserved(key);
  45718. }
  45719. var shape = tmpDuringScope.el.shape;
  45720. if (shape) {
  45721. return shape[key];
  45722. }
  45723. },
  45724. setStyle: function (key, val) {
  45725. if ("development" !== 'production') {
  45726. assertNotReserved(key);
  45727. }
  45728. var el = tmpDuringScope.el;
  45729. var style = el.style;
  45730. if (style) {
  45731. if ("development" !== 'production') {
  45732. if (eqNaN(val)) {
  45733. warn('style.' + key + ' must not be assigned with NaN.');
  45734. }
  45735. }
  45736. style[key] = val;
  45737. el.dirtyStyle && el.dirtyStyle();
  45738. }
  45739. return this;
  45740. },
  45741. getStyle: function (key) {
  45742. if ("development" !== 'production') {
  45743. assertNotReserved(key);
  45744. }
  45745. var style = tmpDuringScope.el.style;
  45746. if (style) {
  45747. return style[key];
  45748. }
  45749. },
  45750. setExtra: function (key, val) {
  45751. if ("development" !== 'production') {
  45752. assertNotReserved(key);
  45753. }
  45754. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  45755. extra[key] = val;
  45756. return this;
  45757. },
  45758. getExtra: function (key) {
  45759. if ("development" !== 'production') {
  45760. assertNotReserved(key);
  45761. }
  45762. var extra = tmpDuringScope.el.extra;
  45763. if (extra) {
  45764. return extra[key];
  45765. }
  45766. }
  45767. };
  45768. function assertNotReserved(key) {
  45769. if ("development" !== 'production') {
  45770. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  45771. throw new Error('key must not be "' + key + '"');
  45772. }
  45773. }
  45774. }
  45775. function duringCall() {
  45776. // Do not provide "percent" until some requirements come.
  45777. // Because consider thies case:
  45778. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  45779. // And enter duration is different from update duration.
  45780. // Thus it might be confused about the meaning of "percent" in during callback.
  45781. var scope = this;
  45782. var el = scope.el;
  45783. if (!el) {
  45784. return;
  45785. }
  45786. // If el is remove from zr by reason like legend, during still need to called,
  45787. // because el will be added back to zr and the prop value should not be incorrect.
  45788. var latestUserDuring = transitionInnerStore(el).userDuring;
  45789. var scopeUserDuring = scope.userDuring;
  45790. // Ensured a during is only called once in each animation frame.
  45791. // If a during is called multiple times in one frame, maybe some users' calculation logic
  45792. // might be wrong (not sure whether this usage exists).
  45793. // The case of a during might be called twice can be: by default there is a animator for
  45794. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  45795. // another animators for 'style'/'shape'/'extra'.
  45796. if (latestUserDuring !== scopeUserDuring) {
  45797. // release
  45798. scope.el = scope.userDuring = null;
  45799. return;
  45800. }
  45801. tmpDuringScope.el = el;
  45802. // Give no `this` to user in "during" calling.
  45803. scopeUserDuring(transitionDuringAPI);
  45804. // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  45805. // consider the issue that the prop might be incorrect when return to "normal" state.
  45806. }
  45807. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  45808. var attrOpt = elOption[mainAttr];
  45809. if (!attrOpt) {
  45810. return;
  45811. }
  45812. var elPropsInAttr = fromEl[mainAttr];
  45813. var transFromPropsInAttr;
  45814. if (elPropsInAttr) {
  45815. var transition = elOption.transition;
  45816. var attrTransition = attrOpt.transition;
  45817. if (attrTransition) {
  45818. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  45819. if (isTransitionAll(attrTransition)) {
  45820. extend(transFromPropsInAttr, elPropsInAttr);
  45821. } else {
  45822. var transitionKeys = normalizeToArray(attrTransition);
  45823. for (var i = 0; i < transitionKeys.length; i++) {
  45824. var key = transitionKeys[i];
  45825. var elVal = elPropsInAttr[key];
  45826. transFromPropsInAttr[key] = elVal;
  45827. }
  45828. }
  45829. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  45830. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  45831. var elPropsInAttrKeys = keys(elPropsInAttr);
  45832. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  45833. var key = elPropsInAttrKeys[i];
  45834. var elVal = elPropsInAttr[key];
  45835. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  45836. transFromPropsInAttr[key] = elVal;
  45837. }
  45838. }
  45839. }
  45840. }
  45841. }
  45842. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  45843. var attrOpt = elOption[mainAttr];
  45844. if (!attrOpt) {
  45845. return;
  45846. }
  45847. var allPropsInAttr = allProps[mainAttr] = {};
  45848. var keysInAttr = keys(attrOpt);
  45849. for (var i = 0; i < keysInAttr.length; i++) {
  45850. var key = keysInAttr[i];
  45851. // To avoid share one object with different element, and
  45852. // to avoid user modify the object inexpectedly, have to clone.
  45853. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  45854. }
  45855. }
  45856. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  45857. var transition = elOption.transition;
  45858. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  45859. for (var i = 0; i < transitionKeys.length; i++) {
  45860. var key = transitionKeys[i];
  45861. if (key === 'style' || key === 'shape' || key === 'extra') {
  45862. continue;
  45863. }
  45864. var elVal = el[key];
  45865. if ("development" !== 'production') {
  45866. checkTransformPropRefer(key, 'el.transition');
  45867. }
  45868. // Do not clone, animator will perform that clone.
  45869. transFromProps[key] = elVal;
  45870. }
  45871. }
  45872. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  45873. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  45874. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  45875. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  45876. var legacyArr = elOption[legacyName];
  45877. if (legacyArr) {
  45878. allProps[xyName[0]] = legacyArr[0];
  45879. allProps[xyName[1]] = legacyArr[1];
  45880. }
  45881. }
  45882. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  45883. var key = TRANSFORMABLE_PROPS[i];
  45884. if (elOption[key] != null) {
  45885. allProps[key] = elOption[key];
  45886. }
  45887. }
  45888. }
  45889. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  45890. if (!styleOpt) {
  45891. return;
  45892. }
  45893. var fromElStyle = fromEl.style;
  45894. var transFromStyleProps;
  45895. if (fromElStyle) {
  45896. var styleTransition = styleOpt.transition;
  45897. var elTransition = elOption.transition;
  45898. if (styleTransition && !isTransitionAll(styleTransition)) {
  45899. var transitionKeys = normalizeToArray(styleTransition);
  45900. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  45901. for (var i = 0; i < transitionKeys.length; i++) {
  45902. var key = transitionKeys[i];
  45903. var elVal = fromElStyle[key];
  45904. // Do not clone, see `checkNonStyleTansitionRefer`.
  45905. transFromStyleProps[key] = elVal;
  45906. }
  45907. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  45908. var animationProps = fromEl.getAnimationStyleProps();
  45909. var animationStyleProps = animationProps ? animationProps.style : null;
  45910. if (animationStyleProps) {
  45911. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  45912. var styleKeys = keys(styleOpt);
  45913. for (var i = 0; i < styleKeys.length; i++) {
  45914. var key = styleKeys[i];
  45915. if (animationStyleProps[key]) {
  45916. var elVal = fromElStyle[key];
  45917. transFromStyleProps[key] = elVal;
  45918. }
  45919. }
  45920. }
  45921. }
  45922. }
  45923. }
  45924. function isNonStyleTransitionEnabled(optVal, elVal) {
  45925. // The same as `checkNonStyleTansitionRefer`.
  45926. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  45927. }
  45928. var checkTransformPropRefer;
  45929. if ("development" !== 'production') {
  45930. checkTransformPropRefer = function (key, usedIn) {
  45931. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  45932. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  45933. }
  45934. };
  45935. }
  45936. var getStateToRestore = makeInner();
  45937. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  45938. /**
  45939. * Stop previous keyframe animation and restore the attributes.
  45940. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  45941. */
  45942. function stopPreviousKeyframeAnimationAndRestore(el) {
  45943. // Stop previous keyframe animation.
  45944. el.stopAnimation('keyframe');
  45945. // Restore
  45946. el.attr(getStateToRestore(el));
  45947. }
  45948. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  45949. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  45950. return;
  45951. }
  45952. if (isArray(animationOpts)) {
  45953. each(animationOpts, function (singleAnimationOpts) {
  45954. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  45955. });
  45956. return;
  45957. }
  45958. var keyframes = animationOpts.keyframes;
  45959. var duration = animationOpts.duration;
  45960. if (animatableModel && duration == null) {
  45961. // Default to use duration of config.
  45962. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  45963. var config = getAnimationConfig('enter', animatableModel, 0);
  45964. duration = config && config.duration;
  45965. }
  45966. if (!keyframes || !duration) {
  45967. return;
  45968. }
  45969. var stateToRestore = getStateToRestore(el);
  45970. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  45971. if (targetPropName && !el[targetPropName]) {
  45972. return;
  45973. }
  45974. var animator;
  45975. var endFrameIsSet = false;
  45976. // Sort keyframes by percent.
  45977. keyframes.sort(function (a, b) {
  45978. return a.percent - b.percent;
  45979. });
  45980. each(keyframes, function (kf) {
  45981. // Stop current animation.
  45982. var animators = el.animators;
  45983. var kfValues = targetPropName ? kf[targetPropName] : kf;
  45984. if ("development" !== 'production') {
  45985. if (kf.percent >= 1) {
  45986. endFrameIsSet = true;
  45987. }
  45988. }
  45989. if (!kfValues) {
  45990. return;
  45991. }
  45992. var propKeys = keys(kfValues);
  45993. if (!targetPropName) {
  45994. // PENDING performance?
  45995. propKeys = filter(propKeys, function (key) {
  45996. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  45997. });
  45998. }
  45999. if (!propKeys.length) {
  46000. return;
  46001. }
  46002. if (!animator) {
  46003. animator = el.animate(targetPropName, animationOpts.loop, true);
  46004. animator.scope = 'keyframe';
  46005. }
  46006. for (var i = 0; i < animators.length; i++) {
  46007. // Stop all other animation that is not keyframe.
  46008. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  46009. animators[i].stopTracks(propKeys);
  46010. }
  46011. }
  46012. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  46013. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  46014. each(propKeys, function (key) {
  46015. // Save original value.
  46016. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  46017. });
  46018. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  46019. });
  46020. if (!animator) {
  46021. return;
  46022. }
  46023. if ("development" !== 'production') {
  46024. if (!endFrameIsSet) {
  46025. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  46026. }
  46027. }
  46028. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  46029. });
  46030. }
  46031. var nonShapeGraphicElements = {
  46032. // Reserved but not supported in graphic component.
  46033. path: null,
  46034. compoundPath: null,
  46035. // Supported in graphic component.
  46036. group: Group,
  46037. image: ZRImage,
  46038. text: ZRText
  46039. };
  46040. var inner$a = makeInner();
  46041. // ------------------------
  46042. // View
  46043. // ------------------------
  46044. var GraphicComponentView = /** @class */function (_super) {
  46045. __extends(GraphicComponentView, _super);
  46046. function GraphicComponentView() {
  46047. var _this = _super !== null && _super.apply(this, arguments) || this;
  46048. _this.type = GraphicComponentView.type;
  46049. return _this;
  46050. }
  46051. GraphicComponentView.prototype.init = function () {
  46052. this._elMap = createHashMap();
  46053. };
  46054. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  46055. // Having leveraged between use cases and algorithm complexity, a very
  46056. // simple layout mechanism is used:
  46057. // The size(width/height) can be determined by itself or its parent (not
  46058. // implemented yet), but can not by its children. (Top-down travel)
  46059. // The location(x/y) can be determined by the bounding rect of itself
  46060. // (can including its descendants or not) and the size of its parent.
  46061. // (Bottom-up travel)
  46062. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  46063. // view will be reused.
  46064. if (graphicModel !== this._lastGraphicModel) {
  46065. this._clear();
  46066. }
  46067. this._lastGraphicModel = graphicModel;
  46068. this._updateElements(graphicModel);
  46069. this._relocate(graphicModel, api);
  46070. };
  46071. /**
  46072. * Update graphic elements.
  46073. */
  46074. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  46075. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  46076. if (!elOptionsToUpdate) {
  46077. return;
  46078. }
  46079. var elMap = this._elMap;
  46080. var rootGroup = this.group;
  46081. var globalZ = graphicModel.get('z');
  46082. var globalZLevel = graphicModel.get('zlevel');
  46083. // Top-down tranverse to assign graphic settings to each elements.
  46084. each(elOptionsToUpdate, function (elOption) {
  46085. var id = convertOptionIdName(elOption.id, null);
  46086. var elExisting = id != null ? elMap.get(id) : null;
  46087. var parentId = convertOptionIdName(elOption.parentId, null);
  46088. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  46089. var elType = elOption.type;
  46090. var elOptionStyle = elOption.style;
  46091. if (elType === 'text' && elOptionStyle) {
  46092. // In top/bottom mode, textVerticalAlign should not be used, which cause
  46093. // inaccurately locating.
  46094. if (elOption.hv && elOption.hv[1]) {
  46095. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  46096. }
  46097. }
  46098. var textContentOption = elOption.textContent;
  46099. var textConfig = elOption.textConfig;
  46100. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  46101. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  46102. if (!textConfig && convertResult.textConfig) {
  46103. textConfig = elOption.textConfig = convertResult.textConfig;
  46104. }
  46105. if (!textContentOption && convertResult.textContent) {
  46106. textContentOption = convertResult.textContent;
  46107. }
  46108. }
  46109. // Remove unnecessary props to avoid potential problems.
  46110. var elOptionCleaned = getCleanedElOption(elOption);
  46111. // For simple, do not support parent change, otherwise reorder is needed.
  46112. if ("development" !== 'production') {
  46113. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  46114. }
  46115. var $action = elOption.$action || 'merge';
  46116. var isMerge = $action === 'merge';
  46117. var isReplace = $action === 'replace';
  46118. if (isMerge) {
  46119. var isInit = !elExisting;
  46120. var el_1 = elExisting;
  46121. if (isInit) {
  46122. el_1 = createEl(id, targetElParent, elOption.type, elMap);
  46123. } else {
  46124. el_1 && (inner$a(el_1).isNew = false);
  46125. // Stop and restore before update any other attributes.
  46126. stopPreviousKeyframeAnimationAndRestore(el_1);
  46127. }
  46128. if (el_1) {
  46129. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  46130. isInit: isInit
  46131. });
  46132. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  46133. }
  46134. } else if (isReplace) {
  46135. removeEl(elExisting, elOption, elMap, graphicModel);
  46136. var el_2 = createEl(id, targetElParent, elOption.type, elMap);
  46137. if (el_2) {
  46138. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  46139. isInit: true
  46140. });
  46141. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  46142. }
  46143. } else if ($action === 'remove') {
  46144. updateLeaveTo(elExisting, elOption);
  46145. removeEl(elExisting, elOption, elMap, graphicModel);
  46146. }
  46147. var el = elMap.get(id);
  46148. if (el && textContentOption) {
  46149. if (isMerge) {
  46150. var textContentExisting = el.getTextContent();
  46151. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  46152. } else if (isReplace) {
  46153. el.setTextContent(new ZRText(textContentOption));
  46154. }
  46155. }
  46156. if (el) {
  46157. var clipPathOption = elOption.clipPath;
  46158. if (clipPathOption) {
  46159. var clipPathType = clipPathOption.type;
  46160. var clipPath = void 0;
  46161. var isInit = false;
  46162. if (isMerge) {
  46163. var oldClipPath = el.getClipPath();
  46164. isInit = !oldClipPath || inner$a(oldClipPath).type !== clipPathType;
  46165. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  46166. } else if (isReplace) {
  46167. isInit = true;
  46168. clipPath = newEl(clipPathType);
  46169. }
  46170. el.setClipPath(clipPath);
  46171. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  46172. isInit: isInit
  46173. });
  46174. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  46175. }
  46176. var elInner = inner$a(el);
  46177. el.setTextConfig(textConfig);
  46178. elInner.option = elOption;
  46179. setEventData(el, graphicModel, elOption);
  46180. setTooltipConfig({
  46181. el: el,
  46182. componentModel: graphicModel,
  46183. itemName: el.name,
  46184. itemTooltipOption: elOption.tooltip
  46185. });
  46186. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  46187. }
  46188. });
  46189. };
  46190. /**
  46191. * Locate graphic elements.
  46192. */
  46193. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  46194. var elOptions = graphicModel.option.elements;
  46195. var rootGroup = this.group;
  46196. var elMap = this._elMap;
  46197. var apiWidth = api.getWidth();
  46198. var apiHeight = api.getHeight();
  46199. var xy = ['x', 'y'];
  46200. // Top-down to calculate percentage width/height of group
  46201. for (var i = 0; i < elOptions.length; i++) {
  46202. var elOption = elOptions[i];
  46203. var id = convertOptionIdName(elOption.id, null);
  46204. var el = id != null ? elMap.get(id) : null;
  46205. if (!el || !el.isGroup) {
  46206. continue;
  46207. }
  46208. var parentEl = el.parent;
  46209. var isParentRoot = parentEl === rootGroup;
  46210. // Like 'position:absolut' in css, default 0.
  46211. var elInner = inner$a(el);
  46212. var parentElInner = inner$a(parentEl);
  46213. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  46214. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  46215. }
  46216. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  46217. for (var i = elOptions.length - 1; i >= 0; i--) {
  46218. var elOption = elOptions[i];
  46219. var id = convertOptionIdName(elOption.id, null);
  46220. var el = id != null ? elMap.get(id) : null;
  46221. if (!el) {
  46222. continue;
  46223. }
  46224. var parentEl = el.parent;
  46225. var parentElInner = inner$a(parentEl);
  46226. var containerInfo = parentEl === rootGroup ? {
  46227. width: apiWidth,
  46228. height: apiHeight
  46229. } : {
  46230. width: parentElInner.width,
  46231. height: parentElInner.height
  46232. };
  46233. // PENDING
  46234. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  46235. // does not include the rect of [0, 0, group.width, group.height], which
  46236. // is probably weird for users. Should we make a break change for it?
  46237. var layoutPos = {};
  46238. var layouted = positionElement(el, elOption, containerInfo, null, {
  46239. hv: elOption.hv,
  46240. boundingMode: elOption.bounding
  46241. }, layoutPos);
  46242. if (!inner$a(el).isNew && layouted) {
  46243. var transition = elOption.transition;
  46244. var animatePos = {};
  46245. for (var k = 0; k < xy.length; k++) {
  46246. var key = xy[k];
  46247. var val = layoutPos[key];
  46248. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  46249. animatePos[key] = val;
  46250. } else {
  46251. el[key] = val;
  46252. }
  46253. }
  46254. updateProps(el, animatePos, graphicModel, 0);
  46255. } else {
  46256. el.attr(layoutPos);
  46257. }
  46258. }
  46259. };
  46260. /**
  46261. * Clear all elements.
  46262. */
  46263. GraphicComponentView.prototype._clear = function () {
  46264. var _this = this;
  46265. var elMap = this._elMap;
  46266. elMap.each(function (el) {
  46267. removeEl(el, inner$a(el).option, elMap, _this._lastGraphicModel);
  46268. });
  46269. this._elMap = createHashMap();
  46270. };
  46271. GraphicComponentView.prototype.dispose = function () {
  46272. this._clear();
  46273. };
  46274. GraphicComponentView.type = 'graphic';
  46275. return GraphicComponentView;
  46276. }(ComponentView);
  46277. function newEl(graphicType) {
  46278. if ("development" !== 'production') {
  46279. assert(graphicType, 'graphic type MUST be set');
  46280. }
  46281. var Clz = hasOwn(nonShapeGraphicElements, graphicType)
  46282. // Those graphic elements are not shapes. They should not be
  46283. // overwritten by users, so do them first.
  46284. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  46285. if ("development" !== 'production') {
  46286. assert(Clz, "graphic type " + graphicType + " can not be found");
  46287. }
  46288. var el = new Clz({});
  46289. inner$a(el).type = graphicType;
  46290. return el;
  46291. }
  46292. function createEl(id, targetElParent, graphicType, elMap) {
  46293. var el = newEl(graphicType);
  46294. targetElParent.add(el);
  46295. elMap.set(id, el);
  46296. inner$a(el).id = id;
  46297. inner$a(el).isNew = true;
  46298. return el;
  46299. }
  46300. function removeEl(elExisting, elOption, elMap, graphicModel) {
  46301. var existElParent = elExisting && elExisting.parent;
  46302. if (existElParent) {
  46303. elExisting.type === 'group' && elExisting.traverse(function (el) {
  46304. removeEl(el, elOption, elMap, graphicModel);
  46305. });
  46306. applyLeaveTransition(elExisting, elOption, graphicModel);
  46307. elMap.removeKey(inner$a(elExisting).id);
  46308. }
  46309. }
  46310. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  46311. if (!el.isGroup) {
  46312. each([['cursor', Displayable.prototype.cursor],
  46313. // We should not support configure z and zlevel in the element level.
  46314. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  46315. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0],
  46316. // z2 must not be null/undefined, otherwise sort error may occur.
  46317. ['z2', 0]], function (item) {
  46318. var prop = item[0];
  46319. if (hasOwn(elOption, prop)) {
  46320. el[prop] = retrieve2(elOption[prop], item[1]);
  46321. } else if (el[prop] == null) {
  46322. el[prop] = item[1];
  46323. }
  46324. });
  46325. }
  46326. each(keys(elOption), function (key) {
  46327. // Assign event handlers.
  46328. // PENDING: should enumerate all event names or use pattern matching?
  46329. if (key.indexOf('on') === 0) {
  46330. var val = elOption[key];
  46331. el[key] = isFunction(val) ? val : null;
  46332. }
  46333. });
  46334. if (hasOwn(elOption, 'draggable')) {
  46335. el.draggable = elOption.draggable;
  46336. }
  46337. // Other attributes
  46338. elOption.name != null && (el.name = elOption.name);
  46339. elOption.id != null && (el.id = elOption.id);
  46340. }
  46341. // Remove unnecessary props to avoid potential problems.
  46342. function getCleanedElOption(elOption) {
  46343. elOption = extend({}, elOption);
  46344. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  46345. delete elOption[name];
  46346. });
  46347. return elOption;
  46348. }
  46349. function setEventData(el, graphicModel, elOption) {
  46350. var eventData = getECData(el).eventData;
  46351. // Simple optimize for large amount of elements that no need event.
  46352. if (!el.silent && !el.ignore && !eventData) {
  46353. eventData = getECData(el).eventData = {
  46354. componentType: 'graphic',
  46355. componentIndex: graphicModel.componentIndex,
  46356. name: el.name
  46357. };
  46358. }
  46359. // `elOption.info` enables user to mount some info on
  46360. // elements and use them in event handlers.
  46361. if (eventData) {
  46362. eventData.info = elOption.info;
  46363. }
  46364. }
  46365. function install$9(registers) {
  46366. registers.registerComponentModel(GraphicComponentModel);
  46367. registers.registerComponentView(GraphicComponentView);
  46368. registers.registerPreprocessor(function (option) {
  46369. var graphicOption = option.graphic;
  46370. // Convert
  46371. // {graphic: [{left: 10, type: 'circle'}, ...]}
  46372. // or
  46373. // {graphic: {left: 10, type: 'circle'}}
  46374. // to
  46375. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  46376. if (isArray(graphicOption)) {
  46377. if (!graphicOption[0] || !graphicOption[0].elements) {
  46378. option.graphic = [{
  46379. elements: graphicOption
  46380. }];
  46381. } else {
  46382. // Only one graphic instance can be instantiated. (We don't
  46383. // want that too many views are created in echarts._viewMap.)
  46384. option.graphic = [option.graphic[0]];
  46385. }
  46386. } else if (graphicOption && !graphicOption.elements) {
  46387. option.graphic = [{
  46388. elements: [graphicOption]
  46389. }];
  46390. }
  46391. });
  46392. }
  46393. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single'];
  46394. // Supported coords.
  46395. // FIXME: polar has been broken (but rarely used).
  46396. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  46397. function isCoordSupported(seriesModel) {
  46398. var coordType = seriesModel.get('coordinateSystem');
  46399. return indexOf(SERIES_COORDS, coordType) >= 0;
  46400. }
  46401. function getAxisMainType(axisDim) {
  46402. if ("development" !== 'production') {
  46403. assert(axisDim);
  46404. }
  46405. return axisDim + 'Axis';
  46406. }
  46407. /**
  46408. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  46409. * This function finds all linked dataZoomModels start from the given payload.
  46410. */
  46411. function findEffectedDataZooms(ecModel, payload) {
  46412. // Key: `DataZoomAxisDimension`
  46413. var axisRecords = createHashMap();
  46414. var effectedModels = [];
  46415. // Key: uid of dataZoomModel
  46416. var effectedModelMap = createHashMap();
  46417. // Find the dataZooms specified by payload.
  46418. ecModel.eachComponent({
  46419. mainType: 'dataZoom',
  46420. query: payload
  46421. }, function (dataZoomModel) {
  46422. if (!effectedModelMap.get(dataZoomModel.uid)) {
  46423. addToEffected(dataZoomModel);
  46424. }
  46425. });
  46426. // Start from the given dataZoomModels, travel the graph to find
  46427. // all of the linked dataZoom models.
  46428. var foundNewLink;
  46429. do {
  46430. foundNewLink = false;
  46431. ecModel.eachComponent('dataZoom', processSingle);
  46432. } while (foundNewLink);
  46433. function processSingle(dataZoomModel) {
  46434. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  46435. addToEffected(dataZoomModel);
  46436. foundNewLink = true;
  46437. }
  46438. }
  46439. function addToEffected(dataZoom) {
  46440. effectedModelMap.set(dataZoom.uid, true);
  46441. effectedModels.push(dataZoom);
  46442. markAxisControlled(dataZoom);
  46443. }
  46444. function isLinked(dataZoomModel) {
  46445. var isLink = false;
  46446. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46447. var axisIdxArr = axisRecords.get(axisDim);
  46448. if (axisIdxArr && axisIdxArr[axisIndex]) {
  46449. isLink = true;
  46450. }
  46451. });
  46452. return isLink;
  46453. }
  46454. function markAxisControlled(dataZoomModel) {
  46455. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46456. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  46457. });
  46458. }
  46459. return effectedModels;
  46460. }
  46461. /**
  46462. * Find the first target coordinate system.
  46463. * Available after model built.
  46464. *
  46465. * @return Like {
  46466. * grid: [
  46467. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  46468. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  46469. * ...
  46470. * ], // cartesians must not be null/undefined.
  46471. * polar: [
  46472. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  46473. * ...
  46474. * ], // polars must not be null/undefined.
  46475. * singleAxis: [
  46476. * {model: coord0, axisModels: [], coordIndex: 0}
  46477. * ]
  46478. * }
  46479. */
  46480. function collectReferCoordSysModelInfo(dataZoomModel) {
  46481. var ecModel = dataZoomModel.ecModel;
  46482. var coordSysInfoWrap = {
  46483. infoList: [],
  46484. infoMap: createHashMap()
  46485. };
  46486. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46487. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46488. if (!axisModel) {
  46489. return;
  46490. }
  46491. var coordSysModel = axisModel.getCoordSysModel();
  46492. if (!coordSysModel) {
  46493. return;
  46494. }
  46495. var coordSysUid = coordSysModel.uid;
  46496. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  46497. if (!coordSysInfo) {
  46498. coordSysInfo = {
  46499. model: coordSysModel,
  46500. axisModels: []
  46501. };
  46502. coordSysInfoWrap.infoList.push(coordSysInfo);
  46503. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  46504. }
  46505. coordSysInfo.axisModels.push(axisModel);
  46506. });
  46507. return coordSysInfoWrap;
  46508. }
  46509. var DataZoomAxisInfo = /** @class */function () {
  46510. function DataZoomAxisInfo() {
  46511. this.indexList = [];
  46512. this.indexMap = [];
  46513. }
  46514. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  46515. // Remove duplication.
  46516. if (!this.indexMap[axisCmptIdx]) {
  46517. this.indexList.push(axisCmptIdx);
  46518. this.indexMap[axisCmptIdx] = true;
  46519. }
  46520. };
  46521. return DataZoomAxisInfo;
  46522. }();
  46523. var DataZoomModel = /** @class */function (_super) {
  46524. __extends(DataZoomModel, _super);
  46525. function DataZoomModel() {
  46526. var _this = _super !== null && _super.apply(this, arguments) || this;
  46527. _this.type = DataZoomModel.type;
  46528. _this._autoThrottle = true;
  46529. _this._noTarget = true;
  46530. /**
  46531. * It is `[rangeModeForMin, rangeModeForMax]`.
  46532. * The optional values for `rangeMode`:
  46533. * + `'value'` mode: the axis extent will always be determined by
  46534. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  46535. * how data like and how `axis.min` and `axis.max` are.
  46536. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  46537. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  46538. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  46539. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  46540. *
  46541. * For example, when users are using dynamic data (update data periodically via `setOption`),
  46542. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  46543. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  46544. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  46545. */
  46546. _this._rangePropMode = ['percent', 'percent'];
  46547. return _this;
  46548. }
  46549. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  46550. var inputRawOption = retrieveRawOption(option);
  46551. /**
  46552. * Suppose a "main process" start at the point that model prepared (that is,
  46553. * model initialized or merged or method called in `action`).
  46554. * We should keep the `main process` idempotent, that is, given a set of values
  46555. * on `option`, we get the same result.
  46556. *
  46557. * But sometimes, values on `option` will be updated for providing users
  46558. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  46559. * should not be the base/input of the `main process`.
  46560. *
  46561. * So in that case we should save and keep the input of the `main process`
  46562. * separately, called `settledOption`.
  46563. *
  46564. * For example, consider the case:
  46565. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  46566. * where the original input `option.startValue`, `option.endValue` are earsed by
  46567. * calculated value.
  46568. * (Step)2) click the legend to hide and show a series,
  46569. * where the new range is calculated by the earsed `startValue` and `endValue`,
  46570. * which brings incorrect result.
  46571. */
  46572. this.settledOption = inputRawOption;
  46573. this.mergeDefaultAndTheme(option, ecModel);
  46574. this._doInit(inputRawOption);
  46575. };
  46576. DataZoomModel.prototype.mergeOption = function (newOption) {
  46577. var inputRawOption = retrieveRawOption(newOption);
  46578. // FIX #2591
  46579. merge(this.option, newOption, true);
  46580. merge(this.settledOption, inputRawOption, true);
  46581. this._doInit(inputRawOption);
  46582. };
  46583. DataZoomModel.prototype._doInit = function (inputRawOption) {
  46584. var thisOption = this.option;
  46585. this._setDefaultThrottle(inputRawOption);
  46586. this._updateRangeUse(inputRawOption);
  46587. var settledOption = this.settledOption;
  46588. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  46589. // start/end has higher priority over startValue/endValue if they
  46590. // both set, but we should make chart.setOption({endValue: 1000})
  46591. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  46592. if (this._rangePropMode[index] === 'value') {
  46593. thisOption[names[0]] = settledOption[names[0]] = null;
  46594. }
  46595. // Otherwise do nothing and use the merge result.
  46596. }, this);
  46597. this._resetTarget();
  46598. };
  46599. DataZoomModel.prototype._resetTarget = function () {
  46600. var optionOrient = this.get('orient', true);
  46601. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  46602. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  46603. if (hasAxisSpecified) {
  46604. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  46605. } else {
  46606. this._orient = optionOrient || 'horizontal';
  46607. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  46608. }
  46609. this._noTarget = true;
  46610. targetAxisIndexMap.each(function (axisInfo) {
  46611. if (axisInfo.indexList.length) {
  46612. this._noTarget = false;
  46613. }
  46614. }, this);
  46615. };
  46616. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  46617. var hasAxisSpecified = false;
  46618. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  46619. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING);
  46620. // When user set axisIndex as a empty array, we think that user specify axisIndex
  46621. // but do not want use auto mode. Because empty array may be encountered when
  46622. // some error occurred.
  46623. if (!refering.specified) {
  46624. return;
  46625. }
  46626. hasAxisSpecified = true;
  46627. var axisInfo = new DataZoomAxisInfo();
  46628. each(refering.models, function (axisModel) {
  46629. axisInfo.add(axisModel.componentIndex);
  46630. });
  46631. targetAxisIndexMap.set(axisDim, axisInfo);
  46632. }, this);
  46633. return hasAxisSpecified;
  46634. };
  46635. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  46636. var ecModel = this.ecModel;
  46637. var needAuto = true;
  46638. // Find axis that parallel to dataZoom as default.
  46639. if (needAuto) {
  46640. var axisDim = orient === 'vertical' ? 'y' : 'x';
  46641. var axisModels = ecModel.findComponents({
  46642. mainType: axisDim + 'Axis'
  46643. });
  46644. setParallelAxis(axisModels, axisDim);
  46645. }
  46646. // Find axis that parallel to dataZoom as default.
  46647. if (needAuto) {
  46648. var axisModels = ecModel.findComponents({
  46649. mainType: 'singleAxis',
  46650. filter: function (axisModel) {
  46651. return axisModel.get('orient', true) === orient;
  46652. }
  46653. });
  46654. setParallelAxis(axisModels, 'single');
  46655. }
  46656. function setParallelAxis(axisModels, axisDim) {
  46657. // At least use the first parallel axis as the target axis.
  46658. var axisModel = axisModels[0];
  46659. if (!axisModel) {
  46660. return;
  46661. }
  46662. var axisInfo = new DataZoomAxisInfo();
  46663. axisInfo.add(axisModel.componentIndex);
  46664. targetAxisIndexMap.set(axisDim, axisInfo);
  46665. needAuto = false;
  46666. // Find parallel axes in the same grid.
  46667. if (axisDim === 'x' || axisDim === 'y') {
  46668. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  46669. gridModel_1 && each(axisModels, function (axModel) {
  46670. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  46671. axisInfo.add(axModel.componentIndex);
  46672. }
  46673. });
  46674. }
  46675. }
  46676. if (needAuto) {
  46677. // If no parallel axis, find the first category axis as default. (Also consider polar).
  46678. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  46679. if (!needAuto) {
  46680. return;
  46681. }
  46682. var axisModels = ecModel.findComponents({
  46683. mainType: getAxisMainType(axisDim),
  46684. filter: function (axisModel) {
  46685. return axisModel.get('type', true) === 'category';
  46686. }
  46687. });
  46688. if (axisModels[0]) {
  46689. var axisInfo = new DataZoomAxisInfo();
  46690. axisInfo.add(axisModels[0].componentIndex);
  46691. targetAxisIndexMap.set(axisDim, axisInfo);
  46692. needAuto = false;
  46693. }
  46694. }, this);
  46695. }
  46696. };
  46697. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  46698. var dim;
  46699. // Find the first axis
  46700. this.eachTargetAxis(function (axisDim) {
  46701. !dim && (dim = axisDim);
  46702. }, this);
  46703. return dim === 'y' ? 'vertical' : 'horizontal';
  46704. };
  46705. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  46706. // When first time user set throttle, auto throttle ends.
  46707. if (inputRawOption.hasOwnProperty('throttle')) {
  46708. this._autoThrottle = false;
  46709. }
  46710. if (this._autoThrottle) {
  46711. var globalOption = this.ecModel.option;
  46712. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  46713. }
  46714. };
  46715. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  46716. var rangePropMode = this._rangePropMode;
  46717. var rangeModeInOption = this.get('rangeMode');
  46718. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  46719. var percentSpecified = inputRawOption[names[0]] != null;
  46720. var valueSpecified = inputRawOption[names[1]] != null;
  46721. if (percentSpecified && !valueSpecified) {
  46722. rangePropMode[index] = 'percent';
  46723. } else if (!percentSpecified && valueSpecified) {
  46724. rangePropMode[index] = 'value';
  46725. } else if (rangeModeInOption) {
  46726. rangePropMode[index] = rangeModeInOption[index];
  46727. } else if (percentSpecified) {
  46728. // percentSpecified && valueSpecified
  46729. rangePropMode[index] = 'percent';
  46730. }
  46731. // else remain its original setting.
  46732. });
  46733. };
  46734. DataZoomModel.prototype.noTarget = function () {
  46735. return this._noTarget;
  46736. };
  46737. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  46738. var firstAxisModel;
  46739. this.eachTargetAxis(function (axisDim, axisIndex) {
  46740. if (firstAxisModel == null) {
  46741. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46742. }
  46743. }, this);
  46744. return firstAxisModel;
  46745. };
  46746. /**
  46747. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  46748. */
  46749. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  46750. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  46751. each(axisInfo.indexList, function (axisIndex) {
  46752. callback.call(context, axisDim, axisIndex);
  46753. });
  46754. });
  46755. };
  46756. /**
  46757. * @return If not found, return null/undefined.
  46758. */
  46759. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  46760. var axisModel = this.getAxisModel(axisDim, axisIndex);
  46761. if (axisModel) {
  46762. return axisModel.__dzAxisProxy;
  46763. }
  46764. };
  46765. /**
  46766. * @return If not found, return null/undefined.
  46767. */
  46768. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  46769. if ("development" !== 'production') {
  46770. assert(axisDim && axisIndex != null);
  46771. }
  46772. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  46773. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  46774. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46775. }
  46776. };
  46777. /**
  46778. * If not specified, set to undefined.
  46779. */
  46780. DataZoomModel.prototype.setRawRange = function (opt) {
  46781. var thisOption = this.option;
  46782. var settledOption = this.settledOption;
  46783. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  46784. // Consider the pair <start, startValue>:
  46785. // If one has value and the other one is `null/undefined`, we both set them
  46786. // to `settledOption`. This strategy enables the feature to clear the original
  46787. // value in `settledOption` to `null/undefined`.
  46788. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  46789. // and keep `settledOption` with the original value. This strategy enables users to
  46790. // only set <end or endValue> but not set <start or startValue> when calling
  46791. // `dispatchAction`.
  46792. // The pair <end, endValue> is treated in the same way.
  46793. if (opt[names[0]] != null || opt[names[1]] != null) {
  46794. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  46795. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  46796. }
  46797. }, this);
  46798. this._updateRangeUse(opt);
  46799. };
  46800. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  46801. var option = this.option;
  46802. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  46803. option[name] = opt[name];
  46804. });
  46805. };
  46806. DataZoomModel.prototype.getPercentRange = function () {
  46807. var axisProxy = this.findRepresentativeAxisProxy();
  46808. if (axisProxy) {
  46809. return axisProxy.getDataPercentWindow();
  46810. }
  46811. };
  46812. /**
  46813. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  46814. *
  46815. * @return [startValue, endValue] value can only be '-' or finite number.
  46816. */
  46817. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  46818. if (axisDim == null && axisIndex == null) {
  46819. var axisProxy = this.findRepresentativeAxisProxy();
  46820. if (axisProxy) {
  46821. return axisProxy.getDataValueWindow();
  46822. }
  46823. } else {
  46824. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  46825. }
  46826. };
  46827. /**
  46828. * @param axisModel If axisModel given, find axisProxy
  46829. * corresponding to the axisModel
  46830. */
  46831. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  46832. if (axisModel) {
  46833. return axisModel.__dzAxisProxy;
  46834. }
  46835. // Find the first hosted axisProxy
  46836. var firstProxy;
  46837. var axisDimList = this._targetAxisInfoMap.keys();
  46838. for (var i = 0; i < axisDimList.length; i++) {
  46839. var axisDim = axisDimList[i];
  46840. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  46841. for (var j = 0; j < axisInfo.indexList.length; j++) {
  46842. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  46843. if (proxy.hostedBy(this)) {
  46844. return proxy;
  46845. }
  46846. if (!firstProxy) {
  46847. firstProxy = proxy;
  46848. }
  46849. }
  46850. }
  46851. // If no hosted proxy found, still need to return a proxy.
  46852. // This case always happens in toolbox dataZoom, where axes are all hosted by
  46853. // other dataZooms.
  46854. return firstProxy;
  46855. };
  46856. DataZoomModel.prototype.getRangePropMode = function () {
  46857. return this._rangePropMode.slice();
  46858. };
  46859. DataZoomModel.prototype.getOrient = function () {
  46860. if ("development" !== 'production') {
  46861. // Should not be called before initialized.
  46862. assert(this._orient);
  46863. }
  46864. return this._orient;
  46865. };
  46866. DataZoomModel.type = 'dataZoom';
  46867. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  46868. DataZoomModel.defaultOption = {
  46869. // zlevel: 0,
  46870. z: 4,
  46871. filterMode: 'filter',
  46872. start: 0,
  46873. end: 100
  46874. };
  46875. return DataZoomModel;
  46876. }(ComponentModel);
  46877. /**
  46878. * Retrieve those raw params from option, which will be cached separately,
  46879. * because they will be overwritten by normalized/calculated values in the main
  46880. * process.
  46881. */
  46882. function retrieveRawOption(option) {
  46883. var ret = {};
  46884. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  46885. option.hasOwnProperty(name) && (ret[name] = option[name]);
  46886. });
  46887. return ret;
  46888. }
  46889. var SelectDataZoomModel = /** @class */function (_super) {
  46890. __extends(SelectDataZoomModel, _super);
  46891. function SelectDataZoomModel() {
  46892. var _this = _super !== null && _super.apply(this, arguments) || this;
  46893. _this.type = SelectDataZoomModel.type;
  46894. return _this;
  46895. }
  46896. SelectDataZoomModel.type = 'dataZoom.select';
  46897. return SelectDataZoomModel;
  46898. }(DataZoomModel);
  46899. var DataZoomView = /** @class */function (_super) {
  46900. __extends(DataZoomView, _super);
  46901. function DataZoomView() {
  46902. var _this = _super !== null && _super.apply(this, arguments) || this;
  46903. _this.type = DataZoomView.type;
  46904. return _this;
  46905. }
  46906. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  46907. this.dataZoomModel = dataZoomModel;
  46908. this.ecModel = ecModel;
  46909. this.api = api;
  46910. };
  46911. DataZoomView.type = 'dataZoom';
  46912. return DataZoomView;
  46913. }(ComponentView);
  46914. var SelectDataZoomView = /** @class */function (_super) {
  46915. __extends(SelectDataZoomView, _super);
  46916. function SelectDataZoomView() {
  46917. var _this = _super !== null && _super.apply(this, arguments) || this;
  46918. _this.type = SelectDataZoomView.type;
  46919. return _this;
  46920. }
  46921. SelectDataZoomView.type = 'dataZoom.select';
  46922. return SelectDataZoomView;
  46923. }(DataZoomView);
  46924. /*
  46925. * Licensed to the Apache Software Foundation (ASF) under one
  46926. * or more contributor license agreements. See the NOTICE file
  46927. * distributed with this work for additional information
  46928. * regarding copyright ownership. The ASF licenses this file
  46929. * to you under the Apache License, Version 2.0 (the
  46930. * "License"); you may not use this file except in compliance
  46931. * with the License. You may obtain a copy of the License at
  46932. *
  46933. * http://www.apache.org/licenses/LICENSE-2.0
  46934. *
  46935. * Unless required by applicable law or agreed to in writing,
  46936. * software distributed under the License is distributed on an
  46937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46938. * KIND, either express or implied. See the License for the
  46939. * specific language governing permissions and limitations
  46940. * under the License.
  46941. */
  46942. /**
  46943. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46944. */
  46945. /*
  46946. * Licensed to the Apache Software Foundation (ASF) under one
  46947. * or more contributor license agreements. See the NOTICE file
  46948. * distributed with this work for additional information
  46949. * regarding copyright ownership. The ASF licenses this file
  46950. * to you under the Apache License, Version 2.0 (the
  46951. * "License"); you may not use this file except in compliance
  46952. * with the License. You may obtain a copy of the License at
  46953. *
  46954. * http://www.apache.org/licenses/LICENSE-2.0
  46955. *
  46956. * Unless required by applicable law or agreed to in writing,
  46957. * software distributed under the License is distributed on an
  46958. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46959. * KIND, either express or implied. See the License for the
  46960. * specific language governing permissions and limitations
  46961. * under the License.
  46962. */
  46963. /**
  46964. * Calculate slider move result.
  46965. * Usage:
  46966. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  46967. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  46968. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  46969. *
  46970. * @param delta Move length.
  46971. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  46972. * handleEnds will be modified in this method.
  46973. * @param extent handleEnds is restricted by extent.
  46974. * extent[0] should less or equals than extent[1].
  46975. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  46976. * @param minSpan The range of dataZoom can not be smaller than that.
  46977. * If not set, handle0 and cross handle1. If set as a non-negative
  46978. * number (including `0`), handles will push each other when reaching
  46979. * the minSpan.
  46980. * @param maxSpan The range of dataZoom can not be larger than that.
  46981. * @return The input handleEnds.
  46982. */
  46983. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  46984. delta = delta || 0;
  46985. var extentSpan = extent[1] - extent[0];
  46986. // Notice maxSpan and minSpan can be null/undefined.
  46987. if (minSpan != null) {
  46988. minSpan = restrict(minSpan, [0, extentSpan]);
  46989. }
  46990. if (maxSpan != null) {
  46991. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  46992. }
  46993. if (handleIndex === 'all') {
  46994. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  46995. handleSpan = restrict(handleSpan, [0, extentSpan]);
  46996. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  46997. handleIndex = 0;
  46998. }
  46999. handleEnds[0] = restrict(handleEnds[0], extent);
  47000. handleEnds[1] = restrict(handleEnds[1], extent);
  47001. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47002. handleEnds[handleIndex] += delta;
  47003. // Restrict in extent.
  47004. var extentMinSpan = minSpan || 0;
  47005. var realExtent = extent.slice();
  47006. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  47007. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  47008. // Expand span.
  47009. var currDistSign;
  47010. currDistSign = getSpanSign(handleEnds, handleIndex);
  47011. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  47012. // If minSpan exists, 'cross' is forbidden.
  47013. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47014. }
  47015. // Shrink span.
  47016. currDistSign = getSpanSign(handleEnds, handleIndex);
  47017. if (maxSpan != null && currDistSign.span > maxSpan) {
  47018. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47019. }
  47020. return handleEnds;
  47021. }
  47022. function getSpanSign(handleEnds, handleIndex) {
  47023. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47024. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47025. // is at left of handleEnds[1] for non-cross case.
  47026. return {
  47027. span: Math.abs(dist),
  47028. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  47029. };
  47030. }
  47031. function restrict(value, extend) {
  47032. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  47033. }
  47034. var each$4 = each;
  47035. var asc$1 = asc;
  47036. /**
  47037. * Operate single axis.
  47038. * One axis can only operated by one axis operator.
  47039. * Different dataZoomModels may be defined to operate the same axis.
  47040. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  47041. * So dataZoomModels share one axisProxy in that case.
  47042. */
  47043. var AxisProxy = /** @class */function () {
  47044. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  47045. this._dimName = dimName;
  47046. this._axisIndex = axisIndex;
  47047. this.ecModel = ecModel;
  47048. this._dataZoomModel = dataZoomModel;
  47049. // /**
  47050. // * @readOnly
  47051. // * @private
  47052. // */
  47053. // this.hasSeriesStacked;
  47054. }
  47055. /**
  47056. * Whether the axisProxy is hosted by dataZoomModel.
  47057. */
  47058. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  47059. return this._dataZoomModel === dataZoomModel;
  47060. };
  47061. /**
  47062. * @return Value can only be NaN or finite value.
  47063. */
  47064. AxisProxy.prototype.getDataValueWindow = function () {
  47065. return this._valueWindow.slice();
  47066. };
  47067. /**
  47068. * @return {Array.<number>}
  47069. */
  47070. AxisProxy.prototype.getDataPercentWindow = function () {
  47071. return this._percentWindow.slice();
  47072. };
  47073. AxisProxy.prototype.getTargetSeriesModels = function () {
  47074. var seriesModels = [];
  47075. this.ecModel.eachSeries(function (seriesModel) {
  47076. if (isCoordSupported(seriesModel)) {
  47077. var axisMainType = getAxisMainType(this._dimName);
  47078. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  47079. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  47080. seriesModels.push(seriesModel);
  47081. }
  47082. }
  47083. }, this);
  47084. return seriesModels;
  47085. };
  47086. AxisProxy.prototype.getAxisModel = function () {
  47087. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  47088. };
  47089. AxisProxy.prototype.getMinMaxSpan = function () {
  47090. return clone(this._minMaxSpan);
  47091. };
  47092. /**
  47093. * Only calculate by given range and this._dataExtent, do not change anything.
  47094. */
  47095. AxisProxy.prototype.calculateDataWindow = function (opt) {
  47096. var dataExtent = this._dataExtent;
  47097. var axisModel = this.getAxisModel();
  47098. var scale = axisModel.axis.scale;
  47099. var rangePropMode = this._dataZoomModel.getRangePropMode();
  47100. var percentExtent = [0, 100];
  47101. var percentWindow = [];
  47102. var valueWindow = [];
  47103. var hasPropModeValue;
  47104. each$4(['start', 'end'], function (prop, idx) {
  47105. var boundPercent = opt[prop];
  47106. var boundValue = opt[prop + 'Value'];
  47107. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  47108. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  47109. // but not min/max of axis, which will be calculated by data window then).
  47110. // The former one is suitable for cases that a dataZoom component controls multiple
  47111. // axes with different unit or extent, and the latter one is suitable for accurate
  47112. // zoom by pixel (e.g., in dataZoomSelect).
  47113. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  47114. // only when setOption or dispatchAction, otherwise it remains its original value.
  47115. // (Why not only record `percentProp` and always map to `valueProp`? Because
  47116. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  47117. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  47118. // data extent. All of values that are overflow the `dataExtent` will be calculated
  47119. // to percent '100%').
  47120. if (rangePropMode[idx] === 'percent') {
  47121. boundPercent == null && (boundPercent = percentExtent[idx]);
  47122. // Use scale.parse to math round for category or time axis.
  47123. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  47124. } else {
  47125. hasPropModeValue = true;
  47126. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  47127. // Calculating `percent` from `value` may be not accurate, because
  47128. // This calculation can not be inversed, because all of values that
  47129. // are overflow the `dataExtent` will be calculated to percent '100%'
  47130. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  47131. }
  47132. // valueWindow[idx] = round(boundValue);
  47133. // percentWindow[idx] = round(boundPercent);
  47134. // fallback to extent start/end when parsed value or percent is invalid
  47135. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  47136. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  47137. });
  47138. asc$1(valueWindow);
  47139. asc$1(percentWindow);
  47140. // The windows from user calling of `dispatchAction` might be out of the extent,
  47141. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  47142. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47143. // where API is able to initialize/modify the window size even though `zoomLock`
  47144. // specified.
  47145. var spans = this._minMaxSpan;
  47146. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47147. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47148. var suffix = toValue ? 'Span' : 'ValueSpan';
  47149. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47150. for (var i = 0; i < 2; i++) {
  47151. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47152. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47153. }
  47154. }
  47155. return {
  47156. valueWindow: valueWindow,
  47157. percentWindow: percentWindow
  47158. };
  47159. };
  47160. /**
  47161. * Notice: reset should not be called before series.restoreData() is called,
  47162. * so it is recommended to be called in "process stage" but not "model init
  47163. * stage".
  47164. */
  47165. AxisProxy.prototype.reset = function (dataZoomModel) {
  47166. if (dataZoomModel !== this._dataZoomModel) {
  47167. return;
  47168. }
  47169. var targetSeries = this.getTargetSeriesModels();
  47170. // Culculate data window and data extent, and record them.
  47171. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47172. // `calculateDataWindow` uses min/maxSpan.
  47173. this._updateMinMaxSpan();
  47174. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47175. this._valueWindow = dataWindow.valueWindow;
  47176. this._percentWindow = dataWindow.percentWindow;
  47177. // Update axis setting then.
  47178. this._setAxisModel();
  47179. };
  47180. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  47181. if (dataZoomModel !== this._dataZoomModel) {
  47182. return;
  47183. }
  47184. var axisDim = this._dimName;
  47185. var seriesModels = this.getTargetSeriesModels();
  47186. var filterMode = dataZoomModel.get('filterMode');
  47187. var valueWindow = this._valueWindow;
  47188. if (filterMode === 'none') {
  47189. return;
  47190. }
  47191. // FIXME
  47192. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47193. // with NaN data, NaN will be filtered and stack will be wrong.
  47194. // So we need to force the mode to be set empty.
  47195. // In fect, it is not a big deal that do not support filterMode-'filter'
  47196. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  47197. // selection" some day, which might need "adapt to data extent on the
  47198. // otherAxis", which is disabled by filterMode-'empty'.
  47199. // But currently, stack has been fixed to based on value but not index,
  47200. // so this is not an issue any more.
  47201. // let otherAxisModel = this.getOtherAxisModel();
  47202. // if (dataZoomModel.get('$fromToolbox')
  47203. // && otherAxisModel
  47204. // && otherAxisModel.hasSeriesStacked
  47205. // ) {
  47206. // filterMode = 'empty';
  47207. // }
  47208. // TODO
  47209. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  47210. each$4(seriesModels, function (seriesModel) {
  47211. var seriesData = seriesModel.getData();
  47212. var dataDims = seriesData.mapDimensionsAll(axisDim);
  47213. if (!dataDims.length) {
  47214. return;
  47215. }
  47216. if (filterMode === 'weakFilter') {
  47217. var store_1 = seriesData.getStore();
  47218. var dataDimIndices_1 = map(dataDims, function (dim) {
  47219. return seriesData.getDimensionIndex(dim);
  47220. }, seriesData);
  47221. seriesData.filterSelf(function (dataIndex) {
  47222. var leftOut;
  47223. var rightOut;
  47224. var hasValue;
  47225. for (var i = 0; i < dataDims.length; i++) {
  47226. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  47227. var thisHasValue = !isNaN(value);
  47228. var thisLeftOut = value < valueWindow[0];
  47229. var thisRightOut = value > valueWindow[1];
  47230. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  47231. return true;
  47232. }
  47233. thisHasValue && (hasValue = true);
  47234. thisLeftOut && (leftOut = true);
  47235. thisRightOut && (rightOut = true);
  47236. }
  47237. // If both left out and right out, do not filter.
  47238. return hasValue && leftOut && rightOut;
  47239. });
  47240. } else {
  47241. each$4(dataDims, function (dim) {
  47242. if (filterMode === 'empty') {
  47243. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  47244. return !isInWindow(value) ? NaN : value;
  47245. }));
  47246. } else {
  47247. var range = {};
  47248. range[dim] = valueWindow;
  47249. // console.time('select');
  47250. seriesData.selectRange(range);
  47251. // console.timeEnd('select');
  47252. }
  47253. });
  47254. }
  47255. each$4(dataDims, function (dim) {
  47256. seriesData.setApproximateExtent(valueWindow, dim);
  47257. });
  47258. });
  47259. function isInWindow(value) {
  47260. return value >= valueWindow[0] && value <= valueWindow[1];
  47261. }
  47262. };
  47263. AxisProxy.prototype._updateMinMaxSpan = function () {
  47264. var minMaxSpan = this._minMaxSpan = {};
  47265. var dataZoomModel = this._dataZoomModel;
  47266. var dataExtent = this._dataExtent;
  47267. each$4(['min', 'max'], function (minMax) {
  47268. var percentSpan = dataZoomModel.get(minMax + 'Span');
  47269. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  47270. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan));
  47271. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  47272. if (valueSpan != null) {
  47273. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  47274. } else if (percentSpan != null) {
  47275. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  47276. }
  47277. minMaxSpan[minMax + 'Span'] = percentSpan;
  47278. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  47279. }, this);
  47280. };
  47281. AxisProxy.prototype._setAxisModel = function () {
  47282. var axisModel = this.getAxisModel();
  47283. var percentWindow = this._percentWindow;
  47284. var valueWindow = this._valueWindow;
  47285. if (!percentWindow) {
  47286. return;
  47287. }
  47288. // [0, 500]: arbitrary value, guess axis extent.
  47289. var precision = getPixelPrecision(valueWindow, [0, 500]);
  47290. precision = Math.min(precision, 20);
  47291. // For value axis, if min/max/scale are not set, we just use the extent obtained
  47292. // by series data, which may be a little different from the extent calculated by
  47293. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  47294. // little when zooming. So it will not be fixed until some users require it strongly.
  47295. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  47296. if (percentWindow[0] !== 0) {
  47297. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  47298. }
  47299. if (percentWindow[1] !== 100) {
  47300. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  47301. }
  47302. rawExtentInfo.freeze();
  47303. };
  47304. return AxisProxy;
  47305. }();
  47306. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  47307. var dataExtent = [Infinity, -Infinity];
  47308. each$4(seriesModels, function (seriesModel) {
  47309. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  47310. });
  47311. // It is important to get "consistent" extent when more then one axes is
  47312. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  47313. // when zooming. But it is difficult to know what is "consistent", considering
  47314. // axes have different type or even different meanings (For example, two
  47315. // time axes are used to compare data of the same date in different years).
  47316. // So basically dataZoom just obtains extent by series.data (in category axis
  47317. // extent can be obtained from axis.data).
  47318. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  47319. // consistent.
  47320. var axisModel = axisProxy.getAxisModel();
  47321. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  47322. return [rawExtentResult.min, rawExtentResult.max];
  47323. }
  47324. var dataZoomProcessor = {
  47325. // `dataZoomProcessor` will only be performed in needed series. Consider if
  47326. // there is a line series and a pie series, it is better not to update the
  47327. // line series if only pie series is needed to be updated.
  47328. getTargetSeries: function (ecModel) {
  47329. function eachAxisModel(cb) {
  47330. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47331. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47332. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  47333. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  47334. });
  47335. });
  47336. }
  47337. // FIXME: it brings side-effect to `getTargetSeries`.
  47338. // Prepare axis proxies.
  47339. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  47340. // dispose all last axis proxy, in case that some axis are deleted.
  47341. axisModel.__dzAxisProxy = null;
  47342. });
  47343. var proxyList = [];
  47344. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  47345. // Different dataZooms may constrol the same axis. In that case,
  47346. // an axisProxy serves both of them.
  47347. if (!axisModel.__dzAxisProxy) {
  47348. // Use the first dataZoomModel as the main model of axisProxy.
  47349. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  47350. proxyList.push(axisModel.__dzAxisProxy);
  47351. }
  47352. });
  47353. var seriesModelMap = createHashMap();
  47354. each(proxyList, function (axisProxy) {
  47355. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  47356. seriesModelMap.set(seriesModel.uid, seriesModel);
  47357. });
  47358. });
  47359. return seriesModelMap;
  47360. },
  47361. // Consider appendData, where filter should be performed. Because data process is
  47362. // in block mode currently, it is not need to worry about that the overallProgress
  47363. // execute every frame.
  47364. overallReset: function (ecModel, api) {
  47365. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47366. // We calculate window and reset axis here but not in model
  47367. // init stage and not after action dispatch handler, because
  47368. // reset should be called after seriesData.restoreData.
  47369. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47370. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  47371. });
  47372. // Caution: data zoom filtering is order sensitive when using
  47373. // percent range and no min/max/scale set on axis.
  47374. // For example, we have dataZoom definition:
  47375. // [
  47376. // {xAxisIndex: 0, start: 30, end: 70},
  47377. // {yAxisIndex: 0, start: 20, end: 80}
  47378. // ]
  47379. // In this case, [20, 80] of y-dataZoom should be based on data
  47380. // that have filtered by x-dataZoom using range of [30, 70],
  47381. // but should not be based on full raw data. Thus sliding
  47382. // x-dataZoom will change both ranges of xAxis and yAxis,
  47383. // while sliding y-dataZoom will only change the range of yAxis.
  47384. // So we should filter x-axis after reset x-axis immediately,
  47385. // and then reset y-axis and filter y-axis.
  47386. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47387. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  47388. });
  47389. });
  47390. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47391. // Fullfill all of the range props so that user
  47392. // is able to get them from chart.getOption().
  47393. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  47394. if (axisProxy) {
  47395. var percentRange = axisProxy.getDataPercentWindow();
  47396. var valueRange = axisProxy.getDataValueWindow();
  47397. dataZoomModel.setCalculatedRange({
  47398. start: percentRange[0],
  47399. end: percentRange[1],
  47400. startValue: valueRange[0],
  47401. endValue: valueRange[1]
  47402. });
  47403. }
  47404. });
  47405. }
  47406. };
  47407. function installDataZoomAction(registers) {
  47408. registers.registerAction('dataZoom', function (payload, ecModel) {
  47409. var effectedModels = findEffectedDataZooms(ecModel, payload);
  47410. each(effectedModels, function (dataZoomModel) {
  47411. dataZoomModel.setRawRange({
  47412. start: payload.start,
  47413. end: payload.end,
  47414. startValue: payload.startValue,
  47415. endValue: payload.endValue
  47416. });
  47417. });
  47418. });
  47419. }
  47420. var installed = false;
  47421. function installCommon(registers) {
  47422. if (installed) {
  47423. return;
  47424. }
  47425. installed = true;
  47426. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  47427. installDataZoomAction(registers);
  47428. registers.registerSubTypeDefaulter('dataZoom', function () {
  47429. // Default 'slider' when no type specified.
  47430. return 'slider';
  47431. });
  47432. }
  47433. function install$a(registers) {
  47434. registers.registerComponentModel(SelectDataZoomModel);
  47435. registers.registerComponentView(SelectDataZoomView);
  47436. installCommon(registers);
  47437. }
  47438. /*
  47439. * Licensed to the Apache Software Foundation (ASF) under one
  47440. * or more contributor license agreements. See the NOTICE file
  47441. * distributed with this work for additional information
  47442. * regarding copyright ownership. The ASF licenses this file
  47443. * to you under the Apache License, Version 2.0 (the
  47444. * "License"); you may not use this file except in compliance
  47445. * with the License. You may obtain a copy of the License at
  47446. *
  47447. * http://www.apache.org/licenses/LICENSE-2.0
  47448. *
  47449. * Unless required by applicable law or agreed to in writing,
  47450. * software distributed under the License is distributed on an
  47451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47452. * KIND, either express or implied. See the License for the
  47453. * specific language governing permissions and limitations
  47454. * under the License.
  47455. */
  47456. /**
  47457. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47458. */
  47459. var ToolboxFeature = /** @class */function () {
  47460. function ToolboxFeature() {}
  47461. return ToolboxFeature;
  47462. }();
  47463. var features = {};
  47464. function registerFeature(name, ctor) {
  47465. features[name] = ctor;
  47466. }
  47467. function getFeature(name) {
  47468. return features[name];
  47469. }
  47470. var ToolboxModel = /** @class */function (_super) {
  47471. __extends(ToolboxModel, _super);
  47472. function ToolboxModel() {
  47473. var _this = _super !== null && _super.apply(this, arguments) || this;
  47474. _this.type = ToolboxModel.type;
  47475. return _this;
  47476. }
  47477. ToolboxModel.prototype.optionUpdated = function () {
  47478. _super.prototype.optionUpdated.apply(this, arguments);
  47479. var ecModel = this.ecModel;
  47480. each(this.option.feature, function (featureOpt, featureName) {
  47481. var Feature = getFeature(featureName);
  47482. if (Feature) {
  47483. if (Feature.getDefaultOption) {
  47484. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  47485. }
  47486. merge(featureOpt, Feature.defaultOption);
  47487. }
  47488. });
  47489. };
  47490. ToolboxModel.type = 'toolbox';
  47491. ToolboxModel.layoutMode = {
  47492. type: 'box',
  47493. ignoreSize: true
  47494. };
  47495. ToolboxModel.defaultOption = {
  47496. show: true,
  47497. z: 6,
  47498. // zlevel: 0,
  47499. orient: 'horizontal',
  47500. left: 'right',
  47501. top: 'top',
  47502. // right
  47503. // bottom
  47504. backgroundColor: 'transparent',
  47505. borderColor: '#ccc',
  47506. borderRadius: 0,
  47507. borderWidth: 0,
  47508. padding: 5,
  47509. itemSize: 15,
  47510. itemGap: 8,
  47511. showTitle: true,
  47512. iconStyle: {
  47513. borderColor: '#666',
  47514. color: 'none'
  47515. },
  47516. emphasis: {
  47517. iconStyle: {
  47518. borderColor: '#3E98C5'
  47519. }
  47520. },
  47521. // textStyle: {},
  47522. // feature
  47523. tooltip: {
  47524. show: false,
  47525. position: 'bottom'
  47526. }
  47527. };
  47528. return ToolboxModel;
  47529. }(ComponentModel);
  47530. /**
  47531. * Layout list like component.
  47532. * It will box layout each items in group of component and then position the whole group in the viewport
  47533. * @param {module:zrender/group/Group} group
  47534. * @param {module:echarts/model/Component} componentModel
  47535. * @param {module:echarts/ExtensionAPI}
  47536. */
  47537. function layout$2(group, componentModel, api) {
  47538. var boxLayoutParams = componentModel.getBoxLayoutParams();
  47539. var padding = componentModel.get('padding');
  47540. var viewportSize = {
  47541. width: api.getWidth(),
  47542. height: api.getHeight()
  47543. };
  47544. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  47545. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  47546. positionElement(group, boxLayoutParams, viewportSize, padding);
  47547. }
  47548. function makeBackground(rect, componentModel) {
  47549. var padding = normalizeCssArray$1(componentModel.get('padding'));
  47550. var style = componentModel.getItemStyle(['color', 'opacity']);
  47551. style.fill = componentModel.get('backgroundColor');
  47552. rect = new Rect({
  47553. shape: {
  47554. x: rect.x - padding[3],
  47555. y: rect.y - padding[0],
  47556. width: rect.width + padding[1] + padding[3],
  47557. height: rect.height + padding[0] + padding[2],
  47558. r: componentModel.get('borderRadius')
  47559. },
  47560. style: style,
  47561. silent: true,
  47562. z2: -1
  47563. });
  47564. // FIXME
  47565. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  47566. // and background rect when setting like `left: 0`, `top: 0`.
  47567. // graphic.subPixelOptimizeRect(rect);
  47568. return rect;
  47569. }
  47570. var ToolboxView = /** @class */function (_super) {
  47571. __extends(ToolboxView, _super);
  47572. function ToolboxView() {
  47573. return _super !== null && _super.apply(this, arguments) || this;
  47574. }
  47575. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  47576. var group = this.group;
  47577. group.removeAll();
  47578. if (!toolboxModel.get('show')) {
  47579. return;
  47580. }
  47581. var itemSize = +toolboxModel.get('itemSize');
  47582. var isVertical = toolboxModel.get('orient') === 'vertical';
  47583. var featureOpts = toolboxModel.get('feature') || {};
  47584. var features = this._features || (this._features = {});
  47585. var featureNames = [];
  47586. each(featureOpts, function (opt, name) {
  47587. featureNames.push(name);
  47588. });
  47589. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute();
  47590. // Keep for diff.
  47591. this._featureNames = featureNames;
  47592. function processFeature(newIndex, oldIndex) {
  47593. var featureName = featureNames[newIndex];
  47594. var oldName = featureNames[oldIndex];
  47595. var featureOpt = featureOpts[featureName];
  47596. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  47597. var feature;
  47598. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  47599. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  47600. featureOpt.title = payload.newTitle;
  47601. }
  47602. if (featureName && !oldName) {
  47603. // Create
  47604. if (isUserFeatureName(featureName)) {
  47605. feature = {
  47606. onclick: featureModel.option.onclick,
  47607. featureName: featureName
  47608. };
  47609. } else {
  47610. var Feature = getFeature(featureName);
  47611. if (!Feature) {
  47612. return;
  47613. }
  47614. feature = new Feature();
  47615. }
  47616. features[featureName] = feature;
  47617. } else {
  47618. feature = features[oldName];
  47619. // If feature does not exist.
  47620. if (!feature) {
  47621. return;
  47622. }
  47623. }
  47624. feature.uid = getUID('toolbox-feature');
  47625. feature.model = featureModel;
  47626. feature.ecModel = ecModel;
  47627. feature.api = api;
  47628. var isToolboxFeature = feature instanceof ToolboxFeature;
  47629. if (!featureName && oldName) {
  47630. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  47631. return;
  47632. }
  47633. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  47634. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  47635. return;
  47636. }
  47637. createIconPaths(featureModel, feature, featureName);
  47638. featureModel.setIconStatus = function (iconName, status) {
  47639. var option = this.option;
  47640. var iconPaths = this.iconPaths;
  47641. option.iconStatus = option.iconStatus || {};
  47642. option.iconStatus[iconName] = status;
  47643. if (iconPaths[iconName]) {
  47644. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  47645. }
  47646. };
  47647. if (feature instanceof ToolboxFeature) {
  47648. if (feature.render) {
  47649. feature.render(featureModel, ecModel, api, payload);
  47650. }
  47651. }
  47652. }
  47653. function createIconPaths(featureModel, feature, featureName) {
  47654. var iconStyleModel = featureModel.getModel('iconStyle');
  47655. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']);
  47656. // If one feature has multiple icons, they are organized as
  47657. // {
  47658. // icon: {
  47659. // foo: '',
  47660. // bar: ''
  47661. // },
  47662. // title: {
  47663. // foo: '',
  47664. // bar: ''
  47665. // }
  47666. // }
  47667. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  47668. var titles = featureModel.get('title') || {};
  47669. var iconsMap;
  47670. var titlesMap;
  47671. if (isString(icons)) {
  47672. iconsMap = {};
  47673. iconsMap[featureName] = icons;
  47674. } else {
  47675. iconsMap = icons;
  47676. }
  47677. if (isString(titles)) {
  47678. titlesMap = {};
  47679. titlesMap[featureName] = titles;
  47680. } else {
  47681. titlesMap = titles;
  47682. }
  47683. var iconPaths = featureModel.iconPaths = {};
  47684. each(iconsMap, function (iconStr, iconName) {
  47685. var path = createIcon(iconStr, {}, {
  47686. x: -itemSize / 2,
  47687. y: -itemSize / 2,
  47688. width: itemSize,
  47689. height: itemSize
  47690. }); // TODO handling image
  47691. path.setStyle(iconStyleModel.getItemStyle());
  47692. var pathEmphasisState = path.ensureState('emphasis');
  47693. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle();
  47694. // Text position calculation
  47695. // TODO: extract `textStyle` from `iconStyle` and use `createTextStyle`
  47696. var textContent = new ZRText({
  47697. style: {
  47698. text: titlesMap[iconName],
  47699. align: iconStyleEmphasisModel.get('textAlign'),
  47700. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  47701. padding: iconStyleEmphasisModel.get('textPadding'),
  47702. fill: null,
  47703. font: getFont({
  47704. fontStyle: iconStyleEmphasisModel.get('textFontStyle'),
  47705. fontFamily: iconStyleEmphasisModel.get('textFontFamily'),
  47706. fontSize: iconStyleEmphasisModel.get('textFontSize'),
  47707. fontWeight: iconStyleEmphasisModel.get('textFontWeight')
  47708. }, ecModel)
  47709. },
  47710. ignore: true
  47711. });
  47712. path.setTextContent(textContent);
  47713. setTooltipConfig({
  47714. el: path,
  47715. componentModel: toolboxModel,
  47716. itemName: iconName,
  47717. formatterParamsExtra: {
  47718. title: titlesMap[iconName]
  47719. }
  47720. });
  47721. path.__title = titlesMap[iconName];
  47722. path.on('mouseover', function () {
  47723. // Should not reuse above hoverStyle, which might be modified.
  47724. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  47725. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  47726. textContent.setStyle({
  47727. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  47728. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  47729. });
  47730. path.setTextConfig({
  47731. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  47732. });
  47733. textContent.ignore = !toolboxModel.get('showTitle');
  47734. // Use enterEmphasis and leaveEmphasis provide by ec.
  47735. // There are flags managed by the echarts.
  47736. api.enterEmphasis(this);
  47737. }).on('mouseout', function () {
  47738. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  47739. api.leaveEmphasis(this);
  47740. }
  47741. textContent.hide();
  47742. });
  47743. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  47744. group.add(path);
  47745. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  47746. iconPaths[iconName] = path;
  47747. });
  47748. }
  47749. layout$2(group, toolboxModel, api);
  47750. // Render background after group is layout
  47751. // FIXME
  47752. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  47753. // Adjust icon title positions to avoid them out of screen
  47754. isVertical || group.eachChild(function (icon) {
  47755. var titleText = icon.__title;
  47756. // const hoverStyle = icon.hoverStyle;
  47757. // TODO simplify code?
  47758. var emphasisState = icon.ensureState('emphasis');
  47759. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  47760. var textContent = icon.getTextContent();
  47761. var emphasisTextState = textContent && textContent.ensureState('emphasis');
  47762. // May be background element
  47763. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  47764. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  47765. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  47766. var offsetX = icon.x + group.x;
  47767. var offsetY = icon.y + group.y + itemSize;
  47768. var needPutOnTop = false;
  47769. if (offsetY + rect.height > api.getHeight()) {
  47770. emphasisTextConfig.position = 'top';
  47771. needPutOnTop = true;
  47772. }
  47773. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  47774. if (offsetX + rect.width / 2 > api.getWidth()) {
  47775. emphasisTextConfig.position = ['100%', topOffset];
  47776. emphasisTextStyle.align = 'right';
  47777. } else if (offsetX - rect.width / 2 < 0) {
  47778. emphasisTextConfig.position = [0, topOffset];
  47779. emphasisTextStyle.align = 'left';
  47780. }
  47781. }
  47782. });
  47783. };
  47784. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  47785. each(this._features, function (feature) {
  47786. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  47787. });
  47788. };
  47789. // updateLayout(toolboxModel, ecModel, api, payload) {
  47790. // zrUtil.each(this._features, function (feature) {
  47791. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  47792. // });
  47793. // },
  47794. ToolboxView.prototype.remove = function (ecModel, api) {
  47795. each(this._features, function (feature) {
  47796. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  47797. });
  47798. this.group.removeAll();
  47799. };
  47800. ToolboxView.prototype.dispose = function (ecModel, api) {
  47801. each(this._features, function (feature) {
  47802. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  47803. });
  47804. };
  47805. ToolboxView.type = 'toolbox';
  47806. return ToolboxView;
  47807. }(ComponentView);
  47808. function isUserFeatureName(featureName) {
  47809. return featureName.indexOf('my') === 0;
  47810. }
  47811. var SaveAsImage = /** @class */function (_super) {
  47812. __extends(SaveAsImage, _super);
  47813. function SaveAsImage() {
  47814. return _super !== null && _super.apply(this, arguments) || this;
  47815. }
  47816. SaveAsImage.prototype.onclick = function (ecModel, api) {
  47817. var model = this.model;
  47818. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  47819. var isSvg = api.getZr().painter.getType() === 'svg';
  47820. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  47821. var url = api.getConnectedDataURL({
  47822. type: type,
  47823. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  47824. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  47825. excludeComponents: model.get('excludeComponents'),
  47826. pixelRatio: model.get('pixelRatio')
  47827. });
  47828. var browser = env.browser;
  47829. // Chrome, Firefox, New Edge
  47830. if (typeof MouseEvent === 'function' && (browser.newEdge || !browser.ie && !browser.edge)) {
  47831. var $a = document.createElement('a');
  47832. $a.download = title + '.' + type;
  47833. $a.target = '_blank';
  47834. $a.href = url;
  47835. var evt = new MouseEvent('click', {
  47836. // some micro front-end framework, window maybe is a Proxy
  47837. view: document.defaultView,
  47838. bubbles: true,
  47839. cancelable: false
  47840. });
  47841. $a.dispatchEvent(evt);
  47842. }
  47843. // IE or old Edge
  47844. else {
  47845. // @ts-ignore
  47846. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  47847. var parts = url.split(',');
  47848. // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  47849. var base64Encoded = parts[0].indexOf('base64') > -1;
  47850. var bstr = isSvg
  47851. // should decode the svg data uri first
  47852. ? decodeURIComponent(parts[1]) : parts[1];
  47853. // only `atob` when the data uri is encoded with base64
  47854. // otherwise, like `svg` data uri exported by zrender,
  47855. // there will be an error, for it's not encoded with base64.
  47856. // (just a url-encoded string through `encodeURIComponent`)
  47857. base64Encoded && (bstr = window.atob(bstr));
  47858. var filename = title + '.' + type;
  47859. // @ts-ignore
  47860. if (window.navigator.msSaveOrOpenBlob) {
  47861. var n = bstr.length;
  47862. var u8arr = new Uint8Array(n);
  47863. while (n--) {
  47864. u8arr[n] = bstr.charCodeAt(n);
  47865. }
  47866. var blob = new Blob([u8arr]); // @ts-ignore
  47867. window.navigator.msSaveOrOpenBlob(blob, filename);
  47868. } else {
  47869. var frame = document.createElement('iframe');
  47870. document.body.appendChild(frame);
  47871. var cw = frame.contentWindow;
  47872. var doc = cw.document;
  47873. doc.open('image/svg+xml', 'replace');
  47874. doc.write(bstr);
  47875. doc.close();
  47876. cw.focus();
  47877. doc.execCommand('SaveAs', true, filename);
  47878. document.body.removeChild(frame);
  47879. }
  47880. } else {
  47881. var lang = model.get('lang');
  47882. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  47883. var tab = window.open();
  47884. tab.document.write(html);
  47885. tab.document.title = title;
  47886. }
  47887. }
  47888. };
  47889. SaveAsImage.getDefaultOption = function (ecModel) {
  47890. var defaultOption = {
  47891. show: true,
  47892. 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',
  47893. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  47894. type: 'png',
  47895. // Default use option.backgroundColor
  47896. // backgroundColor: '#fff',
  47897. connectedBackgroundColor: '#fff',
  47898. name: '',
  47899. excludeComponents: ['toolbox'],
  47900. // use current pixel ratio of device by default
  47901. // pixelRatio: 1,
  47902. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  47903. };
  47904. return defaultOption;
  47905. };
  47906. return SaveAsImage;
  47907. }(ToolboxFeature);
  47908. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  47909. var radioTypes = [['line', 'bar'], ['stack']];
  47910. var MagicType = /** @class */function (_super) {
  47911. __extends(MagicType, _super);
  47912. function MagicType() {
  47913. return _super !== null && _super.apply(this, arguments) || this;
  47914. }
  47915. MagicType.prototype.getIcons = function () {
  47916. var model = this.model;
  47917. var availableIcons = model.get('icon');
  47918. var icons = {};
  47919. each(model.get('type'), function (type) {
  47920. if (availableIcons[type]) {
  47921. icons[type] = availableIcons[type];
  47922. }
  47923. });
  47924. return icons;
  47925. };
  47926. MagicType.getDefaultOption = function (ecModel) {
  47927. var defaultOption = {
  47928. show: true,
  47929. type: [],
  47930. // Icon group
  47931. icon: {
  47932. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  47933. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  47934. // eslint-disable-next-line
  47935. 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
  47936. },
  47937. // `line`, `bar`, `stack`, `tiled`
  47938. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  47939. option: {},
  47940. seriesIndex: {}
  47941. };
  47942. return defaultOption;
  47943. };
  47944. MagicType.prototype.onclick = function (ecModel, api, type) {
  47945. var model = this.model;
  47946. var seriesIndex = model.get(['seriesIndex', type]);
  47947. // Not supported magicType
  47948. if (!seriesOptGenreator[type]) {
  47949. return;
  47950. }
  47951. var newOption = {
  47952. series: []
  47953. };
  47954. var generateNewSeriesTypes = function (seriesModel) {
  47955. var seriesType = seriesModel.subType;
  47956. var seriesId = seriesModel.id;
  47957. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  47958. if (newSeriesOpt) {
  47959. // PENDING If merge original option?
  47960. defaults(newSeriesOpt, seriesModel.option);
  47961. newOption.series.push(newSeriesOpt);
  47962. }
  47963. // Modify boundaryGap
  47964. var coordSys = seriesModel.coordinateSystem;
  47965. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  47966. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  47967. if (categoryAxis) {
  47968. var axisDim = categoryAxis.dim;
  47969. var axisType = axisDim + 'Axis';
  47970. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  47971. var axisIndex = axisModel.componentIndex;
  47972. newOption[axisType] = newOption[axisType] || [];
  47973. for (var i = 0; i <= axisIndex; i++) {
  47974. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  47975. }
  47976. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  47977. }
  47978. }
  47979. };
  47980. each(radioTypes, function (radio) {
  47981. if (indexOf(radio, type) >= 0) {
  47982. each(radio, function (item) {
  47983. model.setIconStatus(item, 'normal');
  47984. });
  47985. }
  47986. });
  47987. model.setIconStatus(type, 'emphasis');
  47988. ecModel.eachComponent({
  47989. mainType: 'series',
  47990. query: seriesIndex == null ? null : {
  47991. seriesIndex: seriesIndex
  47992. }
  47993. }, generateNewSeriesTypes);
  47994. var newTitle;
  47995. var currentType = type;
  47996. // Change title of stack
  47997. if (type === 'stack') {
  47998. // use titles in model instead of ecModel
  47999. // as stack and tiled appears in pair, just flip them
  48000. // no need of checking stack state
  48001. newTitle = merge({
  48002. stack: model.option.title.tiled,
  48003. tiled: model.option.title.stack
  48004. }, model.option.title);
  48005. if (model.get(['iconStatus', type]) !== 'emphasis') {
  48006. currentType = 'tiled';
  48007. }
  48008. }
  48009. api.dispatchAction({
  48010. type: 'changeMagicType',
  48011. currentType: currentType,
  48012. newOption: newOption,
  48013. newTitle: newTitle,
  48014. featureName: 'magicType'
  48015. });
  48016. };
  48017. return MagicType;
  48018. }(ToolboxFeature);
  48019. var seriesOptGenreator = {
  48020. 'line': function (seriesType, seriesId, seriesModel, model) {
  48021. if (seriesType === 'bar') {
  48022. return merge({
  48023. id: seriesId,
  48024. type: 'line',
  48025. // Preserve data related option
  48026. data: seriesModel.get('data'),
  48027. stack: seriesModel.get('stack'),
  48028. markPoint: seriesModel.get('markPoint'),
  48029. markLine: seriesModel.get('markLine')
  48030. }, model.get(['option', 'line']) || {}, true);
  48031. }
  48032. },
  48033. 'bar': function (seriesType, seriesId, seriesModel, model) {
  48034. if (seriesType === 'line') {
  48035. return merge({
  48036. id: seriesId,
  48037. type: 'bar',
  48038. // Preserve data related option
  48039. data: seriesModel.get('data'),
  48040. stack: seriesModel.get('stack'),
  48041. markPoint: seriesModel.get('markPoint'),
  48042. markLine: seriesModel.get('markLine')
  48043. }, model.get(['option', 'bar']) || {}, true);
  48044. }
  48045. },
  48046. 'stack': function (seriesType, seriesId, seriesModel, model) {
  48047. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  48048. if (seriesType === 'line' || seriesType === 'bar') {
  48049. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  48050. return merge({
  48051. id: seriesId,
  48052. stack: isStack ? '' : INNER_STACK_KEYWORD
  48053. }, model.get(['option', 'stack']) || {}, true);
  48054. }
  48055. }
  48056. };
  48057. // TODO: SELF REGISTERED.
  48058. registerAction({
  48059. type: 'changeMagicType',
  48060. event: 'magicTypeChanged',
  48061. update: 'prepareAndUpdate'
  48062. }, function (payload, ecModel) {
  48063. ecModel.mergeOption(payload.newOption);
  48064. });
  48065. /* global document */
  48066. var BLOCK_SPLITER = new Array(60).join('-');
  48067. var ITEM_SPLITER = '\t';
  48068. /**
  48069. * Group series into two types
  48070. * 1. on category axis, like line, bar
  48071. * 2. others, like scatter, pie
  48072. */
  48073. function groupSeries(ecModel) {
  48074. var seriesGroupByCategoryAxis = {};
  48075. var otherSeries = [];
  48076. var meta = [];
  48077. ecModel.eachRawSeries(function (seriesModel) {
  48078. var coordSys = seriesModel.coordinateSystem;
  48079. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  48080. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  48081. var baseAxis = coordSys.getBaseAxis();
  48082. if (baseAxis.type === 'category') {
  48083. var key = baseAxis.dim + '_' + baseAxis.index;
  48084. if (!seriesGroupByCategoryAxis[key]) {
  48085. seriesGroupByCategoryAxis[key] = {
  48086. categoryAxis: baseAxis,
  48087. valueAxis: coordSys.getOtherAxis(baseAxis),
  48088. series: []
  48089. };
  48090. meta.push({
  48091. axisDim: baseAxis.dim,
  48092. axisIndex: baseAxis.index
  48093. });
  48094. }
  48095. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  48096. } else {
  48097. otherSeries.push(seriesModel);
  48098. }
  48099. } else {
  48100. otherSeries.push(seriesModel);
  48101. }
  48102. });
  48103. return {
  48104. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  48105. other: otherSeries,
  48106. meta: meta
  48107. };
  48108. }
  48109. /**
  48110. * Assemble content of series on cateogory axis
  48111. * @inner
  48112. */
  48113. function assembleSeriesWithCategoryAxis(groups) {
  48114. var tables = [];
  48115. each(groups, function (group, key) {
  48116. var categoryAxis = group.categoryAxis;
  48117. var valueAxis = group.valueAxis;
  48118. var valueAxisDim = valueAxis.dim;
  48119. var headers = [' '].concat(map(group.series, function (series) {
  48120. return series.name;
  48121. }));
  48122. // @ts-ignore TODO Polar
  48123. var columns = [categoryAxis.model.getCategories()];
  48124. each(group.series, function (series) {
  48125. var rawData = series.getRawData();
  48126. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  48127. return val;
  48128. }));
  48129. });
  48130. // Assemble table content
  48131. var lines = [headers.join(ITEM_SPLITER)];
  48132. for (var i = 0; i < columns[0].length; i++) {
  48133. var items = [];
  48134. for (var j = 0; j < columns.length; j++) {
  48135. items.push(columns[j][i]);
  48136. }
  48137. lines.push(items.join(ITEM_SPLITER));
  48138. }
  48139. tables.push(lines.join('\n'));
  48140. });
  48141. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  48142. }
  48143. /**
  48144. * Assemble content of other series
  48145. */
  48146. function assembleOtherSeries(series) {
  48147. return map(series, function (series) {
  48148. var data = series.getRawData();
  48149. var lines = [series.name];
  48150. var vals = [];
  48151. data.each(data.dimensions, function () {
  48152. var argLen = arguments.length;
  48153. var dataIndex = arguments[argLen - 1];
  48154. var name = data.getName(dataIndex);
  48155. for (var i = 0; i < argLen - 1; i++) {
  48156. vals[i] = arguments[i];
  48157. }
  48158. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  48159. });
  48160. return lines.join('\n');
  48161. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  48162. }
  48163. function getContentFromModel(ecModel) {
  48164. var result = groupSeries(ecModel);
  48165. return {
  48166. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  48167. return !!str.replace(/[\n\t\s]/g, '');
  48168. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  48169. meta: result.meta
  48170. };
  48171. }
  48172. function trim$1(str) {
  48173. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  48174. }
  48175. /**
  48176. * If a block is tsv format
  48177. */
  48178. function isTSVFormat(block) {
  48179. // Simple method to find out if a block is tsv format
  48180. var firstLine = block.slice(0, block.indexOf('\n'));
  48181. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  48182. return true;
  48183. }
  48184. }
  48185. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  48186. /**
  48187. * @param {string} tsv
  48188. * @return {Object}
  48189. */
  48190. function parseTSVContents(tsv) {
  48191. var tsvLines = tsv.split(/\n+/g);
  48192. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  48193. var categories = [];
  48194. var series = map(headers, function (header) {
  48195. return {
  48196. name: header,
  48197. data: []
  48198. };
  48199. });
  48200. for (var i = 0; i < tsvLines.length; i++) {
  48201. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  48202. categories.push(items.shift());
  48203. for (var j = 0; j < items.length; j++) {
  48204. series[j] && (series[j].data[i] = items[j]);
  48205. }
  48206. }
  48207. return {
  48208. series: series,
  48209. categories: categories
  48210. };
  48211. }
  48212. function parseListContents(str) {
  48213. var lines = str.split(/\n+/g);
  48214. var seriesName = trim$1(lines.shift());
  48215. var data = [];
  48216. for (var i = 0; i < lines.length; i++) {
  48217. // if line is empty, ignore it.
  48218. // there is a case that a user forgot to delete `\n`.
  48219. var line = trim$1(lines[i]);
  48220. if (!line) {
  48221. continue;
  48222. }
  48223. var items = line.split(itemSplitRegex);
  48224. var name_1 = '';
  48225. var value = void 0;
  48226. var hasName = false;
  48227. if (isNaN(items[0])) {
  48228. // First item is name
  48229. hasName = true;
  48230. name_1 = items[0];
  48231. items = items.slice(1);
  48232. data[i] = {
  48233. name: name_1,
  48234. value: []
  48235. };
  48236. value = data[i].value;
  48237. } else {
  48238. value = data[i] = [];
  48239. }
  48240. for (var j = 0; j < items.length; j++) {
  48241. value.push(+items[j]);
  48242. }
  48243. if (value.length === 1) {
  48244. hasName ? data[i].value = value[0] : data[i] = value[0];
  48245. }
  48246. }
  48247. return {
  48248. name: seriesName,
  48249. data: data
  48250. };
  48251. }
  48252. function parseContents(str, blockMetaList) {
  48253. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  48254. var newOption = {
  48255. series: []
  48256. };
  48257. each(blocks, function (block, idx) {
  48258. if (isTSVFormat(block)) {
  48259. var result = parseTSVContents(block);
  48260. var blockMeta = blockMetaList[idx];
  48261. var axisKey = blockMeta.axisDim + 'Axis';
  48262. if (blockMeta) {
  48263. newOption[axisKey] = newOption[axisKey] || [];
  48264. newOption[axisKey][blockMeta.axisIndex] = {
  48265. data: result.categories
  48266. };
  48267. newOption.series = newOption.series.concat(result.series);
  48268. }
  48269. } else {
  48270. var result = parseListContents(block);
  48271. newOption.series.push(result);
  48272. }
  48273. });
  48274. return newOption;
  48275. }
  48276. var DataView = /** @class */function (_super) {
  48277. __extends(DataView, _super);
  48278. function DataView() {
  48279. return _super !== null && _super.apply(this, arguments) || this;
  48280. }
  48281. DataView.prototype.onclick = function (ecModel, api) {
  48282. // FIXME: better way?
  48283. setTimeout(function () {
  48284. api.dispatchAction({
  48285. type: 'hideTip'
  48286. });
  48287. });
  48288. var container = api.getDom();
  48289. var model = this.model;
  48290. if (this._dom) {
  48291. container.removeChild(this._dom);
  48292. }
  48293. var root = document.createElement('div');
  48294. // use padding to avoid 5px whitespace
  48295. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  48296. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  48297. // Create elements
  48298. var header = document.createElement('h4');
  48299. var lang = model.get('lang') || [];
  48300. header.innerHTML = lang[0] || model.get('title');
  48301. header.style.cssText = 'margin:10px 20px';
  48302. header.style.color = model.get('textColor');
  48303. var viewMain = document.createElement('div');
  48304. var textarea = document.createElement('textarea');
  48305. viewMain.style.cssText = 'overflow:auto';
  48306. var optionToContent = model.get('optionToContent');
  48307. var contentToOption = model.get('contentToOption');
  48308. var result = getContentFromModel(ecModel);
  48309. if (isFunction(optionToContent)) {
  48310. var htmlOrDom = optionToContent(api.getOption());
  48311. if (isString(htmlOrDom)) {
  48312. viewMain.innerHTML = htmlOrDom;
  48313. } else if (isDom(htmlOrDom)) {
  48314. viewMain.appendChild(htmlOrDom);
  48315. }
  48316. } else {
  48317. // Use default textarea
  48318. textarea.readOnly = model.get('readOnly');
  48319. var style = textarea.style;
  48320. // eslint-disable-next-line max-len
  48321. style.cssText = 'display:block;width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;resize:none;box-sizing:border-box;outline:none';
  48322. style.color = model.get('textColor');
  48323. style.borderColor = model.get('textareaBorderColor');
  48324. style.backgroundColor = model.get('textareaColor');
  48325. textarea.value = result.value;
  48326. viewMain.appendChild(textarea);
  48327. }
  48328. var blockMetaList = result.meta;
  48329. var buttonContainer = document.createElement('div');
  48330. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0';
  48331. // eslint-disable-next-line max-len
  48332. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  48333. var closeButton = document.createElement('div');
  48334. var refreshButton = document.createElement('div');
  48335. buttonStyle += ';background-color:' + model.get('buttonColor');
  48336. buttonStyle += ';color:' + model.get('buttonTextColor');
  48337. var self = this;
  48338. function close() {
  48339. container.removeChild(root);
  48340. self._dom = null;
  48341. }
  48342. addEventListener(closeButton, 'click', close);
  48343. addEventListener(refreshButton, 'click', function () {
  48344. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  48345. if ("development" !== 'production') {
  48346. // eslint-disable-next-line
  48347. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  48348. }
  48349. close();
  48350. return;
  48351. }
  48352. var newOption;
  48353. try {
  48354. if (isFunction(contentToOption)) {
  48355. newOption = contentToOption(viewMain, api.getOption());
  48356. } else {
  48357. newOption = parseContents(textarea.value, blockMetaList);
  48358. }
  48359. } catch (e) {
  48360. close();
  48361. throw new Error('Data view format error ' + e);
  48362. }
  48363. if (newOption) {
  48364. api.dispatchAction({
  48365. type: 'changeDataView',
  48366. newOption: newOption
  48367. });
  48368. }
  48369. close();
  48370. });
  48371. closeButton.innerHTML = lang[1];
  48372. refreshButton.innerHTML = lang[2];
  48373. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  48374. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  48375. buttonContainer.appendChild(closeButton);
  48376. root.appendChild(header);
  48377. root.appendChild(viewMain);
  48378. root.appendChild(buttonContainer);
  48379. viewMain.style.height = container.clientHeight - 80 + 'px';
  48380. container.appendChild(root);
  48381. this._dom = root;
  48382. };
  48383. DataView.prototype.remove = function (ecModel, api) {
  48384. this._dom && api.getDom().removeChild(this._dom);
  48385. };
  48386. DataView.prototype.dispose = function (ecModel, api) {
  48387. this.remove(ecModel, api);
  48388. };
  48389. DataView.getDefaultOption = function (ecModel) {
  48390. var defaultOption = {
  48391. show: true,
  48392. readOnly: false,
  48393. optionToContent: null,
  48394. contentToOption: null,
  48395. // eslint-disable-next-line
  48396. 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',
  48397. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  48398. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  48399. backgroundColor: '#fff',
  48400. textColor: '#000',
  48401. textareaColor: '#fff',
  48402. textareaBorderColor: '#333',
  48403. buttonColor: '#c23531',
  48404. buttonTextColor: '#fff'
  48405. };
  48406. return defaultOption;
  48407. };
  48408. return DataView;
  48409. }(ToolboxFeature);
  48410. /**
  48411. * @inner
  48412. */
  48413. function tryMergeDataOption(newData, originalData) {
  48414. return map(newData, function (newVal, idx) {
  48415. var original = originalData && originalData[idx];
  48416. if (isObject(original) && !isArray(original)) {
  48417. var newValIsObject = isObject(newVal) && !isArray(newVal);
  48418. if (!newValIsObject) {
  48419. newVal = {
  48420. value: newVal
  48421. };
  48422. }
  48423. // original data has name but new data has no name
  48424. var shouldDeleteName = original.name != null && newVal.name == null;
  48425. // Original data has option
  48426. newVal = defaults(newVal, original);
  48427. shouldDeleteName && delete newVal.name;
  48428. return newVal;
  48429. } else {
  48430. return newVal;
  48431. }
  48432. });
  48433. }
  48434. // TODO: SELF REGISTERED.
  48435. registerAction({
  48436. type: 'changeDataView',
  48437. event: 'dataViewChanged',
  48438. update: 'prepareAndUpdate'
  48439. }, function (payload, ecModel) {
  48440. var newSeriesOptList = [];
  48441. each(payload.newOption.series, function (seriesOpt) {
  48442. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  48443. if (!seriesModel) {
  48444. // New created series
  48445. // Geuss the series type
  48446. newSeriesOptList.push(extend({
  48447. // Default is scatter
  48448. type: 'scatter'
  48449. }, seriesOpt));
  48450. } else {
  48451. var originalData = seriesModel.get('data');
  48452. newSeriesOptList.push({
  48453. name: seriesOpt.name,
  48454. data: tryMergeDataOption(seriesOpt.data, originalData)
  48455. });
  48456. }
  48457. });
  48458. ecModel.mergeOption(defaults({
  48459. series: newSeriesOptList
  48460. }, payload.newOption));
  48461. });
  48462. var each$5 = each;
  48463. var inner$b = makeInner();
  48464. /**
  48465. * @param ecModel
  48466. * @param newSnapshot key is dataZoomId
  48467. */
  48468. function push(ecModel, newSnapshot) {
  48469. var storedSnapshots = getStoreSnapshots(ecModel);
  48470. // If previous dataZoom can not be found,
  48471. // complete an range with current range.
  48472. each$5(newSnapshot, function (batchItem, dataZoomId) {
  48473. var i = storedSnapshots.length - 1;
  48474. for (; i >= 0; i--) {
  48475. var snapshot = storedSnapshots[i];
  48476. if (snapshot[dataZoomId]) {
  48477. break;
  48478. }
  48479. }
  48480. if (i < 0) {
  48481. // No origin range set, create one by current range.
  48482. var dataZoomModel = ecModel.queryComponents({
  48483. mainType: 'dataZoom',
  48484. subType: 'select',
  48485. id: dataZoomId
  48486. })[0];
  48487. if (dataZoomModel) {
  48488. var percentRange = dataZoomModel.getPercentRange();
  48489. storedSnapshots[0][dataZoomId] = {
  48490. dataZoomId: dataZoomId,
  48491. start: percentRange[0],
  48492. end: percentRange[1]
  48493. };
  48494. }
  48495. }
  48496. });
  48497. storedSnapshots.push(newSnapshot);
  48498. }
  48499. function pop(ecModel) {
  48500. var storedSnapshots = getStoreSnapshots(ecModel);
  48501. var head = storedSnapshots[storedSnapshots.length - 1];
  48502. storedSnapshots.length > 1 && storedSnapshots.pop();
  48503. // Find top for all dataZoom.
  48504. var snapshot = {};
  48505. each$5(head, function (batchItem, dataZoomId) {
  48506. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  48507. batchItem = storedSnapshots[i][dataZoomId];
  48508. if (batchItem) {
  48509. snapshot[dataZoomId] = batchItem;
  48510. break;
  48511. }
  48512. }
  48513. });
  48514. return snapshot;
  48515. }
  48516. function clear$1(ecModel) {
  48517. inner$b(ecModel).snapshots = null;
  48518. }
  48519. function count(ecModel) {
  48520. return getStoreSnapshots(ecModel).length;
  48521. }
  48522. /**
  48523. * History length of each dataZoom may be different.
  48524. * this._history[0] is used to store origin range.
  48525. */
  48526. function getStoreSnapshots(ecModel) {
  48527. var store = inner$b(ecModel);
  48528. if (!store.snapshots) {
  48529. store.snapshots = [{}];
  48530. }
  48531. return store.snapshots;
  48532. }
  48533. var RestoreOption = /** @class */function (_super) {
  48534. __extends(RestoreOption, _super);
  48535. function RestoreOption() {
  48536. return _super !== null && _super.apply(this, arguments) || this;
  48537. }
  48538. RestoreOption.prototype.onclick = function (ecModel, api) {
  48539. clear$1(ecModel);
  48540. api.dispatchAction({
  48541. type: 'restore',
  48542. from: this.uid
  48543. });
  48544. };
  48545. RestoreOption.getDefaultOption = function (ecModel) {
  48546. var defaultOption = {
  48547. show: true,
  48548. // eslint-disable-next-line
  48549. 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',
  48550. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  48551. };
  48552. return defaultOption;
  48553. };
  48554. return RestoreOption;
  48555. }(ToolboxFeature);
  48556. // TODO: SELF REGISTERED.
  48557. registerAction({
  48558. type: 'restore',
  48559. event: 'restore',
  48560. update: 'prepareAndUpdate'
  48561. }, function (payload, ecModel) {
  48562. ecModel.resetOption('recreate');
  48563. });
  48564. var ATTR = '\0_ec_interaction_mutex';
  48565. function take(zr, resourceKey, userKey) {
  48566. var store = getStore(zr);
  48567. store[resourceKey] = userKey;
  48568. }
  48569. function release(zr, resourceKey, userKey) {
  48570. var store = getStore(zr);
  48571. var uKey = store[resourceKey];
  48572. if (uKey === userKey) {
  48573. store[resourceKey] = null;
  48574. }
  48575. }
  48576. function isTaken(zr, resourceKey) {
  48577. return !!getStore(zr)[resourceKey];
  48578. }
  48579. function getStore(zr) {
  48580. return zr[ATTR] || (zr[ATTR] = {});
  48581. }
  48582. /**
  48583. * payload: {
  48584. * type: 'takeGlobalCursor',
  48585. * key: 'dataZoomSelect', or 'brush', or ...,
  48586. * If no userKey, release global cursor.
  48587. * }
  48588. */
  48589. // TODO: SELF REGISTERED.
  48590. registerAction({
  48591. type: 'takeGlobalCursor',
  48592. event: 'globalCursorTaken',
  48593. update: 'update'
  48594. }, noop);
  48595. var BRUSH_PANEL_GLOBAL = true;
  48596. var mathMin$7 = Math.min;
  48597. var mathMax$7 = Math.max;
  48598. var mathPow$2 = Math.pow;
  48599. var COVER_Z = 10000;
  48600. var UNSELECT_THRESHOLD = 6;
  48601. var MIN_RESIZE_LINE_WIDTH = 6;
  48602. var MUTEX_RESOURCE_KEY = 'globalPan';
  48603. var DIRECTION_MAP = {
  48604. w: [0, 0],
  48605. e: [0, 1],
  48606. n: [1, 0],
  48607. s: [1, 1]
  48608. };
  48609. var CURSOR_MAP = {
  48610. w: 'ew',
  48611. e: 'ew',
  48612. n: 'ns',
  48613. s: 'ns',
  48614. ne: 'nesw',
  48615. sw: 'nesw',
  48616. nw: 'nwse',
  48617. se: 'nwse'
  48618. };
  48619. var DEFAULT_BRUSH_OPT = {
  48620. brushStyle: {
  48621. lineWidth: 2,
  48622. stroke: 'rgba(210,219,238,0.3)',
  48623. fill: '#D2DBEE'
  48624. },
  48625. transformable: true,
  48626. brushMode: 'single',
  48627. removeOnClick: false
  48628. };
  48629. var baseUID = 0;
  48630. /**
  48631. * params:
  48632. * areas: Array.<Array>, coord relates to container group,
  48633. * If no container specified, to global.
  48634. * opt {
  48635. * isEnd: boolean,
  48636. * removeOnClick: boolean
  48637. * }
  48638. */
  48639. var BrushController = /** @class */function (_super) {
  48640. __extends(BrushController, _super);
  48641. function BrushController(zr) {
  48642. var _this = _super.call(this) || this;
  48643. /**
  48644. * @internal
  48645. */
  48646. _this._track = [];
  48647. /**
  48648. * @internal
  48649. */
  48650. _this._covers = [];
  48651. _this._handlers = {};
  48652. if ("development" !== 'production') {
  48653. assert(zr);
  48654. }
  48655. _this._zr = zr;
  48656. _this.group = new Group();
  48657. _this._uid = 'brushController_' + baseUID++;
  48658. each(pointerHandlers, function (handler, eventName) {
  48659. this._handlers[eventName] = bind(handler, this);
  48660. }, _this);
  48661. return _this;
  48662. }
  48663. /**
  48664. * If set to `false`, select disabled.
  48665. */
  48666. BrushController.prototype.enableBrush = function (brushOption) {
  48667. if ("development" !== 'production') {
  48668. assert(this._mounted);
  48669. }
  48670. this._brushType && this._doDisableBrush();
  48671. brushOption.brushType && this._doEnableBrush(brushOption);
  48672. return this;
  48673. };
  48674. BrushController.prototype._doEnableBrush = function (brushOption) {
  48675. var zr = this._zr;
  48676. // Consider roam, which takes globalPan too.
  48677. if (!this._enableGlobalPan) {
  48678. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  48679. }
  48680. each(this._handlers, function (handler, eventName) {
  48681. zr.on(eventName, handler);
  48682. });
  48683. this._brushType = brushOption.brushType;
  48684. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48685. };
  48686. BrushController.prototype._doDisableBrush = function () {
  48687. var zr = this._zr;
  48688. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  48689. each(this._handlers, function (handler, eventName) {
  48690. zr.off(eventName, handler);
  48691. });
  48692. this._brushType = this._brushOption = null;
  48693. };
  48694. /**
  48695. * @param panelOpts If not pass, it is global brush.
  48696. */
  48697. BrushController.prototype.setPanels = function (panelOpts) {
  48698. if (panelOpts && panelOpts.length) {
  48699. var panels_1 = this._panels = {};
  48700. each(panelOpts, function (panelOpts) {
  48701. panels_1[panelOpts.panelId] = clone(panelOpts);
  48702. });
  48703. } else {
  48704. this._panels = null;
  48705. }
  48706. return this;
  48707. };
  48708. BrushController.prototype.mount = function (opt) {
  48709. opt = opt || {};
  48710. if ("development" !== 'production') {
  48711. this._mounted = true; // should be at first.
  48712. }
  48713. this._enableGlobalPan = opt.enableGlobalPan;
  48714. var thisGroup = this.group;
  48715. this._zr.add(thisGroup);
  48716. thisGroup.attr({
  48717. x: opt.x || 0,
  48718. y: opt.y || 0,
  48719. rotation: opt.rotation || 0,
  48720. scaleX: opt.scaleX || 1,
  48721. scaleY: opt.scaleY || 1
  48722. });
  48723. this._transform = thisGroup.getLocalTransform();
  48724. return this;
  48725. };
  48726. // eachCover(cb, context): void {
  48727. // each(this._covers, cb, context);
  48728. // }
  48729. /**
  48730. * Update covers.
  48731. * @param coverConfigList
  48732. * If coverConfigList is null/undefined, all covers removed.
  48733. */
  48734. BrushController.prototype.updateCovers = function (coverConfigList) {
  48735. if ("development" !== 'production') {
  48736. assert(this._mounted);
  48737. }
  48738. coverConfigList = map(coverConfigList, function (coverConfig) {
  48739. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  48740. });
  48741. var tmpIdPrefix = '\0-brush-index-';
  48742. var oldCovers = this._covers;
  48743. var newCovers = this._covers = [];
  48744. var controller = this;
  48745. var creatingCover = this._creatingCover;
  48746. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  48747. return this;
  48748. function getKey(brushOption, index) {
  48749. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  48750. }
  48751. function oldGetKey(cover, index) {
  48752. return getKey(cover.__brushOption, index);
  48753. }
  48754. function addOrUpdate(newIndex, oldIndex) {
  48755. var newBrushInternal = coverConfigList[newIndex];
  48756. // Consider setOption in event listener of brushSelect,
  48757. // where updating cover when creating should be forbidden.
  48758. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48759. newCovers[newIndex] = oldCovers[oldIndex];
  48760. } else {
  48761. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  48762. updateCoverAfterCreation(controller, cover);
  48763. }
  48764. }
  48765. function remove(oldIndex) {
  48766. if (oldCovers[oldIndex] !== creatingCover) {
  48767. controller.group.remove(oldCovers[oldIndex]);
  48768. }
  48769. }
  48770. };
  48771. BrushController.prototype.unmount = function () {
  48772. if ("development" !== 'production') {
  48773. if (!this._mounted) {
  48774. return;
  48775. }
  48776. }
  48777. this.enableBrush(false);
  48778. // container may 'removeAll' outside.
  48779. clearCovers(this);
  48780. this._zr.remove(this.group);
  48781. if ("development" !== 'production') {
  48782. this._mounted = false; // should be at last.
  48783. }
  48784. return this;
  48785. };
  48786. BrushController.prototype.dispose = function () {
  48787. this.unmount();
  48788. this.off();
  48789. };
  48790. return BrushController;
  48791. }(Eventful);
  48792. function createCover(controller, brushOption) {
  48793. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48794. cover.__brushOption = brushOption;
  48795. updateZ(cover, brushOption);
  48796. controller.group.add(cover);
  48797. return cover;
  48798. }
  48799. function endCreating(controller, creatingCover) {
  48800. var coverRenderer = getCoverRenderer(creatingCover);
  48801. if (coverRenderer.endCreating) {
  48802. coverRenderer.endCreating(controller, creatingCover);
  48803. updateZ(creatingCover, creatingCover.__brushOption);
  48804. }
  48805. return creatingCover;
  48806. }
  48807. function updateCoverShape(controller, cover) {
  48808. var brushOption = cover.__brushOption;
  48809. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  48810. }
  48811. function updateZ(cover, brushOption) {
  48812. var z = brushOption.z;
  48813. z == null && (z = COVER_Z);
  48814. cover.traverse(function (el) {
  48815. el.z = z;
  48816. el.z2 = z; // Consider in given container.
  48817. });
  48818. }
  48819. function updateCoverAfterCreation(controller, cover) {
  48820. getCoverRenderer(cover).updateCommon(controller, cover);
  48821. updateCoverShape(controller, cover);
  48822. }
  48823. function getCoverRenderer(cover) {
  48824. return coverRenderers[cover.__brushOption.brushType];
  48825. }
  48826. // return target panel or `true` (means global panel)
  48827. function getPanelByPoint(controller, e, localCursorPoint) {
  48828. var panels = controller._panels;
  48829. if (!panels) {
  48830. return BRUSH_PANEL_GLOBAL; // Global panel
  48831. }
  48832. var panel;
  48833. var transform = controller._transform;
  48834. each(panels, function (pn) {
  48835. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48836. });
  48837. return panel;
  48838. }
  48839. // Return a panel or true
  48840. function getPanelByCover(controller, cover) {
  48841. var panels = controller._panels;
  48842. if (!panels) {
  48843. return BRUSH_PANEL_GLOBAL; // Global panel
  48844. }
  48845. var panelId = cover.__brushOption.panelId;
  48846. // User may give cover without coord sys info,
  48847. // which is then treated as global panel.
  48848. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  48849. }
  48850. function clearCovers(controller) {
  48851. var covers = controller._covers;
  48852. var originalLength = covers.length;
  48853. each(covers, function (cover) {
  48854. controller.group.remove(cover);
  48855. }, controller);
  48856. covers.length = 0;
  48857. return !!originalLength;
  48858. }
  48859. function trigger(controller, opt) {
  48860. var areas = map(controller._covers, function (cover) {
  48861. var brushOption = cover.__brushOption;
  48862. var range = clone(brushOption.range);
  48863. return {
  48864. brushType: brushOption.brushType,
  48865. panelId: brushOption.panelId,
  48866. range: range
  48867. };
  48868. });
  48869. controller.trigger('brush', {
  48870. areas: areas,
  48871. isEnd: !!opt.isEnd,
  48872. removeOnClick: !!opt.removeOnClick
  48873. });
  48874. }
  48875. function shouldShowCover(controller) {
  48876. var track = controller._track;
  48877. if (!track.length) {
  48878. return false;
  48879. }
  48880. var p2 = track[track.length - 1];
  48881. var p1 = track[0];
  48882. var dx = p2[0] - p1[0];
  48883. var dy = p2[1] - p1[1];
  48884. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48885. return dist > UNSELECT_THRESHOLD;
  48886. }
  48887. function getTrackEnds(track) {
  48888. var tail = track.length - 1;
  48889. tail < 0 && (tail = 0);
  48890. return [track[0], track[tail]];
  48891. }
  48892. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  48893. var cover = new Group();
  48894. cover.add(new Rect({
  48895. name: 'main',
  48896. style: makeStyle(brushOption),
  48897. silent: true,
  48898. draggable: true,
  48899. cursor: 'move',
  48900. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  48901. ondragend: curry(trigger, controller, {
  48902. isEnd: true
  48903. })
  48904. }));
  48905. each(edgeNameSequences, function (nameSequence) {
  48906. cover.add(new Rect({
  48907. name: nameSequence.join(''),
  48908. style: {
  48909. opacity: 0
  48910. },
  48911. draggable: true,
  48912. silent: true,
  48913. invisible: true,
  48914. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  48915. ondragend: curry(trigger, controller, {
  48916. isEnd: true
  48917. })
  48918. }));
  48919. });
  48920. return cover;
  48921. }
  48922. function updateBaseRect(controller, cover, localRange, brushOption) {
  48923. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48924. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48925. var x = localRange[0][0];
  48926. var y = localRange[1][0];
  48927. var xa = x - lineWidth / 2;
  48928. var ya = y - lineWidth / 2;
  48929. var x2 = localRange[0][1];
  48930. var y2 = localRange[1][1];
  48931. var x2a = x2 - handleSize + lineWidth / 2;
  48932. var y2a = y2 - handleSize + lineWidth / 2;
  48933. var width = x2 - x;
  48934. var height = y2 - y;
  48935. var widtha = width + lineWidth;
  48936. var heighta = height + lineWidth;
  48937. updateRectShape(controller, cover, 'main', x, y, width, height);
  48938. if (brushOption.transformable) {
  48939. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48940. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48941. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48942. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48943. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48944. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48945. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48946. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48947. }
  48948. }
  48949. function updateCommon(controller, cover) {
  48950. var brushOption = cover.__brushOption;
  48951. var transformable = brushOption.transformable;
  48952. var mainEl = cover.childAt(0);
  48953. mainEl.useStyle(makeStyle(brushOption));
  48954. mainEl.attr({
  48955. silent: !transformable,
  48956. cursor: transformable ? 'move' : 'default'
  48957. });
  48958. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  48959. var el = cover.childOfName(nameSequence.join(''));
  48960. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  48961. el && el.attr({
  48962. silent: !transformable,
  48963. invisible: !transformable,
  48964. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48965. });
  48966. });
  48967. }
  48968. function updateRectShape(controller, cover, name, x, y, w, h) {
  48969. var el = cover.childOfName(name);
  48970. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  48971. }
  48972. function makeStyle(brushOption) {
  48973. return defaults({
  48974. strokeNoScale: true
  48975. }, brushOption.brushStyle);
  48976. }
  48977. function formatRectRange(x, y, x2, y2) {
  48978. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  48979. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  48980. return [[min[0], max[0]], [min[1], max[1]] // y range
  48981. ];
  48982. }
  48983. function getTransform$1(controller) {
  48984. return getTransform(controller.group);
  48985. }
  48986. function getGlobalDirection1(controller, localDirName) {
  48987. var map = {
  48988. w: 'left',
  48989. e: 'right',
  48990. n: 'top',
  48991. s: 'bottom'
  48992. };
  48993. var inverseMap = {
  48994. left: 'w',
  48995. right: 'e',
  48996. top: 'n',
  48997. bottom: 's'
  48998. };
  48999. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  49000. return inverseMap[dir];
  49001. }
  49002. function getGlobalDirection2(controller, localDirNameSeq) {
  49003. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  49004. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  49005. return globalDir.join('');
  49006. }
  49007. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  49008. var brushOption = cover.__brushOption;
  49009. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  49010. var localDelta = toLocalDelta(controller, dx, dy);
  49011. each(dirNameSequence, function (dirName) {
  49012. var ind = DIRECTION_MAP[dirName];
  49013. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  49014. });
  49015. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  49016. updateCoverAfterCreation(controller, cover);
  49017. trigger(controller, {
  49018. isEnd: false
  49019. });
  49020. }
  49021. function driftPolygon(controller, cover, dx, dy) {
  49022. var range = cover.__brushOption.range;
  49023. var localDelta = toLocalDelta(controller, dx, dy);
  49024. each(range, function (point) {
  49025. point[0] += localDelta[0];
  49026. point[1] += localDelta[1];
  49027. });
  49028. updateCoverAfterCreation(controller, cover);
  49029. trigger(controller, {
  49030. isEnd: false
  49031. });
  49032. }
  49033. function toLocalDelta(controller, dx, dy) {
  49034. var thisGroup = controller.group;
  49035. var localD = thisGroup.transformCoordToLocal(dx, dy);
  49036. var localZero = thisGroup.transformCoordToLocal(0, 0);
  49037. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  49038. }
  49039. function clipByPanel(controller, cover, data) {
  49040. var panel = getPanelByCover(controller, cover);
  49041. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  49042. }
  49043. function pointsToRect(points) {
  49044. var xmin = mathMin$7(points[0][0], points[1][0]);
  49045. var ymin = mathMin$7(points[0][1], points[1][1]);
  49046. var xmax = mathMax$7(points[0][0], points[1][0]);
  49047. var ymax = mathMax$7(points[0][1], points[1][1]);
  49048. return {
  49049. x: xmin,
  49050. y: ymin,
  49051. width: xmax - xmin,
  49052. height: ymax - ymin
  49053. };
  49054. }
  49055. function resetCursor(controller, e, localCursorPoint) {
  49056. if (
  49057. // Check active
  49058. !controller._brushType
  49059. // resetCursor should be always called when mouse is in zr area,
  49060. // but not called when mouse is out of zr area to avoid bad influence
  49061. // if `mousemove`, `mouseup` are triggered from `document` event.
  49062. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  49063. return;
  49064. }
  49065. var zr = controller._zr;
  49066. var covers = controller._covers;
  49067. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  49068. // Check whether in covers.
  49069. if (!controller._dragging) {
  49070. for (var i = 0; i < covers.length; i++) {
  49071. var brushOption = covers[i].__brushOption;
  49072. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  49073. // Use cursor style set on cover.
  49074. return;
  49075. }
  49076. }
  49077. }
  49078. currPanel && zr.setCursorStyle('crosshair');
  49079. }
  49080. function preventDefault(e) {
  49081. var rawE = e.event;
  49082. rawE.preventDefault && rawE.preventDefault();
  49083. }
  49084. function mainShapeContain(cover, x, y) {
  49085. return cover.childOfName('main').contain(x, y);
  49086. }
  49087. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  49088. var creatingCover = controller._creatingCover;
  49089. var panel = controller._creatingPanel;
  49090. var thisBrushOption = controller._brushOption;
  49091. var eventParams;
  49092. controller._track.push(localCursorPoint.slice());
  49093. if (shouldShowCover(controller) || creatingCover) {
  49094. if (panel && !creatingCover) {
  49095. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  49096. var brushOption = clone(thisBrushOption);
  49097. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  49098. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  49099. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  49100. controller._covers.push(creatingCover);
  49101. }
  49102. if (creatingCover) {
  49103. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  49104. var coverBrushOption = creatingCover.__brushOption;
  49105. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  49106. if (isEnd) {
  49107. endCreating(controller, creatingCover);
  49108. coverRenderer.updateCommon(controller, creatingCover);
  49109. }
  49110. updateCoverShape(controller, creatingCover);
  49111. eventParams = {
  49112. isEnd: isEnd
  49113. };
  49114. }
  49115. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  49116. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  49117. // But a single click do not clear covers, because user may have casual
  49118. // clicks (for example, click on other component and do not expect covers
  49119. // disappear).
  49120. // Only some cover removed, trigger action, but not every click trigger action.
  49121. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  49122. eventParams = {
  49123. isEnd: isEnd,
  49124. removeOnClick: true
  49125. };
  49126. }
  49127. }
  49128. return eventParams;
  49129. }
  49130. function determineBrushType(brushType, panel) {
  49131. if (brushType === 'auto') {
  49132. if ("development" !== 'production') {
  49133. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  49134. }
  49135. return panel.defaultBrushType;
  49136. }
  49137. return brushType;
  49138. }
  49139. var pointerHandlers = {
  49140. mousedown: function (e) {
  49141. if (this._dragging) {
  49142. // In case some browser do not support globalOut,
  49143. // and release mouse out side the browser.
  49144. handleDragEnd(this, e);
  49145. } else if (!e.target || !e.target.draggable) {
  49146. preventDefault(e);
  49147. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  49148. this._creatingCover = null;
  49149. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  49150. if (panel) {
  49151. this._dragging = true;
  49152. this._track = [localCursorPoint.slice()];
  49153. }
  49154. }
  49155. },
  49156. mousemove: function (e) {
  49157. var x = e.offsetX;
  49158. var y = e.offsetY;
  49159. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  49160. resetCursor(this, e, localCursorPoint);
  49161. if (this._dragging) {
  49162. preventDefault(e);
  49163. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  49164. eventParams && trigger(this, eventParams);
  49165. }
  49166. },
  49167. mouseup: function (e) {
  49168. handleDragEnd(this, e);
  49169. }
  49170. };
  49171. function handleDragEnd(controller, e) {
  49172. if (controller._dragging) {
  49173. preventDefault(e);
  49174. var x = e.offsetX;
  49175. var y = e.offsetY;
  49176. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  49177. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  49178. controller._dragging = false;
  49179. controller._track = [];
  49180. controller._creatingCover = null;
  49181. // trigger event should be at final, after procedure will be nested.
  49182. eventParams && trigger(controller, eventParams);
  49183. }
  49184. }
  49185. function isOutsideZrArea(controller, x, y) {
  49186. var zr = controller._zr;
  49187. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  49188. }
  49189. /**
  49190. * key: brushType
  49191. */
  49192. var coverRenderers = {
  49193. lineX: getLineRenderer(0),
  49194. lineY: getLineRenderer(1),
  49195. rect: {
  49196. createCover: function (controller, brushOption) {
  49197. function returnInput(range) {
  49198. return range;
  49199. }
  49200. return createBaseRectCover({
  49201. toRectRange: returnInput,
  49202. fromRectRange: returnInput
  49203. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  49204. },
  49205. getCreatingRange: function (localTrack) {
  49206. var ends = getTrackEnds(localTrack);
  49207. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  49208. },
  49209. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49210. updateBaseRect(controller, cover, localRange, brushOption);
  49211. },
  49212. updateCommon: updateCommon,
  49213. contain: mainShapeContain
  49214. },
  49215. polygon: {
  49216. createCover: function (controller, brushOption) {
  49217. var cover = new Group();
  49218. // Do not use graphic.Polygon because graphic.Polyline do not close the
  49219. // border of the shape when drawing, which is a better experience for user.
  49220. cover.add(new Polyline({
  49221. name: 'main',
  49222. style: makeStyle(brushOption),
  49223. silent: true
  49224. }));
  49225. return cover;
  49226. },
  49227. getCreatingRange: function (localTrack) {
  49228. return localTrack;
  49229. },
  49230. endCreating: function (controller, cover) {
  49231. cover.remove(cover.childAt(0));
  49232. // Use graphic.Polygon close the shape.
  49233. cover.add(new Polygon({
  49234. name: 'main',
  49235. draggable: true,
  49236. drift: curry(driftPolygon, controller, cover),
  49237. ondragend: curry(trigger, controller, {
  49238. isEnd: true
  49239. })
  49240. }));
  49241. },
  49242. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49243. cover.childAt(0).setShape({
  49244. points: clipByPanel(controller, cover, localRange)
  49245. });
  49246. },
  49247. updateCommon: updateCommon,
  49248. contain: mainShapeContain
  49249. }
  49250. };
  49251. function getLineRenderer(xyIndex) {
  49252. return {
  49253. createCover: function (controller, brushOption) {
  49254. return createBaseRectCover({
  49255. toRectRange: function (range) {
  49256. var rectRange = [range, [0, 100]];
  49257. xyIndex && rectRange.reverse();
  49258. return rectRange;
  49259. },
  49260. fromRectRange: function (rectRange) {
  49261. return rectRange[xyIndex];
  49262. }
  49263. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  49264. },
  49265. getCreatingRange: function (localTrack) {
  49266. var ends = getTrackEnds(localTrack);
  49267. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  49268. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  49269. return [min, max];
  49270. },
  49271. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49272. var otherExtent;
  49273. // If brushWidth not specified, fit the panel.
  49274. var panel = getPanelByCover(controller, cover);
  49275. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  49276. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  49277. } else {
  49278. var zr = controller._zr;
  49279. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  49280. }
  49281. var rectRange = [localRange, otherExtent];
  49282. xyIndex && rectRange.reverse();
  49283. updateBaseRect(controller, cover, rectRange, brushOption);
  49284. },
  49285. updateCommon: updateCommon,
  49286. contain: mainShapeContain
  49287. };
  49288. }
  49289. /*
  49290. * Licensed to the Apache Software Foundation (ASF) under one
  49291. * or more contributor license agreements. See the NOTICE file
  49292. * distributed with this work for additional information
  49293. * regarding copyright ownership. The ASF licenses this file
  49294. * to you under the Apache License, Version 2.0 (the
  49295. * "License"); you may not use this file except in compliance
  49296. * with the License. You may obtain a copy of the License at
  49297. *
  49298. * http://www.apache.org/licenses/LICENSE-2.0
  49299. *
  49300. * Unless required by applicable law or agreed to in writing,
  49301. * software distributed under the License is distributed on an
  49302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49303. * KIND, either express or implied. See the License for the
  49304. * specific language governing permissions and limitations
  49305. * under the License.
  49306. */
  49307. /**
  49308. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49309. */
  49310. /*
  49311. * Licensed to the Apache Software Foundation (ASF) under one
  49312. * or more contributor license agreements. See the NOTICE file
  49313. * distributed with this work for additional information
  49314. * regarding copyright ownership. The ASF licenses this file
  49315. * to you under the Apache License, Version 2.0 (the
  49316. * "License"); you may not use this file except in compliance
  49317. * with the License. You may obtain a copy of the License at
  49318. *
  49319. * http://www.apache.org/licenses/LICENSE-2.0
  49320. *
  49321. * Unless required by applicable law or agreed to in writing,
  49322. * software distributed under the License is distributed on an
  49323. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49324. * KIND, either express or implied. See the License for the
  49325. * specific language governing permissions and limitations
  49326. * under the License.
  49327. */
  49328. var IRRELEVANT_EXCLUDES = {
  49329. 'axisPointer': 1,
  49330. 'tooltip': 1,
  49331. 'brush': 1
  49332. };
  49333. /**
  49334. * Avoid that: mouse click on a elements that is over geo or graph,
  49335. * but roam is triggered.
  49336. */
  49337. function onIrrelevantElement(e, api, targetCoordSysModel) {
  49338. var model = api.getComponentByElement(e.topTarget);
  49339. // If model is axisModel, it works only if it is injected with coordinateSystem.
  49340. var coordSys = model && model.coordinateSystem;
  49341. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  49342. }
  49343. function makeRectPanelClipPath(rect) {
  49344. rect = normalizeRect(rect);
  49345. return function (localPoints) {
  49346. return clipPointsByRect(localPoints, rect);
  49347. };
  49348. }
  49349. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  49350. rect = normalizeRect(rect);
  49351. return function (xyIndex) {
  49352. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  49353. var brushWidth = idx ? rect.width : rect.height;
  49354. var base = idx ? rect.x : rect.y;
  49355. return [base, base + (brushWidth || 0)];
  49356. };
  49357. }
  49358. function makeRectIsTargetByCursor(rect, api, targetModel) {
  49359. var boundingRect = normalizeRect(rect);
  49360. return function (e, localCursorPoint) {
  49361. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  49362. };
  49363. }
  49364. // Consider width/height is negative.
  49365. function normalizeRect(rect) {
  49366. return BoundingRect.create(rect);
  49367. }
  49368. // FIXME
  49369. // how to genarialize to more coordinate systems.
  49370. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  49371. var BrushTargetManager = /** @class */function () {
  49372. /**
  49373. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  49374. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  49375. * @param opt.include include coordinate system types.
  49376. */
  49377. function BrushTargetManager(finder, ecModel, opt) {
  49378. var _this = this;
  49379. this._targetInfoList = [];
  49380. var foundCpts = parseFinder$1(ecModel, finder);
  49381. each(targetInfoBuilders, function (builder, type) {
  49382. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  49383. builder(foundCpts, _this._targetInfoList);
  49384. }
  49385. });
  49386. }
  49387. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  49388. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49389. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  49390. // area.coordRange is the first of area.coordRanges
  49391. if (!area.coordRange) {
  49392. area.coordRange = coordRange;
  49393. // In 'category' axis, coord to pixel is not reversible, so we can not
  49394. // rebuild range by coordRange accrately, which may bring trouble when
  49395. // brushing only one item. So we use __rangeOffset to rebuilding range
  49396. // by coordRange. And this it only used in brush component so it is no
  49397. // need to be adapted to coordRanges.
  49398. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  49399. area.__rangeOffset = {
  49400. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  49401. xyMinMax: result.xyMinMax
  49402. };
  49403. }
  49404. });
  49405. return areas;
  49406. };
  49407. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  49408. each(areas, function (area) {
  49409. var targetInfo = this.findTargetInfo(area, ecModel);
  49410. if (targetInfo && targetInfo !== true) {
  49411. each(targetInfo.coordSyses, function (coordSys) {
  49412. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  49413. cb(area, result.values, coordSys, ecModel);
  49414. });
  49415. }
  49416. }, this);
  49417. };
  49418. /**
  49419. * the `areas` is `BrushModel.areas`.
  49420. * Called in layout stage.
  49421. * convert `area.coordRange` to global range and set panelId to `area.range`.
  49422. */
  49423. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  49424. each(areas, function (area) {
  49425. var targetInfo = this.findTargetInfo(area, ecModel);
  49426. if ("development" !== 'production') {
  49427. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  49428. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  49429. }
  49430. area.range = area.range || [];
  49431. // convert coordRange to global range and set panelId.
  49432. if (targetInfo && targetInfo !== true) {
  49433. area.panelId = targetInfo.panelId;
  49434. // (1) area.range should always be calculate from coordRange but does
  49435. // not keep its original value, for the sake of the dataZoom scenario,
  49436. // where area.coordRange remains unchanged but area.range may be changed.
  49437. // (2) Only support converting one coordRange to pixel range in brush
  49438. // component. So do not consider `coordRanges`.
  49439. // (3) About __rangeOffset, see comment above.
  49440. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  49441. var rangeOffset = area.__rangeOffset;
  49442. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  49443. }
  49444. }, this);
  49445. };
  49446. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  49447. return map(this._targetInfoList, function (targetInfo) {
  49448. var rect = targetInfo.getPanelRect();
  49449. return {
  49450. panelId: targetInfo.panelId,
  49451. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  49452. clipPath: makeRectPanelClipPath(rect),
  49453. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  49454. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  49455. };
  49456. });
  49457. };
  49458. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  49459. // Check whether area is bound in coord, and series do not belong to that coord.
  49460. // If do not do this check, some brush (like lineX) will controll all axes.
  49461. var targetInfo = this.findTargetInfo(area, ecModel);
  49462. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  49463. };
  49464. /**
  49465. * If return Object, a coord found.
  49466. * If return true, global found.
  49467. * Otherwise nothing found.
  49468. */
  49469. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  49470. var targetInfoList = this._targetInfoList;
  49471. var foundCpts = parseFinder$1(ecModel, area);
  49472. for (var i = 0; i < targetInfoList.length; i++) {
  49473. var targetInfo = targetInfoList[i];
  49474. var areaPanelId = area.panelId;
  49475. if (areaPanelId) {
  49476. if (targetInfo.panelId === areaPanelId) {
  49477. return targetInfo;
  49478. }
  49479. } else {
  49480. for (var j = 0; j < targetInfoMatchers.length; j++) {
  49481. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  49482. return targetInfo;
  49483. }
  49484. }
  49485. }
  49486. }
  49487. return true;
  49488. };
  49489. return BrushTargetManager;
  49490. }();
  49491. function formatMinMax(minMax) {
  49492. minMax[0] > minMax[1] && minMax.reverse();
  49493. return minMax;
  49494. }
  49495. function parseFinder$1(ecModel, finder) {
  49496. return parseFinder(ecModel, finder, {
  49497. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  49498. });
  49499. }
  49500. var targetInfoBuilders = {
  49501. grid: function (foundCpts, targetInfoList) {
  49502. var xAxisModels = foundCpts.xAxisModels;
  49503. var yAxisModels = foundCpts.yAxisModels;
  49504. var gridModels = foundCpts.gridModels;
  49505. // Remove duplicated.
  49506. var gridModelMap = createHashMap();
  49507. var xAxesHas = {};
  49508. var yAxesHas = {};
  49509. if (!xAxisModels && !yAxisModels && !gridModels) {
  49510. return;
  49511. }
  49512. each(xAxisModels, function (axisModel) {
  49513. var gridModel = axisModel.axis.grid.model;
  49514. gridModelMap.set(gridModel.id, gridModel);
  49515. xAxesHas[gridModel.id] = true;
  49516. });
  49517. each(yAxisModels, function (axisModel) {
  49518. var gridModel = axisModel.axis.grid.model;
  49519. gridModelMap.set(gridModel.id, gridModel);
  49520. yAxesHas[gridModel.id] = true;
  49521. });
  49522. each(gridModels, function (gridModel) {
  49523. gridModelMap.set(gridModel.id, gridModel);
  49524. xAxesHas[gridModel.id] = true;
  49525. yAxesHas[gridModel.id] = true;
  49526. });
  49527. gridModelMap.each(function (gridModel) {
  49528. var grid = gridModel.coordinateSystem;
  49529. var cartesians = [];
  49530. each(grid.getCartesians(), function (cartesian, index) {
  49531. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  49532. cartesians.push(cartesian);
  49533. }
  49534. });
  49535. targetInfoList.push({
  49536. panelId: 'grid--' + gridModel.id,
  49537. gridModel: gridModel,
  49538. coordSysModel: gridModel,
  49539. // Use the first one as the representitive coordSys.
  49540. coordSys: cartesians[0],
  49541. coordSyses: cartesians,
  49542. getPanelRect: panelRectBuilders.grid,
  49543. xAxisDeclared: xAxesHas[gridModel.id],
  49544. yAxisDeclared: yAxesHas[gridModel.id]
  49545. });
  49546. });
  49547. },
  49548. geo: function (foundCpts, targetInfoList) {
  49549. each(foundCpts.geoModels, function (geoModel) {
  49550. var coordSys = geoModel.coordinateSystem;
  49551. targetInfoList.push({
  49552. panelId: 'geo--' + geoModel.id,
  49553. geoModel: geoModel,
  49554. coordSysModel: geoModel,
  49555. coordSys: coordSys,
  49556. coordSyses: [coordSys],
  49557. getPanelRect: panelRectBuilders.geo
  49558. });
  49559. });
  49560. }
  49561. };
  49562. var targetInfoMatchers = [
  49563. // grid
  49564. function (foundCpts, targetInfo) {
  49565. var xAxisModel = foundCpts.xAxisModel;
  49566. var yAxisModel = foundCpts.yAxisModel;
  49567. var gridModel = foundCpts.gridModel;
  49568. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  49569. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  49570. return gridModel && gridModel === targetInfo.gridModel;
  49571. },
  49572. // geo
  49573. function (foundCpts, targetInfo) {
  49574. var geoModel = foundCpts.geoModel;
  49575. return geoModel && geoModel === targetInfo.geoModel;
  49576. }];
  49577. var panelRectBuilders = {
  49578. grid: function () {
  49579. // grid is not Transformable.
  49580. return this.coordSys.master.getRect().clone();
  49581. },
  49582. geo: function () {
  49583. var coordSys = this.coordSys;
  49584. var rect = coordSys.getBoundingRect().clone();
  49585. // geo roam and zoom transform
  49586. rect.applyTransform(getTransform(coordSys));
  49587. return rect;
  49588. }
  49589. };
  49590. var coordConvert = {
  49591. lineX: curry(axisConvert, 0),
  49592. lineY: curry(axisConvert, 1),
  49593. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  49594. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  49595. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  49596. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  49597. return {
  49598. values: values,
  49599. xyMinMax: values
  49600. };
  49601. },
  49602. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  49603. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  49604. var values = map(rangeOrCoordRange, function (item) {
  49605. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  49606. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  49607. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  49608. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  49609. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  49610. return p;
  49611. });
  49612. return {
  49613. values: values,
  49614. xyMinMax: xyMinMax
  49615. };
  49616. }
  49617. };
  49618. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  49619. if ("development" !== 'production') {
  49620. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  49621. }
  49622. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  49623. var values = formatMinMax(map([0, 1], function (i) {
  49624. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  49625. }));
  49626. var xyMinMax = [];
  49627. xyMinMax[axisNameIndex] = values;
  49628. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  49629. return {
  49630. values: values,
  49631. xyMinMax: xyMinMax
  49632. };
  49633. }
  49634. var diffProcessor = {
  49635. lineX: curry(axisDiffProcessor, 0),
  49636. lineY: curry(axisDiffProcessor, 1),
  49637. rect: function (values, refer, scales) {
  49638. return [[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]], [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]];
  49639. },
  49640. polygon: function (values, refer, scales) {
  49641. return map(values, function (item, idx) {
  49642. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  49643. });
  49644. }
  49645. };
  49646. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  49647. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  49648. }
  49649. // We have to process scale caused by dataZoom manually,
  49650. // although it might be not accurate.
  49651. // Return [0~1, 0~1]
  49652. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  49653. var sizeCurr = getSize$1(xyMinMaxCurr);
  49654. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  49655. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  49656. isNaN(scales[0]) && (scales[0] = 1);
  49657. isNaN(scales[1]) && (scales[1] = 1);
  49658. return scales;
  49659. }
  49660. function getSize$1(xyMinMax) {
  49661. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  49662. }
  49663. var each$6 = each;
  49664. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  49665. var DataZoomFeature = /** @class */function (_super) {
  49666. __extends(DataZoomFeature, _super);
  49667. function DataZoomFeature() {
  49668. return _super !== null && _super.apply(this, arguments) || this;
  49669. }
  49670. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  49671. if (!this._brushController) {
  49672. this._brushController = new BrushController(api.getZr());
  49673. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  49674. }
  49675. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  49676. updateBackBtnStatus(featureModel, ecModel);
  49677. };
  49678. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  49679. handlers[type].call(this);
  49680. };
  49681. DataZoomFeature.prototype.remove = function (ecModel, api) {
  49682. this._brushController && this._brushController.unmount();
  49683. };
  49684. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  49685. this._brushController && this._brushController.dispose();
  49686. };
  49687. DataZoomFeature.prototype._onBrush = function (eventParam) {
  49688. var areas = eventParam.areas;
  49689. if (!eventParam.isEnd || !areas.length) {
  49690. return;
  49691. }
  49692. var snapshot = {};
  49693. var ecModel = this.ecModel;
  49694. this._brushController.updateCovers([]); // remove cover
  49695. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  49696. include: ['grid']
  49697. });
  49698. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49699. if (coordSys.type !== 'cartesian2d') {
  49700. return;
  49701. }
  49702. var brushType = area.brushType;
  49703. if (brushType === 'rect') {
  49704. setBatch('x', coordSys, coordRange[0]);
  49705. setBatch('y', coordSys, coordRange[1]);
  49706. } else {
  49707. setBatch({
  49708. lineX: 'x',
  49709. lineY: 'y'
  49710. }[brushType], coordSys, coordRange);
  49711. }
  49712. });
  49713. push(ecModel, snapshot);
  49714. this._dispatchZoomAction(snapshot);
  49715. function setBatch(dimName, coordSys, minMax) {
  49716. var axis = coordSys.getAxis(dimName);
  49717. var axisModel = axis.model;
  49718. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  49719. // Restrict range.
  49720. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  49721. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  49722. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  49723. }
  49724. dataZoomModel && (snapshot[dataZoomModel.id] = {
  49725. dataZoomId: dataZoomModel.id,
  49726. startValue: minMax[0],
  49727. endValue: minMax[1]
  49728. });
  49729. }
  49730. function findDataZoom(dimName, axisModel, ecModel) {
  49731. var found;
  49732. ecModel.eachComponent({
  49733. mainType: 'dataZoom',
  49734. subType: 'select'
  49735. }, function (dzModel) {
  49736. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  49737. has && (found = dzModel);
  49738. });
  49739. return found;
  49740. }
  49741. };
  49742. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  49743. var batch = [];
  49744. // Convert from hash map to array.
  49745. each$6(snapshot, function (batchItem, dataZoomId) {
  49746. batch.push(clone(batchItem));
  49747. });
  49748. batch.length && this.api.dispatchAction({
  49749. type: 'dataZoom',
  49750. from: this.uid,
  49751. batch: batch
  49752. });
  49753. };
  49754. DataZoomFeature.getDefaultOption = function (ecModel) {
  49755. var defaultOption = {
  49756. show: true,
  49757. filterMode: 'filter',
  49758. // Icon group
  49759. icon: {
  49760. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  49761. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  49762. },
  49763. // `zoom`, `back`
  49764. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  49765. brushStyle: {
  49766. borderWidth: 0,
  49767. color: 'rgba(210,219,238,0.2)'
  49768. }
  49769. };
  49770. return defaultOption;
  49771. };
  49772. return DataZoomFeature;
  49773. }(ToolboxFeature);
  49774. var handlers = {
  49775. zoom: function () {
  49776. var nextActive = !this._isZoomActive;
  49777. this.api.dispatchAction({
  49778. type: 'takeGlobalCursor',
  49779. key: 'dataZoomSelect',
  49780. dataZoomSelectActive: nextActive
  49781. });
  49782. },
  49783. back: function () {
  49784. this._dispatchZoomAction(pop(this.ecModel));
  49785. }
  49786. };
  49787. function makeAxisFinder(dzFeatureModel) {
  49788. var setting = {
  49789. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  49790. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  49791. xAxisId: dzFeatureModel.get('xAxisId', true),
  49792. yAxisId: dzFeatureModel.get('yAxisId', true)
  49793. };
  49794. // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  49795. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  49796. // Some old cases set like this below to close yAxis control but leave xAxis control:
  49797. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  49798. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  49799. setting.xAxisIndex = 'all';
  49800. }
  49801. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  49802. setting.yAxisIndex = 'all';
  49803. }
  49804. return setting;
  49805. }
  49806. function updateBackBtnStatus(featureModel, ecModel) {
  49807. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  49808. }
  49809. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  49810. var zoomActive = view._isZoomActive;
  49811. if (payload && payload.type === 'takeGlobalCursor') {
  49812. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  49813. }
  49814. view._isZoomActive = zoomActive;
  49815. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  49816. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  49817. include: ['grid']
  49818. });
  49819. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  49820. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  49821. });
  49822. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  49823. brushType: 'auto',
  49824. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  49825. } : false);
  49826. }
  49827. registerInternalOptionCreator('dataZoom', function (ecModel) {
  49828. var toolboxModel = ecModel.getComponent('toolbox', 0);
  49829. var featureDataZoomPath = ['feature', 'dataZoom'];
  49830. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  49831. return;
  49832. }
  49833. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  49834. var dzOptions = [];
  49835. var finder = makeAxisFinder(dzFeatureModel);
  49836. var finderResult = parseFinder(ecModel, finder);
  49837. each$6(finderResult.xAxisModels, function (axisModel) {
  49838. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  49839. });
  49840. each$6(finderResult.yAxisModels, function (axisModel) {
  49841. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  49842. });
  49843. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  49844. var axisIndex = axisModel.componentIndex;
  49845. var newOpt = {
  49846. type: 'select',
  49847. $fromToolbox: true,
  49848. // Default to be filter
  49849. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  49850. // Id for merge mapping.
  49851. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  49852. };
  49853. newOpt[axisIndexPropName] = axisIndex;
  49854. dzOptions.push(newOpt);
  49855. }
  49856. return dzOptions;
  49857. });
  49858. function install$b(registers) {
  49859. registers.registerComponentModel(ToolboxModel);
  49860. registers.registerComponentView(ToolboxView);
  49861. registerFeature('saveAsImage', SaveAsImage);
  49862. registerFeature('magicType', MagicType);
  49863. registerFeature('dataView', DataView);
  49864. registerFeature('dataZoom', DataZoomFeature);
  49865. registerFeature('restore', RestoreOption);
  49866. use(install$a);
  49867. }
  49868. var TooltipModel = /** @class */function (_super) {
  49869. __extends(TooltipModel, _super);
  49870. function TooltipModel() {
  49871. var _this = _super !== null && _super.apply(this, arguments) || this;
  49872. _this.type = TooltipModel.type;
  49873. return _this;
  49874. }
  49875. TooltipModel.type = 'tooltip';
  49876. TooltipModel.dependencies = ['axisPointer'];
  49877. TooltipModel.defaultOption = {
  49878. // zlevel: 0,
  49879. z: 60,
  49880. show: true,
  49881. // tooltip main content
  49882. showContent: true,
  49883. // 'trigger' only works on coordinate system.
  49884. // 'item' | 'axis' | 'none'
  49885. trigger: 'item',
  49886. // 'click' | 'mousemove' | 'none'
  49887. triggerOn: 'mousemove|click',
  49888. alwaysShowContent: false,
  49889. displayMode: 'single',
  49890. renderMode: 'auto',
  49891. // whether restraint content inside viewRect.
  49892. // If renderMode: 'richText', default true.
  49893. // If renderMode: 'html', defaut false (for backward compat).
  49894. confine: null,
  49895. showDelay: 0,
  49896. hideDelay: 100,
  49897. // Animation transition time, unit is second
  49898. transitionDuration: 0.4,
  49899. enterable: false,
  49900. backgroundColor: '#fff',
  49901. // box shadow
  49902. shadowBlur: 10,
  49903. shadowColor: 'rgba(0, 0, 0, .2)',
  49904. shadowOffsetX: 1,
  49905. shadowOffsetY: 2,
  49906. // tooltip border radius, unit is px, default is 4
  49907. borderRadius: 4,
  49908. // tooltip border width, unit is px, default is 0 (no border)
  49909. borderWidth: 1,
  49910. // Tooltip inside padding, default is 5 for all direction
  49911. // Array is allowed to set up, right, bottom, left, same with css
  49912. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  49913. padding: null,
  49914. // Extra css text
  49915. extraCssText: '',
  49916. // axis indicator, trigger by axis
  49917. axisPointer: {
  49918. // default is line
  49919. // legal values: 'line' | 'shadow' | 'cross'
  49920. type: 'line',
  49921. // Valid when type is line, appoint tooltip line locate on which line. Optional
  49922. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  49923. // default is 'auto', chose the axis which type is category.
  49924. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  49925. axis: 'auto',
  49926. animation: 'auto',
  49927. animationDurationUpdate: 200,
  49928. animationEasingUpdate: 'exponentialOut',
  49929. crossStyle: {
  49930. color: '#999',
  49931. width: 1,
  49932. type: 'dashed',
  49933. // TODO formatter
  49934. textStyle: {}
  49935. }
  49936. // lineStyle and shadowStyle should not be specified here,
  49937. // otherwise it will always override those styles on option.axisPointer.
  49938. },
  49939. textStyle: {
  49940. color: '#666',
  49941. fontSize: 14
  49942. }
  49943. };
  49944. return TooltipModel;
  49945. }(ComponentModel);
  49946. /* global document */
  49947. function shouldTooltipConfine(tooltipModel) {
  49948. var confineOption = tooltipModel.get('confine');
  49949. return confineOption != null ? !!confineOption
  49950. // In richText mode, the outside part can not be visible.
  49951. : tooltipModel.get('renderMode') === 'richText';
  49952. }
  49953. function testStyle(styleProps) {
  49954. if (!env.domSupported) {
  49955. return;
  49956. }
  49957. var style = document.documentElement.style;
  49958. for (var i = 0, len = styleProps.length; i < len; i++) {
  49959. if (styleProps[i] in style) {
  49960. return styleProps[i];
  49961. }
  49962. }
  49963. }
  49964. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  49965. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  49966. function toCSSVendorPrefix(styleVendor, styleProp) {
  49967. if (!styleVendor) {
  49968. return styleProp;
  49969. }
  49970. styleProp = toCamelCase(styleProp, true);
  49971. var idx = styleVendor.indexOf(styleProp);
  49972. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  49973. return styleVendor.toLowerCase();
  49974. }
  49975. function getComputedStyle(el, style) {
  49976. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  49977. return stl ? style ? stl[style] : stl : null;
  49978. }
  49979. /* global document, window */
  49980. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  49981. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform');
  49982. // eslint-disable-next-line
  49983. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  49984. function mirrorPos(pos) {
  49985. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  49986. return pos;
  49987. }
  49988. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  49989. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  49990. return '';
  49991. }
  49992. var backgroundColor = tooltipModel.get('backgroundColor');
  49993. var borderWidth = tooltipModel.get('borderWidth');
  49994. borderColor = convertToColorString(borderColor);
  49995. var arrowPos = mirrorPos(arrowPosition);
  49996. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  49997. var positionStyle = '';
  49998. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  49999. var rotateDeg;
  50000. if (indexOf(['left', 'right'], arrowPos) > -1) {
  50001. positionStyle += 'top:50%';
  50002. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  50003. } else {
  50004. positionStyle += 'left:50%';
  50005. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  50006. }
  50007. var rotateRadian = rotateDeg * Math.PI / 180;
  50008. var arrowWH = arrowSize + borderWidth;
  50009. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  50010. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  50011. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  50012. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  50013. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  50014. return "<div style=\"" + styleCss.join('') + "\"></div>";
  50015. }
  50016. function assembleTransition(duration, onlyFade) {
  50017. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  50018. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  50019. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  50020. if (!onlyFade) {
  50021. transitionOption = " " + duration + "s " + transitionCurve;
  50022. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  50023. }
  50024. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  50025. }
  50026. function assembleTransform(x, y, toString) {
  50027. // If using float on style, the final width of the dom might
  50028. // keep changing slightly while mouse move. So `toFixed(0)` them.
  50029. var x0 = x.toFixed(0) + 'px';
  50030. var y0 = y.toFixed(0) + 'px';
  50031. // not support transform, use `left` and `top` instead.
  50032. if (!env.transformSupported) {
  50033. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  50034. }
  50035. // support transform
  50036. var is3d = env.transform3dSupported;
  50037. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  50038. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  50039. }
  50040. /**
  50041. * @param {Object} textStyle
  50042. * @return {string}
  50043. * @inner
  50044. */
  50045. function assembleFont(textStyleModel) {
  50046. var cssText = [];
  50047. var fontSize = textStyleModel.get('fontSize');
  50048. var color = textStyleModel.getTextColor();
  50049. color && cssText.push('color:' + color);
  50050. cssText.push('font:' + textStyleModel.getFont());
  50051. // @ts-ignore, leave it to the tooltip refactor.
  50052. var lineHeight = retrieve2(textStyleModel.get('lineHeight'), Math.round(fontSize * 3 / 2));
  50053. fontSize && cssText.push('line-height:' + lineHeight + 'px');
  50054. var shadowColor = textStyleModel.get('textShadowColor');
  50055. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  50056. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  50057. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  50058. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  50059. each(['decoration', 'align'], function (name) {
  50060. var val = textStyleModel.get(name);
  50061. val && cssText.push('text-' + name + ':' + val);
  50062. });
  50063. return cssText.join(';');
  50064. }
  50065. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  50066. var cssText = [];
  50067. var transitionDuration = tooltipModel.get('transitionDuration');
  50068. var backgroundColor = tooltipModel.get('backgroundColor');
  50069. var shadowBlur = tooltipModel.get('shadowBlur');
  50070. var shadowColor = tooltipModel.get('shadowColor');
  50071. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  50072. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  50073. var textStyleModel = tooltipModel.getModel('textStyle');
  50074. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  50075. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  50076. cssText.push('box-shadow:' + boxShadow);
  50077. // Animation transition. Do not animate when transitionDuration is 0.
  50078. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  50079. if (backgroundColor) {
  50080. cssText.push('background-color:' + backgroundColor);
  50081. }
  50082. // Border style
  50083. each(['width', 'color', 'radius'], function (name) {
  50084. var borderName = 'border-' + name;
  50085. var camelCase = toCamelCase(borderName);
  50086. var val = tooltipModel.get(camelCase);
  50087. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  50088. });
  50089. // Text style
  50090. cssText.push(assembleFont(textStyleModel));
  50091. // Padding
  50092. if (padding != null) {
  50093. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  50094. }
  50095. return cssText.join(';') + ';';
  50096. }
  50097. // If not able to make, do not modify the input `out`.
  50098. function makeStyleCoord(out, zr, container, zrX, zrY) {
  50099. var zrPainter = zr && zr.painter;
  50100. if (container) {
  50101. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  50102. if (zrViewportRoot) {
  50103. // Some APPs might use scale on body, so we support CSS transform here.
  50104. transformLocalCoord(out, zrViewportRoot, container, zrX, zrY);
  50105. }
  50106. } else {
  50107. out[0] = zrX;
  50108. out[1] = zrY;
  50109. // xy should be based on canvas root. But tooltipContent is
  50110. // the sibling of canvas root. So padding of ec container
  50111. // should be considered here.
  50112. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  50113. if (viewportRootOffset) {
  50114. out[0] += viewportRootOffset.offsetLeft;
  50115. out[1] += viewportRootOffset.offsetTop;
  50116. }
  50117. }
  50118. out[2] = out[0] / zr.getWidth();
  50119. out[3] = out[1] / zr.getHeight();
  50120. }
  50121. var TooltipHTMLContent = /** @class */function () {
  50122. function TooltipHTMLContent(api, opt) {
  50123. this._show = false;
  50124. this._styleCoord = [0, 0, 0, 0];
  50125. this._enterable = true;
  50126. this._alwaysShowContent = false;
  50127. this._firstShow = true;
  50128. this._longHide = true;
  50129. if (env.wxa) {
  50130. return null;
  50131. }
  50132. var el = document.createElement('div');
  50133. // TODO: TYPE
  50134. el.domBelongToZr = true;
  50135. this.el = el;
  50136. var zr = this._zr = api.getZr();
  50137. var appendTo = opt.appendTo;
  50138. var container = appendTo && (isString(appendTo) ? document.querySelector(appendTo) : isDom(appendTo) ? appendTo : isFunction(appendTo) && appendTo(api.getDom()));
  50139. makeStyleCoord(this._styleCoord, zr, container, api.getWidth() / 2, api.getHeight() / 2);
  50140. (container || api.getDom()).appendChild(el);
  50141. this._api = api;
  50142. this._container = container;
  50143. // FIXME
  50144. // Is it needed to trigger zr event manually if
  50145. // the browser do not support `pointer-events: none`.
  50146. var self = this;
  50147. el.onmouseenter = function () {
  50148. // clear the timeout in hideLater and keep showing tooltip
  50149. if (self._enterable) {
  50150. clearTimeout(self._hideTimeout);
  50151. self._show = true;
  50152. }
  50153. self._inContent = true;
  50154. };
  50155. el.onmousemove = function (e) {
  50156. e = e || window.event;
  50157. if (!self._enterable) {
  50158. // `pointer-events: none` is set to tooltip content div
  50159. // if `enterable` is set as `false`, and `el.onmousemove`
  50160. // can not be triggered. But in browser that do not
  50161. // support `pointer-events`, we need to do this:
  50162. // Try trigger zrender event to avoid mouse
  50163. // in and out shape too frequently
  50164. var handler = zr.handler;
  50165. var zrViewportRoot = zr.painter.getViewportRoot();
  50166. normalizeEvent(zrViewportRoot, e, true);
  50167. handler.dispatch('mousemove', e);
  50168. }
  50169. };
  50170. el.onmouseleave = function () {
  50171. // set `_inContent` to `false` before `hideLater`
  50172. self._inContent = false;
  50173. if (self._enterable) {
  50174. if (self._show) {
  50175. self.hideLater(self._hideDelay);
  50176. }
  50177. }
  50178. };
  50179. }
  50180. /**
  50181. * Update when tooltip is rendered
  50182. */
  50183. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  50184. // FIXME
  50185. // Move this logic to ec main?
  50186. if (!this._container) {
  50187. var container = this._api.getDom();
  50188. var position = getComputedStyle(container, 'position');
  50189. var domStyle = container.style;
  50190. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  50191. domStyle.position = 'relative';
  50192. }
  50193. }
  50194. // move tooltip if chart resized
  50195. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  50196. alwaysShowContent && this._moveIfResized();
  50197. // update alwaysShowContent
  50198. this._alwaysShowContent = alwaysShowContent;
  50199. // update className
  50200. this.el.className = tooltipModel.get('className') || '';
  50201. // Hide the tooltip
  50202. // PENDING
  50203. // this.hide();
  50204. };
  50205. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  50206. clearTimeout(this._hideTimeout);
  50207. clearTimeout(this._longHideTimeout);
  50208. var el = this.el;
  50209. var style = el.style;
  50210. var styleCoord = this._styleCoord;
  50211. if (!el.innerHTML) {
  50212. style.display = 'none';
  50213. } else {
  50214. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide)
  50215. // initial transform
  50216. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '')
  50217. // If mouse occasionally move over the tooltip, a mouseout event will be
  50218. // triggered by canvas, and cause some unexpectable result like dragging
  50219. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  50220. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  50221. // scenario.
  50222. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  50223. }
  50224. this._show = true;
  50225. this._firstShow = false;
  50226. this._longHide = false;
  50227. };
  50228. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  50229. var el = this.el;
  50230. if (content == null) {
  50231. el.innerHTML = '';
  50232. return;
  50233. }
  50234. var arrow = '';
  50235. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  50236. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  50237. }
  50238. if (isString(content)) {
  50239. el.innerHTML = content + arrow;
  50240. } else if (content) {
  50241. // Clear previous
  50242. el.innerHTML = '';
  50243. if (!isArray(content)) {
  50244. content = [content];
  50245. }
  50246. for (var i = 0; i < content.length; i++) {
  50247. if (isDom(content[i]) && content[i].parentNode !== el) {
  50248. el.appendChild(content[i]);
  50249. }
  50250. }
  50251. // no arrow if empty
  50252. if (arrow && el.childNodes.length) {
  50253. // no need to create a new parent element, but it's not supported by IE 10 and older.
  50254. // const arrowEl = document.createRange().createContextualFragment(arrow);
  50255. var arrowEl = document.createElement('div');
  50256. arrowEl.innerHTML = arrow;
  50257. el.appendChild(arrowEl);
  50258. }
  50259. }
  50260. };
  50261. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  50262. this._enterable = enterable;
  50263. };
  50264. TooltipHTMLContent.prototype.getSize = function () {
  50265. var el = this.el;
  50266. return el ? [el.offsetWidth, el.offsetHeight] : [0, 0];
  50267. };
  50268. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  50269. if (!this.el) {
  50270. return;
  50271. }
  50272. var styleCoord = this._styleCoord;
  50273. makeStyleCoord(styleCoord, this._zr, this._container, zrX, zrY);
  50274. if (styleCoord[0] != null && styleCoord[1] != null) {
  50275. var style_1 = this.el.style;
  50276. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  50277. each(transforms, function (transform) {
  50278. style_1[transform[0]] = transform[1];
  50279. });
  50280. }
  50281. };
  50282. /**
  50283. * when `alwaysShowContent` is true,
  50284. * move the tooltip after chart resized
  50285. */
  50286. TooltipHTMLContent.prototype._moveIfResized = function () {
  50287. // The ratio of left to width
  50288. var ratioX = this._styleCoord[2];
  50289. // The ratio of top to height
  50290. var ratioY = this._styleCoord[3];
  50291. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  50292. };
  50293. TooltipHTMLContent.prototype.hide = function () {
  50294. var _this = this;
  50295. var style = this.el.style;
  50296. style.visibility = 'hidden';
  50297. style.opacity = '0';
  50298. env.transform3dSupported && (style.willChange = '');
  50299. this._show = false;
  50300. this._longHideTimeout = setTimeout(function () {
  50301. return _this._longHide = true;
  50302. }, 500);
  50303. };
  50304. TooltipHTMLContent.prototype.hideLater = function (time) {
  50305. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  50306. if (time) {
  50307. this._hideDelay = time;
  50308. // Set show false to avoid invoke hideLater multiple times
  50309. this._show = false;
  50310. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  50311. } else {
  50312. this.hide();
  50313. }
  50314. }
  50315. };
  50316. TooltipHTMLContent.prototype.isShow = function () {
  50317. return this._show;
  50318. };
  50319. TooltipHTMLContent.prototype.dispose = function () {
  50320. clearTimeout(this._hideTimeout);
  50321. clearTimeout(this._longHideTimeout);
  50322. var parentNode = this.el.parentNode;
  50323. parentNode && parentNode.removeChild(this.el);
  50324. this.el = this._container = null;
  50325. };
  50326. return TooltipHTMLContent;
  50327. }();
  50328. var TooltipRichContent = /** @class */function () {
  50329. function TooltipRichContent(api) {
  50330. this._show = false;
  50331. this._styleCoord = [0, 0, 0, 0];
  50332. this._alwaysShowContent = false;
  50333. this._enterable = true;
  50334. this._zr = api.getZr();
  50335. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  50336. }
  50337. /**
  50338. * Update when tooltip is rendered
  50339. */
  50340. TooltipRichContent.prototype.update = function (tooltipModel) {
  50341. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  50342. alwaysShowContent && this._moveIfResized();
  50343. // update alwaysShowContent
  50344. this._alwaysShowContent = alwaysShowContent;
  50345. };
  50346. TooltipRichContent.prototype.show = function () {
  50347. if (this._hideTimeout) {
  50348. clearTimeout(this._hideTimeout);
  50349. }
  50350. this.el.show();
  50351. this._show = true;
  50352. };
  50353. /**
  50354. * Set tooltip content
  50355. */
  50356. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  50357. var _this = this;
  50358. if (isObject(content)) {
  50359. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  50360. }
  50361. if (this.el) {
  50362. this._zr.remove(this.el);
  50363. }
  50364. var textStyleModel = tooltipModel.getModel('textStyle');
  50365. this.el = new ZRText({
  50366. style: {
  50367. rich: markupStyleCreator.richTextStyles,
  50368. text: content,
  50369. lineHeight: 22,
  50370. borderWidth: 1,
  50371. borderColor: borderColor,
  50372. textShadowColor: textStyleModel.get('textShadowColor'),
  50373. fill: tooltipModel.get(['textStyle', 'color']),
  50374. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  50375. verticalAlign: 'top',
  50376. align: 'left'
  50377. },
  50378. z: tooltipModel.get('z')
  50379. });
  50380. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  50381. _this.el.style[propName] = tooltipModel.get(propName);
  50382. });
  50383. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  50384. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  50385. });
  50386. this._zr.add(this.el);
  50387. var self = this;
  50388. this.el.on('mouseover', function () {
  50389. // clear the timeout in hideLater and keep showing tooltip
  50390. if (self._enterable) {
  50391. clearTimeout(self._hideTimeout);
  50392. self._show = true;
  50393. }
  50394. self._inContent = true;
  50395. });
  50396. this.el.on('mouseout', function () {
  50397. if (self._enterable) {
  50398. if (self._show) {
  50399. self.hideLater(self._hideDelay);
  50400. }
  50401. }
  50402. self._inContent = false;
  50403. });
  50404. };
  50405. TooltipRichContent.prototype.setEnterable = function (enterable) {
  50406. this._enterable = enterable;
  50407. };
  50408. TooltipRichContent.prototype.getSize = function () {
  50409. var el = this.el;
  50410. var bounding = this.el.getBoundingRect();
  50411. // bounding rect does not include shadow. For renderMode richText,
  50412. // if overflow, it will be cut. So calculate them accurately.
  50413. var shadowOuterSize = calcShadowOuterSize(el.style);
  50414. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  50415. };
  50416. TooltipRichContent.prototype.moveTo = function (x, y) {
  50417. var el = this.el;
  50418. if (el) {
  50419. var styleCoord = this._styleCoord;
  50420. makeStyleCoord$1(styleCoord, this._zr, x, y);
  50421. x = styleCoord[0];
  50422. y = styleCoord[1];
  50423. var style = el.style;
  50424. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  50425. var shadowOuterSize = calcShadowOuterSize(style);
  50426. // rich text x, y do not include border.
  50427. el.x = x + borderWidth + shadowOuterSize.left;
  50428. el.y = y + borderWidth + shadowOuterSize.top;
  50429. el.markRedraw();
  50430. }
  50431. };
  50432. /**
  50433. * when `alwaysShowContent` is true,
  50434. * move the tooltip after chart resized
  50435. */
  50436. TooltipRichContent.prototype._moveIfResized = function () {
  50437. // The ratio of left to width
  50438. var ratioX = this._styleCoord[2];
  50439. // The ratio of top to height
  50440. var ratioY = this._styleCoord[3];
  50441. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  50442. };
  50443. TooltipRichContent.prototype.hide = function () {
  50444. if (this.el) {
  50445. this.el.hide();
  50446. }
  50447. this._show = false;
  50448. };
  50449. TooltipRichContent.prototype.hideLater = function (time) {
  50450. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  50451. if (time) {
  50452. this._hideDelay = time;
  50453. // Set show false to avoid invoke hideLater multiple times
  50454. this._show = false;
  50455. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  50456. } else {
  50457. this.hide();
  50458. }
  50459. }
  50460. };
  50461. TooltipRichContent.prototype.isShow = function () {
  50462. return this._show;
  50463. };
  50464. TooltipRichContent.prototype.dispose = function () {
  50465. this._zr.remove(this.el);
  50466. };
  50467. return TooltipRichContent;
  50468. }();
  50469. function mathMaxWith0(val) {
  50470. return Math.max(0, val);
  50471. }
  50472. function calcShadowOuterSize(style) {
  50473. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  50474. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  50475. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  50476. return {
  50477. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  50478. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  50479. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  50480. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  50481. };
  50482. }
  50483. function makeStyleCoord$1(out, zr, zrX, zrY) {
  50484. out[0] = zrX;
  50485. out[1] = zrY;
  50486. out[2] = out[0] / zr.getWidth();
  50487. out[3] = out[1] / zr.getHeight();
  50488. }
  50489. var proxyRect = new Rect({
  50490. shape: {
  50491. x: -1,
  50492. y: -1,
  50493. width: 2,
  50494. height: 2
  50495. }
  50496. });
  50497. var TooltipView = /** @class */function (_super) {
  50498. __extends(TooltipView, _super);
  50499. function TooltipView() {
  50500. var _this = _super !== null && _super.apply(this, arguments) || this;
  50501. _this.type = TooltipView.type;
  50502. return _this;
  50503. }
  50504. TooltipView.prototype.init = function (ecModel, api) {
  50505. if (env.node || !api.getDom()) {
  50506. return;
  50507. }
  50508. var tooltipModel = ecModel.getComponent('tooltip');
  50509. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  50510. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api, {
  50511. appendTo: tooltipModel.get('appendToBody', true) ? 'body' : tooltipModel.get('appendTo', true)
  50512. });
  50513. };
  50514. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  50515. if (env.node || !api.getDom()) {
  50516. return;
  50517. }
  50518. // Reset
  50519. this.group.removeAll();
  50520. this._tooltipModel = tooltipModel;
  50521. this._ecModel = ecModel;
  50522. this._api = api;
  50523. var tooltipContent = this._tooltipContent;
  50524. tooltipContent.update(tooltipModel);
  50525. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  50526. this._initGlobalListener();
  50527. this._keepShow();
  50528. // PENDING
  50529. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  50530. // which causes that the `updatePosition` function was also called frequently.
  50531. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  50532. // To avoid frequent triggering,
  50533. // consider throttling it in 50ms when transition is enabled
  50534. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  50535. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  50536. } else {
  50537. clear(this, '_updatePosition');
  50538. }
  50539. };
  50540. TooltipView.prototype._initGlobalListener = function () {
  50541. var tooltipModel = this._tooltipModel;
  50542. var triggerOn = tooltipModel.get('triggerOn');
  50543. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  50544. // If 'none', it is not controlled by mouse totally.
  50545. if (triggerOn !== 'none') {
  50546. if (triggerOn.indexOf(currTrigger) >= 0) {
  50547. this._tryShow(e, dispatchAction);
  50548. } else if (currTrigger === 'leave') {
  50549. this._hide(dispatchAction);
  50550. }
  50551. }
  50552. }, this));
  50553. };
  50554. TooltipView.prototype._keepShow = function () {
  50555. var tooltipModel = this._tooltipModel;
  50556. var ecModel = this._ecModel;
  50557. var api = this._api;
  50558. var triggerOn = tooltipModel.get('triggerOn');
  50559. // Try to keep the tooltip show when refreshing
  50560. if (this._lastX != null && this._lastY != null
  50561. // When user is willing to control tooltip totally using API,
  50562. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  50563. // which is not expected.
  50564. && triggerOn !== 'none' && triggerOn !== 'click') {
  50565. var self_1 = this;
  50566. clearTimeout(this._refreshUpdateTimeout);
  50567. this._refreshUpdateTimeout = setTimeout(function () {
  50568. // Show tip next tick after other charts are rendered
  50569. // In case highlight action has wrong result
  50570. // FIXME
  50571. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  50572. x: self_1._lastX,
  50573. y: self_1._lastY,
  50574. dataByCoordSys: self_1._lastDataByCoordSys
  50575. });
  50576. });
  50577. }
  50578. };
  50579. /**
  50580. * Show tip manually by
  50581. * dispatchAction({
  50582. * type: 'showTip',
  50583. * x: 10,
  50584. * y: 10
  50585. * });
  50586. * Or
  50587. * dispatchAction({
  50588. * type: 'showTip',
  50589. * seriesIndex: 0,
  50590. * dataIndex or dataIndexInside or name
  50591. * });
  50592. *
  50593. * TODO Batch
  50594. */
  50595. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  50596. if (payload.from === this.uid || env.node || !api.getDom()) {
  50597. return;
  50598. }
  50599. var dispatchAction = makeDispatchAction$1(payload, api);
  50600. // Reset ticket
  50601. this._ticket = '';
  50602. // When triggered from axisPointer.
  50603. var dataByCoordSys = payload.dataByCoordSys;
  50604. var cmptRef = findComponentReference(payload, ecModel, api);
  50605. if (cmptRef) {
  50606. var rect = cmptRef.el.getBoundingRect().clone();
  50607. rect.applyTransform(cmptRef.el.transform);
  50608. this._tryShow({
  50609. offsetX: rect.x + rect.width / 2,
  50610. offsetY: rect.y + rect.height / 2,
  50611. target: cmptRef.el,
  50612. position: payload.position,
  50613. // When manully trigger, the mouse is not on the el, so we'd better to
  50614. // position tooltip on the bottom of the el and display arrow is possible.
  50615. positionDefault: 'bottom'
  50616. }, dispatchAction);
  50617. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  50618. var el = proxyRect;
  50619. el.x = payload.x;
  50620. el.y = payload.y;
  50621. el.update();
  50622. getECData(el).tooltipConfig = {
  50623. name: null,
  50624. option: payload.tooltip
  50625. };
  50626. // Manually show tooltip while view is not using zrender elements.
  50627. this._tryShow({
  50628. offsetX: payload.x,
  50629. offsetY: payload.y,
  50630. target: el
  50631. }, dispatchAction);
  50632. } else if (dataByCoordSys) {
  50633. this._tryShow({
  50634. offsetX: payload.x,
  50635. offsetY: payload.y,
  50636. position: payload.position,
  50637. dataByCoordSys: dataByCoordSys,
  50638. tooltipOption: payload.tooltipOption
  50639. }, dispatchAction);
  50640. } else if (payload.seriesIndex != null) {
  50641. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  50642. return;
  50643. }
  50644. var pointInfo = findPointFromSeries(payload, ecModel);
  50645. var cx = pointInfo.point[0];
  50646. var cy = pointInfo.point[1];
  50647. if (cx != null && cy != null) {
  50648. this._tryShow({
  50649. offsetX: cx,
  50650. offsetY: cy,
  50651. target: pointInfo.el,
  50652. position: payload.position,
  50653. // When manully trigger, the mouse is not on the el, so we'd better to
  50654. // position tooltip on the bottom of the el and display arrow is possible.
  50655. positionDefault: 'bottom'
  50656. }, dispatchAction);
  50657. }
  50658. } else if (payload.x != null && payload.y != null) {
  50659. // FIXME
  50660. // should wrap dispatchAction like `axisPointer/globalListener` ?
  50661. api.dispatchAction({
  50662. type: 'updateAxisPointer',
  50663. x: payload.x,
  50664. y: payload.y
  50665. });
  50666. this._tryShow({
  50667. offsetX: payload.x,
  50668. offsetY: payload.y,
  50669. position: payload.position,
  50670. target: api.getZr().findHover(payload.x, payload.y).target
  50671. }, dispatchAction);
  50672. }
  50673. };
  50674. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  50675. var tooltipContent = this._tooltipContent;
  50676. if (this._tooltipModel) {
  50677. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  50678. }
  50679. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  50680. if (payload.from !== this.uid) {
  50681. this._hide(makeDispatchAction$1(payload, api));
  50682. }
  50683. };
  50684. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  50685. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  50686. // and tooltip.
  50687. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  50688. var seriesIndex = payload.seriesIndex;
  50689. var dataIndex = payload.dataIndex;
  50690. // @ts-ignore
  50691. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  50692. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  50693. return;
  50694. }
  50695. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  50696. if (!seriesModel) {
  50697. return;
  50698. }
  50699. var data = seriesModel.getData();
  50700. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  50701. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  50702. return;
  50703. }
  50704. api.dispatchAction({
  50705. type: 'updateAxisPointer',
  50706. seriesIndex: seriesIndex,
  50707. dataIndex: dataIndex,
  50708. position: payload.position
  50709. });
  50710. return true;
  50711. };
  50712. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  50713. var el = e.target;
  50714. var tooltipModel = this._tooltipModel;
  50715. if (!tooltipModel) {
  50716. return;
  50717. }
  50718. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  50719. this._lastX = e.offsetX;
  50720. this._lastY = e.offsetY;
  50721. var dataByCoordSys = e.dataByCoordSys;
  50722. if (dataByCoordSys && dataByCoordSys.length) {
  50723. this._showAxisTooltip(dataByCoordSys, e);
  50724. } else if (el) {
  50725. var ecData = getECData(el);
  50726. if (ecData.ssrType === 'legend') {
  50727. // Don't trigger tooltip for legend tooltip item
  50728. return;
  50729. }
  50730. this._lastDataByCoordSys = null;
  50731. var seriesDispatcher_1;
  50732. var cmptDispatcher_1;
  50733. findEventDispatcher(el, function (target) {
  50734. // Always show item tooltip if mouse is on the element with dataIndex
  50735. if (getECData(target).dataIndex != null) {
  50736. seriesDispatcher_1 = target;
  50737. return true;
  50738. }
  50739. // Tooltip provided directly. Like legend.
  50740. if (getECData(target).tooltipConfig != null) {
  50741. cmptDispatcher_1 = target;
  50742. return true;
  50743. }
  50744. }, true);
  50745. if (seriesDispatcher_1) {
  50746. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  50747. } else if (cmptDispatcher_1) {
  50748. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  50749. } else {
  50750. this._hide(dispatchAction);
  50751. }
  50752. } else {
  50753. this._lastDataByCoordSys = null;
  50754. this._hide(dispatchAction);
  50755. }
  50756. };
  50757. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  50758. // showDelay is used in this case: tooltip.enterable is set
  50759. // as true. User intent to move mouse into tooltip and click
  50760. // something. `showDelay` makes it easier to enter the content
  50761. // but tooltip do not move immediately.
  50762. var delay = tooltipModel.get('showDelay');
  50763. cb = bind(cb, this);
  50764. clearTimeout(this._showTimout);
  50765. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  50766. };
  50767. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  50768. var ecModel = this._ecModel;
  50769. var globalTooltipModel = this._tooltipModel;
  50770. var point = [e.offsetX, e.offsetY];
  50771. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  50772. var renderMode = this._renderMode;
  50773. var cbParamsList = [];
  50774. var articleMarkup = createTooltipMarkup('section', {
  50775. blocks: [],
  50776. noHeader: true
  50777. });
  50778. // Only for legacy: `Serise['formatTooltip']` returns a string.
  50779. var markupTextArrLegacy = [];
  50780. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50781. each(dataByCoordSys, function (itemCoordSys) {
  50782. each(itemCoordSys.dataByAxis, function (axisItem) {
  50783. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  50784. var axisValue = axisItem.value;
  50785. if (!axisModel || axisValue == null) {
  50786. return;
  50787. }
  50788. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  50789. var axisSectionMarkup = createTooltipMarkup('section', {
  50790. header: axisValueLabel,
  50791. noHeader: !trim(axisValueLabel),
  50792. sortBlocks: true,
  50793. blocks: []
  50794. });
  50795. articleMarkup.blocks.push(axisSectionMarkup);
  50796. each(axisItem.seriesDataIndices, function (idxItem) {
  50797. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  50798. var dataIndex = idxItem.dataIndexInside;
  50799. var cbParams = series.getDataParams(dataIndex);
  50800. // Can't find data.
  50801. if (cbParams.dataIndex < 0) {
  50802. return;
  50803. }
  50804. cbParams.axisDim = axisItem.axisDim;
  50805. cbParams.axisIndex = axisItem.axisIndex;
  50806. cbParams.axisType = axisItem.axisType;
  50807. cbParams.axisId = axisItem.axisId;
  50808. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  50809. value: axisValue
  50810. });
  50811. cbParams.axisValueLabel = axisValueLabel;
  50812. // Pre-create marker style for makers. Users can assemble richText
  50813. // text in `formatter` callback and use those markers style.
  50814. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  50815. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  50816. var frag = seriesTooltipResult.frag;
  50817. if (frag) {
  50818. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  50819. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  50820. valueFormatter: valueFormatter
  50821. }, frag) : frag);
  50822. }
  50823. if (seriesTooltipResult.text) {
  50824. markupTextArrLegacy.push(seriesTooltipResult.text);
  50825. }
  50826. cbParamsList.push(cbParams);
  50827. });
  50828. });
  50829. });
  50830. // In most cases, the second axis is displays upper on the first one.
  50831. // So we reverse it to look better.
  50832. articleMarkup.blocks.reverse();
  50833. markupTextArrLegacy.reverse();
  50834. var positionExpr = e.position;
  50835. var orderMode = singleTooltipModel.get('order');
  50836. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  50837. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  50838. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  50839. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  50840. this._showOrMove(singleTooltipModel, function () {
  50841. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  50842. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  50843. } else {
  50844. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  50845. }
  50846. });
  50847. // Do not trigger events here, because this branch only be entered
  50848. // from dispatchAction.
  50849. };
  50850. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  50851. var ecModel = this._ecModel;
  50852. var ecData = getECData(dispatcher);
  50853. // Use dataModel in element if possible
  50854. // Used when mouseover on a element like markPoint or edge
  50855. // In which case, the data is not main data in series.
  50856. var seriesIndex = ecData.seriesIndex;
  50857. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  50858. // For example, graph link.
  50859. var dataModel = ecData.dataModel || seriesModel;
  50860. var dataIndex = ecData.dataIndex;
  50861. var dataType = ecData.dataType;
  50862. var data = dataModel.getData(dataType);
  50863. var renderMode = this._renderMode;
  50864. var positionDefault = e.positionDefault;
  50865. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  50866. position: positionDefault
  50867. } : null);
  50868. var tooltipTrigger = tooltipModel.get('trigger');
  50869. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  50870. return;
  50871. }
  50872. var params = dataModel.getDataParams(dataIndex, dataType);
  50873. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50874. // Pre-create marker style for makers. Users can assemble richText
  50875. // text in `formatter` callback and use those markers style.
  50876. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  50877. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  50878. var orderMode = tooltipModel.get('order');
  50879. var valueFormatter = tooltipModel.get('valueFormatter');
  50880. var frag = seriesTooltipResult.frag;
  50881. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  50882. valueFormatter: valueFormatter
  50883. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  50884. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  50885. this._showOrMove(tooltipModel, function () {
  50886. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  50887. });
  50888. // FIXME
  50889. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  50890. dispatchAction({
  50891. type: 'showTip',
  50892. dataIndexInside: dataIndex,
  50893. dataIndex: data.getRawIndex(dataIndex),
  50894. seriesIndex: seriesIndex,
  50895. from: this.uid
  50896. });
  50897. };
  50898. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  50899. var isHTMLRenderMode = this._renderMode === 'html';
  50900. var ecData = getECData(el);
  50901. var tooltipConfig = ecData.tooltipConfig;
  50902. var tooltipOpt = tooltipConfig.option || {};
  50903. var encodeHTMLContent = tooltipOpt.encodeHTMLContent;
  50904. if (isString(tooltipOpt)) {
  50905. var content = tooltipOpt;
  50906. tooltipOpt = {
  50907. content: content,
  50908. // Fixed formatter
  50909. formatter: content
  50910. };
  50911. // when `tooltipConfig.option` is a string rather than an object,
  50912. // we can't know if the content needs to be encoded
  50913. // for the sake of security, encode it by default.
  50914. encodeHTMLContent = true;
  50915. }
  50916. if (encodeHTMLContent && isHTMLRenderMode && tooltipOpt.content) {
  50917. // clone might be unnecessary?
  50918. tooltipOpt = clone(tooltipOpt);
  50919. tooltipOpt.content = encodeHTML(tooltipOpt.content);
  50920. }
  50921. var tooltipModelCascade = [tooltipOpt];
  50922. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  50923. if (cmpt) {
  50924. tooltipModelCascade.push(cmpt);
  50925. }
  50926. // In most cases, component tooltip formatter has different params with series tooltip formatter,
  50927. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  50928. // by convention, we do not use it as the default formatter for component.
  50929. tooltipModelCascade.push({
  50930. formatter: tooltipOpt.content
  50931. });
  50932. var positionDefault = e.positionDefault;
  50933. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  50934. position: positionDefault
  50935. } : null);
  50936. var defaultHtml = subTooltipModel.get('content');
  50937. var asyncTicket = Math.random() + '';
  50938. // PENDING: this case do not support richText style yet.
  50939. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50940. // Do not check whether `trigger` is 'none' here, because `trigger`
  50941. // only works on coordinate system. In fact, we have not found case
  50942. // that requires setting `trigger` nothing on component yet.
  50943. this._showOrMove(subTooltipModel, function () {
  50944. // Use formatterParams from element defined in component
  50945. // Avoid users modify it.
  50946. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  50947. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  50948. });
  50949. // If not dispatch showTip, tip may be hide triggered by axis.
  50950. dispatchAction({
  50951. type: 'showTip',
  50952. from: this.uid
  50953. });
  50954. };
  50955. TooltipView.prototype._showTooltipContent = function (
  50956. // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  50957. // Instead of top level tooltip.
  50958. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  50959. // Reset ticket
  50960. this._ticket = '';
  50961. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  50962. return;
  50963. }
  50964. var tooltipContent = this._tooltipContent;
  50965. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  50966. var formatter = tooltipModel.get('formatter');
  50967. positionExpr = positionExpr || tooltipModel.get('position');
  50968. var html = defaultHtml;
  50969. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  50970. var nearPointColor = nearPoint.color;
  50971. if (formatter) {
  50972. if (isString(formatter)) {
  50973. var useUTC = tooltipModel.ecModel.get('useUTC');
  50974. var params0 = isArray(params) ? params[0] : params;
  50975. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  50976. html = formatter;
  50977. if (isTimeAxis) {
  50978. html = format(params0.axisValue, html, useUTC);
  50979. }
  50980. html = formatTpl(html, params, true);
  50981. } else if (isFunction(formatter)) {
  50982. var callback = bind(function (cbTicket, html) {
  50983. if (cbTicket === this._ticket) {
  50984. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  50985. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  50986. }
  50987. }, this);
  50988. this._ticket = asyncTicket;
  50989. html = formatter(params, asyncTicket, callback);
  50990. } else {
  50991. html = formatter;
  50992. }
  50993. }
  50994. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  50995. tooltipContent.show(tooltipModel, nearPointColor);
  50996. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  50997. };
  50998. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  50999. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  51000. return {
  51001. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  51002. };
  51003. }
  51004. if (!isArray(tooltipDataParams)) {
  51005. return {
  51006. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  51007. };
  51008. }
  51009. };
  51010. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x,
  51011. // Mouse x
  51012. y,
  51013. // Mouse y
  51014. content, params, el) {
  51015. var viewWidth = this._api.getWidth();
  51016. var viewHeight = this._api.getHeight();
  51017. positionExpr = positionExpr || tooltipModel.get('position');
  51018. var contentSize = content.getSize();
  51019. var align = tooltipModel.get('align');
  51020. var vAlign = tooltipModel.get('verticalAlign');
  51021. var rect = el && el.getBoundingRect().clone();
  51022. el && rect.applyTransform(el.transform);
  51023. if (isFunction(positionExpr)) {
  51024. // Callback of position can be an array or a string specify the position
  51025. positionExpr = positionExpr([x, y], params, content.el, rect, {
  51026. viewSize: [viewWidth, viewHeight],
  51027. contentSize: contentSize.slice()
  51028. });
  51029. }
  51030. if (isArray(positionExpr)) {
  51031. x = parsePercent$1(positionExpr[0], viewWidth);
  51032. y = parsePercent$1(positionExpr[1], viewHeight);
  51033. } else if (isObject(positionExpr)) {
  51034. var boxLayoutPosition = positionExpr;
  51035. boxLayoutPosition.width = contentSize[0];
  51036. boxLayoutPosition.height = contentSize[1];
  51037. var layoutRect = getLayoutRect(boxLayoutPosition, {
  51038. width: viewWidth,
  51039. height: viewHeight
  51040. });
  51041. x = layoutRect.x;
  51042. y = layoutRect.y;
  51043. align = null;
  51044. // When positionExpr is left/top/right/bottom,
  51045. // align and verticalAlign will not work.
  51046. vAlign = null;
  51047. }
  51048. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  51049. else if (isString(positionExpr) && el) {
  51050. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  51051. x = pos[0];
  51052. y = pos[1];
  51053. } else {
  51054. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  51055. x = pos[0];
  51056. y = pos[1];
  51057. }
  51058. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  51059. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  51060. if (shouldTooltipConfine(tooltipModel)) {
  51061. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  51062. x = pos[0];
  51063. y = pos[1];
  51064. }
  51065. content.moveTo(x, y);
  51066. };
  51067. // FIXME
  51068. // Should we remove this but leave this to user?
  51069. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  51070. var lastCoordSys = this._lastDataByCoordSys;
  51071. var lastCbParamsList = this._cbParamsList;
  51072. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  51073. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  51074. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  51075. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  51076. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  51077. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  51078. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  51079. var thisItem = thisDataByAxis[indexAxis] || {};
  51080. var lastIndices = lastItem.seriesDataIndices || [];
  51081. var newIndices = thisItem.seriesDataIndices || [];
  51082. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  51083. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  51084. var newIdxItem = newIndices[j];
  51085. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  51086. });
  51087. // check is cbParams data value changed
  51088. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  51089. var seriesIdx = idxItem.seriesIndex;
  51090. var cbParams = cbParamsList[seriesIdx];
  51091. var lastCbParams = lastCbParamsList[seriesIdx];
  51092. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  51093. contentNotChanged = false;
  51094. }
  51095. });
  51096. });
  51097. });
  51098. this._lastDataByCoordSys = dataByCoordSys;
  51099. this._cbParamsList = cbParamsList;
  51100. return !!contentNotChanged;
  51101. };
  51102. TooltipView.prototype._hide = function (dispatchAction) {
  51103. // Do not directly hideLater here, because this behavior may be prevented
  51104. // in dispatchAction when showTip is dispatched.
  51105. // FIXME
  51106. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  51107. this._lastDataByCoordSys = null;
  51108. dispatchAction({
  51109. type: 'hideTip',
  51110. from: this.uid
  51111. });
  51112. };
  51113. TooltipView.prototype.dispose = function (ecModel, api) {
  51114. if (env.node || !api.getDom()) {
  51115. return;
  51116. }
  51117. clear(this, '_updatePosition');
  51118. this._tooltipContent.dispose();
  51119. unregister('itemTooltip', api);
  51120. };
  51121. TooltipView.type = 'tooltip';
  51122. return TooltipView;
  51123. }(ComponentView);
  51124. /**
  51125. * From top to bottom. (the last one should be globalTooltipModel);
  51126. */
  51127. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  51128. // Last is always tooltip model.
  51129. var ecModel = globalTooltipModel.ecModel;
  51130. var resultModel;
  51131. if (defaultTooltipOption) {
  51132. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  51133. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  51134. } else {
  51135. resultModel = globalTooltipModel;
  51136. }
  51137. for (var i = modelCascade.length - 1; i >= 0; i--) {
  51138. var tooltipOpt = modelCascade[i];
  51139. if (tooltipOpt) {
  51140. if (tooltipOpt instanceof Model) {
  51141. tooltipOpt = tooltipOpt.get('tooltip', true);
  51142. }
  51143. // In each data item tooltip can be simply write:
  51144. // {
  51145. // value: 10,
  51146. // tooltip: 'Something you need to know'
  51147. // }
  51148. if (isString(tooltipOpt)) {
  51149. tooltipOpt = {
  51150. formatter: tooltipOpt
  51151. };
  51152. }
  51153. if (tooltipOpt) {
  51154. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  51155. }
  51156. }
  51157. }
  51158. return resultModel;
  51159. }
  51160. function makeDispatchAction$1(payload, api) {
  51161. return payload.dispatchAction || bind(api.dispatchAction, api);
  51162. }
  51163. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  51164. var size = content.getSize();
  51165. var width = size[0];
  51166. var height = size[1];
  51167. if (gapH != null) {
  51168. // Add extra 2 pixels for this case:
  51169. // At present the "values" in default tooltip are using CSS `float: right`.
  51170. // When the right edge of the tooltip box is on the right side of the
  51171. // viewport, the `float` layout might push the "values" to the second line.
  51172. if (x + width + gapH + 2 > viewWidth) {
  51173. x -= width + gapH;
  51174. } else {
  51175. x += gapH;
  51176. }
  51177. }
  51178. if (gapV != null) {
  51179. if (y + height + gapV > viewHeight) {
  51180. y -= height + gapV;
  51181. } else {
  51182. y += gapV;
  51183. }
  51184. }
  51185. return [x, y];
  51186. }
  51187. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  51188. var size = content.getSize();
  51189. var width = size[0];
  51190. var height = size[1];
  51191. x = Math.min(x + width, viewWidth) - width;
  51192. y = Math.min(y + height, viewHeight) - height;
  51193. x = Math.max(x, 0);
  51194. y = Math.max(y, 0);
  51195. return [x, y];
  51196. }
  51197. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  51198. var domWidth = contentSize[0];
  51199. var domHeight = contentSize[1];
  51200. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  51201. var x = 0;
  51202. var y = 0;
  51203. var rectWidth = rect.width;
  51204. var rectHeight = rect.height;
  51205. switch (position) {
  51206. case 'inside':
  51207. x = rect.x + rectWidth / 2 - domWidth / 2;
  51208. y = rect.y + rectHeight / 2 - domHeight / 2;
  51209. break;
  51210. case 'top':
  51211. x = rect.x + rectWidth / 2 - domWidth / 2;
  51212. y = rect.y - domHeight - offset;
  51213. break;
  51214. case 'bottom':
  51215. x = rect.x + rectWidth / 2 - domWidth / 2;
  51216. y = rect.y + rectHeight + offset;
  51217. break;
  51218. case 'left':
  51219. x = rect.x - domWidth - offset;
  51220. y = rect.y + rectHeight / 2 - domHeight / 2;
  51221. break;
  51222. case 'right':
  51223. x = rect.x + rectWidth + offset;
  51224. y = rect.y + rectHeight / 2 - domHeight / 2;
  51225. }
  51226. return [x, y];
  51227. }
  51228. function isCenterAlign(align) {
  51229. return align === 'center' || align === 'middle';
  51230. }
  51231. /**
  51232. * Find target component by payload like:
  51233. * ```js
  51234. * { legendId: 'some_id', name: 'xxx' }
  51235. * { toolboxIndex: 1, name: 'xxx' }
  51236. * { geoName: 'some_name', name: 'xxx' }
  51237. * ```
  51238. * PENDING: at present only
  51239. *
  51240. * If not found, return null/undefined.
  51241. */
  51242. function findComponentReference(payload, ecModel, api) {
  51243. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  51244. var componentMainType = queryOptionMap.keys()[0];
  51245. if (!componentMainType || componentMainType === 'series') {
  51246. return;
  51247. }
  51248. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  51249. useDefault: false,
  51250. enableAll: false,
  51251. enableNone: false
  51252. });
  51253. var model = queryResult.models[0];
  51254. if (!model) {
  51255. return;
  51256. }
  51257. var view = api.getViewOfComponentModel(model);
  51258. var el;
  51259. view.group.traverse(function (subEl) {
  51260. var tooltipConfig = getECData(subEl).tooltipConfig;
  51261. if (tooltipConfig && tooltipConfig.name === payload.name) {
  51262. el = subEl;
  51263. return true; // stop
  51264. }
  51265. });
  51266. if (el) {
  51267. return {
  51268. componentMainType: componentMainType,
  51269. componentIndex: model.componentIndex,
  51270. el: el
  51271. };
  51272. }
  51273. }
  51274. function install$c(registers) {
  51275. use(install$7);
  51276. registers.registerComponentModel(TooltipModel);
  51277. registers.registerComponentView(TooltipView);
  51278. /**
  51279. * @action
  51280. * @property {string} type
  51281. * @property {number} seriesIndex
  51282. * @property {number} dataIndex
  51283. * @property {number} [x]
  51284. * @property {number} [y]
  51285. */
  51286. registers.registerAction({
  51287. type: 'showTip',
  51288. event: 'showTip',
  51289. update: 'tooltip:manuallyShowTip'
  51290. }, noop);
  51291. registers.registerAction({
  51292. type: 'hideTip',
  51293. event: 'hideTip',
  51294. update: 'tooltip:manuallyHideTip'
  51295. }, noop);
  51296. }
  51297. var TitleModel = /** @class */function (_super) {
  51298. __extends(TitleModel, _super);
  51299. function TitleModel() {
  51300. var _this = _super !== null && _super.apply(this, arguments) || this;
  51301. _this.type = TitleModel.type;
  51302. _this.layoutMode = {
  51303. type: 'box',
  51304. ignoreSize: true
  51305. };
  51306. return _this;
  51307. }
  51308. TitleModel.type = 'title';
  51309. TitleModel.defaultOption = {
  51310. // zlevel: 0,
  51311. z: 6,
  51312. show: true,
  51313. text: '',
  51314. target: 'blank',
  51315. subtext: '',
  51316. subtarget: 'blank',
  51317. left: 0,
  51318. top: 0,
  51319. backgroundColor: 'rgba(0,0,0,0)',
  51320. borderColor: '#ccc',
  51321. borderWidth: 0,
  51322. padding: 5,
  51323. itemGap: 10,
  51324. textStyle: {
  51325. fontSize: 18,
  51326. fontWeight: 'bold',
  51327. color: '#464646'
  51328. },
  51329. subtextStyle: {
  51330. fontSize: 12,
  51331. color: '#6E7079'
  51332. }
  51333. };
  51334. return TitleModel;
  51335. }(ComponentModel);
  51336. // View
  51337. var TitleView = /** @class */function (_super) {
  51338. __extends(TitleView, _super);
  51339. function TitleView() {
  51340. var _this = _super !== null && _super.apply(this, arguments) || this;
  51341. _this.type = TitleView.type;
  51342. return _this;
  51343. }
  51344. TitleView.prototype.render = function (titleModel, ecModel, api) {
  51345. this.group.removeAll();
  51346. if (!titleModel.get('show')) {
  51347. return;
  51348. }
  51349. var group = this.group;
  51350. var textStyleModel = titleModel.getModel('textStyle');
  51351. var subtextStyleModel = titleModel.getModel('subtextStyle');
  51352. var textAlign = titleModel.get('textAlign');
  51353. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  51354. var textEl = new ZRText({
  51355. style: createTextStyle(textStyleModel, {
  51356. text: titleModel.get('text'),
  51357. fill: textStyleModel.getTextColor()
  51358. }, {
  51359. disableBox: true
  51360. }),
  51361. z2: 10
  51362. });
  51363. var textRect = textEl.getBoundingRect();
  51364. var subText = titleModel.get('subtext');
  51365. var subTextEl = new ZRText({
  51366. style: createTextStyle(subtextStyleModel, {
  51367. text: subText,
  51368. fill: subtextStyleModel.getTextColor(),
  51369. y: textRect.height + titleModel.get('itemGap'),
  51370. verticalAlign: 'top'
  51371. }, {
  51372. disableBox: true
  51373. }),
  51374. z2: 10
  51375. });
  51376. var link = titleModel.get('link');
  51377. var sublink = titleModel.get('sublink');
  51378. var triggerEvent = titleModel.get('triggerEvent', true);
  51379. textEl.silent = !link && !triggerEvent;
  51380. subTextEl.silent = !sublink && !triggerEvent;
  51381. if (link) {
  51382. textEl.on('click', function () {
  51383. windowOpen(link, '_' + titleModel.get('target'));
  51384. });
  51385. }
  51386. if (sublink) {
  51387. subTextEl.on('click', function () {
  51388. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  51389. });
  51390. }
  51391. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  51392. componentType: 'title',
  51393. componentIndex: titleModel.componentIndex
  51394. } : null;
  51395. group.add(textEl);
  51396. subText && group.add(subTextEl);
  51397. // If no subText, but add subTextEl, there will be an empty line.
  51398. var groupRect = group.getBoundingRect();
  51399. var layoutOption = titleModel.getBoxLayoutParams();
  51400. layoutOption.width = groupRect.width;
  51401. layoutOption.height = groupRect.height;
  51402. var layoutRect = getLayoutRect(layoutOption, {
  51403. width: api.getWidth(),
  51404. height: api.getHeight()
  51405. }, titleModel.get('padding'));
  51406. // Adjust text align based on position
  51407. if (!textAlign) {
  51408. // Align left if title is on the left. center and right is same
  51409. textAlign = titleModel.get('left') || titleModel.get('right');
  51410. // @ts-ignore
  51411. if (textAlign === 'middle') {
  51412. textAlign = 'center';
  51413. }
  51414. // Adjust layout by text align
  51415. if (textAlign === 'right') {
  51416. layoutRect.x += layoutRect.width;
  51417. } else if (textAlign === 'center') {
  51418. layoutRect.x += layoutRect.width / 2;
  51419. }
  51420. }
  51421. if (!textVerticalAlign) {
  51422. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  51423. // @ts-ignore
  51424. if (textVerticalAlign === 'center') {
  51425. textVerticalAlign = 'middle';
  51426. }
  51427. if (textVerticalAlign === 'bottom') {
  51428. layoutRect.y += layoutRect.height;
  51429. } else if (textVerticalAlign === 'middle') {
  51430. layoutRect.y += layoutRect.height / 2;
  51431. }
  51432. textVerticalAlign = textVerticalAlign || 'top';
  51433. }
  51434. group.x = layoutRect.x;
  51435. group.y = layoutRect.y;
  51436. group.markRedraw();
  51437. var alignStyle = {
  51438. align: textAlign,
  51439. verticalAlign: textVerticalAlign
  51440. };
  51441. textEl.setStyle(alignStyle);
  51442. subTextEl.setStyle(alignStyle);
  51443. // Render background
  51444. // Get groupRect again because textAlign has been changed
  51445. groupRect = group.getBoundingRect();
  51446. var padding = layoutRect.margin;
  51447. var style = titleModel.getItemStyle(['color', 'opacity']);
  51448. style.fill = titleModel.get('backgroundColor');
  51449. var rect = new Rect({
  51450. shape: {
  51451. x: groupRect.x - padding[3],
  51452. y: groupRect.y - padding[0],
  51453. width: groupRect.width + padding[1] + padding[3],
  51454. height: groupRect.height + padding[0] + padding[2],
  51455. r: titleModel.get('borderRadius')
  51456. },
  51457. style: style,
  51458. subPixelOptimize: true,
  51459. silent: true
  51460. });
  51461. group.add(rect);
  51462. };
  51463. TitleView.type = 'title';
  51464. return TitleView;
  51465. }(ComponentView);
  51466. function install$d(registers) {
  51467. registers.registerComponentModel(TitleModel);
  51468. registers.registerComponentView(TitleView);
  51469. }
  51470. function checkMarkerInSeries(seriesOpts, markerType) {
  51471. if (!seriesOpts) {
  51472. return false;
  51473. }
  51474. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  51475. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  51476. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  51477. return true;
  51478. }
  51479. }
  51480. return false;
  51481. }
  51482. function fillLabel(opt) {
  51483. defaultEmphasis(opt, 'label', ['show']);
  51484. }
  51485. // { [componentType]: MarkerModel }
  51486. var inner$c = makeInner();
  51487. var MarkerModel = /** @class */function (_super) {
  51488. __extends(MarkerModel, _super);
  51489. function MarkerModel() {
  51490. var _this = _super !== null && _super.apply(this, arguments) || this;
  51491. _this.type = MarkerModel.type;
  51492. /**
  51493. * If marker model is created by self from series
  51494. */
  51495. _this.createdBySelf = false;
  51496. return _this;
  51497. }
  51498. /**
  51499. * @overrite
  51500. */
  51501. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  51502. if ("development" !== 'production') {
  51503. if (this.type === 'marker') {
  51504. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  51505. }
  51506. }
  51507. this.mergeDefaultAndTheme(option, ecModel);
  51508. this._mergeOption(option, ecModel, false, true);
  51509. };
  51510. MarkerModel.prototype.isAnimationEnabled = function () {
  51511. if (env.node) {
  51512. return false;
  51513. }
  51514. var hostSeries = this.__hostSeries;
  51515. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  51516. };
  51517. /**
  51518. * @overrite
  51519. */
  51520. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  51521. this._mergeOption(newOpt, ecModel, false, false);
  51522. };
  51523. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  51524. var componentType = this.mainType;
  51525. if (!createdBySelf) {
  51526. ecModel.eachSeries(function (seriesModel) {
  51527. // mainType can be markPoint, markLine, markArea
  51528. var markerOpt = seriesModel.get(this.mainType, true);
  51529. var markerModel = inner$c(seriesModel)[componentType];
  51530. if (!markerOpt || !markerOpt.data) {
  51531. inner$c(seriesModel)[componentType] = null;
  51532. return;
  51533. }
  51534. if (!markerModel) {
  51535. if (isInit) {
  51536. // Default label emphasis `position` and `show`
  51537. fillLabel(markerOpt);
  51538. }
  51539. each(markerOpt.data, function (item) {
  51540. // FIXME Overwrite fillLabel method ?
  51541. if (item instanceof Array) {
  51542. fillLabel(item[0]);
  51543. fillLabel(item[1]);
  51544. } else {
  51545. fillLabel(item);
  51546. }
  51547. });
  51548. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel);
  51549. // markerModel = new ImplementedMarkerModel(
  51550. // markerOpt, this, ecModel
  51551. // );
  51552. extend(markerModel, {
  51553. mainType: this.mainType,
  51554. // Use the same series index and name
  51555. seriesIndex: seriesModel.seriesIndex,
  51556. name: seriesModel.name,
  51557. createdBySelf: true
  51558. });
  51559. markerModel.__hostSeries = seriesModel;
  51560. } else {
  51561. markerModel._mergeOption(markerOpt, ecModel, true);
  51562. }
  51563. inner$c(seriesModel)[componentType] = markerModel;
  51564. }, this);
  51565. }
  51566. };
  51567. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  51568. var data = this.getData();
  51569. var value = this.getRawValue(dataIndex);
  51570. var itemName = data.getName(dataIndex);
  51571. return createTooltipMarkup('section', {
  51572. header: this.name,
  51573. blocks: [createTooltipMarkup('nameValue', {
  51574. name: itemName,
  51575. value: value,
  51576. noName: !itemName,
  51577. noValue: value == null
  51578. })]
  51579. });
  51580. };
  51581. MarkerModel.prototype.getData = function () {
  51582. return this._data;
  51583. };
  51584. MarkerModel.prototype.setData = function (data) {
  51585. this._data = data;
  51586. };
  51587. MarkerModel.prototype.getDataParams = function (dataIndex, dataType) {
  51588. var params = DataFormatMixin.prototype.getDataParams.call(this, dataIndex, dataType);
  51589. var hostSeries = this.__hostSeries;
  51590. if (hostSeries) {
  51591. params.seriesId = hostSeries.id;
  51592. params.seriesName = hostSeries.name;
  51593. params.seriesType = hostSeries.subType;
  51594. }
  51595. return params;
  51596. };
  51597. MarkerModel.getMarkerModelFromSeries = function (seriesModel,
  51598. // Support three types of markers. Strict check.
  51599. componentType) {
  51600. return inner$c(seriesModel)[componentType];
  51601. };
  51602. MarkerModel.type = 'marker';
  51603. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  51604. return MarkerModel;
  51605. }(ComponentModel);
  51606. mixin(MarkerModel, DataFormatMixin.prototype);
  51607. var MarkPointModel = /** @class */function (_super) {
  51608. __extends(MarkPointModel, _super);
  51609. function MarkPointModel() {
  51610. var _this = _super !== null && _super.apply(this, arguments) || this;
  51611. _this.type = MarkPointModel.type;
  51612. return _this;
  51613. }
  51614. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  51615. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  51616. };
  51617. MarkPointModel.type = 'markPoint';
  51618. MarkPointModel.defaultOption = {
  51619. // zlevel: 0,
  51620. z: 5,
  51621. symbol: 'pin',
  51622. symbolSize: 50,
  51623. // symbolRotate: 0,
  51624. // symbolOffset: [0, 0]
  51625. tooltip: {
  51626. trigger: 'item'
  51627. },
  51628. label: {
  51629. show: true,
  51630. position: 'inside'
  51631. },
  51632. itemStyle: {
  51633. borderWidth: 2
  51634. },
  51635. emphasis: {
  51636. label: {
  51637. show: true
  51638. }
  51639. }
  51640. };
  51641. return MarkPointModel;
  51642. }(MarkerModel);
  51643. function hasXOrY(item) {
  51644. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  51645. }
  51646. function hasXAndY(item) {
  51647. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  51648. }
  51649. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  51650. var coordArr = [];
  51651. var stacked = isDimensionStacked(data, targetDataDim /* , otherDataDim */);
  51652. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  51653. var value = numCalculate(data, calcDataDim, markerType);
  51654. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  51655. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  51656. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  51657. var coordArrValue = data.get(targetDataDim, dataIndex);
  51658. // Make it simple, do not visit all stacked value to count precision.
  51659. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  51660. precision = Math.min(precision, 20);
  51661. if (precision >= 0) {
  51662. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  51663. }
  51664. return [coordArr, coordArrValue];
  51665. }
  51666. // TODO Specified percent
  51667. var markerTypeCalculator = {
  51668. min: curry(markerTypeCalculatorWithExtent, 'min'),
  51669. max: curry(markerTypeCalculatorWithExtent, 'max'),
  51670. average: curry(markerTypeCalculatorWithExtent, 'average'),
  51671. median: curry(markerTypeCalculatorWithExtent, 'median')
  51672. };
  51673. /**
  51674. * Transform markPoint data item to format used in List by do the following
  51675. * 1. Calculate statistic like `max`, `min`, `average`
  51676. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  51677. */
  51678. function dataTransform(seriesModel, item) {
  51679. if (!item) {
  51680. return;
  51681. }
  51682. var data = seriesModel.getData();
  51683. var coordSys = seriesModel.coordinateSystem;
  51684. var dims = coordSys && coordSys.dimensions;
  51685. // 1. If not specify the position with pixel directly
  51686. // 2. If `coord` is not a data array. Which uses `xAxis`,
  51687. // `yAxis` to specify the coord on each dimension
  51688. // parseFloat first because item.x and item.y can be percent string like '20%'
  51689. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  51690. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  51691. // Clone the option
  51692. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  51693. item = clone(item);
  51694. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  51695. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  51696. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  51697. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  51698. item.coord = coordInfo[0];
  51699. // Force to use the value of calculated value.
  51700. // let item use the value without stack.
  51701. item.value = coordInfo[1];
  51702. } else {
  51703. // FIXME Only has one of xAxis and yAxis.
  51704. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  51705. }
  51706. }
  51707. // x y is provided
  51708. if (item.coord == null || !isArray(dims)) {
  51709. item.coord = [];
  51710. } else {
  51711. // Each coord support max, min, average
  51712. var coord = item.coord;
  51713. for (var i = 0; i < 2; i++) {
  51714. if (markerTypeCalculator[coord[i]]) {
  51715. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  51716. }
  51717. }
  51718. }
  51719. return item;
  51720. }
  51721. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  51722. var ret = {};
  51723. if (item.valueIndex != null || item.valueDim != null) {
  51724. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  51725. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  51726. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  51727. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  51728. } else {
  51729. ret.baseAxis = seriesModel.getBaseAxis();
  51730. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  51731. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  51732. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  51733. }
  51734. return ret;
  51735. }
  51736. function dataDimToCoordDim(seriesModel, dataDim) {
  51737. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  51738. return dimItem && dimItem.coordDim;
  51739. }
  51740. /**
  51741. * Filter data which is out of coordinateSystem range
  51742. * [dataFilter description]
  51743. */
  51744. function dataFilter$1(
  51745. // Currently only polar and cartesian has containData.
  51746. coordSys, item) {
  51747. // Always return true if there is no coordSys
  51748. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  51749. }
  51750. function zoneFilter(
  51751. // Currently only polar and cartesian has containData.
  51752. coordSys, item1, item2) {
  51753. // Always return true if there is no coordSys
  51754. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  51755. }
  51756. function createMarkerDimValueGetter(inCoordSys, dims) {
  51757. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  51758. var rawVal = dimIndex < 2
  51759. // x, y, radius, angle
  51760. ? item.coord && item.coord[dimIndex] : item.value;
  51761. return parseDataValue(rawVal, dims[dimIndex]);
  51762. } : function (item, dimName, dataIndex, dimIndex) {
  51763. return parseDataValue(item.value, dims[dimIndex]);
  51764. };
  51765. }
  51766. function numCalculate(data, valueDataDim, type) {
  51767. if (type === 'average') {
  51768. var sum_1 = 0;
  51769. var count_1 = 0;
  51770. data.each(valueDataDim, function (val, idx) {
  51771. if (!isNaN(val)) {
  51772. sum_1 += val;
  51773. count_1++;
  51774. }
  51775. });
  51776. return sum_1 / count_1;
  51777. } else if (type === 'median') {
  51778. return data.getMedian(valueDataDim);
  51779. } else {
  51780. // max & min
  51781. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  51782. }
  51783. }
  51784. var inner$d = makeInner();
  51785. var MarkerView = /** @class */function (_super) {
  51786. __extends(MarkerView, _super);
  51787. function MarkerView() {
  51788. var _this = _super !== null && _super.apply(this, arguments) || this;
  51789. _this.type = MarkerView.type;
  51790. return _this;
  51791. }
  51792. MarkerView.prototype.init = function () {
  51793. this.markerGroupMap = createHashMap();
  51794. };
  51795. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  51796. var _this = this;
  51797. var markerGroupMap = this.markerGroupMap;
  51798. markerGroupMap.each(function (item) {
  51799. inner$d(item).keep = false;
  51800. });
  51801. ecModel.eachSeries(function (seriesModel) {
  51802. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  51803. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  51804. });
  51805. markerGroupMap.each(function (item) {
  51806. !inner$d(item).keep && _this.group.remove(item.group);
  51807. });
  51808. };
  51809. MarkerView.prototype.markKeep = function (drawGroup) {
  51810. inner$d(drawGroup).keep = true;
  51811. };
  51812. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  51813. var _this = this;
  51814. each(seriesModelList, function (seriesModel) {
  51815. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  51816. if (markerModel) {
  51817. var data = markerModel.getData();
  51818. data.eachItemGraphicEl(function (el) {
  51819. if (el) {
  51820. isBlur ? enterBlur(el) : leaveBlur(el);
  51821. }
  51822. });
  51823. }
  51824. });
  51825. };
  51826. MarkerView.type = 'marker';
  51827. return MarkerView;
  51828. }(ComponentView);
  51829. function updateMarkerLayout(mpData, seriesModel, api) {
  51830. var coordSys = seriesModel.coordinateSystem;
  51831. mpData.each(function (idx) {
  51832. var itemModel = mpData.getItemModel(idx);
  51833. var point;
  51834. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  51835. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  51836. if (!isNaN(xPx) && !isNaN(yPx)) {
  51837. point = [xPx, yPx];
  51838. }
  51839. // Chart like bar may have there own marker positioning logic
  51840. else if (seriesModel.getMarkerPosition) {
  51841. // Use the getMarkerPosition
  51842. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  51843. } else if (coordSys) {
  51844. var x = mpData.get(coordSys.dimensions[0], idx);
  51845. var y = mpData.get(coordSys.dimensions[1], idx);
  51846. point = coordSys.dataToPoint([x, y]);
  51847. }
  51848. // Use x, y if has any
  51849. if (!isNaN(xPx)) {
  51850. point[0] = xPx;
  51851. }
  51852. if (!isNaN(yPx)) {
  51853. point[1] = yPx;
  51854. }
  51855. mpData.setItemLayout(idx, point);
  51856. });
  51857. }
  51858. var MarkPointView = /** @class */function (_super) {
  51859. __extends(MarkPointView, _super);
  51860. function MarkPointView() {
  51861. var _this = _super !== null && _super.apply(this, arguments) || this;
  51862. _this.type = MarkPointView.type;
  51863. return _this;
  51864. }
  51865. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  51866. ecModel.eachSeries(function (seriesModel) {
  51867. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  51868. if (mpModel) {
  51869. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  51870. this.markerGroupMap.get(seriesModel.id).updateLayout();
  51871. }
  51872. }, this);
  51873. };
  51874. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  51875. var coordSys = seriesModel.coordinateSystem;
  51876. var seriesId = seriesModel.id;
  51877. var seriesData = seriesModel.getData();
  51878. var symbolDrawMap = this.markerGroupMap;
  51879. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  51880. var mpData = createData(coordSys, seriesModel, mpModel);
  51881. // FIXME
  51882. mpModel.setData(mpData);
  51883. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  51884. mpData.each(function (idx) {
  51885. var itemModel = mpData.getItemModel(idx);
  51886. var symbol = itemModel.getShallow('symbol');
  51887. var symbolSize = itemModel.getShallow('symbolSize');
  51888. var symbolRotate = itemModel.getShallow('symbolRotate');
  51889. var symbolOffset = itemModel.getShallow('symbolOffset');
  51890. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect');
  51891. // TODO: refactor needed: single data item should not support callback function
  51892. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  51893. var rawIdx = mpModel.getRawValue(idx);
  51894. var dataParams = mpModel.getDataParams(idx);
  51895. if (isFunction(symbol)) {
  51896. symbol = symbol(rawIdx, dataParams);
  51897. }
  51898. if (isFunction(symbolSize)) {
  51899. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  51900. symbolSize = symbolSize(rawIdx, dataParams);
  51901. }
  51902. if (isFunction(symbolRotate)) {
  51903. symbolRotate = symbolRotate(rawIdx, dataParams);
  51904. }
  51905. if (isFunction(symbolOffset)) {
  51906. symbolOffset = symbolOffset(rawIdx, dataParams);
  51907. }
  51908. }
  51909. var style = itemModel.getModel('itemStyle').getItemStyle();
  51910. var color = getVisualFromData(seriesData, 'color');
  51911. if (!style.fill) {
  51912. style.fill = color;
  51913. }
  51914. mpData.setItemVisual(idx, {
  51915. symbol: symbol,
  51916. symbolSize: symbolSize,
  51917. symbolRotate: symbolRotate,
  51918. symbolOffset: symbolOffset,
  51919. symbolKeepAspect: symbolKeepAspect,
  51920. style: style
  51921. });
  51922. });
  51923. // TODO Text are wrong
  51924. symbolDraw.updateData(mpData);
  51925. this.group.add(symbolDraw.group);
  51926. // Set host model for tooltip
  51927. // FIXME
  51928. mpData.eachItemGraphicEl(function (el) {
  51929. el.traverse(function (child) {
  51930. getECData(child).dataModel = mpModel;
  51931. });
  51932. });
  51933. this.markKeep(symbolDraw);
  51934. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  51935. };
  51936. MarkPointView.type = 'markPoint';
  51937. return MarkPointView;
  51938. }(MarkerView);
  51939. function createData(coordSys, seriesModel, mpModel) {
  51940. var coordDimsInfos;
  51941. if (coordSys) {
  51942. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  51943. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  51944. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  51945. return extend(extend({}, info), {
  51946. name: coordDim,
  51947. // DON'T use ordinalMeta to parse and collect ordinal.
  51948. ordinalMeta: null
  51949. });
  51950. });
  51951. } else {
  51952. coordDimsInfos = [{
  51953. name: 'value',
  51954. type: 'float'
  51955. }];
  51956. }
  51957. var mpData = new SeriesData(coordDimsInfos, mpModel);
  51958. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  51959. if (coordSys) {
  51960. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  51961. }
  51962. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  51963. mpData.initData(dataOpt, null, dimValueGetter);
  51964. return mpData;
  51965. }
  51966. function install$e(registers) {
  51967. registers.registerComponentModel(MarkPointModel);
  51968. registers.registerComponentView(MarkPointView);
  51969. registers.registerPreprocessor(function (opt) {
  51970. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  51971. // Make sure markPoint component is enabled
  51972. opt.markPoint = opt.markPoint || {};
  51973. }
  51974. });
  51975. }
  51976. var MarkLineModel = /** @class */function (_super) {
  51977. __extends(MarkLineModel, _super);
  51978. function MarkLineModel() {
  51979. var _this = _super !== null && _super.apply(this, arguments) || this;
  51980. _this.type = MarkLineModel.type;
  51981. return _this;
  51982. }
  51983. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  51984. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  51985. };
  51986. MarkLineModel.type = 'markLine';
  51987. MarkLineModel.defaultOption = {
  51988. // zlevel: 0,
  51989. z: 5,
  51990. symbol: ['circle', 'arrow'],
  51991. symbolSize: [8, 16],
  51992. // symbolRotate: 0,
  51993. symbolOffset: 0,
  51994. precision: 2,
  51995. tooltip: {
  51996. trigger: 'item'
  51997. },
  51998. label: {
  51999. show: true,
  52000. position: 'end',
  52001. distance: 5
  52002. },
  52003. lineStyle: {
  52004. type: 'dashed'
  52005. },
  52006. emphasis: {
  52007. label: {
  52008. show: true
  52009. },
  52010. lineStyle: {
  52011. width: 3
  52012. }
  52013. },
  52014. animationEasing: 'linear'
  52015. };
  52016. return MarkLineModel;
  52017. }(MarkerModel);
  52018. var straightLineProto = Line.prototype;
  52019. var bezierCurveProto = BezierCurve.prototype;
  52020. var StraightLineShape = /** @class */function () {
  52021. function StraightLineShape() {
  52022. // Start point
  52023. this.x1 = 0;
  52024. this.y1 = 0;
  52025. // End point
  52026. this.x2 = 0;
  52027. this.y2 = 0;
  52028. this.percent = 1;
  52029. }
  52030. return StraightLineShape;
  52031. }();
  52032. var CurveShape = /** @class */function (_super) {
  52033. __extends(CurveShape, _super);
  52034. function CurveShape() {
  52035. return _super !== null && _super.apply(this, arguments) || this;
  52036. }
  52037. return CurveShape;
  52038. }(StraightLineShape);
  52039. function isStraightLine(shape) {
  52040. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  52041. }
  52042. var ECLinePath = /** @class */function (_super) {
  52043. __extends(ECLinePath, _super);
  52044. function ECLinePath(opts) {
  52045. var _this = _super.call(this, opts) || this;
  52046. _this.type = 'ec-line';
  52047. return _this;
  52048. }
  52049. ECLinePath.prototype.getDefaultStyle = function () {
  52050. return {
  52051. stroke: '#000',
  52052. fill: null
  52053. };
  52054. };
  52055. ECLinePath.prototype.getDefaultShape = function () {
  52056. return new StraightLineShape();
  52057. };
  52058. ECLinePath.prototype.buildPath = function (ctx, shape) {
  52059. if (isStraightLine(shape)) {
  52060. straightLineProto.buildPath.call(this, ctx, shape);
  52061. } else {
  52062. bezierCurveProto.buildPath.call(this, ctx, shape);
  52063. }
  52064. };
  52065. ECLinePath.prototype.pointAt = function (t) {
  52066. if (isStraightLine(this.shape)) {
  52067. return straightLineProto.pointAt.call(this, t);
  52068. } else {
  52069. return bezierCurveProto.pointAt.call(this, t);
  52070. }
  52071. };
  52072. ECLinePath.prototype.tangentAt = function (t) {
  52073. var shape = this.shape;
  52074. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  52075. return normalize(p, p);
  52076. };
  52077. return ECLinePath;
  52078. }(Path);
  52079. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  52080. function makeSymbolTypeKey(symbolCategory) {
  52081. return '_' + symbolCategory + 'Type';
  52082. }
  52083. function makeSymbolTypeValue(name, lineData, idx) {
  52084. var symbolType = lineData.getItemVisual(idx, name);
  52085. if (!symbolType || symbolType === 'none') {
  52086. return symbolType;
  52087. }
  52088. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52089. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52090. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52091. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52092. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52093. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52094. return symbolType + symbolSizeArr + symbolOffsetArr + (symbolRotate || '') + (symbolKeepAspect || '');
  52095. }
  52096. /**
  52097. * @inner
  52098. */
  52099. function createSymbol$1(name, lineData, idx) {
  52100. var symbolType = lineData.getItemVisual(idx, name);
  52101. if (!symbolType || symbolType === 'none') {
  52102. return;
  52103. }
  52104. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52105. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52106. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52107. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52108. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52109. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52110. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  52111. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  52112. symbolPath.name = name;
  52113. return symbolPath;
  52114. }
  52115. function createLine(points) {
  52116. var line = new ECLinePath({
  52117. name: 'line',
  52118. subPixelOptimize: true
  52119. });
  52120. setLinePoints(line.shape, points);
  52121. return line;
  52122. }
  52123. function setLinePoints(targetShape, points) {
  52124. targetShape.x1 = points[0][0];
  52125. targetShape.y1 = points[0][1];
  52126. targetShape.x2 = points[1][0];
  52127. targetShape.y2 = points[1][1];
  52128. targetShape.percent = 1;
  52129. var cp1 = points[2];
  52130. if (cp1) {
  52131. targetShape.cpx1 = cp1[0];
  52132. targetShape.cpy1 = cp1[1];
  52133. } else {
  52134. targetShape.cpx1 = NaN;
  52135. targetShape.cpy1 = NaN;
  52136. }
  52137. }
  52138. var Line$1 = /** @class */function (_super) {
  52139. __extends(Line, _super);
  52140. function Line(lineData, idx, seriesScope) {
  52141. var _this = _super.call(this) || this;
  52142. _this._createLine(lineData, idx, seriesScope);
  52143. return _this;
  52144. }
  52145. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  52146. var seriesModel = lineData.hostModel;
  52147. var linePoints = lineData.getItemLayout(idx);
  52148. var line = createLine(linePoints);
  52149. line.shape.percent = 0;
  52150. initProps(line, {
  52151. shape: {
  52152. percent: 1
  52153. }
  52154. }, seriesModel, idx);
  52155. this.add(line);
  52156. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52157. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52158. // symbols must added after line to make sure
  52159. // it will be updated after line#update.
  52160. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  52161. this.add(symbol);
  52162. this[makeSymbolTypeKey(symbolCategory)] = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52163. }, this);
  52164. this._updateCommonStl(lineData, idx, seriesScope);
  52165. };
  52166. // TODO More strict on the List type in parameters?
  52167. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  52168. var seriesModel = lineData.hostModel;
  52169. var line = this.childOfName('line');
  52170. var linePoints = lineData.getItemLayout(idx);
  52171. var target = {
  52172. shape: {}
  52173. };
  52174. setLinePoints(target.shape, linePoints);
  52175. updateProps(line, target, seriesModel, idx);
  52176. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52177. var symbolType = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52178. var key = makeSymbolTypeKey(symbolCategory);
  52179. // Symbol changed
  52180. if (this[key] !== symbolType) {
  52181. this.remove(this.childOfName(symbolCategory));
  52182. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52183. this.add(symbol);
  52184. }
  52185. this[key] = symbolType;
  52186. }, this);
  52187. this._updateCommonStl(lineData, idx, seriesScope);
  52188. };
  52189. Line.prototype.getLinePath = function () {
  52190. return this.childAt(0);
  52191. };
  52192. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  52193. var seriesModel = lineData.hostModel;
  52194. var line = this.childOfName('line');
  52195. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  52196. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  52197. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  52198. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  52199. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  52200. var focus = seriesScope && seriesScope.focus;
  52201. var blurScope = seriesScope && seriesScope.blurScope;
  52202. // Optimization for large dataset
  52203. if (!seriesScope || lineData.hasItemOption) {
  52204. var itemModel = lineData.getItemModel(idx);
  52205. var emphasisModel = itemModel.getModel('emphasis');
  52206. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  52207. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  52208. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  52209. emphasisDisabled = emphasisModel.get('disabled');
  52210. focus = emphasisModel.get('focus');
  52211. blurScope = emphasisModel.get('blurScope');
  52212. labelStatesModels = getLabelStatesModels(itemModel);
  52213. }
  52214. var lineStyle = lineData.getItemVisual(idx, 'style');
  52215. var visualColor = lineStyle.stroke;
  52216. line.useStyle(lineStyle);
  52217. line.style.fill = null;
  52218. line.style.strokeNoScale = true;
  52219. line.ensureState('emphasis').style = emphasisLineStyle;
  52220. line.ensureState('blur').style = blurLineStyle;
  52221. line.ensureState('select').style = selectLineStyle;
  52222. // Update symbol
  52223. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52224. var symbol = this.childOfName(symbolCategory);
  52225. if (symbol) {
  52226. // Share opacity and color with line.
  52227. symbol.setColor(visualColor);
  52228. symbol.style.opacity = lineStyle.opacity;
  52229. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  52230. var stateName = SPECIAL_STATES[i];
  52231. var lineState = line.getState(stateName);
  52232. if (lineState) {
  52233. var lineStateStyle = lineState.style || {};
  52234. var state = symbol.ensureState(stateName);
  52235. var stateStyle = state.style || (state.style = {});
  52236. if (lineStateStyle.stroke != null) {
  52237. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  52238. }
  52239. if (lineStateStyle.opacity != null) {
  52240. stateStyle.opacity = lineStateStyle.opacity;
  52241. }
  52242. }
  52243. }
  52244. symbol.markRedraw();
  52245. }
  52246. }, this);
  52247. var rawVal = seriesModel.getRawValue(idx);
  52248. setLabelStyle(this, labelStatesModels, {
  52249. labelDataIndex: idx,
  52250. labelFetcher: {
  52251. getFormattedLabel: function (dataIndex, stateName) {
  52252. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  52253. }
  52254. },
  52255. inheritColor: visualColor || '#000',
  52256. defaultOpacity: lineStyle.opacity,
  52257. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  52258. });
  52259. var label = this.getTextContent();
  52260. // Always set `textStyle` even if `normalStyle.text` is null, because default
  52261. // values have to be set on `normalStyle`.
  52262. if (label) {
  52263. var labelNormalModel = labelStatesModels.normal;
  52264. label.__align = label.style.align;
  52265. label.__verticalAlign = label.style.verticalAlign;
  52266. // 'start', 'middle', 'end'
  52267. label.__position = labelNormalModel.get('position') || 'middle';
  52268. var distance = labelNormalModel.get('distance');
  52269. if (!isArray(distance)) {
  52270. distance = [distance, distance];
  52271. }
  52272. label.__labelDistance = distance;
  52273. }
  52274. this.setTextConfig({
  52275. position: null,
  52276. local: true,
  52277. inside: false // Can't be inside for stroke element.
  52278. });
  52279. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  52280. };
  52281. Line.prototype.highlight = function () {
  52282. enterEmphasis(this);
  52283. };
  52284. Line.prototype.downplay = function () {
  52285. leaveEmphasis(this);
  52286. };
  52287. Line.prototype.updateLayout = function (lineData, idx) {
  52288. this.setLinePoints(lineData.getItemLayout(idx));
  52289. };
  52290. Line.prototype.setLinePoints = function (points) {
  52291. var linePath = this.childOfName('line');
  52292. setLinePoints(linePath.shape, points);
  52293. linePath.dirty();
  52294. };
  52295. Line.prototype.beforeUpdate = function () {
  52296. var lineGroup = this;
  52297. var symbolFrom = lineGroup.childOfName('fromSymbol');
  52298. var symbolTo = lineGroup.childOfName('toSymbol');
  52299. var label = lineGroup.getTextContent();
  52300. // Quick reject
  52301. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  52302. return;
  52303. }
  52304. var invScale = 1;
  52305. var parentNode = this.parent;
  52306. while (parentNode) {
  52307. if (parentNode.scaleX) {
  52308. invScale /= parentNode.scaleX;
  52309. }
  52310. parentNode = parentNode.parent;
  52311. }
  52312. var line = lineGroup.childOfName('line');
  52313. // If line not changed
  52314. // FIXME Parent scale changed
  52315. if (!this.__dirty && !line.__dirty) {
  52316. return;
  52317. }
  52318. var percent = line.shape.percent;
  52319. var fromPos = line.pointAt(0);
  52320. var toPos = line.pointAt(percent);
  52321. var d = sub([], toPos, fromPos);
  52322. normalize(d, d);
  52323. function setSymbolRotation(symbol, percent) {
  52324. // Fix #12388
  52325. // when symbol is set to be 'arrow' in markLine,
  52326. // symbolRotate value will be ignored, and compulsively use tangent angle.
  52327. // rotate by default if symbol rotation is not specified
  52328. var specifiedRotation = symbol.__specifiedRotation;
  52329. if (specifiedRotation == null) {
  52330. var tangent = line.tangentAt(percent);
  52331. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  52332. } else {
  52333. symbol.attr('rotation', specifiedRotation);
  52334. }
  52335. }
  52336. if (symbolFrom) {
  52337. symbolFrom.setPosition(fromPos);
  52338. setSymbolRotation(symbolFrom, 0);
  52339. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  52340. symbolFrom.markRedraw();
  52341. }
  52342. if (symbolTo) {
  52343. symbolTo.setPosition(toPos);
  52344. setSymbolRotation(symbolTo, 1);
  52345. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  52346. symbolTo.markRedraw();
  52347. }
  52348. if (label && !label.ignore) {
  52349. label.x = label.y = 0;
  52350. label.originX = label.originY = 0;
  52351. var textAlign = void 0;
  52352. var textVerticalAlign = void 0;
  52353. var distance = label.__labelDistance;
  52354. var distanceX = distance[0] * invScale;
  52355. var distanceY = distance[1] * invScale;
  52356. var halfPercent = percent / 2;
  52357. var tangent = line.tangentAt(halfPercent);
  52358. var n = [tangent[1], -tangent[0]];
  52359. var cp = line.pointAt(halfPercent);
  52360. if (n[1] > 0) {
  52361. n[0] = -n[0];
  52362. n[1] = -n[1];
  52363. }
  52364. var dir = tangent[0] < 0 ? -1 : 1;
  52365. if (label.__position !== 'start' && label.__position !== 'end') {
  52366. var rotation = -Math.atan2(tangent[1], tangent[0]);
  52367. if (toPos[0] < fromPos[0]) {
  52368. rotation = Math.PI + rotation;
  52369. }
  52370. label.rotation = rotation;
  52371. }
  52372. var dy = void 0;
  52373. switch (label.__position) {
  52374. case 'insideStartTop':
  52375. case 'insideMiddleTop':
  52376. case 'insideEndTop':
  52377. case 'middle':
  52378. dy = -distanceY;
  52379. textVerticalAlign = 'bottom';
  52380. break;
  52381. case 'insideStartBottom':
  52382. case 'insideMiddleBottom':
  52383. case 'insideEndBottom':
  52384. dy = distanceY;
  52385. textVerticalAlign = 'top';
  52386. break;
  52387. default:
  52388. dy = 0;
  52389. textVerticalAlign = 'middle';
  52390. }
  52391. switch (label.__position) {
  52392. case 'end':
  52393. label.x = d[0] * distanceX + toPos[0];
  52394. label.y = d[1] * distanceY + toPos[1];
  52395. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  52396. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  52397. break;
  52398. case 'start':
  52399. label.x = -d[0] * distanceX + fromPos[0];
  52400. label.y = -d[1] * distanceY + fromPos[1];
  52401. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  52402. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  52403. break;
  52404. case 'insideStartTop':
  52405. case 'insideStart':
  52406. case 'insideStartBottom':
  52407. label.x = distanceX * dir + fromPos[0];
  52408. label.y = fromPos[1] + dy;
  52409. textAlign = tangent[0] < 0 ? 'right' : 'left';
  52410. label.originX = -distanceX * dir;
  52411. label.originY = -dy;
  52412. break;
  52413. case 'insideMiddleTop':
  52414. case 'insideMiddle':
  52415. case 'insideMiddleBottom':
  52416. case 'middle':
  52417. label.x = cp[0];
  52418. label.y = cp[1] + dy;
  52419. textAlign = 'center';
  52420. label.originY = -dy;
  52421. break;
  52422. case 'insideEndTop':
  52423. case 'insideEnd':
  52424. case 'insideEndBottom':
  52425. label.x = -distanceX * dir + toPos[0];
  52426. label.y = toPos[1] + dy;
  52427. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  52428. label.originX = distanceX * dir;
  52429. label.originY = -dy;
  52430. break;
  52431. }
  52432. label.scaleX = label.scaleY = invScale;
  52433. label.setStyle({
  52434. // Use the user specified text align and baseline first
  52435. verticalAlign: label.__verticalAlign || textVerticalAlign,
  52436. align: label.__align || textAlign
  52437. });
  52438. }
  52439. };
  52440. return Line;
  52441. }(Group);
  52442. var LineDraw = /** @class */function () {
  52443. function LineDraw(LineCtor) {
  52444. this.group = new Group();
  52445. this._LineCtor = LineCtor || Line$1;
  52446. }
  52447. LineDraw.prototype.updateData = function (lineData) {
  52448. var _this = this;
  52449. // Remove progressive els.
  52450. this._progressiveEls = null;
  52451. var lineDraw = this;
  52452. var group = lineDraw.group;
  52453. var oldLineData = lineDraw._lineData;
  52454. lineDraw._lineData = lineData;
  52455. // There is no oldLineData only when first rendering or switching from
  52456. // stream mode to normal mode, where previous elements should be removed.
  52457. if (!oldLineData) {
  52458. group.removeAll();
  52459. }
  52460. var seriesScope = makeSeriesScope$1(lineData);
  52461. lineData.diff(oldLineData).add(function (idx) {
  52462. _this._doAdd(lineData, idx, seriesScope);
  52463. }).update(function (newIdx, oldIdx) {
  52464. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  52465. }).remove(function (idx) {
  52466. group.remove(oldLineData.getItemGraphicEl(idx));
  52467. }).execute();
  52468. };
  52469. LineDraw.prototype.updateLayout = function () {
  52470. var lineData = this._lineData;
  52471. // Do not support update layout in incremental mode.
  52472. if (!lineData) {
  52473. return;
  52474. }
  52475. lineData.eachItemGraphicEl(function (el, idx) {
  52476. el.updateLayout(lineData, idx);
  52477. }, this);
  52478. };
  52479. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  52480. this._seriesScope = makeSeriesScope$1(lineData);
  52481. this._lineData = null;
  52482. this.group.removeAll();
  52483. };
  52484. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  52485. this._progressiveEls = [];
  52486. function updateIncrementalAndHover(el) {
  52487. if (!el.isGroup && !isEffectObject(el)) {
  52488. el.incremental = true;
  52489. el.ensureState('emphasis').hoverLayer = true;
  52490. }
  52491. }
  52492. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  52493. var itemLayout = lineData.getItemLayout(idx);
  52494. if (lineNeedsDraw(itemLayout)) {
  52495. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  52496. el.traverse(updateIncrementalAndHover);
  52497. this.group.add(el);
  52498. lineData.setItemGraphicEl(idx, el);
  52499. this._progressiveEls.push(el);
  52500. }
  52501. }
  52502. };
  52503. LineDraw.prototype.remove = function () {
  52504. this.group.removeAll();
  52505. };
  52506. LineDraw.prototype.eachRendered = function (cb) {
  52507. traverseElements(this._progressiveEls || this.group, cb);
  52508. };
  52509. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  52510. var itemLayout = lineData.getItemLayout(idx);
  52511. if (!lineNeedsDraw(itemLayout)) {
  52512. return;
  52513. }
  52514. var el = new this._LineCtor(lineData, idx, seriesScope);
  52515. lineData.setItemGraphicEl(idx, el);
  52516. this.group.add(el);
  52517. };
  52518. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  52519. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  52520. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  52521. this.group.remove(itemEl);
  52522. return;
  52523. }
  52524. if (!itemEl) {
  52525. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  52526. } else {
  52527. itemEl.updateData(newLineData, newIdx, seriesScope);
  52528. }
  52529. newLineData.setItemGraphicEl(newIdx, itemEl);
  52530. this.group.add(itemEl);
  52531. };
  52532. return LineDraw;
  52533. }();
  52534. function isEffectObject(el) {
  52535. return el.animators && el.animators.length > 0;
  52536. }
  52537. function makeSeriesScope$1(lineData) {
  52538. var hostModel = lineData.hostModel;
  52539. var emphasisModel = hostModel.getModel('emphasis');
  52540. return {
  52541. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  52542. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  52543. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  52544. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  52545. emphasisDisabled: emphasisModel.get('disabled'),
  52546. blurScope: emphasisModel.get('blurScope'),
  52547. focus: emphasisModel.get('focus'),
  52548. labelStatesModels: getLabelStatesModels(hostModel)
  52549. };
  52550. }
  52551. function isPointNaN(pt) {
  52552. return isNaN(pt[0]) || isNaN(pt[1]);
  52553. }
  52554. function lineNeedsDraw(pts) {
  52555. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  52556. }
  52557. var inner$e = makeInner();
  52558. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  52559. var data = seriesModel.getData();
  52560. var itemArray;
  52561. if (!isArray(item)) {
  52562. // Special type markLine like 'min', 'max', 'average', 'median'
  52563. var mlType = item.type;
  52564. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  52565. // In case
  52566. // data: [{
  52567. // yAxis: 10
  52568. // }]
  52569. || item.xAxis != null || item.yAxis != null) {
  52570. var valueAxis = void 0;
  52571. var value = void 0;
  52572. if (item.yAxis != null || item.xAxis != null) {
  52573. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  52574. value = retrieve(item.yAxis, item.xAxis);
  52575. } else {
  52576. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  52577. valueAxis = axisInfo.valueAxis;
  52578. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  52579. value = numCalculate(data, valueDataDim, mlType);
  52580. }
  52581. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  52582. var baseIndex = 1 - valueIndex;
  52583. // Normized to 2d data with start and end point
  52584. var mlFrom = clone(item);
  52585. var mlTo = {
  52586. coord: []
  52587. };
  52588. mlFrom.type = null;
  52589. mlFrom.coord = [];
  52590. mlFrom.coord[baseIndex] = -Infinity;
  52591. mlTo.coord[baseIndex] = Infinity;
  52592. var precision = mlModel.get('precision');
  52593. if (precision >= 0 && isNumber(value)) {
  52594. value = +value.toFixed(Math.min(precision, 20));
  52595. }
  52596. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  52597. itemArray = [mlFrom, mlTo, {
  52598. type: mlType,
  52599. valueIndex: item.valueIndex,
  52600. // Force to use the value of calculated value.
  52601. value: value
  52602. }];
  52603. } else {
  52604. // Invalid data
  52605. if ("development" !== 'production') {
  52606. logError('Invalid markLine data.');
  52607. }
  52608. itemArray = [];
  52609. }
  52610. } else {
  52611. itemArray = item;
  52612. }
  52613. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])];
  52614. // Avoid line data type is extended by from(to) data type
  52615. normalizedItem[2].type = normalizedItem[2].type || null;
  52616. // Merge from option and to option into line option
  52617. merge(normalizedItem[2], normalizedItem[0]);
  52618. merge(normalizedItem[2], normalizedItem[1]);
  52619. return normalizedItem;
  52620. };
  52621. function isInfinity(val) {
  52622. return !isNaN(val) && !isFinite(val);
  52623. }
  52624. // If a markLine has one dim
  52625. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  52626. var otherDimIndex = 1 - dimIndex;
  52627. var dimName = coordSys.dimensions[dimIndex];
  52628. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  52629. }
  52630. function markLineFilter(coordSys, item) {
  52631. if (coordSys.type === 'cartesian2d') {
  52632. var fromCoord = item[0].coord;
  52633. var toCoord = item[1].coord;
  52634. // In case
  52635. // {
  52636. // markLine: {
  52637. // data: [{ yAxis: 2 }]
  52638. // }
  52639. // }
  52640. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  52641. return true;
  52642. }
  52643. }
  52644. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  52645. }
  52646. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  52647. var coordSys = seriesModel.coordinateSystem;
  52648. var itemModel = data.getItemModel(idx);
  52649. var point;
  52650. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  52651. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  52652. if (!isNaN(xPx) && !isNaN(yPx)) {
  52653. point = [xPx, yPx];
  52654. } else {
  52655. // Chart like bar may have there own marker positioning logic
  52656. if (seriesModel.getMarkerPosition) {
  52657. // Use the getMarkerPosition
  52658. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  52659. } else {
  52660. var dims = coordSys.dimensions;
  52661. var x = data.get(dims[0], idx);
  52662. var y = data.get(dims[1], idx);
  52663. point = coordSys.dataToPoint([x, y]);
  52664. }
  52665. // Expand line to the edge of grid if value on one axis is Inifnity
  52666. // In case
  52667. // markLine: {
  52668. // data: [{
  52669. // yAxis: 2
  52670. // // or
  52671. // type: 'average'
  52672. // }]
  52673. // }
  52674. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  52675. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  52676. var xAxis = coordSys.getAxis('x');
  52677. var yAxis = coordSys.getAxis('y');
  52678. var dims = coordSys.dimensions;
  52679. if (isInfinity(data.get(dims[0], idx))) {
  52680. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  52681. } else if (isInfinity(data.get(dims[1], idx))) {
  52682. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  52683. }
  52684. }
  52685. // Use x, y if has any
  52686. if (!isNaN(xPx)) {
  52687. point[0] = xPx;
  52688. }
  52689. if (!isNaN(yPx)) {
  52690. point[1] = yPx;
  52691. }
  52692. }
  52693. data.setItemLayout(idx, point);
  52694. }
  52695. var MarkLineView = /** @class */function (_super) {
  52696. __extends(MarkLineView, _super);
  52697. function MarkLineView() {
  52698. var _this = _super !== null && _super.apply(this, arguments) || this;
  52699. _this.type = MarkLineView.type;
  52700. return _this;
  52701. }
  52702. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  52703. ecModel.eachSeries(function (seriesModel) {
  52704. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  52705. if (mlModel) {
  52706. var mlData_1 = mlModel.getData();
  52707. var fromData_1 = inner$e(mlModel).from;
  52708. var toData_1 = inner$e(mlModel).to;
  52709. // Update visual and layout of from symbol and to symbol
  52710. fromData_1.each(function (idx) {
  52711. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  52712. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  52713. });
  52714. // Update layout of line
  52715. mlData_1.each(function (idx) {
  52716. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  52717. });
  52718. this.markerGroupMap.get(seriesModel.id).updateLayout();
  52719. }
  52720. }, this);
  52721. };
  52722. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  52723. var coordSys = seriesModel.coordinateSystem;
  52724. var seriesId = seriesModel.id;
  52725. var seriesData = seriesModel.getData();
  52726. var lineDrawMap = this.markerGroupMap;
  52727. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  52728. this.group.add(lineDraw.group);
  52729. var mlData = createList$1(coordSys, seriesModel, mlModel);
  52730. var fromData = mlData.from;
  52731. var toData = mlData.to;
  52732. var lineData = mlData.line;
  52733. inner$e(mlModel).from = fromData;
  52734. inner$e(mlModel).to = toData;
  52735. // Line data for tooltip and formatter
  52736. mlModel.setData(lineData);
  52737. // TODO
  52738. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  52739. // But the related logic and type definition are not finished yet.
  52740. // Finish it if required
  52741. var symbolType = mlModel.get('symbol');
  52742. var symbolSize = mlModel.get('symbolSize');
  52743. var symbolRotate = mlModel.get('symbolRotate');
  52744. var symbolOffset = mlModel.get('symbolOffset');
  52745. // TODO: support callback function like markPoint
  52746. if (!isArray(symbolType)) {
  52747. symbolType = [symbolType, symbolType];
  52748. }
  52749. if (!isArray(symbolSize)) {
  52750. symbolSize = [symbolSize, symbolSize];
  52751. }
  52752. if (!isArray(symbolRotate)) {
  52753. symbolRotate = [symbolRotate, symbolRotate];
  52754. }
  52755. if (!isArray(symbolOffset)) {
  52756. symbolOffset = [symbolOffset, symbolOffset];
  52757. }
  52758. // Update visual and layout of from symbol and to symbol
  52759. mlData.from.each(function (idx) {
  52760. updateDataVisualAndLayout(fromData, idx, true);
  52761. updateDataVisualAndLayout(toData, idx, false);
  52762. });
  52763. // Update visual and layout of line
  52764. lineData.each(function (idx) {
  52765. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle();
  52766. // lineData.setItemVisual(idx, {
  52767. // color: lineColor || fromData.getItemVisual(idx, 'color')
  52768. // });
  52769. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  52770. if (lineStyle.stroke == null) {
  52771. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  52772. }
  52773. lineData.setItemVisual(idx, {
  52774. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  52775. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  52776. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  52777. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  52778. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  52779. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  52780. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  52781. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  52782. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  52783. toSymbol: toData.getItemVisual(idx, 'symbol'),
  52784. style: lineStyle
  52785. });
  52786. });
  52787. lineDraw.updateData(lineData);
  52788. // Set host model for tooltip
  52789. // FIXME
  52790. mlData.line.eachItemGraphicEl(function (el) {
  52791. getECData(el).dataModel = mlModel;
  52792. el.traverse(function (child) {
  52793. getECData(child).dataModel = mlModel;
  52794. });
  52795. });
  52796. function updateDataVisualAndLayout(data, idx, isFrom) {
  52797. var itemModel = data.getItemModel(idx);
  52798. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  52799. var style = itemModel.getModel('itemStyle').getItemStyle();
  52800. if (style.fill == null) {
  52801. style.fill = getVisualFromData(seriesData, 'color');
  52802. }
  52803. data.setItemVisual(idx, {
  52804. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  52805. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  52806. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  52807. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  52808. // TODO: when 2d array is supported, it should ignore parent
  52809. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  52810. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  52811. style: style
  52812. });
  52813. }
  52814. this.markKeep(lineDraw);
  52815. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  52816. };
  52817. MarkLineView.type = 'markLine';
  52818. return MarkLineView;
  52819. }(MarkerView);
  52820. function createList$1(coordSys, seriesModel, mlModel) {
  52821. var coordDimsInfos;
  52822. if (coordSys) {
  52823. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  52824. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  52825. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  52826. return extend(extend({}, info), {
  52827. name: coordDim,
  52828. // DON'T use ordinalMeta to parse and collect ordinal.
  52829. ordinalMeta: null
  52830. });
  52831. });
  52832. } else {
  52833. coordDimsInfos = [{
  52834. name: 'value',
  52835. type: 'float'
  52836. }];
  52837. }
  52838. var fromData = new SeriesData(coordDimsInfos, mlModel);
  52839. var toData = new SeriesData(coordDimsInfos, mlModel);
  52840. // No dimensions
  52841. var lineData = new SeriesData([], mlModel);
  52842. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  52843. if (coordSys) {
  52844. optData = filter(optData, curry(markLineFilter, coordSys));
  52845. }
  52846. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  52847. fromData.initData(map(optData, function (item) {
  52848. return item[0];
  52849. }), null, dimValueGetter);
  52850. toData.initData(map(optData, function (item) {
  52851. return item[1];
  52852. }), null, dimValueGetter);
  52853. lineData.initData(map(optData, function (item) {
  52854. return item[2];
  52855. }));
  52856. lineData.hasItemOption = true;
  52857. return {
  52858. from: fromData,
  52859. to: toData,
  52860. line: lineData
  52861. };
  52862. }
  52863. function install$f(registers) {
  52864. registers.registerComponentModel(MarkLineModel);
  52865. registers.registerComponentView(MarkLineView);
  52866. registers.registerPreprocessor(function (opt) {
  52867. if (checkMarkerInSeries(opt.series, 'markLine')) {
  52868. // Make sure markLine component is enabled
  52869. opt.markLine = opt.markLine || {};
  52870. }
  52871. });
  52872. }
  52873. var MarkAreaModel = /** @class */function (_super) {
  52874. __extends(MarkAreaModel, _super);
  52875. function MarkAreaModel() {
  52876. var _this = _super !== null && _super.apply(this, arguments) || this;
  52877. _this.type = MarkAreaModel.type;
  52878. return _this;
  52879. }
  52880. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  52881. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  52882. };
  52883. MarkAreaModel.type = 'markArea';
  52884. MarkAreaModel.defaultOption = {
  52885. // zlevel: 0,
  52886. // PENDING
  52887. z: 1,
  52888. tooltip: {
  52889. trigger: 'item'
  52890. },
  52891. // markArea should fixed on the coordinate system
  52892. animation: false,
  52893. label: {
  52894. show: true,
  52895. position: 'top'
  52896. },
  52897. itemStyle: {
  52898. // color and borderColor default to use color from series
  52899. // color: 'auto'
  52900. // borderColor: 'auto'
  52901. borderWidth: 0
  52902. },
  52903. emphasis: {
  52904. label: {
  52905. show: true,
  52906. position: 'top'
  52907. }
  52908. }
  52909. };
  52910. return MarkAreaModel;
  52911. }(MarkerModel);
  52912. var inner$f = makeInner();
  52913. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  52914. // item may be null
  52915. var item0 = item[0];
  52916. var item1 = item[1];
  52917. if (!item0 || !item1) {
  52918. return;
  52919. }
  52920. var lt = dataTransform(seriesModel, item0);
  52921. var rb = dataTransform(seriesModel, item1);
  52922. // FIXME make sure lt is less than rb
  52923. var ltCoord = lt.coord;
  52924. var rbCoord = rb.coord;
  52925. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  52926. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  52927. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  52928. rbCoord[1] = retrieve(rbCoord[1], Infinity);
  52929. // Merge option into one
  52930. var result = mergeAll([{}, lt, rb]);
  52931. result.coord = [lt.coord, rb.coord];
  52932. result.x0 = lt.x;
  52933. result.y0 = lt.y;
  52934. result.x1 = rb.x;
  52935. result.y1 = rb.y;
  52936. return result;
  52937. };
  52938. function isInfinity$1(val) {
  52939. return !isNaN(val) && !isFinite(val);
  52940. }
  52941. // If a markArea has one dim
  52942. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  52943. var otherDimIndex = 1 - dimIndex;
  52944. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  52945. }
  52946. function markAreaFilter(coordSys, item) {
  52947. var fromCoord = item.coord[0];
  52948. var toCoord = item.coord[1];
  52949. var item0 = {
  52950. coord: fromCoord,
  52951. x: item.x0,
  52952. y: item.y0
  52953. };
  52954. var item1 = {
  52955. coord: toCoord,
  52956. x: item.x1,
  52957. y: item.y1
  52958. };
  52959. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  52960. // In case
  52961. // {
  52962. // markArea: {
  52963. // data: [{ yAxis: 2 }]
  52964. // }
  52965. // }
  52966. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  52967. return true;
  52968. }
  52969. // Directly returning true may also do the work,
  52970. // because markArea will not be shown automatically
  52971. // when it's not included in coordinate system.
  52972. // But filtering ahead can avoid keeping rendering markArea
  52973. // when there are too many of them.
  52974. return zoneFilter(coordSys, item0, item1);
  52975. }
  52976. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  52977. }
  52978. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  52979. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  52980. var coordSys = seriesModel.coordinateSystem;
  52981. var itemModel = data.getItemModel(idx);
  52982. var point;
  52983. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  52984. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  52985. if (!isNaN(xPx) && !isNaN(yPx)) {
  52986. point = [xPx, yPx];
  52987. } else {
  52988. // Chart like bar may have there own marker positioning logic
  52989. if (seriesModel.getMarkerPosition) {
  52990. // Consider the case that user input the right-bottom point first
  52991. // Pick the larger x and y as 'x1' and 'y1'
  52992. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  52993. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  52994. var clampPointValue0 = coordSys.clampData(pointValue0);
  52995. var clampPointValue1 = coordSys.clampData(pointValue1);
  52996. var pointValue = [];
  52997. if (dims[0] === 'x0') {
  52998. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  52999. } else {
  53000. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  53001. }
  53002. if (dims[1] === 'y0') {
  53003. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  53004. } else {
  53005. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  53006. }
  53007. // Use the getMarkerPosition
  53008. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  53009. } else {
  53010. var x = data.get(dims[0], idx);
  53011. var y = data.get(dims[1], idx);
  53012. var pt = [x, y];
  53013. coordSys.clampData && coordSys.clampData(pt, pt);
  53014. point = coordSys.dataToPoint(pt, true);
  53015. }
  53016. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  53017. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  53018. var xAxis = coordSys.getAxis('x');
  53019. var yAxis = coordSys.getAxis('y');
  53020. var x = data.get(dims[0], idx);
  53021. var y = data.get(dims[1], idx);
  53022. if (isInfinity$1(x)) {
  53023. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  53024. } else if (isInfinity$1(y)) {
  53025. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  53026. }
  53027. }
  53028. // Use x, y if has any
  53029. if (!isNaN(xPx)) {
  53030. point[0] = xPx;
  53031. }
  53032. if (!isNaN(yPx)) {
  53033. point[1] = yPx;
  53034. }
  53035. }
  53036. return point;
  53037. }
  53038. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  53039. var MarkAreaView = /** @class */function (_super) {
  53040. __extends(MarkAreaView, _super);
  53041. function MarkAreaView() {
  53042. var _this = _super !== null && _super.apply(this, arguments) || this;
  53043. _this.type = MarkAreaView.type;
  53044. return _this;
  53045. }
  53046. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  53047. ecModel.eachSeries(function (seriesModel) {
  53048. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  53049. if (maModel) {
  53050. var areaData_1 = maModel.getData();
  53051. areaData_1.each(function (idx) {
  53052. var points = map(dimPermutations, function (dim) {
  53053. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  53054. });
  53055. // Layout
  53056. areaData_1.setItemLayout(idx, points);
  53057. var el = areaData_1.getItemGraphicEl(idx);
  53058. el.setShape('points', points);
  53059. });
  53060. }
  53061. }, this);
  53062. };
  53063. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  53064. var coordSys = seriesModel.coordinateSystem;
  53065. var seriesId = seriesModel.id;
  53066. var seriesData = seriesModel.getData();
  53067. var areaGroupMap = this.markerGroupMap;
  53068. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  53069. group: new Group()
  53070. });
  53071. this.group.add(polygonGroup.group);
  53072. this.markKeep(polygonGroup);
  53073. var areaData = createList$2(coordSys, seriesModel, maModel);
  53074. // Line data for tooltip and formatter
  53075. maModel.setData(areaData);
  53076. // Update visual and layout of line
  53077. areaData.each(function (idx) {
  53078. // Layout
  53079. var points = map(dimPermutations, function (dim) {
  53080. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  53081. });
  53082. var xAxisScale = coordSys.getAxis('x').scale;
  53083. var yAxisScale = coordSys.getAxis('y').scale;
  53084. var xAxisExtent = xAxisScale.getExtent();
  53085. var yAxisExtent = yAxisScale.getExtent();
  53086. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  53087. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  53088. asc(xPointExtent);
  53089. asc(yPointExtent);
  53090. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]);
  53091. // If none of the area is inside coordSys, allClipped is set to be true
  53092. // in layout so that label will not be displayed. See #12591
  53093. var allClipped = !overlapped;
  53094. areaData.setItemLayout(idx, {
  53095. points: points,
  53096. allClipped: allClipped
  53097. });
  53098. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  53099. var color$1 = getVisualFromData(seriesData, 'color');
  53100. if (!style.fill) {
  53101. style.fill = color$1;
  53102. if (isString(style.fill)) {
  53103. style.fill = modifyAlpha(style.fill, 0.4);
  53104. }
  53105. }
  53106. if (!style.stroke) {
  53107. style.stroke = color$1;
  53108. }
  53109. // Visual
  53110. areaData.setItemVisual(idx, 'style', style);
  53111. });
  53112. areaData.diff(inner$f(polygonGroup).data).add(function (idx) {
  53113. var layout = areaData.getItemLayout(idx);
  53114. if (!layout.allClipped) {
  53115. var polygon = new Polygon({
  53116. shape: {
  53117. points: layout.points
  53118. }
  53119. });
  53120. areaData.setItemGraphicEl(idx, polygon);
  53121. polygonGroup.group.add(polygon);
  53122. }
  53123. }).update(function (newIdx, oldIdx) {
  53124. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(oldIdx);
  53125. var layout = areaData.getItemLayout(newIdx);
  53126. if (!layout.allClipped) {
  53127. if (polygon) {
  53128. updateProps(polygon, {
  53129. shape: {
  53130. points: layout.points
  53131. }
  53132. }, maModel, newIdx);
  53133. } else {
  53134. polygon = new Polygon({
  53135. shape: {
  53136. points: layout.points
  53137. }
  53138. });
  53139. }
  53140. areaData.setItemGraphicEl(newIdx, polygon);
  53141. polygonGroup.group.add(polygon);
  53142. } else if (polygon) {
  53143. polygonGroup.group.remove(polygon);
  53144. }
  53145. }).remove(function (idx) {
  53146. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(idx);
  53147. polygonGroup.group.remove(polygon);
  53148. }).execute();
  53149. areaData.eachItemGraphicEl(function (polygon, idx) {
  53150. var itemModel = areaData.getItemModel(idx);
  53151. var style = areaData.getItemVisual(idx, 'style');
  53152. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  53153. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  53154. labelFetcher: maModel,
  53155. labelDataIndex: idx,
  53156. defaultText: areaData.getName(idx) || '',
  53157. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  53158. });
  53159. setStatesStylesFromModel(polygon, itemModel);
  53160. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  53161. getECData(polygon).dataModel = maModel;
  53162. });
  53163. inner$f(polygonGroup).data = areaData;
  53164. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  53165. };
  53166. MarkAreaView.type = 'markArea';
  53167. return MarkAreaView;
  53168. }(MarkerView);
  53169. function createList$2(coordSys, seriesModel, maModel) {
  53170. var areaData;
  53171. var dataDims;
  53172. var dims = ['x0', 'y0', 'x1', 'y1'];
  53173. if (coordSys) {
  53174. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  53175. var data = seriesModel.getData();
  53176. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {};
  53177. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  53178. return extend(extend({}, info), {
  53179. name: coordDim,
  53180. // DON'T use ordinalMeta to parse and collect ordinal.
  53181. ordinalMeta: null
  53182. });
  53183. });
  53184. dataDims = map(dims, function (dim, idx) {
  53185. return {
  53186. name: dim,
  53187. type: coordDimsInfos_1[idx % 2].type
  53188. };
  53189. });
  53190. areaData = new SeriesData(dataDims, maModel);
  53191. } else {
  53192. dataDims = [{
  53193. name: 'value',
  53194. type: 'float'
  53195. }];
  53196. areaData = new SeriesData(dataDims, maModel);
  53197. }
  53198. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  53199. if (coordSys) {
  53200. optData = filter(optData, curry(markAreaFilter, coordSys));
  53201. }
  53202. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  53203. // TODO should convert to ParsedValue?
  53204. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  53205. return parseDataValue(rawVal, dataDims[dimIndex]);
  53206. } : function (item, dimName, dataIndex, dimIndex) {
  53207. return parseDataValue(item.value, dataDims[dimIndex]);
  53208. };
  53209. areaData.initData(optData, null, dimValueGetter);
  53210. areaData.hasItemOption = true;
  53211. return areaData;
  53212. }
  53213. function install$g(registers) {
  53214. registers.registerComponentModel(MarkAreaModel);
  53215. registers.registerComponentView(MarkAreaView);
  53216. registers.registerPreprocessor(function (opt) {
  53217. if (checkMarkerInSeries(opt.series, 'markArea')) {
  53218. // Make sure markArea component is enabled
  53219. opt.markArea = opt.markArea || {};
  53220. }
  53221. });
  53222. }
  53223. var getDefaultSelectorOptions = function (ecModel, type) {
  53224. if (type === 'all') {
  53225. return {
  53226. type: 'all',
  53227. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  53228. };
  53229. } else if (type === 'inverse') {
  53230. return {
  53231. type: 'inverse',
  53232. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  53233. };
  53234. }
  53235. };
  53236. var LegendModel = /** @class */function (_super) {
  53237. __extends(LegendModel, _super);
  53238. function LegendModel() {
  53239. var _this = _super !== null && _super.apply(this, arguments) || this;
  53240. _this.type = LegendModel.type;
  53241. _this.layoutMode = {
  53242. type: 'box',
  53243. // legend.width/height are maxWidth/maxHeight actually,
  53244. // whereas real width/height is calculated by its content.
  53245. // (Setting {left: 10, right: 10} does not make sense).
  53246. // So consider the case:
  53247. // `setOption({legend: {left: 10});`
  53248. // then `setOption({legend: {right: 10});`
  53249. // The previous `left` should be cleared by setting `ignoreSize`.
  53250. ignoreSize: true
  53251. };
  53252. return _this;
  53253. }
  53254. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  53255. this.mergeDefaultAndTheme(option, ecModel);
  53256. option.selected = option.selected || {};
  53257. this._updateSelector(option);
  53258. };
  53259. LegendModel.prototype.mergeOption = function (option, ecModel) {
  53260. _super.prototype.mergeOption.call(this, option, ecModel);
  53261. this._updateSelector(option);
  53262. };
  53263. LegendModel.prototype._updateSelector = function (option) {
  53264. var selector = option.selector;
  53265. var ecModel = this.ecModel;
  53266. if (selector === true) {
  53267. selector = option.selector = ['all', 'inverse'];
  53268. }
  53269. if (isArray(selector)) {
  53270. each(selector, function (item, index) {
  53271. isString(item) && (item = {
  53272. type: item
  53273. });
  53274. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  53275. });
  53276. }
  53277. };
  53278. LegendModel.prototype.optionUpdated = function () {
  53279. this._updateData(this.ecModel);
  53280. var legendData = this._data;
  53281. // If selectedMode is single, try to select one
  53282. if (legendData[0] && this.get('selectedMode') === 'single') {
  53283. var hasSelected = false;
  53284. // If has any selected in option.selected
  53285. for (var i = 0; i < legendData.length; i++) {
  53286. var name_1 = legendData[i].get('name');
  53287. if (this.isSelected(name_1)) {
  53288. // Force to unselect others
  53289. this.select(name_1);
  53290. hasSelected = true;
  53291. break;
  53292. }
  53293. }
  53294. // Try select the first if selectedMode is single
  53295. !hasSelected && this.select(legendData[0].get('name'));
  53296. }
  53297. };
  53298. LegendModel.prototype._updateData = function (ecModel) {
  53299. var potentialData = [];
  53300. var availableNames = [];
  53301. ecModel.eachRawSeries(function (seriesModel) {
  53302. var seriesName = seriesModel.name;
  53303. availableNames.push(seriesName);
  53304. var isPotential;
  53305. if (seriesModel.legendVisualProvider) {
  53306. var provider = seriesModel.legendVisualProvider;
  53307. var names = provider.getAllNames();
  53308. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53309. availableNames = availableNames.concat(names);
  53310. }
  53311. if (names.length) {
  53312. potentialData = potentialData.concat(names);
  53313. } else {
  53314. isPotential = true;
  53315. }
  53316. } else {
  53317. isPotential = true;
  53318. }
  53319. if (isPotential && isNameSpecified(seriesModel)) {
  53320. potentialData.push(seriesModel.name);
  53321. }
  53322. });
  53323. /**
  53324. * @type {Array.<string>}
  53325. * @private
  53326. */
  53327. this._availableNames = availableNames;
  53328. // If legend.data is not specified in option, use availableNames as data,
  53329. // which is convenient for user preparing option.
  53330. var rawData = this.get('data') || potentialData;
  53331. var legendNameMap = createHashMap();
  53332. var legendData = map(rawData, function (dataItem) {
  53333. // Can be string or number
  53334. if (isString(dataItem) || isNumber(dataItem)) {
  53335. dataItem = {
  53336. name: dataItem
  53337. };
  53338. }
  53339. if (legendNameMap.get(dataItem.name)) {
  53340. // remove legend name duplicate
  53341. return null;
  53342. }
  53343. legendNameMap.set(dataItem.name, true);
  53344. return new Model(dataItem, this, this.ecModel);
  53345. }, this);
  53346. /**
  53347. * @type {Array.<module:echarts/model/Model>}
  53348. * @private
  53349. */
  53350. this._data = filter(legendData, function (item) {
  53351. return !!item;
  53352. });
  53353. };
  53354. LegendModel.prototype.getData = function () {
  53355. return this._data;
  53356. };
  53357. LegendModel.prototype.select = function (name) {
  53358. var selected = this.option.selected;
  53359. var selectedMode = this.get('selectedMode');
  53360. if (selectedMode === 'single') {
  53361. var data = this._data;
  53362. each(data, function (dataItem) {
  53363. selected[dataItem.get('name')] = false;
  53364. });
  53365. }
  53366. selected[name] = true;
  53367. };
  53368. LegendModel.prototype.unSelect = function (name) {
  53369. if (this.get('selectedMode') !== 'single') {
  53370. this.option.selected[name] = false;
  53371. }
  53372. };
  53373. LegendModel.prototype.toggleSelected = function (name) {
  53374. var selected = this.option.selected;
  53375. // Default is true
  53376. if (!selected.hasOwnProperty(name)) {
  53377. selected[name] = true;
  53378. }
  53379. this[selected[name] ? 'unSelect' : 'select'](name);
  53380. };
  53381. LegendModel.prototype.allSelect = function () {
  53382. var data = this._data;
  53383. var selected = this.option.selected;
  53384. each(data, function (dataItem) {
  53385. selected[dataItem.get('name', true)] = true;
  53386. });
  53387. };
  53388. LegendModel.prototype.inverseSelect = function () {
  53389. var data = this._data;
  53390. var selected = this.option.selected;
  53391. each(data, function (dataItem) {
  53392. var name = dataItem.get('name', true);
  53393. // Initially, default value is true
  53394. if (!selected.hasOwnProperty(name)) {
  53395. selected[name] = true;
  53396. }
  53397. selected[name] = !selected[name];
  53398. });
  53399. };
  53400. LegendModel.prototype.isSelected = function (name) {
  53401. var selected = this.option.selected;
  53402. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  53403. };
  53404. LegendModel.prototype.getOrient = function () {
  53405. return this.get('orient') === 'vertical' ? {
  53406. index: 1,
  53407. name: 'vertical'
  53408. } : {
  53409. index: 0,
  53410. name: 'horizontal'
  53411. };
  53412. };
  53413. LegendModel.type = 'legend.plain';
  53414. LegendModel.dependencies = ['series'];
  53415. LegendModel.defaultOption = {
  53416. // zlevel: 0,
  53417. z: 4,
  53418. show: true,
  53419. orient: 'horizontal',
  53420. left: 'center',
  53421. // right: 'center',
  53422. top: 0,
  53423. // bottom: null,
  53424. align: 'auto',
  53425. backgroundColor: 'rgba(0,0,0,0)',
  53426. borderColor: '#ccc',
  53427. borderRadius: 0,
  53428. borderWidth: 0,
  53429. padding: 5,
  53430. itemGap: 10,
  53431. itemWidth: 25,
  53432. itemHeight: 14,
  53433. symbolRotate: 'inherit',
  53434. symbolKeepAspect: true,
  53435. inactiveColor: '#ccc',
  53436. inactiveBorderColor: '#ccc',
  53437. inactiveBorderWidth: 'auto',
  53438. itemStyle: {
  53439. color: 'inherit',
  53440. opacity: 'inherit',
  53441. borderColor: 'inherit',
  53442. borderWidth: 'auto',
  53443. borderCap: 'inherit',
  53444. borderJoin: 'inherit',
  53445. borderDashOffset: 'inherit',
  53446. borderMiterLimit: 'inherit'
  53447. },
  53448. lineStyle: {
  53449. width: 'auto',
  53450. color: 'inherit',
  53451. inactiveColor: '#ccc',
  53452. inactiveWidth: 2,
  53453. opacity: 'inherit',
  53454. type: 'inherit',
  53455. cap: 'inherit',
  53456. join: 'inherit',
  53457. dashOffset: 'inherit',
  53458. miterLimit: 'inherit'
  53459. },
  53460. textStyle: {
  53461. color: '#333'
  53462. },
  53463. selectedMode: true,
  53464. selector: false,
  53465. selectorLabel: {
  53466. show: true,
  53467. borderRadius: 10,
  53468. padding: [3, 5, 3, 5],
  53469. fontSize: 12,
  53470. fontFamily: 'sans-serif',
  53471. color: '#666',
  53472. borderWidth: 1,
  53473. borderColor: '#666'
  53474. },
  53475. emphasis: {
  53476. selectorLabel: {
  53477. show: true,
  53478. color: '#eee',
  53479. backgroundColor: '#666'
  53480. }
  53481. },
  53482. selectorPosition: 'auto',
  53483. selectorItemGap: 7,
  53484. selectorButtonGap: 10,
  53485. tooltip: {
  53486. show: false
  53487. }
  53488. };
  53489. return LegendModel;
  53490. }(ComponentModel);
  53491. var curry$1 = curry;
  53492. var each$7 = each;
  53493. var Group$1 = Group;
  53494. var LegendView = /** @class */function (_super) {
  53495. __extends(LegendView, _super);
  53496. function LegendView() {
  53497. var _this = _super !== null && _super.apply(this, arguments) || this;
  53498. _this.type = LegendView.type;
  53499. _this.newlineDisabled = false;
  53500. return _this;
  53501. }
  53502. LegendView.prototype.init = function () {
  53503. this.group.add(this._contentGroup = new Group$1());
  53504. this.group.add(this._selectorGroup = new Group$1());
  53505. this._isFirstRender = true;
  53506. };
  53507. /**
  53508. * @protected
  53509. */
  53510. LegendView.prototype.getContentGroup = function () {
  53511. return this._contentGroup;
  53512. };
  53513. /**
  53514. * @protected
  53515. */
  53516. LegendView.prototype.getSelectorGroup = function () {
  53517. return this._selectorGroup;
  53518. };
  53519. /**
  53520. * @override
  53521. */
  53522. LegendView.prototype.render = function (legendModel, ecModel, api) {
  53523. var isFirstRender = this._isFirstRender;
  53524. this._isFirstRender = false;
  53525. this.resetInner();
  53526. if (!legendModel.get('show', true)) {
  53527. return;
  53528. }
  53529. var itemAlign = legendModel.get('align');
  53530. var orient = legendModel.get('orient');
  53531. if (!itemAlign || itemAlign === 'auto') {
  53532. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  53533. }
  53534. // selector has been normalized to an array in model
  53535. var selector = legendModel.get('selector', true);
  53536. var selectorPosition = legendModel.get('selectorPosition', true);
  53537. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  53538. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  53539. }
  53540. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  53541. // Perform layout.
  53542. var positionInfo = legendModel.getBoxLayoutParams();
  53543. var viewportSize = {
  53544. width: api.getWidth(),
  53545. height: api.getHeight()
  53546. };
  53547. var padding = legendModel.get('padding');
  53548. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  53549. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  53550. // Place mainGroup, based on the calculated `mainRect`.
  53551. var layoutRect = getLayoutRect(defaults({
  53552. width: mainRect.width,
  53553. height: mainRect.height
  53554. }, positionInfo), viewportSize, padding);
  53555. this.group.x = layoutRect.x - mainRect.x;
  53556. this.group.y = layoutRect.y - mainRect.y;
  53557. this.group.markRedraw();
  53558. // Render background after group is layout.
  53559. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  53560. };
  53561. LegendView.prototype.resetInner = function () {
  53562. this.getContentGroup().removeAll();
  53563. this._backgroundEl && this.group.remove(this._backgroundEl);
  53564. this.getSelectorGroup().removeAll();
  53565. };
  53566. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  53567. var contentGroup = this.getContentGroup();
  53568. var legendDrawnMap = createHashMap();
  53569. var selectMode = legendModel.get('selectedMode');
  53570. var excludeSeriesId = [];
  53571. ecModel.eachRawSeries(function (seriesModel) {
  53572. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  53573. });
  53574. each$7(legendModel.getData(), function (legendItemModel, dataIndex) {
  53575. var name = legendItemModel.get('name');
  53576. // Use empty string or \n as a newline string
  53577. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  53578. var g = new Group$1();
  53579. // @ts-ignore
  53580. g.newline = true;
  53581. contentGroup.add(g);
  53582. return;
  53583. }
  53584. // Representitive series.
  53585. var seriesModel = ecModel.getSeriesByName(name)[0];
  53586. if (legendDrawnMap.get(name)) {
  53587. // Have been drawn
  53588. return;
  53589. }
  53590. // Legend to control series.
  53591. if (seriesModel) {
  53592. var data = seriesModel.getData();
  53593. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  53594. var legendIcon = data.getVisual('legendIcon');
  53595. /**
  53596. * `data.getVisual('style')` may be the color from the register
  53597. * in series. For example, for line series,
  53598. */
  53599. var style = data.getVisual('style');
  53600. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  53601. itemGroup.on('click', curry$1(dispatchSelectAction, name, null, api, excludeSeriesId)).on('mouseover', curry$1(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  53602. if (ecModel.ssr) {
  53603. itemGroup.eachChild(function (child) {
  53604. var ecData = getECData(child);
  53605. ecData.seriesIndex = seriesModel.seriesIndex;
  53606. ecData.dataIndex = dataIndex;
  53607. ecData.ssrType = 'legend';
  53608. });
  53609. }
  53610. legendDrawnMap.set(name, true);
  53611. } else {
  53612. // Legend to control data. In pie and funnel.
  53613. ecModel.eachRawSeries(function (seriesModel) {
  53614. // In case multiple series has same data name
  53615. if (legendDrawnMap.get(name)) {
  53616. return;
  53617. }
  53618. if (seriesModel.legendVisualProvider) {
  53619. var provider = seriesModel.legendVisualProvider;
  53620. if (!provider.containName(name)) {
  53621. return;
  53622. }
  53623. var idx = provider.indexOfName(name);
  53624. var style = provider.getItemVisual(idx, 'style');
  53625. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  53626. var colorArr = parse(style.fill);
  53627. // Color may be set to transparent in visualMap when data is out of range.
  53628. // Do not show nothing.
  53629. if (colorArr && colorArr[3] === 0) {
  53630. colorArr[3] = 0.2;
  53631. // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  53632. style = extend(extend({}, style), {
  53633. fill: stringify(colorArr, 'rgba')
  53634. });
  53635. }
  53636. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api);
  53637. // FIXME: consider different series has items with the same name.
  53638. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId))
  53639. // Should not specify the series name, consider legend controls
  53640. // more than one pie series.
  53641. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  53642. if (ecModel.ssr) {
  53643. itemGroup.eachChild(function (child) {
  53644. var ecData = getECData(child);
  53645. ecData.seriesIndex = seriesModel.seriesIndex;
  53646. ecData.dataIndex = dataIndex;
  53647. ecData.ssrType = 'legend';
  53648. });
  53649. }
  53650. legendDrawnMap.set(name, true);
  53651. }
  53652. }, this);
  53653. }
  53654. if ("development" !== 'production') {
  53655. if (!legendDrawnMap.get(name)) {
  53656. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  53657. }
  53658. }
  53659. }, this);
  53660. if (selector) {
  53661. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  53662. }
  53663. };
  53664. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  53665. var selectorGroup = this.getSelectorGroup();
  53666. each$7(selector, function createSelectorButton(selectorItem) {
  53667. var type = selectorItem.type;
  53668. var labelText = new ZRText({
  53669. style: {
  53670. x: 0,
  53671. y: 0,
  53672. align: 'center',
  53673. verticalAlign: 'middle'
  53674. },
  53675. onclick: function () {
  53676. api.dispatchAction({
  53677. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect',
  53678. legendId: legendModel.id
  53679. });
  53680. }
  53681. });
  53682. selectorGroup.add(labelText);
  53683. var labelModel = legendModel.getModel('selectorLabel');
  53684. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  53685. setLabelStyle(labelText, {
  53686. normal: labelModel,
  53687. emphasis: emphasisLabelModel
  53688. }, {
  53689. defaultText: selectorItem.title
  53690. });
  53691. enableHoverEmphasis(labelText);
  53692. });
  53693. };
  53694. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  53695. var drawType = seriesModel.visualDrawType;
  53696. var itemWidth = legendModel.get('itemWidth');
  53697. var itemHeight = legendModel.get('itemHeight');
  53698. var isSelected = legendModel.isSelected(name);
  53699. var iconRotate = legendItemModel.get('symbolRotate');
  53700. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  53701. var legendIconType = legendItemModel.get('icon');
  53702. legendIcon = legendIconType || legendIcon || 'roundRect';
  53703. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  53704. var itemGroup = new Group$1();
  53705. var textStyleModel = legendItemModel.getModel('textStyle');
  53706. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  53707. // Series has specific way to define legend icon
  53708. itemGroup.add(seriesModel.getLegendIcon({
  53709. itemWidth: itemWidth,
  53710. itemHeight: itemHeight,
  53711. icon: legendIcon,
  53712. iconRotate: iconRotate,
  53713. itemStyle: style.itemStyle,
  53714. lineStyle: style.lineStyle,
  53715. symbolKeepAspect: symbolKeepAspect
  53716. }));
  53717. } else {
  53718. // Use default legend icon policy for most series
  53719. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  53720. itemGroup.add(getDefaultLegendIcon({
  53721. itemWidth: itemWidth,
  53722. itemHeight: itemHeight,
  53723. icon: legendIcon,
  53724. iconRotate: rotate,
  53725. itemStyle: style.itemStyle,
  53726. lineStyle: style.lineStyle,
  53727. symbolKeepAspect: symbolKeepAspect
  53728. }));
  53729. }
  53730. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  53731. var textAlign = itemAlign;
  53732. var formatter = legendModel.get('formatter');
  53733. var content = name;
  53734. if (isString(formatter) && formatter) {
  53735. content = formatter.replace('{name}', name != null ? name : '');
  53736. } else if (isFunction(formatter)) {
  53737. content = formatter(name);
  53738. }
  53739. var textColor = isSelected ? textStyleModel.getTextColor() : legendItemModel.get('inactiveColor');
  53740. itemGroup.add(new ZRText({
  53741. style: createTextStyle(textStyleModel, {
  53742. text: content,
  53743. x: textX,
  53744. y: itemHeight / 2,
  53745. fill: textColor,
  53746. align: textAlign,
  53747. verticalAlign: 'middle'
  53748. }, {
  53749. inheritColor: textColor
  53750. })
  53751. }));
  53752. // Add a invisible rect to increase the area of mouse hover
  53753. var hitRect = new Rect({
  53754. shape: itemGroup.getBoundingRect(),
  53755. style: {
  53756. // Cannot use 'invisible' because SVG SSR will miss the node
  53757. fill: 'transparent'
  53758. }
  53759. });
  53760. var tooltipModel = legendItemModel.getModel('tooltip');
  53761. if (tooltipModel.get('show')) {
  53762. setTooltipConfig({
  53763. el: hitRect,
  53764. componentModel: legendModel,
  53765. itemName: name,
  53766. itemTooltipOption: tooltipModel.option
  53767. });
  53768. }
  53769. itemGroup.add(hitRect);
  53770. itemGroup.eachChild(function (child) {
  53771. child.silent = true;
  53772. });
  53773. hitRect.silent = !selectMode;
  53774. this.getContentGroup().add(itemGroup);
  53775. enableHoverEmphasis(itemGroup);
  53776. // @ts-ignore
  53777. itemGroup.__legendDataIndex = dataIndex;
  53778. return itemGroup;
  53779. };
  53780. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  53781. var contentGroup = this.getContentGroup();
  53782. var selectorGroup = this.getSelectorGroup();
  53783. // Place items in contentGroup.
  53784. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  53785. var contentRect = contentGroup.getBoundingRect();
  53786. var contentPos = [-contentRect.x, -contentRect.y];
  53787. selectorGroup.markRedraw();
  53788. contentGroup.markRedraw();
  53789. if (selector) {
  53790. // Place buttons in selectorGroup
  53791. box(
  53792. // Buttons in selectorGroup always layout horizontally
  53793. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  53794. var selectorRect = selectorGroup.getBoundingRect();
  53795. var selectorPos = [-selectorRect.x, -selectorRect.y];
  53796. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  53797. var orientIdx = legendModel.getOrient().index;
  53798. var wh = orientIdx === 0 ? 'width' : 'height';
  53799. var hw = orientIdx === 0 ? 'height' : 'width';
  53800. var yx = orientIdx === 0 ? 'y' : 'x';
  53801. if (selectorPosition === 'end') {
  53802. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  53803. } else {
  53804. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  53805. }
  53806. // Always align selector to content as 'middle'
  53807. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  53808. selectorGroup.x = selectorPos[0];
  53809. selectorGroup.y = selectorPos[1];
  53810. contentGroup.x = contentPos[0];
  53811. contentGroup.y = contentPos[1];
  53812. var mainRect = {
  53813. x: 0,
  53814. y: 0
  53815. };
  53816. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  53817. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  53818. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  53819. return mainRect;
  53820. } else {
  53821. contentGroup.x = contentPos[0];
  53822. contentGroup.y = contentPos[1];
  53823. return this.group.getBoundingRect();
  53824. }
  53825. };
  53826. /**
  53827. * @protected
  53828. */
  53829. LegendView.prototype.remove = function () {
  53830. this.getContentGroup().removeAll();
  53831. this._isFirstRender = true;
  53832. };
  53833. LegendView.type = 'legend.plain';
  53834. return LegendView;
  53835. }(ComponentView);
  53836. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  53837. /**
  53838. * Use series style if is inherit;
  53839. * elsewise, use legend style
  53840. */
  53841. function handleCommonProps(style, visualStyle) {
  53842. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  53843. if (style.lineWidth === 'auto') {
  53844. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  53845. }
  53846. each$7(style, function (propVal, propName) {
  53847. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  53848. });
  53849. }
  53850. // itemStyle
  53851. var itemStyleModel = legendItemModel.getModel('itemStyle');
  53852. var itemStyle = itemStyleModel.getItemStyle();
  53853. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  53854. var decalStyle = itemStyleModel.getShallow('decal');
  53855. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  53856. if (itemStyle.fill === 'inherit') {
  53857. /**
  53858. * Series with visualDrawType as 'stroke' should have
  53859. * series stroke as legend fill
  53860. */
  53861. itemStyle.fill = itemVisualStyle[drawType];
  53862. }
  53863. if (itemStyle.stroke === 'inherit') {
  53864. /**
  53865. * icon type with "emptyXXX" should use fill color
  53866. * in visual style
  53867. */
  53868. itemStyle.stroke = itemVisualStyle[iconBrushType];
  53869. }
  53870. if (itemStyle.opacity === 'inherit') {
  53871. /**
  53872. * Use lineStyle.opacity if drawType is stroke
  53873. */
  53874. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  53875. }
  53876. handleCommonProps(itemStyle, itemVisualStyle);
  53877. // lineStyle
  53878. var legendLineModel = legendItemModel.getModel('lineStyle');
  53879. var lineStyle = legendLineModel.getLineStyle();
  53880. handleCommonProps(lineStyle, lineVisualStyle);
  53881. // Fix auto color to real color
  53882. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  53883. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  53884. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  53885. if (!isSelected) {
  53886. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  53887. /**
  53888. * Since stroke is set to be inactiveBorderColor, it may occur that
  53889. * there is no border in series but border in legend, so we need to
  53890. * use border only when series has border if is set to be auto
  53891. */
  53892. var visualHasBorder = itemStyle[iconBrushType];
  53893. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  53894. itemStyle.fill = legendItemModel.get('inactiveColor');
  53895. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  53896. lineStyle.stroke = legendLineModel.get('inactiveColor');
  53897. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  53898. }
  53899. return {
  53900. itemStyle: itemStyle,
  53901. lineStyle: lineStyle
  53902. };
  53903. }
  53904. function getDefaultLegendIcon(opt) {
  53905. var symboType = opt.icon || 'roundRect';
  53906. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  53907. icon.setStyle(opt.itemStyle);
  53908. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  53909. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  53910. if (symboType.indexOf('empty') > -1) {
  53911. icon.style.stroke = icon.style.fill;
  53912. icon.style.fill = '#fff';
  53913. icon.style.lineWidth = 2;
  53914. }
  53915. return icon;
  53916. }
  53917. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  53918. // downplay before unselect
  53919. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  53920. api.dispatchAction({
  53921. type: 'legendToggleSelect',
  53922. name: seriesName != null ? seriesName : dataName
  53923. });
  53924. // highlight after select
  53925. // TODO highlight immediately may cause animation loss.
  53926. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  53927. }
  53928. function isUseHoverLayer(api) {
  53929. var list = api.getZr().storage.getDisplayList();
  53930. var emphasisState;
  53931. var i = 0;
  53932. var len = list.length;
  53933. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  53934. i++;
  53935. }
  53936. return emphasisState && emphasisState.hoverLayer;
  53937. }
  53938. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  53939. // If element hover will move to a hoverLayer.
  53940. if (!isUseHoverLayer(api)) {
  53941. api.dispatchAction({
  53942. type: 'highlight',
  53943. seriesName: seriesName,
  53944. name: dataName,
  53945. excludeSeriesId: excludeSeriesId
  53946. });
  53947. }
  53948. }
  53949. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  53950. // If element hover will move to a hoverLayer.
  53951. if (!isUseHoverLayer(api)) {
  53952. api.dispatchAction({
  53953. type: 'downplay',
  53954. seriesName: seriesName,
  53955. name: dataName,
  53956. excludeSeriesId: excludeSeriesId
  53957. });
  53958. }
  53959. }
  53960. /*
  53961. * Licensed to the Apache Software Foundation (ASF) under one
  53962. * or more contributor license agreements. See the NOTICE file
  53963. * distributed with this work for additional information
  53964. * regarding copyright ownership. The ASF licenses this file
  53965. * to you under the Apache License, Version 2.0 (the
  53966. * "License"); you may not use this file except in compliance
  53967. * with the License. You may obtain a copy of the License at
  53968. *
  53969. * http://www.apache.org/licenses/LICENSE-2.0
  53970. *
  53971. * Unless required by applicable law or agreed to in writing,
  53972. * software distributed under the License is distributed on an
  53973. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53974. * KIND, either express or implied. See the License for the
  53975. * specific language governing permissions and limitations
  53976. * under the License.
  53977. */
  53978. /**
  53979. * AUTO-GENERATED FILE. DO NOT MODIFY.
  53980. */
  53981. /*
  53982. * Licensed to the Apache Software Foundation (ASF) under one
  53983. * or more contributor license agreements. See the NOTICE file
  53984. * distributed with this work for additional information
  53985. * regarding copyright ownership. The ASF licenses this file
  53986. * to you under the Apache License, Version 2.0 (the
  53987. * "License"); you may not use this file except in compliance
  53988. * with the License. You may obtain a copy of the License at
  53989. *
  53990. * http://www.apache.org/licenses/LICENSE-2.0
  53991. *
  53992. * Unless required by applicable law or agreed to in writing,
  53993. * software distributed under the License is distributed on an
  53994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53995. * KIND, either express or implied. See the License for the
  53996. * specific language governing permissions and limitations
  53997. * under the License.
  53998. */
  53999. function legendFilter(ecModel) {
  54000. var legendModels = ecModel.findComponents({
  54001. mainType: 'legend'
  54002. });
  54003. if (legendModels && legendModels.length) {
  54004. ecModel.filterSeries(function (series) {
  54005. // If in any legend component the status is not selected.
  54006. // Because in legend series is assumed selected when it is not in the legend data.
  54007. for (var i = 0; i < legendModels.length; i++) {
  54008. if (!legendModels[i].isSelected(series.name)) {
  54009. return false;
  54010. }
  54011. }
  54012. return true;
  54013. });
  54014. }
  54015. }
  54016. function legendSelectActionHandler(methodName, payload, ecModel) {
  54017. var isAllSelect = methodName === 'allSelect' || methodName === 'inverseSelect';
  54018. var selectedMap = {};
  54019. var actionLegendIndices = [];
  54020. ecModel.eachComponent({
  54021. mainType: 'legend',
  54022. query: payload
  54023. }, function (legendModel) {
  54024. if (isAllSelect) {
  54025. legendModel[methodName]();
  54026. } else {
  54027. legendModel[methodName](payload.name);
  54028. }
  54029. makeSelectedMap(legendModel, selectedMap);
  54030. actionLegendIndices.push(legendModel.componentIndex);
  54031. });
  54032. var allSelectedMap = {};
  54033. // make selectedMap from all legend components
  54034. ecModel.eachComponent('legend', function (legendModel) {
  54035. each(selectedMap, function (isSelected, name) {
  54036. // Force other legend has same selected status
  54037. // Or the first is toggled to true and other are toggled to false
  54038. // In the case one legend has some item unSelected in option. And if other legend
  54039. // doesn't has the item, they will assume it is selected.
  54040. legendModel[isSelected ? 'select' : 'unSelect'](name);
  54041. });
  54042. makeSelectedMap(legendModel, allSelectedMap);
  54043. });
  54044. // Return the event explicitly
  54045. return isAllSelect ? {
  54046. selected: allSelectedMap,
  54047. // return legendIndex array to tell the developers which legends are allSelect / inverseSelect
  54048. legendIndex: actionLegendIndices
  54049. } : {
  54050. name: payload.name,
  54051. selected: allSelectedMap
  54052. };
  54053. }
  54054. function makeSelectedMap(legendModel, out) {
  54055. var selectedMap = out || {};
  54056. each(legendModel.getData(), function (model) {
  54057. var name = model.get('name');
  54058. // Wrap element
  54059. if (name === '\n' || name === '') {
  54060. return;
  54061. }
  54062. var isItemSelected = legendModel.isSelected(name);
  54063. if (hasOwn(selectedMap, name)) {
  54064. // Unselected if any legend is unselected
  54065. selectedMap[name] = selectedMap[name] && isItemSelected;
  54066. } else {
  54067. selectedMap[name] = isItemSelected;
  54068. }
  54069. });
  54070. return selectedMap;
  54071. }
  54072. function installLegendAction(registers) {
  54073. /**
  54074. * @event legendToggleSelect
  54075. * @type {Object}
  54076. * @property {string} type 'legendToggleSelect'
  54077. * @property {string} [from]
  54078. * @property {string} name Series name or data item name
  54079. */
  54080. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  54081. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  54082. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  54083. /**
  54084. * @event legendSelect
  54085. * @type {Object}
  54086. * @property {string} type 'legendSelect'
  54087. * @property {string} name Series name or data item name
  54088. */
  54089. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  54090. /**
  54091. * @event legendUnSelect
  54092. * @type {Object}
  54093. * @property {string} type 'legendUnSelect'
  54094. * @property {string} name Series name or data item name
  54095. */
  54096. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  54097. }
  54098. function install$h(registers) {
  54099. registers.registerComponentModel(LegendModel);
  54100. registers.registerComponentView(LegendView);
  54101. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  54102. registers.registerSubTypeDefaulter('legend', function () {
  54103. return 'plain';
  54104. });
  54105. installLegendAction(registers);
  54106. }
  54107. var ScrollableLegendModel = /** @class */function (_super) {
  54108. __extends(ScrollableLegendModel, _super);
  54109. function ScrollableLegendModel() {
  54110. var _this = _super !== null && _super.apply(this, arguments) || this;
  54111. _this.type = ScrollableLegendModel.type;
  54112. return _this;
  54113. }
  54114. /**
  54115. * @param {number} scrollDataIndex
  54116. */
  54117. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  54118. this.option.scrollDataIndex = scrollDataIndex;
  54119. };
  54120. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  54121. var inputPositionParams = getLayoutParams(option);
  54122. _super.prototype.init.call(this, option, parentModel, ecModel);
  54123. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  54124. };
  54125. /**
  54126. * @override
  54127. */
  54128. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  54129. _super.prototype.mergeOption.call(this, option, ecModel);
  54130. mergeAndNormalizeLayoutParams(this, this.option, option);
  54131. };
  54132. ScrollableLegendModel.type = 'legend.scroll';
  54133. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  54134. scrollDataIndex: 0,
  54135. pageButtonItemGap: 5,
  54136. pageButtonGap: null,
  54137. pageButtonPosition: 'end',
  54138. pageFormatter: '{current}/{total}',
  54139. pageIcons: {
  54140. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  54141. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  54142. },
  54143. pageIconColor: '#2f4554',
  54144. pageIconInactiveColor: '#aaa',
  54145. pageIconSize: 15,
  54146. pageTextStyle: {
  54147. color: '#333'
  54148. },
  54149. animationDurationUpdate: 800
  54150. });
  54151. return ScrollableLegendModel;
  54152. }(LegendModel);
  54153. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  54154. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  54155. var orient = legendModel.getOrient();
  54156. var ignoreSize = [1, 1];
  54157. ignoreSize[orient.index] = 0;
  54158. mergeLayoutParam(target, raw, {
  54159. type: 'box',
  54160. ignoreSize: !!ignoreSize
  54161. });
  54162. }
  54163. var Group$2 = Group;
  54164. var WH = ['width', 'height'];
  54165. var XY = ['x', 'y'];
  54166. var ScrollableLegendView = /** @class */function (_super) {
  54167. __extends(ScrollableLegendView, _super);
  54168. function ScrollableLegendView() {
  54169. var _this = _super !== null && _super.apply(this, arguments) || this;
  54170. _this.type = ScrollableLegendView.type;
  54171. _this.newlineDisabled = true;
  54172. _this._currentIndex = 0;
  54173. return _this;
  54174. }
  54175. ScrollableLegendView.prototype.init = function () {
  54176. _super.prototype.init.call(this);
  54177. this.group.add(this._containerGroup = new Group$2());
  54178. this._containerGroup.add(this.getContentGroup());
  54179. this.group.add(this._controllerGroup = new Group$2());
  54180. };
  54181. /**
  54182. * @override
  54183. */
  54184. ScrollableLegendView.prototype.resetInner = function () {
  54185. _super.prototype.resetInner.call(this);
  54186. this._controllerGroup.removeAll();
  54187. this._containerGroup.removeClipPath();
  54188. this._containerGroup.__rectSize = null;
  54189. };
  54190. /**
  54191. * @override
  54192. */
  54193. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  54194. var self = this;
  54195. // Render content items.
  54196. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  54197. var controllerGroup = this._controllerGroup;
  54198. // FIXME: support be 'auto' adapt to size number text length,
  54199. // e.g., '3/12345' should not overlap with the control arrow button.
  54200. var pageIconSize = legendModel.get('pageIconSize', true);
  54201. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  54202. createPageButton('pagePrev', 0);
  54203. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  54204. controllerGroup.add(new ZRText({
  54205. name: 'pageText',
  54206. style: {
  54207. // Placeholder to calculate a proper layout.
  54208. text: 'xx/xx',
  54209. fill: pageTextStyleModel.getTextColor(),
  54210. font: pageTextStyleModel.getFont(),
  54211. verticalAlign: 'middle',
  54212. align: 'center'
  54213. },
  54214. silent: true
  54215. }));
  54216. createPageButton('pageNext', 1);
  54217. function createPageButton(name, iconIdx) {
  54218. var pageDataIndexName = name + 'DataIndex';
  54219. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  54220. // Buttons will be created in each render, so we do not need
  54221. // to worry about avoiding using legendModel kept in scope.
  54222. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  54223. }, {
  54224. x: -pageIconSizeArr[0] / 2,
  54225. y: -pageIconSizeArr[1] / 2,
  54226. width: pageIconSizeArr[0],
  54227. height: pageIconSizeArr[1]
  54228. });
  54229. icon.name = name;
  54230. controllerGroup.add(icon);
  54231. }
  54232. };
  54233. /**
  54234. * @override
  54235. */
  54236. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  54237. var selectorGroup = this.getSelectorGroup();
  54238. var orientIdx = legendModel.getOrient().index;
  54239. var wh = WH[orientIdx];
  54240. var xy = XY[orientIdx];
  54241. var hw = WH[1 - orientIdx];
  54242. var yx = XY[1 - orientIdx];
  54243. selector && box(
  54244. // Buttons in selectorGroup always layout horizontally
  54245. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  54246. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  54247. var selectorRect = selectorGroup.getBoundingRect();
  54248. var selectorPos = [-selectorRect.x, -selectorRect.y];
  54249. var processMaxSize = clone(maxSize);
  54250. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  54251. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  54252. if (selector) {
  54253. if (selectorPosition === 'end') {
  54254. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  54255. } else {
  54256. var offset = selectorRect[wh] + selectorButtonGap;
  54257. selectorPos[orientIdx] -= offset;
  54258. mainRect[xy] -= offset;
  54259. }
  54260. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  54261. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  54262. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  54263. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  54264. selectorGroup.x = selectorPos[0];
  54265. selectorGroup.y = selectorPos[1];
  54266. selectorGroup.markRedraw();
  54267. }
  54268. return mainRect;
  54269. };
  54270. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  54271. var contentGroup = this.getContentGroup();
  54272. var containerGroup = this._containerGroup;
  54273. var controllerGroup = this._controllerGroup;
  54274. // Place items in contentGroup.
  54275. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  54276. box(
  54277. // Buttons in controller are layout always horizontally.
  54278. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  54279. var contentRect = contentGroup.getBoundingRect();
  54280. var controllerRect = controllerGroup.getBoundingRect();
  54281. var showController = this._showController = contentRect[wh] > maxSize[wh];
  54282. // In case that the inner elements of contentGroup layout do not based on [0, 0]
  54283. var contentPos = [-contentRect.x, -contentRect.y];
  54284. // Remain contentPos when scroll animation perfroming.
  54285. // If first rendering, `contentGroup.position` is [0, 0], which
  54286. // does not make sense and may cause unexepcted animation if adopted.
  54287. if (!isFirstRender) {
  54288. contentPos[orientIdx] = contentGroup[xy];
  54289. }
  54290. // Layout container group based on 0.
  54291. var containerPos = [0, 0];
  54292. var controllerPos = [-controllerRect.x, -controllerRect.y];
  54293. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true));
  54294. // Place containerGroup and controllerGroup and contentGroup.
  54295. if (showController) {
  54296. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  54297. // controller is on the right / bottom.
  54298. if (pageButtonPosition === 'end') {
  54299. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  54300. }
  54301. // controller is on the left / top.
  54302. else {
  54303. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  54304. }
  54305. }
  54306. // Always align controller to content as 'middle'.
  54307. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  54308. contentGroup.setPosition(contentPos);
  54309. containerGroup.setPosition(containerPos);
  54310. controllerGroup.setPosition(controllerPos);
  54311. // Calculate `mainRect` and set `clipPath`.
  54312. // mainRect should not be calculated by `this.group.getBoundingRect()`
  54313. // for sake of the overflow.
  54314. var mainRect = {
  54315. x: 0,
  54316. y: 0
  54317. };
  54318. // Consider content may be overflow (should be clipped).
  54319. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  54320. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  54321. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  54322. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  54323. containerGroup.__rectSize = maxSize[wh];
  54324. if (showController) {
  54325. var clipShape = {
  54326. x: 0,
  54327. y: 0
  54328. };
  54329. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  54330. clipShape[hw] = mainRect[hw];
  54331. containerGroup.setClipPath(new Rect({
  54332. shape: clipShape
  54333. }));
  54334. // Consider content may be larger than container, container rect
  54335. // can not be obtained from `containerGroup.getBoundingRect()`.
  54336. containerGroup.__rectSize = clipShape[wh];
  54337. } else {
  54338. // Do not remove or ignore controller. Keep them set as placeholders.
  54339. controllerGroup.eachChild(function (child) {
  54340. child.attr({
  54341. invisible: true,
  54342. silent: true
  54343. });
  54344. });
  54345. }
  54346. // Content translate animation.
  54347. var pageInfo = this._getPageInfo(legendModel);
  54348. pageInfo.pageIndex != null && updateProps(contentGroup, {
  54349. x: pageInfo.contentPosition[0],
  54350. y: pageInfo.contentPosition[1]
  54351. },
  54352. // When switch from "show controller" to "not show controller", view should be
  54353. // updated immediately without animation, otherwise causes weird effect.
  54354. showController ? legendModel : null);
  54355. this._updatePageInfoView(legendModel, pageInfo);
  54356. return mainRect;
  54357. };
  54358. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  54359. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  54360. scrollDataIndex != null && api.dispatchAction({
  54361. type: 'legendScroll',
  54362. scrollDataIndex: scrollDataIndex,
  54363. legendId: legendModel.id
  54364. });
  54365. };
  54366. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  54367. var controllerGroup = this._controllerGroup;
  54368. each(['pagePrev', 'pageNext'], function (name) {
  54369. var key = name + 'DataIndex';
  54370. var canJump = pageInfo[key] != null;
  54371. var icon = controllerGroup.childOfName(name);
  54372. if (icon) {
  54373. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  54374. icon.cursor = canJump ? 'pointer' : 'default';
  54375. }
  54376. });
  54377. var pageText = controllerGroup.childOfName('pageText');
  54378. var pageFormatter = legendModel.get('pageFormatter');
  54379. var pageIndex = pageInfo.pageIndex;
  54380. var current = pageIndex != null ? pageIndex + 1 : 0;
  54381. var total = pageInfo.pageCount;
  54382. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  54383. current: current,
  54384. total: total
  54385. }));
  54386. };
  54387. /**
  54388. * contentPosition: Array.<number>, null when data item not found.
  54389. * pageIndex: number, null when data item not found.
  54390. * pageCount: number, always be a number, can be 0.
  54391. * pagePrevDataIndex: number, null when no previous page.
  54392. * pageNextDataIndex: number, null when no next page.
  54393. * }
  54394. */
  54395. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  54396. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  54397. var contentGroup = this.getContentGroup();
  54398. var containerRectSize = this._containerGroup.__rectSize;
  54399. var orientIdx = legendModel.getOrient().index;
  54400. var wh = WH[orientIdx];
  54401. var xy = XY[orientIdx];
  54402. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  54403. var children = contentGroup.children();
  54404. var targetItem = children[targetItemIndex];
  54405. var itemCount = children.length;
  54406. var pCount = !itemCount ? 0 : 1;
  54407. var result = {
  54408. contentPosition: [contentGroup.x, contentGroup.y],
  54409. pageCount: pCount,
  54410. pageIndex: pCount - 1,
  54411. pagePrevDataIndex: null,
  54412. pageNextDataIndex: null
  54413. };
  54414. if (!targetItem) {
  54415. return result;
  54416. }
  54417. var targetItemInfo = getItemInfo(targetItem);
  54418. result.contentPosition[orientIdx] = -targetItemInfo.s;
  54419. // Strategy:
  54420. // (1) Always align based on the left/top most item.
  54421. // (2) It is user-friendly that the last item shown in the
  54422. // current window is shown at the begining of next window.
  54423. // Otherwise if half of the last item is cut by the window,
  54424. // it will have no chance to display entirely.
  54425. // (3) Consider that item size probably be different, we
  54426. // have calculate pageIndex by size rather than item index,
  54427. // and we can not get page index directly by division.
  54428. // (4) The window is to narrow to contain more than
  54429. // one item, we should make sure that the page can be fliped.
  54430. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  54431. currItemInfo = getItemInfo(children[i]);
  54432. if (
  54433. // Half of the last item is out of the window.
  54434. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize
  54435. // If the current item does not intersect with the window, the new page
  54436. // can be started at the current item or the last item.
  54437. || currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  54438. if (winEndItemInfo.i > winStartItemInfo.i) {
  54439. winStartItemInfo = winEndItemInfo;
  54440. } else {
  54441. // e.g., when page size is smaller than item size.
  54442. winStartItemInfo = currItemInfo;
  54443. }
  54444. if (winStartItemInfo) {
  54445. if (result.pageNextDataIndex == null) {
  54446. result.pageNextDataIndex = winStartItemInfo.i;
  54447. }
  54448. ++result.pageCount;
  54449. }
  54450. }
  54451. winEndItemInfo = currItemInfo;
  54452. }
  54453. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  54454. currItemInfo = getItemInfo(children[i]);
  54455. if (
  54456. // If the the end item does not intersect with the window started
  54457. // from the current item, a page can be settled.
  54458. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)
  54459. // e.g., when page size is smaller than item size.
  54460. ) && winStartItemInfo.i < winEndItemInfo.i) {
  54461. winEndItemInfo = winStartItemInfo;
  54462. if (result.pagePrevDataIndex == null) {
  54463. result.pagePrevDataIndex = winStartItemInfo.i;
  54464. }
  54465. ++result.pageCount;
  54466. ++result.pageIndex;
  54467. }
  54468. winStartItemInfo = currItemInfo;
  54469. }
  54470. return result;
  54471. function getItemInfo(el) {
  54472. if (el) {
  54473. var itemRect = el.getBoundingRect();
  54474. var start = itemRect[xy] + el[xy];
  54475. return {
  54476. s: start,
  54477. e: start + itemRect[wh],
  54478. i: el.__legendDataIndex
  54479. };
  54480. }
  54481. }
  54482. function intersect(itemInfo, winStart) {
  54483. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  54484. }
  54485. };
  54486. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  54487. if (!this._showController) {
  54488. return 0;
  54489. }
  54490. var index;
  54491. var contentGroup = this.getContentGroup();
  54492. var defaultIndex;
  54493. contentGroup.eachChild(function (child, idx) {
  54494. var legendDataIdx = child.__legendDataIndex;
  54495. // FIXME
  54496. // If the given targetDataIndex (from model) is illegal,
  54497. // we use defaultIndex. But the index on the legend model and
  54498. // action payload is still illegal. That case will not be
  54499. // changed until some scenario requires.
  54500. if (defaultIndex == null && legendDataIdx != null) {
  54501. defaultIndex = idx;
  54502. }
  54503. if (legendDataIdx === targetDataIndex) {
  54504. index = idx;
  54505. }
  54506. });
  54507. return index != null ? index : defaultIndex;
  54508. };
  54509. ScrollableLegendView.type = 'legend.scroll';
  54510. return ScrollableLegendView;
  54511. }(LegendView);
  54512. /*
  54513. * Licensed to the Apache Software Foundation (ASF) under one
  54514. * or more contributor license agreements. See the NOTICE file
  54515. * distributed with this work for additional information
  54516. * regarding copyright ownership. The ASF licenses this file
  54517. * to you under the Apache License, Version 2.0 (the
  54518. * "License"); you may not use this file except in compliance
  54519. * with the License. You may obtain a copy of the License at
  54520. *
  54521. * http://www.apache.org/licenses/LICENSE-2.0
  54522. *
  54523. * Unless required by applicable law or agreed to in writing,
  54524. * software distributed under the License is distributed on an
  54525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54526. * KIND, either express or implied. See the License for the
  54527. * specific language governing permissions and limitations
  54528. * under the License.
  54529. */
  54530. /**
  54531. * AUTO-GENERATED FILE. DO NOT MODIFY.
  54532. */
  54533. /*
  54534. * Licensed to the Apache Software Foundation (ASF) under one
  54535. * or more contributor license agreements. See the NOTICE file
  54536. * distributed with this work for additional information
  54537. * regarding copyright ownership. The ASF licenses this file
  54538. * to you under the Apache License, Version 2.0 (the
  54539. * "License"); you may not use this file except in compliance
  54540. * with the License. You may obtain a copy of the License at
  54541. *
  54542. * http://www.apache.org/licenses/LICENSE-2.0
  54543. *
  54544. * Unless required by applicable law or agreed to in writing,
  54545. * software distributed under the License is distributed on an
  54546. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54547. * KIND, either express or implied. See the License for the
  54548. * specific language governing permissions and limitations
  54549. * under the License.
  54550. */
  54551. function installScrollableLegendAction(registers) {
  54552. /**
  54553. * @event legendScroll
  54554. * @type {Object}
  54555. * @property {string} type 'legendScroll'
  54556. * @property {string} scrollDataIndex
  54557. */
  54558. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  54559. var scrollDataIndex = payload.scrollDataIndex;
  54560. scrollDataIndex != null && ecModel.eachComponent({
  54561. mainType: 'legend',
  54562. subType: 'scroll',
  54563. query: payload
  54564. }, function (legendModel) {
  54565. legendModel.setScrollDataIndex(scrollDataIndex);
  54566. });
  54567. });
  54568. }
  54569. function install$i(registers) {
  54570. use(install$h);
  54571. registers.registerComponentModel(ScrollableLegendModel);
  54572. registers.registerComponentView(ScrollableLegendView);
  54573. installScrollableLegendAction(registers);
  54574. }
  54575. function install$j(registers) {
  54576. use(install$h);
  54577. use(install$i);
  54578. }
  54579. var InsideZoomModel = /** @class */function (_super) {
  54580. __extends(InsideZoomModel, _super);
  54581. function InsideZoomModel() {
  54582. var _this = _super !== null && _super.apply(this, arguments) || this;
  54583. _this.type = InsideZoomModel.type;
  54584. return _this;
  54585. }
  54586. InsideZoomModel.type = 'dataZoom.inside';
  54587. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  54588. disabled: false,
  54589. zoomLock: false,
  54590. zoomOnMouseWheel: true,
  54591. moveOnMouseMove: true,
  54592. moveOnMouseWheel: false,
  54593. preventDefaultMouseMove: true
  54594. });
  54595. return InsideZoomModel;
  54596. }(DataZoomModel);
  54597. var RoamController = /** @class */function (_super) {
  54598. __extends(RoamController, _super);
  54599. function RoamController(zr) {
  54600. var _this = _super.call(this) || this;
  54601. _this._zr = zr;
  54602. // Avoid two roamController bind the same handler
  54603. var mousedownHandler = bind(_this._mousedownHandler, _this);
  54604. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  54605. var mouseupHandler = bind(_this._mouseupHandler, _this);
  54606. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  54607. var pinchHandler = bind(_this._pinchHandler, _this);
  54608. /**
  54609. * Notice: only enable needed types. For example, if 'zoom'
  54610. * is not needed, 'zoom' should not be enabled, otherwise
  54611. * default mousewheel behaviour (scroll page) will be disabled.
  54612. */
  54613. _this.enable = function (controlType, opt) {
  54614. // Disable previous first
  54615. this.disable();
  54616. this._opt = defaults(clone(opt) || {}, {
  54617. zoomOnMouseWheel: true,
  54618. moveOnMouseMove: true,
  54619. // By default, wheel do not trigger move.
  54620. moveOnMouseWheel: false,
  54621. preventDefaultMouseMove: true
  54622. });
  54623. if (controlType == null) {
  54624. controlType = true;
  54625. }
  54626. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  54627. zr.on('mousedown', mousedownHandler);
  54628. zr.on('mousemove', mousemoveHandler);
  54629. zr.on('mouseup', mouseupHandler);
  54630. }
  54631. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  54632. zr.on('mousewheel', mousewheelHandler);
  54633. zr.on('pinch', pinchHandler);
  54634. }
  54635. };
  54636. _this.disable = function () {
  54637. zr.off('mousedown', mousedownHandler);
  54638. zr.off('mousemove', mousemoveHandler);
  54639. zr.off('mouseup', mouseupHandler);
  54640. zr.off('mousewheel', mousewheelHandler);
  54641. zr.off('pinch', pinchHandler);
  54642. };
  54643. return _this;
  54644. }
  54645. RoamController.prototype.isDragging = function () {
  54646. return this._dragging;
  54647. };
  54648. RoamController.prototype.isPinching = function () {
  54649. return this._pinching;
  54650. };
  54651. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  54652. this.pointerChecker = pointerChecker;
  54653. };
  54654. RoamController.prototype.dispose = function () {
  54655. this.disable();
  54656. };
  54657. RoamController.prototype._mousedownHandler = function (e) {
  54658. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  54659. return;
  54660. }
  54661. var el = e.target;
  54662. while (el) {
  54663. if (el.draggable) {
  54664. return;
  54665. }
  54666. // check if host is draggable
  54667. el = el.__hostTarget || el.parent;
  54668. }
  54669. var x = e.offsetX;
  54670. var y = e.offsetY;
  54671. // Only check on mosedown, but not mousemove.
  54672. // Mouse can be out of target when mouse moving.
  54673. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  54674. this._x = x;
  54675. this._y = y;
  54676. this._dragging = true;
  54677. }
  54678. };
  54679. RoamController.prototype._mousemoveHandler = function (e) {
  54680. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  54681. return;
  54682. }
  54683. var x = e.offsetX;
  54684. var y = e.offsetY;
  54685. var oldX = this._x;
  54686. var oldY = this._y;
  54687. var dx = x - oldX;
  54688. var dy = y - oldY;
  54689. this._x = x;
  54690. this._y = y;
  54691. this._opt.preventDefaultMouseMove && stop(e.event);
  54692. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  54693. dx: dx,
  54694. dy: dy,
  54695. oldX: oldX,
  54696. oldY: oldY,
  54697. newX: x,
  54698. newY: y,
  54699. isAvailableBehavior: null
  54700. });
  54701. };
  54702. RoamController.prototype._mouseupHandler = function (e) {
  54703. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  54704. this._dragging = false;
  54705. }
  54706. };
  54707. RoamController.prototype._mousewheelHandler = function (e) {
  54708. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  54709. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  54710. var wheelDelta = e.wheelDelta;
  54711. var absWheelDeltaDelta = Math.abs(wheelDelta);
  54712. var originX = e.offsetX;
  54713. var originY = e.offsetY;
  54714. // wheelDelta maybe -0 in chrome mac.
  54715. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  54716. return;
  54717. }
  54718. // If both `shouldZoom` and `shouldMove` is true, trigger
  54719. // their event both, and the final behavior is determined
  54720. // by event listener themselves.
  54721. if (shouldZoom) {
  54722. // Convenience:
  54723. // Mac and VM Windows on Mac: scroll up: zoom out.
  54724. // Windows: scroll up: zoom in.
  54725. // FIXME: Should do more test in different environment.
  54726. // wheelDelta is too complicated in difference nvironment
  54727. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  54728. // although it has been normallized by zrender.
  54729. // wheelDelta of mouse wheel is bigger than touch pad.
  54730. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  54731. var scale = wheelDelta > 0 ? factor : 1 / factor;
  54732. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  54733. scale: scale,
  54734. originX: originX,
  54735. originY: originY,
  54736. isAvailableBehavior: null
  54737. });
  54738. }
  54739. if (shouldMove) {
  54740. // FIXME: Should do more test in different environment.
  54741. var absDelta = Math.abs(wheelDelta);
  54742. // wheelDelta of mouse wheel is bigger than touch pad.
  54743. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  54744. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  54745. scrollDelta: scrollDelta,
  54746. originX: originX,
  54747. originY: originY,
  54748. isAvailableBehavior: null
  54749. });
  54750. }
  54751. };
  54752. RoamController.prototype._pinchHandler = function (e) {
  54753. if (isTaken(this._zr, 'globalPan')) {
  54754. return;
  54755. }
  54756. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  54757. checkPointerAndTrigger(this, 'zoom', null, e, {
  54758. scale: scale,
  54759. originX: e.pinchX,
  54760. originY: e.pinchY,
  54761. isAvailableBehavior: null
  54762. });
  54763. };
  54764. return RoamController;
  54765. }(Eventful);
  54766. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  54767. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  54768. // When mouse is out of roamController rect,
  54769. // default befavoius should not be be disabled, otherwise
  54770. // page sliding is disabled, contrary to expectation.
  54771. stop(e.event);
  54772. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  54773. }
  54774. }
  54775. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  54776. // Also provide behavior checker for event listener, for some case that
  54777. // multiple components share one listener.
  54778. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  54779. // TODO should not have type issue.
  54780. controller.trigger(eventName, contollerEvent);
  54781. }
  54782. // settings: {
  54783. // zoomOnMouseWheel
  54784. // moveOnMouseMove
  54785. // moveOnMouseWheel
  54786. // }
  54787. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  54788. function isAvailableBehavior(behaviorToCheck, e, settings) {
  54789. var setting = settings[behaviorToCheck];
  54790. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  54791. }
  54792. var inner$g = makeInner();
  54793. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  54794. inner$g(api).coordSysRecordMap.each(function (coordSysRecord) {
  54795. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  54796. if (dzInfo) {
  54797. dzInfo.getRange = getRange;
  54798. }
  54799. });
  54800. }
  54801. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  54802. var coordSysRecordMap = inner$g(api).coordSysRecordMap;
  54803. var coordSysKeyArr = coordSysRecordMap.keys();
  54804. for (var i = 0; i < coordSysKeyArr.length; i++) {
  54805. var coordSysKey = coordSysKeyArr[i];
  54806. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  54807. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  54808. if (dataZoomInfoMap) {
  54809. var dzUid = dataZoomModel.uid;
  54810. var dzInfo = dataZoomInfoMap.get(dzUid);
  54811. if (dzInfo) {
  54812. dataZoomInfoMap.removeKey(dzUid);
  54813. if (!dataZoomInfoMap.keys().length) {
  54814. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  54815. }
  54816. }
  54817. }
  54818. }
  54819. }
  54820. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  54821. if (coordSysRecord) {
  54822. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  54823. var controller = coordSysRecord.controller;
  54824. controller && controller.dispose();
  54825. }
  54826. }
  54827. function createCoordSysRecord(api, coordSysModel) {
  54828. // These init props will never change after record created.
  54829. var coordSysRecord = {
  54830. model: coordSysModel,
  54831. containsPoint: curry(containsPoint, coordSysModel),
  54832. dispatchAction: curry(dispatchAction, api),
  54833. dataZoomInfoMap: null,
  54834. controller: null
  54835. };
  54836. // Must not do anything depends on coordSysRecord outside the event handler here,
  54837. // because coordSysRecord not completed yet.
  54838. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  54839. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  54840. controller.on(eventName, function (event) {
  54841. var batch = [];
  54842. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  54843. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  54844. // moveOnMouseWheel, ...) enabled.
  54845. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  54846. return;
  54847. }
  54848. var method = (dzInfo.getRange || {})[eventName];
  54849. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  54850. !dzInfo.model.get('disabled', true) && range && batch.push({
  54851. dataZoomId: dzInfo.model.id,
  54852. start: range[0],
  54853. end: range[1]
  54854. });
  54855. });
  54856. batch.length && coordSysRecord.dispatchAction(batch);
  54857. });
  54858. });
  54859. return coordSysRecord;
  54860. }
  54861. /**
  54862. * This action will be throttled.
  54863. */
  54864. function dispatchAction(api, batch) {
  54865. if (!api.isDisposed()) {
  54866. api.dispatchAction({
  54867. type: 'dataZoom',
  54868. animation: {
  54869. easing: 'cubicOut',
  54870. duration: 100
  54871. },
  54872. batch: batch
  54873. });
  54874. }
  54875. }
  54876. function containsPoint(coordSysModel, e, x, y) {
  54877. return coordSysModel.coordinateSystem.containPoint([x, y]);
  54878. }
  54879. /**
  54880. * Merge roamController settings when multiple dataZooms share one roamController.
  54881. */
  54882. function mergeControllerParams(dataZoomInfoMap) {
  54883. var controlType;
  54884. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  54885. // as string, it is probably revert to reserved word by compress tool. See #7411.
  54886. var prefix = 'type_';
  54887. var typePriority = {
  54888. 'type_true': 2,
  54889. 'type_move': 1,
  54890. 'type_false': 0,
  54891. 'type_undefined': -1
  54892. };
  54893. var preventDefaultMouseMove = true;
  54894. dataZoomInfoMap.each(function (dataZoomInfo) {
  54895. var dataZoomModel = dataZoomInfo.model;
  54896. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  54897. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  54898. controlType = oneType;
  54899. }
  54900. // Prevent default move event by default. If one false, do not prevent. Otherwise
  54901. // users may be confused why it does not work when multiple insideZooms exist.
  54902. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  54903. });
  54904. return {
  54905. controlType: controlType,
  54906. opt: {
  54907. // RoamController will enable all of these functionalities,
  54908. // and the final behavior is determined by its event listener
  54909. // provided by each inside zoom.
  54910. zoomOnMouseWheel: true,
  54911. moveOnMouseMove: true,
  54912. moveOnMouseWheel: true,
  54913. preventDefaultMouseMove: !!preventDefaultMouseMove
  54914. }
  54915. };
  54916. }
  54917. function installDataZoomRoamProcessor(registers) {
  54918. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  54919. var apiInner = inner$g(api);
  54920. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  54921. coordSysRecordMap.each(function (coordSysRecord) {
  54922. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  54923. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  54924. coordSysRecord.dataZoomInfoMap = null;
  54925. });
  54926. ecModel.eachComponent({
  54927. mainType: 'dataZoom',
  54928. subType: 'inside'
  54929. }, function (dataZoomModel) {
  54930. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  54931. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  54932. var coordSysUid = dzCoordSysInfo.model.uid;
  54933. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  54934. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap());
  54935. // Notice these props might be changed each time for a single dataZoomModel.
  54936. dataZoomInfoMap.set(dataZoomModel.uid, {
  54937. dzReferCoordSysInfo: dzCoordSysInfo,
  54938. model: dataZoomModel,
  54939. getRange: null
  54940. });
  54941. });
  54942. });
  54943. // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  54944. // (2) Clear coord sys if not refered by any dataZoom.
  54945. coordSysRecordMap.each(function (coordSysRecord) {
  54946. var controller = coordSysRecord.controller;
  54947. var firstDzInfo;
  54948. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  54949. if (dataZoomInfoMap) {
  54950. var firstDzKey = dataZoomInfoMap.keys()[0];
  54951. if (firstDzKey != null) {
  54952. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  54953. }
  54954. }
  54955. if (!firstDzInfo) {
  54956. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  54957. return;
  54958. }
  54959. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  54960. controller.enable(controllerParams.controlType, controllerParams.opt);
  54961. controller.setPointerChecker(coordSysRecord.containsPoint);
  54962. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  54963. });
  54964. });
  54965. }
  54966. var InsideZoomView = /** @class */function (_super) {
  54967. __extends(InsideZoomView, _super);
  54968. function InsideZoomView() {
  54969. var _this = _super !== null && _super.apply(this, arguments) || this;
  54970. _this.type = 'dataZoom.inside';
  54971. return _this;
  54972. }
  54973. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  54974. _super.prototype.render.apply(this, arguments);
  54975. if (dataZoomModel.noTarget()) {
  54976. this._clear();
  54977. return;
  54978. }
  54979. // Hence the `throttle` util ensures to preserve command order,
  54980. // here simply updating range all the time will not cause missing
  54981. // any of the the roam change.
  54982. this.range = dataZoomModel.getPercentRange();
  54983. // Reset controllers.
  54984. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  54985. pan: bind(getRangeHandlers.pan, this),
  54986. zoom: bind(getRangeHandlers.zoom, this),
  54987. scrollMove: bind(getRangeHandlers.scrollMove, this)
  54988. });
  54989. };
  54990. InsideZoomView.prototype.dispose = function () {
  54991. this._clear();
  54992. _super.prototype.dispose.apply(this, arguments);
  54993. };
  54994. InsideZoomView.prototype._clear = function () {
  54995. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  54996. this.range = null;
  54997. };
  54998. InsideZoomView.type = 'dataZoom.inside';
  54999. return InsideZoomView;
  55000. }(DataZoomView);
  55001. var getRangeHandlers = {
  55002. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  55003. var lastRange = this.range;
  55004. var range = lastRange.slice();
  55005. // Calculate transform by the first axis.
  55006. var axisModel = coordSysInfo.axisModels[0];
  55007. if (!axisModel) {
  55008. return;
  55009. }
  55010. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  55011. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  55012. var scale = Math.max(1 / e.scale, 0);
  55013. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  55014. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  55015. // Restrict range.
  55016. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55017. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  55018. this.range = range;
  55019. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  55020. return range;
  55021. }
  55022. },
  55023. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  55024. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  55025. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  55026. }),
  55027. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  55028. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  55029. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  55030. })
  55031. };
  55032. function makeMover(getPercentDelta) {
  55033. return function (coordSysInfo, coordSysMainType, controller, e) {
  55034. var lastRange = this.range;
  55035. var range = lastRange.slice();
  55036. // Calculate transform by the first axis.
  55037. var axisModel = coordSysInfo.axisModels[0];
  55038. if (!axisModel) {
  55039. return;
  55040. }
  55041. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  55042. sliderMove(percentDelta, range, [0, 100], 'all');
  55043. this.range = range;
  55044. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  55045. return range;
  55046. }
  55047. };
  55048. }
  55049. var getDirectionInfo = {
  55050. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  55051. var axis = axisModel.axis;
  55052. var ret = {};
  55053. var rect = coordSysInfo.model.coordinateSystem.getRect();
  55054. oldPoint = oldPoint || [0, 0];
  55055. if (axis.dim === 'x') {
  55056. ret.pixel = newPoint[0] - oldPoint[0];
  55057. ret.pixelLength = rect.width;
  55058. ret.pixelStart = rect.x;
  55059. ret.signal = axis.inverse ? 1 : -1;
  55060. } else {
  55061. // axis.dim === 'y'
  55062. ret.pixel = newPoint[1] - oldPoint[1];
  55063. ret.pixelLength = rect.height;
  55064. ret.pixelStart = rect.y;
  55065. ret.signal = axis.inverse ? -1 : 1;
  55066. }
  55067. return ret;
  55068. },
  55069. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  55070. var axis = axisModel.axis;
  55071. var ret = {};
  55072. var polar = coordSysInfo.model.coordinateSystem;
  55073. var radiusExtent = polar.getRadiusAxis().getExtent();
  55074. var angleExtent = polar.getAngleAxis().getExtent();
  55075. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  55076. newPoint = polar.pointToCoord(newPoint);
  55077. if (axisModel.mainType === 'radiusAxis') {
  55078. ret.pixel = newPoint[0] - oldPoint[0];
  55079. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  55080. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  55081. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  55082. ret.pixelStart = radiusExtent[0];
  55083. ret.signal = axis.inverse ? 1 : -1;
  55084. } else {
  55085. // 'angleAxis'
  55086. ret.pixel = newPoint[1] - oldPoint[1];
  55087. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  55088. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  55089. ret.pixelLength = angleExtent[1] - angleExtent[0];
  55090. ret.pixelStart = angleExtent[0];
  55091. ret.signal = axis.inverse ? -1 : 1;
  55092. }
  55093. return ret;
  55094. },
  55095. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  55096. var axis = axisModel.axis;
  55097. var rect = coordSysInfo.model.coordinateSystem.getRect();
  55098. var ret = {};
  55099. oldPoint = oldPoint || [0, 0];
  55100. if (axis.orient === 'horizontal') {
  55101. ret.pixel = newPoint[0] - oldPoint[0];
  55102. ret.pixelLength = rect.width;
  55103. ret.pixelStart = rect.x;
  55104. ret.signal = axis.inverse ? 1 : -1;
  55105. } else {
  55106. // 'vertical'
  55107. ret.pixel = newPoint[1] - oldPoint[1];
  55108. ret.pixelLength = rect.height;
  55109. ret.pixelStart = rect.y;
  55110. ret.signal = axis.inverse ? -1 : 1;
  55111. }
  55112. return ret;
  55113. }
  55114. };
  55115. function install$k(registers) {
  55116. installCommon(registers);
  55117. registers.registerComponentModel(InsideZoomModel);
  55118. registers.registerComponentView(InsideZoomView);
  55119. installDataZoomRoamProcessor(registers);
  55120. }
  55121. var SliderZoomModel = /** @class */function (_super) {
  55122. __extends(SliderZoomModel, _super);
  55123. function SliderZoomModel() {
  55124. var _this = _super !== null && _super.apply(this, arguments) || this;
  55125. _this.type = SliderZoomModel.type;
  55126. return _this;
  55127. }
  55128. SliderZoomModel.type = 'dataZoom.slider';
  55129. SliderZoomModel.layoutMode = 'box';
  55130. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  55131. show: true,
  55132. // deault value can only be drived in view stage.
  55133. right: 'ph',
  55134. top: 'ph',
  55135. width: 'ph',
  55136. height: 'ph',
  55137. left: null,
  55138. bottom: null,
  55139. borderColor: '#d2dbee',
  55140. borderRadius: 3,
  55141. backgroundColor: 'rgba(47,69,84,0)',
  55142. // dataBackgroundColor: '#ddd',
  55143. dataBackground: {
  55144. lineStyle: {
  55145. color: '#d2dbee',
  55146. width: 0.5
  55147. },
  55148. areaStyle: {
  55149. color: '#d2dbee',
  55150. opacity: 0.2
  55151. }
  55152. },
  55153. selectedDataBackground: {
  55154. lineStyle: {
  55155. color: '#8fb0f7',
  55156. width: 0.5
  55157. },
  55158. areaStyle: {
  55159. color: '#8fb0f7',
  55160. opacity: 0.2
  55161. }
  55162. },
  55163. // Color of selected window.
  55164. fillerColor: 'rgba(135,175,274,0.2)',
  55165. handleIcon: 'path://M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z',
  55166. // Percent of the slider height
  55167. handleSize: '100%',
  55168. handleStyle: {
  55169. color: '#fff',
  55170. borderColor: '#ACB8D1'
  55171. },
  55172. moveHandleSize: 7,
  55173. moveHandleIcon: 'path://M-320.9-50L-320.9-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-348-41-339-50-320.9-50z M-212.3-50L-212.3-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-239.4-41-230.4-50-212.3-50z M-103.7-50L-103.7-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-130.9-41-121.8-50-103.7-50z',
  55174. moveHandleStyle: {
  55175. color: '#D2DBEE',
  55176. opacity: 0.7
  55177. },
  55178. showDetail: true,
  55179. showDataShadow: 'auto',
  55180. realtime: true,
  55181. zoomLock: false,
  55182. textStyle: {
  55183. color: '#6E7079'
  55184. },
  55185. brushSelect: true,
  55186. brushStyle: {
  55187. color: 'rgba(135,175,274,0.15)'
  55188. },
  55189. emphasis: {
  55190. handleLabel: {
  55191. show: true
  55192. },
  55193. handleStyle: {
  55194. borderColor: '#8FB0F7'
  55195. },
  55196. moveHandleStyle: {
  55197. color: '#8FB0F7'
  55198. }
  55199. }
  55200. });
  55201. return SliderZoomModel;
  55202. }(DataZoomModel);
  55203. var Rect$1 = Rect;
  55204. // Constants
  55205. var DEFAULT_LOCATION_EDGE_GAP = 7;
  55206. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  55207. var DEFAULT_FILLER_SIZE = 30;
  55208. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  55209. var HORIZONTAL = 'horizontal';
  55210. var VERTICAL = 'vertical';
  55211. var LABEL_GAP = 5;
  55212. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  55213. var REALTIME_ANIMATION_CONFIG = {
  55214. easing: 'cubicOut',
  55215. duration: 100,
  55216. delay: 0
  55217. };
  55218. var SliderZoomView = /** @class */function (_super) {
  55219. __extends(SliderZoomView, _super);
  55220. function SliderZoomView() {
  55221. var _this = _super !== null && _super.apply(this, arguments) || this;
  55222. _this.type = SliderZoomView.type;
  55223. _this._displayables = {};
  55224. return _this;
  55225. }
  55226. SliderZoomView.prototype.init = function (ecModel, api) {
  55227. this.api = api;
  55228. // A unique handler for each dataZoom component
  55229. this._onBrush = bind(this._onBrush, this);
  55230. this._onBrushEnd = bind(this._onBrushEnd, this);
  55231. };
  55232. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  55233. _super.prototype.render.apply(this, arguments);
  55234. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  55235. this._orient = dataZoomModel.getOrient();
  55236. if (dataZoomModel.get('show') === false) {
  55237. this.group.removeAll();
  55238. return;
  55239. }
  55240. if (dataZoomModel.noTarget()) {
  55241. this._clear();
  55242. this.group.removeAll();
  55243. return;
  55244. }
  55245. // Notice: this._resetInterval() should not be executed when payload.type
  55246. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  55247. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  55248. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  55249. this._buildView();
  55250. }
  55251. this._updateView();
  55252. };
  55253. SliderZoomView.prototype.dispose = function () {
  55254. this._clear();
  55255. _super.prototype.dispose.apply(this, arguments);
  55256. };
  55257. SliderZoomView.prototype._clear = function () {
  55258. clear(this, '_dispatchZoomAction');
  55259. var zr = this.api.getZr();
  55260. zr.off('mousemove', this._onBrush);
  55261. zr.off('mouseup', this._onBrushEnd);
  55262. };
  55263. SliderZoomView.prototype._buildView = function () {
  55264. var thisGroup = this.group;
  55265. thisGroup.removeAll();
  55266. this._brushing = false;
  55267. this._displayables.brushRect = null;
  55268. this._resetLocation();
  55269. this._resetInterval();
  55270. var barGroup = this._displayables.sliderGroup = new Group();
  55271. this._renderBackground();
  55272. this._renderHandle();
  55273. this._renderDataShadow();
  55274. thisGroup.add(barGroup);
  55275. this._positionGroup();
  55276. };
  55277. SliderZoomView.prototype._resetLocation = function () {
  55278. var dataZoomModel = this.dataZoomModel;
  55279. var api = this.api;
  55280. var showMoveHandle = dataZoomModel.get('brushSelect');
  55281. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0;
  55282. // If some of x/y/width/height are not specified,
  55283. // auto-adapt according to target grid.
  55284. var coordRect = this._findCoordRect();
  55285. var ecSize = {
  55286. width: api.getWidth(),
  55287. height: api.getHeight()
  55288. };
  55289. // Default align by coordinate system rect.
  55290. var positionInfo = this._orient === HORIZONTAL ? {
  55291. // Why using 'right', because right should be used in vertical,
  55292. // and it is better to be consistent for dealing with position param merge.
  55293. right: ecSize.width - coordRect.x - coordRect.width,
  55294. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  55295. width: coordRect.width,
  55296. height: DEFAULT_FILLER_SIZE
  55297. } : {
  55298. right: DEFAULT_LOCATION_EDGE_GAP,
  55299. top: coordRect.y,
  55300. width: DEFAULT_FILLER_SIZE,
  55301. height: coordRect.height
  55302. };
  55303. // Do not write back to option and replace value 'ph', because
  55304. // the 'ph' value should be recalculated when resize.
  55305. var layoutParams = getLayoutParams(dataZoomModel.option);
  55306. // Replace the placeholder value.
  55307. each(['right', 'top', 'width', 'height'], function (name) {
  55308. if (layoutParams[name] === 'ph') {
  55309. layoutParams[name] = positionInfo[name];
  55310. }
  55311. });
  55312. var layoutRect = getLayoutRect(layoutParams, ecSize);
  55313. this._location = {
  55314. x: layoutRect.x,
  55315. y: layoutRect.y
  55316. };
  55317. this._size = [layoutRect.width, layoutRect.height];
  55318. this._orient === VERTICAL && this._size.reverse();
  55319. };
  55320. SliderZoomView.prototype._positionGroup = function () {
  55321. var thisGroup = this.group;
  55322. var location = this._location;
  55323. var orient = this._orient;
  55324. // Just use the first axis to determine mapping.
  55325. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  55326. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  55327. var sliderGroup = this._displayables.sliderGroup;
  55328. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  55329. // Transform barGroup.
  55330. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  55331. scaleY: otherAxisInverse ? 1 : -1,
  55332. scaleX: 1
  55333. } : orient === HORIZONTAL && inverse ? {
  55334. scaleY: otherAxisInverse ? 1 : -1,
  55335. scaleX: -1
  55336. } : orient === VERTICAL && !inverse ? {
  55337. scaleY: otherAxisInverse ? -1 : 1,
  55338. scaleX: 1,
  55339. rotation: Math.PI / 2
  55340. }
  55341. // Don't use Math.PI, considering shadow direction.
  55342. : {
  55343. scaleY: otherAxisInverse ? -1 : 1,
  55344. scaleX: -1,
  55345. rotation: Math.PI / 2
  55346. });
  55347. // Position barGroup
  55348. var rect = thisGroup.getBoundingRect([sliderGroup]);
  55349. thisGroup.x = location.x - rect.x;
  55350. thisGroup.y = location.y - rect.y;
  55351. thisGroup.markRedraw();
  55352. };
  55353. SliderZoomView.prototype._getViewExtent = function () {
  55354. return [0, this._size[0]];
  55355. };
  55356. SliderZoomView.prototype._renderBackground = function () {
  55357. var dataZoomModel = this.dataZoomModel;
  55358. var size = this._size;
  55359. var barGroup = this._displayables.sliderGroup;
  55360. var brushSelect = dataZoomModel.get('brushSelect');
  55361. barGroup.add(new Rect$1({
  55362. silent: true,
  55363. shape: {
  55364. x: 0,
  55365. y: 0,
  55366. width: size[0],
  55367. height: size[1]
  55368. },
  55369. style: {
  55370. fill: dataZoomModel.get('backgroundColor')
  55371. },
  55372. z2: -40
  55373. }));
  55374. // Click panel, over shadow, below handles.
  55375. var clickPanel = new Rect$1({
  55376. shape: {
  55377. x: 0,
  55378. y: 0,
  55379. width: size[0],
  55380. height: size[1]
  55381. },
  55382. style: {
  55383. fill: 'transparent'
  55384. },
  55385. z2: 0,
  55386. onclick: bind(this._onClickPanel, this)
  55387. });
  55388. var zr = this.api.getZr();
  55389. if (brushSelect) {
  55390. clickPanel.on('mousedown', this._onBrushStart, this);
  55391. clickPanel.cursor = 'crosshair';
  55392. zr.on('mousemove', this._onBrush);
  55393. zr.on('mouseup', this._onBrushEnd);
  55394. } else {
  55395. zr.off('mousemove', this._onBrush);
  55396. zr.off('mouseup', this._onBrushEnd);
  55397. }
  55398. barGroup.add(clickPanel);
  55399. };
  55400. SliderZoomView.prototype._renderDataShadow = function () {
  55401. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  55402. this._displayables.dataShadowSegs = [];
  55403. if (!info) {
  55404. return;
  55405. }
  55406. var size = this._size;
  55407. var oldSize = this._shadowSize || [];
  55408. var seriesModel = info.series;
  55409. var data = seriesModel.getRawData();
  55410. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  55411. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  55412. : info.otherDim;
  55413. if (otherDim == null) {
  55414. return;
  55415. }
  55416. var polygonPts = this._shadowPolygonPts;
  55417. var polylinePts = this._shadowPolylinePts;
  55418. // Not re-render if data doesn't change.
  55419. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  55420. var otherDataExtent_1 = data.getDataExtent(otherDim);
  55421. // Nice extent.
  55422. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  55423. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  55424. var otherShadowExtent_1 = [0, size[1]];
  55425. var thisShadowExtent = [0, size[0]];
  55426. var areaPoints_1 = [[size[0], 0], [0, 0]];
  55427. var linePoints_1 = [];
  55428. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  55429. var thisCoord_1 = 0;
  55430. // Optimize for large data shadow
  55431. var stride_1 = Math.round(data.count() / size[0]);
  55432. var lastIsEmpty_1;
  55433. data.each([otherDim], function (value, index) {
  55434. if (stride_1 > 0 && index % stride_1) {
  55435. thisCoord_1 += step_1;
  55436. return;
  55437. }
  55438. // FIXME
  55439. // Should consider axis.min/axis.max when drawing dataShadow.
  55440. // FIXME
  55441. // 应该使用统一的空判断?还是在list里进行空判断?
  55442. var isEmpty = value == null || isNaN(value) || value === '';
  55443. // See #4235.
  55444. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true);
  55445. // Attempt to draw data shadow precisely when there are empty value.
  55446. if (isEmpty && !lastIsEmpty_1 && index) {
  55447. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  55448. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  55449. } else if (!isEmpty && lastIsEmpty_1) {
  55450. areaPoints_1.push([thisCoord_1, 0]);
  55451. linePoints_1.push([thisCoord_1, 0]);
  55452. }
  55453. areaPoints_1.push([thisCoord_1, otherCoord]);
  55454. linePoints_1.push([thisCoord_1, otherCoord]);
  55455. thisCoord_1 += step_1;
  55456. lastIsEmpty_1 = isEmpty;
  55457. });
  55458. polygonPts = this._shadowPolygonPts = areaPoints_1;
  55459. polylinePts = this._shadowPolylinePts = linePoints_1;
  55460. }
  55461. this._shadowData = data;
  55462. this._shadowDim = otherDim;
  55463. this._shadowSize = [size[0], size[1]];
  55464. var dataZoomModel = this.dataZoomModel;
  55465. function createDataShadowGroup(isSelectedArea) {
  55466. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  55467. var group = new Group();
  55468. var polygon = new Polygon({
  55469. shape: {
  55470. points: polygonPts
  55471. },
  55472. segmentIgnoreThreshold: 1,
  55473. style: model.getModel('areaStyle').getAreaStyle(),
  55474. silent: true,
  55475. z2: -20
  55476. });
  55477. var polyline = new Polyline({
  55478. shape: {
  55479. points: polylinePts
  55480. },
  55481. segmentIgnoreThreshold: 1,
  55482. style: model.getModel('lineStyle').getLineStyle(),
  55483. silent: true,
  55484. z2: -19
  55485. });
  55486. group.add(polygon);
  55487. group.add(polyline);
  55488. return group;
  55489. }
  55490. // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  55491. for (var i = 0; i < 3; i++) {
  55492. var group = createDataShadowGroup(i === 1);
  55493. this._displayables.sliderGroup.add(group);
  55494. this._displayables.dataShadowSegs.push(group);
  55495. }
  55496. };
  55497. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  55498. var dataZoomModel = this.dataZoomModel;
  55499. var showDataShadow = dataZoomModel.get('showDataShadow');
  55500. if (showDataShadow === false) {
  55501. return;
  55502. }
  55503. // Find a representative series.
  55504. var result;
  55505. var ecModel = this.ecModel;
  55506. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  55507. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  55508. each(seriesModels, function (seriesModel) {
  55509. if (result) {
  55510. return;
  55511. }
  55512. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  55513. return;
  55514. }
  55515. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  55516. var otherDim = getOtherDim(axisDim);
  55517. var otherAxisInverse;
  55518. var coordSys = seriesModel.coordinateSystem;
  55519. if (otherDim != null && coordSys.getOtherAxis) {
  55520. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  55521. }
  55522. otherDim = seriesModel.getData().mapDimension(otherDim);
  55523. result = {
  55524. thisAxis: thisAxis,
  55525. series: seriesModel,
  55526. thisDim: axisDim,
  55527. otherDim: otherDim,
  55528. otherAxisInverse: otherAxisInverse
  55529. };
  55530. }, this);
  55531. }, this);
  55532. return result;
  55533. };
  55534. SliderZoomView.prototype._renderHandle = function () {
  55535. var thisGroup = this.group;
  55536. var displayables = this._displayables;
  55537. var handles = displayables.handles = [null, null];
  55538. var handleLabels = displayables.handleLabels = [null, null];
  55539. var sliderGroup = this._displayables.sliderGroup;
  55540. var size = this._size;
  55541. var dataZoomModel = this.dataZoomModel;
  55542. var api = this.api;
  55543. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  55544. var brushSelect = dataZoomModel.get('brushSelect');
  55545. var filler = displayables.filler = new Rect$1({
  55546. silent: brushSelect,
  55547. style: {
  55548. fill: dataZoomModel.get('fillerColor')
  55549. },
  55550. textConfig: {
  55551. position: 'inside'
  55552. }
  55553. });
  55554. sliderGroup.add(filler);
  55555. // Frame border.
  55556. sliderGroup.add(new Rect$1({
  55557. silent: true,
  55558. subPixelOptimize: true,
  55559. shape: {
  55560. x: 0,
  55561. y: 0,
  55562. width: size[0],
  55563. height: size[1],
  55564. r: borderRadius
  55565. },
  55566. style: {
  55567. // deprecated option
  55568. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  55569. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  55570. fill: 'rgba(0,0,0,0)'
  55571. }
  55572. }));
  55573. // Left and right handle to resize
  55574. each([0, 1], function (handleIndex) {
  55575. var iconStr = dataZoomModel.get('handleIcon');
  55576. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  55577. // Compatitable with the old icon parsers. Which can use a path string without path://
  55578. iconStr = 'path://' + iconStr;
  55579. if ("development" !== 'production') {
  55580. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  55581. }
  55582. }
  55583. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  55584. path.attr({
  55585. cursor: getCursor(this._orient),
  55586. draggable: true,
  55587. drift: bind(this._onDragMove, this, handleIndex),
  55588. ondragend: bind(this._onDragEnd, this),
  55589. onmouseover: bind(this._showDataInfo, this, true),
  55590. onmouseout: bind(this._showDataInfo, this, false),
  55591. z2: 5
  55592. });
  55593. var bRect = path.getBoundingRect();
  55594. var handleSize = dataZoomModel.get('handleSize');
  55595. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  55596. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  55597. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  55598. path.style.strokeNoScale = true;
  55599. path.rectHover = true;
  55600. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  55601. enableHoverEmphasis(path);
  55602. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  55603. // Compatitable with previous version
  55604. if (handleColor != null) {
  55605. path.style.fill = handleColor;
  55606. }
  55607. sliderGroup.add(handles[handleIndex] = path);
  55608. var textStyleModel = dataZoomModel.getModel('textStyle');
  55609. var handleLabel = dataZoomModel.get('handleLabel') || {};
  55610. var handleLabelShow = handleLabel.show || false;
  55611. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  55612. silent: true,
  55613. invisible: !handleLabelShow,
  55614. style: createTextStyle(textStyleModel, {
  55615. x: 0,
  55616. y: 0,
  55617. text: '',
  55618. verticalAlign: 'middle',
  55619. align: 'center',
  55620. fill: textStyleModel.getTextColor(),
  55621. font: textStyleModel.getFont()
  55622. }),
  55623. z2: 10
  55624. }));
  55625. }, this);
  55626. // Handle to move. Only visible when brushSelect is set true.
  55627. var actualMoveZone = filler;
  55628. if (brushSelect) {
  55629. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  55630. var moveHandle_1 = displayables.moveHandle = new Rect({
  55631. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  55632. silent: true,
  55633. shape: {
  55634. r: [0, 0, 2, 2],
  55635. y: size[1] - 0.5,
  55636. height: moveHandleHeight
  55637. }
  55638. });
  55639. var iconSize = moveHandleHeight * 0.8;
  55640. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  55641. moveHandleIcon.silent = true;
  55642. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  55643. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  55644. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  55645. actualMoveZone = displayables.moveZone = new Rect({
  55646. invisible: true,
  55647. shape: {
  55648. y: size[1] - moveZoneExpandSize,
  55649. height: moveHandleHeight + moveZoneExpandSize
  55650. }
  55651. });
  55652. actualMoveZone.on('mouseover', function () {
  55653. api.enterEmphasis(moveHandle_1);
  55654. }).on('mouseout', function () {
  55655. api.leaveEmphasis(moveHandle_1);
  55656. });
  55657. sliderGroup.add(moveHandle_1);
  55658. sliderGroup.add(moveHandleIcon);
  55659. sliderGroup.add(actualMoveZone);
  55660. }
  55661. actualMoveZone.attr({
  55662. draggable: true,
  55663. cursor: getCursor(this._orient),
  55664. drift: bind(this._onDragMove, this, 'all'),
  55665. ondragstart: bind(this._showDataInfo, this, true),
  55666. ondragend: bind(this._onDragEnd, this),
  55667. onmouseover: bind(this._showDataInfo, this, true),
  55668. onmouseout: bind(this._showDataInfo, this, false)
  55669. });
  55670. };
  55671. SliderZoomView.prototype._resetInterval = function () {
  55672. var range = this._range = this.dataZoomModel.getPercentRange();
  55673. var viewExtent = this._getViewExtent();
  55674. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  55675. };
  55676. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  55677. var dataZoomModel = this.dataZoomModel;
  55678. var handleEnds = this._handleEnds;
  55679. var viewExtend = this._getViewExtent();
  55680. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55681. var percentExtent = [0, 100];
  55682. sliderMove(delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, minMaxSpan.minSpan != null ? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null);
  55683. var lastRange = this._range;
  55684. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  55685. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  55686. };
  55687. SliderZoomView.prototype._updateView = function (nonRealtime) {
  55688. var displaybles = this._displayables;
  55689. var handleEnds = this._handleEnds;
  55690. var handleInterval = asc(handleEnds.slice());
  55691. var size = this._size;
  55692. each([0, 1], function (handleIndex) {
  55693. // Handles
  55694. var handle = displaybles.handles[handleIndex];
  55695. var handleHeight = this._handleHeight;
  55696. handle.attr({
  55697. scaleX: handleHeight / 2,
  55698. scaleY: handleHeight / 2,
  55699. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  55700. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  55701. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  55702. y: size[1] / 2 - handleHeight / 2
  55703. });
  55704. }, this);
  55705. // Filler
  55706. displaybles.filler.setShape({
  55707. x: handleInterval[0],
  55708. y: 0,
  55709. width: handleInterval[1] - handleInterval[0],
  55710. height: size[1]
  55711. });
  55712. var viewExtent = {
  55713. x: handleInterval[0],
  55714. width: handleInterval[1] - handleInterval[0]
  55715. };
  55716. // Move handle
  55717. if (displaybles.moveHandle) {
  55718. displaybles.moveHandle.setShape(viewExtent);
  55719. displaybles.moveZone.setShape(viewExtent);
  55720. // Force update path on the invisible object
  55721. displaybles.moveZone.getBoundingRect();
  55722. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  55723. }
  55724. // update clip path of shadow.
  55725. var dataShadowSegs = displaybles.dataShadowSegs;
  55726. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  55727. for (var i = 0; i < dataShadowSegs.length; i++) {
  55728. var segGroup = dataShadowSegs[i];
  55729. var clipPath = segGroup.getClipPath();
  55730. if (!clipPath) {
  55731. clipPath = new Rect();
  55732. segGroup.setClipPath(clipPath);
  55733. }
  55734. clipPath.setShape({
  55735. x: segIntervals[i],
  55736. y: 0,
  55737. width: segIntervals[i + 1] - segIntervals[i],
  55738. height: size[1]
  55739. });
  55740. }
  55741. this._updateDataInfo(nonRealtime);
  55742. };
  55743. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  55744. var dataZoomModel = this.dataZoomModel;
  55745. var displaybles = this._displayables;
  55746. var handleLabels = displaybles.handleLabels;
  55747. var orient = this._orient;
  55748. var labelTexts = ['', ''];
  55749. // FIXME
  55750. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  55751. if (dataZoomModel.get('showDetail')) {
  55752. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55753. if (axisProxy) {
  55754. var axis = axisProxy.getAxisModel().axis;
  55755. var range = this._range;
  55756. var dataInterval = nonRealtime
  55757. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  55758. ? axisProxy.calculateDataWindow({
  55759. start: range[0],
  55760. end: range[1]
  55761. }).valueWindow : axisProxy.getDataValueWindow();
  55762. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  55763. }
  55764. }
  55765. var orderedHandleEnds = asc(this._handleEnds.slice());
  55766. setLabel.call(this, 0);
  55767. setLabel.call(this, 1);
  55768. function setLabel(handleIndex) {
  55769. // Label
  55770. // Text should not transform by barGroup.
  55771. // Ignore handlers transform
  55772. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  55773. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  55774. var offset = this._handleWidth / 2 + LABEL_GAP;
  55775. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  55776. handleLabels[handleIndex].setStyle({
  55777. x: textPoint[0],
  55778. y: textPoint[1],
  55779. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  55780. align: orient === HORIZONTAL ? direction : 'center',
  55781. text: labelTexts[handleIndex]
  55782. });
  55783. }
  55784. };
  55785. SliderZoomView.prototype._formatLabel = function (value, axis) {
  55786. var dataZoomModel = this.dataZoomModel;
  55787. var labelFormatter = dataZoomModel.get('labelFormatter');
  55788. var labelPrecision = dataZoomModel.get('labelPrecision');
  55789. if (labelPrecision == null || labelPrecision === 'auto') {
  55790. labelPrecision = axis.getPixelPrecision();
  55791. }
  55792. var valueStr = value == null || isNaN(value) ? ''
  55793. // FIXME Glue code
  55794. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  55795. value: Math.round(value)
  55796. })
  55797. // param of toFixed should less then 20.
  55798. : value.toFixed(Math.min(labelPrecision, 20));
  55799. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  55800. };
  55801. /**
  55802. * @param isEmphasis true: show, false: hide
  55803. */
  55804. SliderZoomView.prototype._showDataInfo = function (isEmphasis) {
  55805. var handleLabel = this.dataZoomModel.get('handleLabel') || {};
  55806. var normalShow = handleLabel.show || false;
  55807. var emphasisHandleLabel = this.dataZoomModel.getModel(['emphasis', 'handleLabel']);
  55808. var emphasisShow = emphasisHandleLabel.get('show') || false;
  55809. // Dragging is considered as emphasis, unless emphasisShow is false
  55810. var toShow = isEmphasis || this._dragging ? emphasisShow : normalShow;
  55811. var displayables = this._displayables;
  55812. var handleLabels = displayables.handleLabels;
  55813. handleLabels[0].attr('invisible', !toShow);
  55814. handleLabels[1].attr('invisible', !toShow);
  55815. // Highlight move handle
  55816. displayables.moveHandle && this.api[toShow ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  55817. };
  55818. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  55819. this._dragging = true;
  55820. // For mobile device, prevent screen slider on the button.
  55821. stop(event.event);
  55822. // Transform dx, dy to bar coordination.
  55823. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  55824. var vertex = applyTransform$1([dx, dy], barTransform, true);
  55825. var changed = this._updateInterval(handleIndex, vertex[0]);
  55826. var realtime = this.dataZoomModel.get('realtime');
  55827. this._updateView(!realtime);
  55828. // Avoid dispatch dataZoom repeatly but range not changed,
  55829. // which cause bad visual effect when progressive enabled.
  55830. changed && realtime && this._dispatchZoomAction(true);
  55831. };
  55832. SliderZoomView.prototype._onDragEnd = function () {
  55833. this._dragging = false;
  55834. this._showDataInfo(false);
  55835. // While in realtime mode and stream mode, dispatch action when
  55836. // drag end will cause the whole view rerender, which is unnecessary.
  55837. var realtime = this.dataZoomModel.get('realtime');
  55838. !realtime && this._dispatchZoomAction(false);
  55839. };
  55840. SliderZoomView.prototype._onClickPanel = function (e) {
  55841. var size = this._size;
  55842. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  55843. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  55844. return;
  55845. }
  55846. var handleEnds = this._handleEnds;
  55847. var center = (handleEnds[0] + handleEnds[1]) / 2;
  55848. var changed = this._updateInterval('all', localPoint[0] - center);
  55849. this._updateView();
  55850. changed && this._dispatchZoomAction(false);
  55851. };
  55852. SliderZoomView.prototype._onBrushStart = function (e) {
  55853. var x = e.offsetX;
  55854. var y = e.offsetY;
  55855. this._brushStart = new Point(x, y);
  55856. this._brushing = true;
  55857. this._brushStartTime = +new Date();
  55858. // this._updateBrushRect(x, y);
  55859. };
  55860. SliderZoomView.prototype._onBrushEnd = function (e) {
  55861. if (!this._brushing) {
  55862. return;
  55863. }
  55864. var brushRect = this._displayables.brushRect;
  55865. this._brushing = false;
  55866. if (!brushRect) {
  55867. return;
  55868. }
  55869. brushRect.attr('ignore', true);
  55870. var brushShape = brushRect.shape;
  55871. var brushEndTime = +new Date();
  55872. // console.log(brushEndTime - this._brushStartTime);
  55873. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  55874. // Will treat it as a click
  55875. return;
  55876. }
  55877. var viewExtend = this._getViewExtent();
  55878. var percentExtent = [0, 100];
  55879. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  55880. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  55881. this._updateView();
  55882. this._dispatchZoomAction(false);
  55883. };
  55884. SliderZoomView.prototype._onBrush = function (e) {
  55885. if (this._brushing) {
  55886. // For mobile device, prevent screen slider on the button.
  55887. stop(e.event);
  55888. this._updateBrushRect(e.offsetX, e.offsetY);
  55889. }
  55890. };
  55891. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  55892. var displayables = this._displayables;
  55893. var dataZoomModel = this.dataZoomModel;
  55894. var brushRect = displayables.brushRect;
  55895. if (!brushRect) {
  55896. brushRect = displayables.brushRect = new Rect$1({
  55897. silent: true,
  55898. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  55899. });
  55900. displayables.sliderGroup.add(brushRect);
  55901. }
  55902. brushRect.attr('ignore', false);
  55903. var brushStart = this._brushStart;
  55904. var sliderGroup = this._displayables.sliderGroup;
  55905. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  55906. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  55907. var size = this._size;
  55908. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  55909. brushRect.setShape({
  55910. x: startPoint[0],
  55911. y: 0,
  55912. width: endPoint[0] - startPoint[0],
  55913. height: size[1]
  55914. });
  55915. };
  55916. /**
  55917. * This action will be throttled.
  55918. */
  55919. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  55920. var range = this._range;
  55921. this.api.dispatchAction({
  55922. type: 'dataZoom',
  55923. from: this.uid,
  55924. dataZoomId: this.dataZoomModel.id,
  55925. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  55926. start: range[0],
  55927. end: range[1]
  55928. });
  55929. };
  55930. SliderZoomView.prototype._findCoordRect = function () {
  55931. // Find the grid corresponding to the first axis referred by dataZoom.
  55932. var rect;
  55933. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  55934. if (!rect && coordSysInfoList.length) {
  55935. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  55936. rect = coordSys.getRect && coordSys.getRect();
  55937. }
  55938. if (!rect) {
  55939. var width = this.api.getWidth();
  55940. var height = this.api.getHeight();
  55941. rect = {
  55942. x: width * 0.2,
  55943. y: height * 0.2,
  55944. width: width * 0.6,
  55945. height: height * 0.6
  55946. };
  55947. }
  55948. return rect;
  55949. };
  55950. SliderZoomView.type = 'dataZoom.slider';
  55951. return SliderZoomView;
  55952. }(DataZoomView);
  55953. function getOtherDim(thisDim) {
  55954. // FIXME
  55955. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  55956. var map = {
  55957. x: 'y',
  55958. y: 'x',
  55959. radius: 'angle',
  55960. angle: 'radius'
  55961. };
  55962. return map[thisDim];
  55963. }
  55964. function getCursor(orient) {
  55965. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  55966. }
  55967. function install$l(registers) {
  55968. registers.registerComponentModel(SliderZoomModel);
  55969. registers.registerComponentView(SliderZoomView);
  55970. installCommon(registers);
  55971. }
  55972. function install$m(registers) {
  55973. use(install$k);
  55974. use(install$l);
  55975. // Do not install './dataZoomSelect',
  55976. // since it only work for toolbox dataZoom.
  55977. }
  55978. var DEFAULT_OPTION = {
  55979. label: {
  55980. enabled: true
  55981. },
  55982. decal: {
  55983. show: false
  55984. }
  55985. };
  55986. var inner$h = makeInner();
  55987. var decalPaletteScope = {};
  55988. function ariaVisual(ecModel, api) {
  55989. var ariaModel = ecModel.getModel('aria');
  55990. // See "area enabled" detection code in `GlobalModel.ts`.
  55991. if (!ariaModel.get('enabled')) {
  55992. return;
  55993. }
  55994. var defaultOption = clone(DEFAULT_OPTION);
  55995. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  55996. merge(ariaModel.option, defaultOption, false);
  55997. setDecal();
  55998. setLabel();
  55999. function setDecal() {
  56000. var decalModel = ariaModel.getModel('decal');
  56001. var useDecal = decalModel.get('show');
  56002. if (useDecal) {
  56003. // Each type of series use one scope.
  56004. // Pie and funnel are using different scopes.
  56005. var paletteScopeGroupByType_1 = createHashMap();
  56006. ecModel.eachSeries(function (seriesModel) {
  56007. if (seriesModel.isColorBySeries()) {
  56008. return;
  56009. }
  56010. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  56011. if (!decalScope) {
  56012. decalScope = {};
  56013. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  56014. }
  56015. inner$h(seriesModel).scope = decalScope;
  56016. });
  56017. ecModel.eachRawSeries(function (seriesModel) {
  56018. if (ecModel.isSeriesFiltered(seriesModel)) {
  56019. return;
  56020. }
  56021. if (isFunction(seriesModel.enableAriaDecal)) {
  56022. // Let series define how to use decal palette on data
  56023. seriesModel.enableAriaDecal();
  56024. return;
  56025. }
  56026. var data = seriesModel.getData();
  56027. if (!seriesModel.isColorBySeries()) {
  56028. var dataAll_1 = seriesModel.getRawData();
  56029. var idxMap_1 = {};
  56030. var decalScope_1 = inner$h(seriesModel).scope;
  56031. data.each(function (idx) {
  56032. var rawIdx = data.getRawIndex(idx);
  56033. idxMap_1[rawIdx] = idx;
  56034. });
  56035. var dataCount_1 = dataAll_1.count();
  56036. dataAll_1.each(function (rawIdx) {
  56037. var idx = idxMap_1[rawIdx];
  56038. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  56039. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  56040. var specifiedDecal = data.getItemVisual(idx, 'decal');
  56041. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  56042. });
  56043. } else {
  56044. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  56045. var specifiedDecal = data.getVisual('decal');
  56046. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  56047. }
  56048. function mergeDecal(specifiedDecal, paletteDecal) {
  56049. // Merge decal from palette to decal from itemStyle.
  56050. // User do not need to specify all of the decal props.
  56051. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  56052. resultDecal.dirty = true;
  56053. return resultDecal;
  56054. }
  56055. });
  56056. }
  56057. }
  56058. function setLabel() {
  56059. var dom = api.getZr().dom;
  56060. // TODO: support for SSR
  56061. if (!dom) {
  56062. return;
  56063. }
  56064. var labelLocale = ecModel.getLocaleModel().get('aria');
  56065. var labelModel = ariaModel.getModel('label');
  56066. labelModel.option = defaults(labelModel.option, labelLocale);
  56067. if (!labelModel.get('enabled')) {
  56068. return;
  56069. }
  56070. dom.setAttribute('role', 'img');
  56071. if (labelModel.get('description')) {
  56072. dom.setAttribute('aria-label', labelModel.get('description'));
  56073. return;
  56074. }
  56075. var seriesCnt = ecModel.getSeriesCount();
  56076. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  56077. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  56078. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  56079. var ariaLabel;
  56080. if (seriesCnt < 1) {
  56081. // No series, no aria label
  56082. return;
  56083. } else {
  56084. var title = getTitle();
  56085. if (title) {
  56086. var withTitle = labelModel.get(['general', 'withTitle']);
  56087. ariaLabel = replace(withTitle, {
  56088. title: title
  56089. });
  56090. } else {
  56091. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  56092. }
  56093. var seriesLabels_1 = [];
  56094. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  56095. ariaLabel += replace(prefix, {
  56096. seriesCount: seriesCnt
  56097. });
  56098. ecModel.eachSeries(function (seriesModel, idx) {
  56099. if (idx < displaySeriesCnt) {
  56100. var seriesLabel = void 0;
  56101. var seriesName = seriesModel.get('name');
  56102. var withName = seriesName ? 'withName' : 'withoutName';
  56103. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  56104. seriesLabel = replace(seriesLabel, {
  56105. seriesId: seriesModel.seriesIndex,
  56106. seriesName: seriesModel.get('name'),
  56107. seriesType: getSeriesTypeName(seriesModel.subType)
  56108. });
  56109. var data = seriesModel.getData();
  56110. if (data.count() > maxDataCnt) {
  56111. // Show part of data
  56112. var partialLabel = labelModel.get(['data', 'partialData']);
  56113. seriesLabel += replace(partialLabel, {
  56114. displayCnt: maxDataCnt
  56115. });
  56116. } else {
  56117. seriesLabel += labelModel.get(['data', 'allData']);
  56118. }
  56119. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  56120. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  56121. var excludeDimensionId_1 = labelModel.get(['data', 'excludeDimensionId']);
  56122. var dataLabels = [];
  56123. for (var i = 0; i < data.count(); i++) {
  56124. if (i < maxDataCnt) {
  56125. var name_1 = data.getName(i);
  56126. var value = !excludeDimensionId_1 ? data.getValues(i) : filter(data.getValues(i), function (v, j) {
  56127. return indexOf(excludeDimensionId_1, j) === -1;
  56128. });
  56129. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  56130. dataLabels.push(replace(dataLabel, {
  56131. name: name_1,
  56132. value: value.join(middleSeparator_1)
  56133. }));
  56134. }
  56135. }
  56136. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  56137. seriesLabels_1.push(seriesLabel);
  56138. }
  56139. });
  56140. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  56141. var middleSeparator = separatorModel.get('middle');
  56142. var endSeparator = separatorModel.get('end');
  56143. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  56144. dom.setAttribute('aria-label', ariaLabel);
  56145. }
  56146. }
  56147. function replace(str, keyValues) {
  56148. if (!isString(str)) {
  56149. return str;
  56150. }
  56151. var result = str;
  56152. each(keyValues, function (value, key) {
  56153. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  56154. });
  56155. return result;
  56156. }
  56157. function getTitle() {
  56158. var title = ecModel.get('title');
  56159. if (title && title.length) {
  56160. title = title[0];
  56161. }
  56162. return title && title.text;
  56163. }
  56164. function getSeriesTypeName(type) {
  56165. var typeNames = ecModel.getLocaleModel().get(['series', 'typeNames']);
  56166. return typeNames[type] || typeNames.chart;
  56167. }
  56168. }
  56169. function ariaPreprocessor(option) {
  56170. if (!option || !option.aria) {
  56171. return;
  56172. }
  56173. var aria = option.aria;
  56174. // aria.show is deprecated and should use aria.enabled instead
  56175. if (aria.show != null) {
  56176. aria.enabled = aria.show;
  56177. }
  56178. aria.label = aria.label || {};
  56179. // move description, general, series, data to be under aria.label
  56180. each(['description', 'general', 'series', 'data'], function (name) {
  56181. if (aria[name] != null) {
  56182. aria.label[name] = aria[name];
  56183. }
  56184. });
  56185. }
  56186. function install$n(registers) {
  56187. registers.registerPreprocessor(ariaPreprocessor);
  56188. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  56189. }
  56190. var DatasetModel = /** @class */function (_super) {
  56191. __extends(DatasetModel, _super);
  56192. function DatasetModel() {
  56193. var _this = _super !== null && _super.apply(this, arguments) || this;
  56194. _this.type = 'dataset';
  56195. return _this;
  56196. }
  56197. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  56198. _super.prototype.init.call(this, option, parentModel, ecModel);
  56199. this._sourceManager = new SourceManager(this);
  56200. disableTransformOptionMerge(this);
  56201. };
  56202. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  56203. _super.prototype.mergeOption.call(this, newOption, ecModel);
  56204. disableTransformOptionMerge(this);
  56205. };
  56206. DatasetModel.prototype.optionUpdated = function () {
  56207. this._sourceManager.dirty();
  56208. };
  56209. DatasetModel.prototype.getSourceManager = function () {
  56210. return this._sourceManager;
  56211. };
  56212. DatasetModel.type = 'dataset';
  56213. DatasetModel.defaultOption = {
  56214. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  56215. };
  56216. return DatasetModel;
  56217. }(ComponentModel);
  56218. var DatasetView = /** @class */function (_super) {
  56219. __extends(DatasetView, _super);
  56220. function DatasetView() {
  56221. var _this = _super !== null && _super.apply(this, arguments) || this;
  56222. _this.type = 'dataset';
  56223. return _this;
  56224. }
  56225. DatasetView.type = 'dataset';
  56226. return DatasetView;
  56227. }(ComponentView);
  56228. function install$o(registers) {
  56229. registers.registerComponentModel(DatasetModel);
  56230. registers.registerComponentView(DatasetView);
  56231. }
  56232. use([install$1]);
  56233. use([install]);
  56234. use([install$2, install$3, install$4, install$6]);
  56235. use([install$9, install$c, install$7, install$j, install$8, install$d, install$e, install$f, install$g, install$m, install$b, install$n, install$o]);
  56236. exports.Axis = Axis;
  56237. exports.ChartView = ChartView;
  56238. exports.ComponentModel = ComponentModel;
  56239. exports.ComponentView = ComponentView;
  56240. exports.List = SeriesData;
  56241. exports.Model = Model;
  56242. exports.PRIORITY = PRIORITY;
  56243. exports.SeriesModel = SeriesModel;
  56244. exports.color = color;
  56245. exports.connect = connect;
  56246. exports.dataTool = dataTool;
  56247. exports.dependencies = dependencies;
  56248. exports.disConnect = disConnect;
  56249. exports.disconnect = disconnect;
  56250. exports.dispose = dispose$1;
  56251. exports.env = env;
  56252. exports.extendChartView = extendChartView;
  56253. exports.extendComponentModel = extendComponentModel;
  56254. exports.extendComponentView = extendComponentView;
  56255. exports.extendSeriesModel = extendSeriesModel;
  56256. exports.format = format$1;
  56257. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  56258. exports.getInstanceByDom = getInstanceByDom;
  56259. exports.getInstanceById = getInstanceById;
  56260. exports.getMap = getMap;
  56261. exports.graphic = graphic$1;
  56262. exports.helper = helper;
  56263. exports.init = init$1;
  56264. exports.innerDrawElementOnCanvas = brushSingle;
  56265. exports.matrix = matrix;
  56266. exports.number = number;
  56267. exports.parseGeoJSON = parseGeoJSON;
  56268. exports.parseGeoJson = parseGeoJSON;
  56269. exports.registerAction = registerAction;
  56270. exports.registerCoordinateSystem = registerCoordinateSystem;
  56271. exports.registerLayout = registerLayout;
  56272. exports.registerLoading = registerLoading;
  56273. exports.registerLocale = registerLocale;
  56274. exports.registerMap = registerMap;
  56275. exports.registerPostInit = registerPostInit;
  56276. exports.registerPostUpdate = registerPostUpdate;
  56277. exports.registerPreprocessor = registerPreprocessor;
  56278. exports.registerProcessor = registerProcessor;
  56279. exports.registerTheme = registerTheme;
  56280. exports.registerTransform = registerTransform;
  56281. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  56282. exports.registerVisual = registerVisual;
  56283. exports.setCanvasCreator = setCanvasCreator;
  56284. exports.setPlatformAPI = setPlatformAPI;
  56285. exports.throttle = throttle;
  56286. exports.time = time;
  56287. exports.use = use;
  56288. exports.util = util$1;
  56289. exports.vector = vector;
  56290. exports.version = version$1;
  56291. exports.zrUtil = util;
  56292. exports.zrender = zrender;
  56293. Object.defineProperty(exports, '__esModule', { value: true });
  56294. })));
  56295. //# sourceMappingURL=echarts.common.js.map