echarts.common.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469
  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 (typeof navigator === 'undefined') {
  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+)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; i < keysArr.length; 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) {
  1538. var aa = a[0];
  1539. var ac = a[2];
  1540. var atx = a[4];
  1541. var ab = a[1];
  1542. var ad = a[3];
  1543. var aty = a[5];
  1544. var st = Math.sin(rad);
  1545. var ct = Math.cos(rad);
  1546. out[0] = aa * ct + ab * st;
  1547. out[1] = -aa * st + ab * ct;
  1548. out[2] = ac * ct + ad * st;
  1549. out[3] = -ac * st + ct * ad;
  1550. out[4] = ct * atx + st * aty;
  1551. out[5] = ct * aty - st * atx;
  1552. return out;
  1553. }
  1554. function scale$1(out, a, v) {
  1555. var vx = v[0];
  1556. var vy = v[1];
  1557. out[0] = a[0] * vx;
  1558. out[1] = a[1] * vy;
  1559. out[2] = a[2] * vx;
  1560. out[3] = a[3] * vy;
  1561. out[4] = a[4] * vx;
  1562. out[5] = a[5] * vy;
  1563. return out;
  1564. }
  1565. function invert(out, a) {
  1566. var aa = a[0];
  1567. var ac = a[2];
  1568. var atx = a[4];
  1569. var ab = a[1];
  1570. var ad = a[3];
  1571. var aty = a[5];
  1572. var det = aa * ad - ab * ac;
  1573. if (!det) {
  1574. return null;
  1575. }
  1576. det = 1.0 / det;
  1577. out[0] = ad * det;
  1578. out[1] = -ab * det;
  1579. out[2] = -ac * det;
  1580. out[3] = aa * det;
  1581. out[4] = (ac * aty - ad * atx) * det;
  1582. out[5] = (ab * atx - aa * aty) * det;
  1583. return out;
  1584. }
  1585. function clone$2(a) {
  1586. var b = create$1();
  1587. copy$1(b, a);
  1588. return b;
  1589. }
  1590. var matrix = /*#__PURE__*/Object.freeze({
  1591. __proto__: null,
  1592. create: create$1,
  1593. identity: identity,
  1594. copy: copy$1,
  1595. mul: mul$1,
  1596. translate: translate,
  1597. rotate: rotate,
  1598. scale: scale$1,
  1599. invert: invert,
  1600. clone: clone$2
  1601. });
  1602. var Point = (function () {
  1603. function Point(x, y) {
  1604. this.x = x || 0;
  1605. this.y = y || 0;
  1606. }
  1607. Point.prototype.copy = function (other) {
  1608. this.x = other.x;
  1609. this.y = other.y;
  1610. return this;
  1611. };
  1612. Point.prototype.clone = function () {
  1613. return new Point(this.x, this.y);
  1614. };
  1615. Point.prototype.set = function (x, y) {
  1616. this.x = x;
  1617. this.y = y;
  1618. return this;
  1619. };
  1620. Point.prototype.equal = function (other) {
  1621. return other.x === this.x && other.y === this.y;
  1622. };
  1623. Point.prototype.add = function (other) {
  1624. this.x += other.x;
  1625. this.y += other.y;
  1626. return this;
  1627. };
  1628. Point.prototype.scale = function (scalar) {
  1629. this.x *= scalar;
  1630. this.y *= scalar;
  1631. };
  1632. Point.prototype.scaleAndAdd = function (other, scalar) {
  1633. this.x += other.x * scalar;
  1634. this.y += other.y * scalar;
  1635. };
  1636. Point.prototype.sub = function (other) {
  1637. this.x -= other.x;
  1638. this.y -= other.y;
  1639. return this;
  1640. };
  1641. Point.prototype.dot = function (other) {
  1642. return this.x * other.x + this.y * other.y;
  1643. };
  1644. Point.prototype.len = function () {
  1645. return Math.sqrt(this.x * this.x + this.y * this.y);
  1646. };
  1647. Point.prototype.lenSquare = function () {
  1648. return this.x * this.x + this.y * this.y;
  1649. };
  1650. Point.prototype.normalize = function () {
  1651. var len = this.len();
  1652. this.x /= len;
  1653. this.y /= len;
  1654. return this;
  1655. };
  1656. Point.prototype.distance = function (other) {
  1657. var dx = this.x - other.x;
  1658. var dy = this.y - other.y;
  1659. return Math.sqrt(dx * dx + dy * dy);
  1660. };
  1661. Point.prototype.distanceSquare = function (other) {
  1662. var dx = this.x - other.x;
  1663. var dy = this.y - other.y;
  1664. return dx * dx + dy * dy;
  1665. };
  1666. Point.prototype.negate = function () {
  1667. this.x = -this.x;
  1668. this.y = -this.y;
  1669. return this;
  1670. };
  1671. Point.prototype.transform = function (m) {
  1672. if (!m) {
  1673. return;
  1674. }
  1675. var x = this.x;
  1676. var y = this.y;
  1677. this.x = m[0] * x + m[2] * y + m[4];
  1678. this.y = m[1] * x + m[3] * y + m[5];
  1679. return this;
  1680. };
  1681. Point.prototype.toArray = function (out) {
  1682. out[0] = this.x;
  1683. out[1] = this.y;
  1684. return out;
  1685. };
  1686. Point.prototype.fromArray = function (input) {
  1687. this.x = input[0];
  1688. this.y = input[1];
  1689. };
  1690. Point.set = function (p, x, y) {
  1691. p.x = x;
  1692. p.y = y;
  1693. };
  1694. Point.copy = function (p, p2) {
  1695. p.x = p2.x;
  1696. p.y = p2.y;
  1697. };
  1698. Point.len = function (p) {
  1699. return Math.sqrt(p.x * p.x + p.y * p.y);
  1700. };
  1701. Point.lenSquare = function (p) {
  1702. return p.x * p.x + p.y * p.y;
  1703. };
  1704. Point.dot = function (p0, p1) {
  1705. return p0.x * p1.x + p0.y * p1.y;
  1706. };
  1707. Point.add = function (out, p0, p1) {
  1708. out.x = p0.x + p1.x;
  1709. out.y = p0.y + p1.y;
  1710. };
  1711. Point.sub = function (out, p0, p1) {
  1712. out.x = p0.x - p1.x;
  1713. out.y = p0.y - p1.y;
  1714. };
  1715. Point.scale = function (out, p0, scalar) {
  1716. out.x = p0.x * scalar;
  1717. out.y = p0.y * scalar;
  1718. };
  1719. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1720. out.x = p0.x + p1.x * scalar;
  1721. out.y = p0.y + p1.y * scalar;
  1722. };
  1723. Point.lerp = function (out, p0, p1, t) {
  1724. var onet = 1 - t;
  1725. out.x = onet * p0.x + t * p1.x;
  1726. out.y = onet * p0.y + t * p1.y;
  1727. };
  1728. return Point;
  1729. }());
  1730. var mathMin = Math.min;
  1731. var mathMax = Math.max;
  1732. var lt = new Point();
  1733. var rb = new Point();
  1734. var lb = new Point();
  1735. var rt = new Point();
  1736. var minTv = new Point();
  1737. var maxTv = new Point();
  1738. var BoundingRect = (function () {
  1739. function BoundingRect(x, y, width, height) {
  1740. if (width < 0) {
  1741. x = x + width;
  1742. width = -width;
  1743. }
  1744. if (height < 0) {
  1745. y = y + height;
  1746. height = -height;
  1747. }
  1748. this.x = x;
  1749. this.y = y;
  1750. this.width = width;
  1751. this.height = height;
  1752. }
  1753. BoundingRect.prototype.union = function (other) {
  1754. var x = mathMin(other.x, this.x);
  1755. var y = mathMin(other.y, this.y);
  1756. if (isFinite(this.x) && isFinite(this.width)) {
  1757. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1758. }
  1759. else {
  1760. this.width = other.width;
  1761. }
  1762. if (isFinite(this.y) && isFinite(this.height)) {
  1763. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1764. }
  1765. else {
  1766. this.height = other.height;
  1767. }
  1768. this.x = x;
  1769. this.y = y;
  1770. };
  1771. BoundingRect.prototype.applyTransform = function (m) {
  1772. BoundingRect.applyTransform(this, this, m);
  1773. };
  1774. BoundingRect.prototype.calculateTransform = function (b) {
  1775. var a = this;
  1776. var sx = b.width / a.width;
  1777. var sy = b.height / a.height;
  1778. var m = create$1();
  1779. translate(m, m, [-a.x, -a.y]);
  1780. scale$1(m, m, [sx, sy]);
  1781. translate(m, m, [b.x, b.y]);
  1782. return m;
  1783. };
  1784. BoundingRect.prototype.intersect = function (b, mtv) {
  1785. if (!b) {
  1786. return false;
  1787. }
  1788. if (!(b instanceof BoundingRect)) {
  1789. b = BoundingRect.create(b);
  1790. }
  1791. var a = this;
  1792. var ax0 = a.x;
  1793. var ax1 = a.x + a.width;
  1794. var ay0 = a.y;
  1795. var ay1 = a.y + a.height;
  1796. var bx0 = b.x;
  1797. var bx1 = b.x + b.width;
  1798. var by0 = b.y;
  1799. var by1 = b.y + b.height;
  1800. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1801. if (mtv) {
  1802. var dMin = Infinity;
  1803. var dMax = 0;
  1804. var d0 = Math.abs(ax1 - bx0);
  1805. var d1 = Math.abs(bx1 - ax0);
  1806. var d2 = Math.abs(ay1 - by0);
  1807. var d3 = Math.abs(by1 - ay0);
  1808. var dx = Math.min(d0, d1);
  1809. var dy = Math.min(d2, d3);
  1810. if (ax1 < bx0 || bx1 < ax0) {
  1811. if (dx > dMax) {
  1812. dMax = dx;
  1813. if (d0 < d1) {
  1814. Point.set(maxTv, -d0, 0);
  1815. }
  1816. else {
  1817. Point.set(maxTv, d1, 0);
  1818. }
  1819. }
  1820. }
  1821. else {
  1822. if (dx < dMin) {
  1823. dMin = dx;
  1824. if (d0 < d1) {
  1825. Point.set(minTv, d0, 0);
  1826. }
  1827. else {
  1828. Point.set(minTv, -d1, 0);
  1829. }
  1830. }
  1831. }
  1832. if (ay1 < by0 || by1 < ay0) {
  1833. if (dy > dMax) {
  1834. dMax = dy;
  1835. if (d2 < d3) {
  1836. Point.set(maxTv, 0, -d2);
  1837. }
  1838. else {
  1839. Point.set(maxTv, 0, d3);
  1840. }
  1841. }
  1842. }
  1843. else {
  1844. if (dx < dMin) {
  1845. dMin = dx;
  1846. if (d2 < d3) {
  1847. Point.set(minTv, 0, d2);
  1848. }
  1849. else {
  1850. Point.set(minTv, 0, -d3);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. if (mtv) {
  1856. Point.copy(mtv, overlap ? minTv : maxTv);
  1857. }
  1858. return overlap;
  1859. };
  1860. BoundingRect.prototype.contain = function (x, y) {
  1861. var rect = this;
  1862. return x >= rect.x
  1863. && x <= (rect.x + rect.width)
  1864. && y >= rect.y
  1865. && y <= (rect.y + rect.height);
  1866. };
  1867. BoundingRect.prototype.clone = function () {
  1868. return new BoundingRect(this.x, this.y, this.width, this.height);
  1869. };
  1870. BoundingRect.prototype.copy = function (other) {
  1871. BoundingRect.copy(this, other);
  1872. };
  1873. BoundingRect.prototype.plain = function () {
  1874. return {
  1875. x: this.x,
  1876. y: this.y,
  1877. width: this.width,
  1878. height: this.height
  1879. };
  1880. };
  1881. BoundingRect.prototype.isFinite = function () {
  1882. return isFinite(this.x)
  1883. && isFinite(this.y)
  1884. && isFinite(this.width)
  1885. && isFinite(this.height);
  1886. };
  1887. BoundingRect.prototype.isZero = function () {
  1888. return this.width === 0 || this.height === 0;
  1889. };
  1890. BoundingRect.create = function (rect) {
  1891. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1892. };
  1893. BoundingRect.copy = function (target, source) {
  1894. target.x = source.x;
  1895. target.y = source.y;
  1896. target.width = source.width;
  1897. target.height = source.height;
  1898. };
  1899. BoundingRect.applyTransform = function (target, source, m) {
  1900. if (!m) {
  1901. if (target !== source) {
  1902. BoundingRect.copy(target, source);
  1903. }
  1904. return;
  1905. }
  1906. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1907. var sx = m[0];
  1908. var sy = m[3];
  1909. var tx = m[4];
  1910. var ty = m[5];
  1911. target.x = source.x * sx + tx;
  1912. target.y = source.y * sy + ty;
  1913. target.width = source.width * sx;
  1914. target.height = source.height * sy;
  1915. if (target.width < 0) {
  1916. target.x += target.width;
  1917. target.width = -target.width;
  1918. }
  1919. if (target.height < 0) {
  1920. target.y += target.height;
  1921. target.height = -target.height;
  1922. }
  1923. return;
  1924. }
  1925. lt.x = lb.x = source.x;
  1926. lt.y = rt.y = source.y;
  1927. rb.x = rt.x = source.x + source.width;
  1928. rb.y = lb.y = source.y + source.height;
  1929. lt.transform(m);
  1930. rt.transform(m);
  1931. rb.transform(m);
  1932. lb.transform(m);
  1933. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1934. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1935. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1936. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1937. target.width = maxX - target.x;
  1938. target.height = maxY - target.y;
  1939. };
  1940. return BoundingRect;
  1941. }());
  1942. var SILENT = 'silent';
  1943. function makeEventPacket(eveType, targetInfo, event) {
  1944. return {
  1945. type: eveType,
  1946. event: event,
  1947. target: targetInfo.target,
  1948. topTarget: targetInfo.topTarget,
  1949. cancelBubble: false,
  1950. offsetX: event.zrX,
  1951. offsetY: event.zrY,
  1952. gestureEvent: event.gestureEvent,
  1953. pinchX: event.pinchX,
  1954. pinchY: event.pinchY,
  1955. pinchScale: event.pinchScale,
  1956. wheelDelta: event.zrDelta,
  1957. zrByTouch: event.zrByTouch,
  1958. which: event.which,
  1959. stop: stopEvent
  1960. };
  1961. }
  1962. function stopEvent() {
  1963. stop(this.event);
  1964. }
  1965. var EmptyProxy = (function (_super) {
  1966. __extends(EmptyProxy, _super);
  1967. function EmptyProxy() {
  1968. var _this = _super !== null && _super.apply(this, arguments) || this;
  1969. _this.handler = null;
  1970. return _this;
  1971. }
  1972. EmptyProxy.prototype.dispose = function () { };
  1973. EmptyProxy.prototype.setCursor = function () { };
  1974. return EmptyProxy;
  1975. }(Eventful));
  1976. var HoveredResult = (function () {
  1977. function HoveredResult(x, y) {
  1978. this.x = x;
  1979. this.y = y;
  1980. }
  1981. return HoveredResult;
  1982. }());
  1983. var handlerNames = [
  1984. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1985. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1986. ];
  1987. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1988. var Handler = (function (_super) {
  1989. __extends(Handler, _super);
  1990. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1991. var _this = _super.call(this) || this;
  1992. _this._hovered = new HoveredResult(0, 0);
  1993. _this.storage = storage;
  1994. _this.painter = painter;
  1995. _this.painterRoot = painterRoot;
  1996. _this._pointerSize = pointerSize;
  1997. proxy = proxy || new EmptyProxy();
  1998. _this.proxy = null;
  1999. _this.setHandlerProxy(proxy);
  2000. _this._draggingMgr = new Draggable(_this);
  2001. return _this;
  2002. }
  2003. Handler.prototype.setHandlerProxy = function (proxy) {
  2004. if (this.proxy) {
  2005. this.proxy.dispose();
  2006. }
  2007. if (proxy) {
  2008. each(handlerNames, function (name) {
  2009. proxy.on && proxy.on(name, this[name], this);
  2010. }, this);
  2011. proxy.handler = this;
  2012. }
  2013. this.proxy = proxy;
  2014. };
  2015. Handler.prototype.mousemove = function (event) {
  2016. var x = event.zrX;
  2017. var y = event.zrY;
  2018. var isOutside = isOutsideBoundary(this, x, y);
  2019. var lastHovered = this._hovered;
  2020. var lastHoveredTarget = lastHovered.target;
  2021. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2022. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2023. lastHoveredTarget = lastHovered.target;
  2024. }
  2025. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2026. var hoveredTarget = hovered.target;
  2027. var proxy = this.proxy;
  2028. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2029. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2030. this.dispatchToElement(lastHovered, 'mouseout', event);
  2031. }
  2032. this.dispatchToElement(hovered, 'mousemove', event);
  2033. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2034. this.dispatchToElement(hovered, 'mouseover', event);
  2035. }
  2036. };
  2037. Handler.prototype.mouseout = function (event) {
  2038. var eventControl = event.zrEventControl;
  2039. if (eventControl !== 'only_globalout') {
  2040. this.dispatchToElement(this._hovered, 'mouseout', event);
  2041. }
  2042. if (eventControl !== 'no_globalout') {
  2043. this.trigger('globalout', { type: 'globalout', event: event });
  2044. }
  2045. };
  2046. Handler.prototype.resize = function () {
  2047. this._hovered = new HoveredResult(0, 0);
  2048. };
  2049. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2050. var handler = this[eventName];
  2051. handler && handler.call(this, eventArgs);
  2052. };
  2053. Handler.prototype.dispose = function () {
  2054. this.proxy.dispose();
  2055. this.storage = null;
  2056. this.proxy = null;
  2057. this.painter = null;
  2058. };
  2059. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2060. var proxy = this.proxy;
  2061. proxy.setCursor && proxy.setCursor(cursorStyle);
  2062. };
  2063. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2064. targetInfo = targetInfo || {};
  2065. var el = targetInfo.target;
  2066. if (el && el.silent) {
  2067. return;
  2068. }
  2069. var eventKey = ('on' + eventName);
  2070. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2071. while (el) {
  2072. el[eventKey]
  2073. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2074. el.trigger(eventName, eventPacket);
  2075. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2076. if (eventPacket.cancelBubble) {
  2077. break;
  2078. }
  2079. }
  2080. if (!eventPacket.cancelBubble) {
  2081. this.trigger(eventName, eventPacket);
  2082. if (this.painter && this.painter.eachOtherLayer) {
  2083. this.painter.eachOtherLayer(function (layer) {
  2084. if (typeof (layer[eventKey]) === 'function') {
  2085. layer[eventKey].call(layer, eventPacket);
  2086. }
  2087. if (layer.trigger) {
  2088. layer.trigger(eventName, eventPacket);
  2089. }
  2090. });
  2091. }
  2092. }
  2093. };
  2094. Handler.prototype.findHover = function (x, y, exclude) {
  2095. var list = this.storage.getDisplayList();
  2096. var out = new HoveredResult(x, y);
  2097. setHoverTarget(list, out, x, y, exclude);
  2098. if (this._pointerSize && !out.target) {
  2099. var candidates = [];
  2100. var pointerSize = this._pointerSize;
  2101. var targetSizeHalf = pointerSize / 2;
  2102. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2103. for (var i = list.length - 1; i >= 0; i--) {
  2104. var el = list[i];
  2105. if (el !== exclude
  2106. && !el.ignore
  2107. && !el.ignoreCoarsePointer
  2108. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2109. tmpRect.copy(el.getBoundingRect());
  2110. if (el.transform) {
  2111. tmpRect.applyTransform(el.transform);
  2112. }
  2113. if (tmpRect.intersect(pointerRect)) {
  2114. candidates.push(el);
  2115. }
  2116. }
  2117. }
  2118. if (candidates.length) {
  2119. var rStep = 4;
  2120. var thetaStep = Math.PI / 12;
  2121. var PI2 = Math.PI * 2;
  2122. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2123. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2124. var x1 = x + r * Math.cos(theta);
  2125. var y1 = y + r * Math.sin(theta);
  2126. setHoverTarget(candidates, out, x1, y1, exclude);
  2127. if (out.target) {
  2128. return out;
  2129. }
  2130. }
  2131. }
  2132. }
  2133. }
  2134. return out;
  2135. };
  2136. Handler.prototype.processGesture = function (event, stage) {
  2137. if (!this._gestureMgr) {
  2138. this._gestureMgr = new GestureMgr();
  2139. }
  2140. var gestureMgr = this._gestureMgr;
  2141. stage === 'start' && gestureMgr.clear();
  2142. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2143. stage === 'end' && gestureMgr.clear();
  2144. if (gestureInfo) {
  2145. var type = gestureInfo.type;
  2146. event.gestureEvent = type;
  2147. var res = new HoveredResult();
  2148. res.target = gestureInfo.target;
  2149. this.dispatchToElement(res, type, gestureInfo.event);
  2150. }
  2151. };
  2152. return Handler;
  2153. }(Eventful));
  2154. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2155. Handler.prototype[name] = function (event) {
  2156. var x = event.zrX;
  2157. var y = event.zrY;
  2158. var isOutside = isOutsideBoundary(this, x, y);
  2159. var hovered;
  2160. var hoveredTarget;
  2161. if (name !== 'mouseup' || !isOutside) {
  2162. hovered = this.findHover(x, y);
  2163. hoveredTarget = hovered.target;
  2164. }
  2165. if (name === 'mousedown') {
  2166. this._downEl = hoveredTarget;
  2167. this._downPoint = [event.zrX, event.zrY];
  2168. this._upEl = hoveredTarget;
  2169. }
  2170. else if (name === 'mouseup') {
  2171. this._upEl = hoveredTarget;
  2172. }
  2173. else if (name === 'click') {
  2174. if (this._downEl !== this._upEl
  2175. || !this._downPoint
  2176. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2177. return;
  2178. }
  2179. this._downPoint = null;
  2180. }
  2181. this.dispatchToElement(hovered, name, event);
  2182. };
  2183. });
  2184. function isHover(displayable, x, y) {
  2185. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2186. var el = displayable;
  2187. var isSilent = void 0;
  2188. var ignoreClip = false;
  2189. while (el) {
  2190. if (el.ignoreClip) {
  2191. ignoreClip = true;
  2192. }
  2193. if (!ignoreClip) {
  2194. var clipPath = el.getClipPath();
  2195. if (clipPath && !clipPath.contain(x, y)) {
  2196. return false;
  2197. }
  2198. if (el.silent) {
  2199. isSilent = true;
  2200. }
  2201. }
  2202. var hostEl = el.__hostTarget;
  2203. el = hostEl ? hostEl : el.parent;
  2204. }
  2205. return isSilent ? SILENT : true;
  2206. }
  2207. return false;
  2208. }
  2209. function setHoverTarget(list, out, x, y, exclude) {
  2210. for (var i = list.length - 1; i >= 0; i--) {
  2211. var el = list[i];
  2212. var hoverCheckResult = void 0;
  2213. if (el !== exclude
  2214. && !el.ignore
  2215. && (hoverCheckResult = isHover(el, x, y))) {
  2216. !out.topTarget && (out.topTarget = el);
  2217. if (hoverCheckResult !== SILENT) {
  2218. out.target = el;
  2219. break;
  2220. }
  2221. }
  2222. }
  2223. }
  2224. function isOutsideBoundary(handlerInstance, x, y) {
  2225. var painter = handlerInstance.painter;
  2226. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2227. }
  2228. var DEFAULT_MIN_MERGE = 32;
  2229. var DEFAULT_MIN_GALLOPING = 7;
  2230. function minRunLength(n) {
  2231. var r = 0;
  2232. while (n >= DEFAULT_MIN_MERGE) {
  2233. r |= n & 1;
  2234. n >>= 1;
  2235. }
  2236. return n + r;
  2237. }
  2238. function makeAscendingRun(array, lo, hi, compare) {
  2239. var runHi = lo + 1;
  2240. if (runHi === hi) {
  2241. return 1;
  2242. }
  2243. if (compare(array[runHi++], array[lo]) < 0) {
  2244. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2245. runHi++;
  2246. }
  2247. reverseRun(array, lo, runHi);
  2248. }
  2249. else {
  2250. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2251. runHi++;
  2252. }
  2253. }
  2254. return runHi - lo;
  2255. }
  2256. function reverseRun(array, lo, hi) {
  2257. hi--;
  2258. while (lo < hi) {
  2259. var t = array[lo];
  2260. array[lo++] = array[hi];
  2261. array[hi--] = t;
  2262. }
  2263. }
  2264. function binaryInsertionSort(array, lo, hi, start, compare) {
  2265. if (start === lo) {
  2266. start++;
  2267. }
  2268. for (; start < hi; start++) {
  2269. var pivot = array[start];
  2270. var left = lo;
  2271. var right = start;
  2272. var mid;
  2273. while (left < right) {
  2274. mid = left + right >>> 1;
  2275. if (compare(pivot, array[mid]) < 0) {
  2276. right = mid;
  2277. }
  2278. else {
  2279. left = mid + 1;
  2280. }
  2281. }
  2282. var n = start - left;
  2283. switch (n) {
  2284. case 3:
  2285. array[left + 3] = array[left + 2];
  2286. case 2:
  2287. array[left + 2] = array[left + 1];
  2288. case 1:
  2289. array[left + 1] = array[left];
  2290. break;
  2291. default:
  2292. while (n > 0) {
  2293. array[left + n] = array[left + n - 1];
  2294. n--;
  2295. }
  2296. }
  2297. array[left] = pivot;
  2298. }
  2299. }
  2300. function gallopLeft(value, array, start, length, hint, compare) {
  2301. var lastOffset = 0;
  2302. var maxOffset = 0;
  2303. var offset = 1;
  2304. if (compare(value, array[start + hint]) > 0) {
  2305. maxOffset = length - hint;
  2306. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2307. lastOffset = offset;
  2308. offset = (offset << 1) + 1;
  2309. if (offset <= 0) {
  2310. offset = maxOffset;
  2311. }
  2312. }
  2313. if (offset > maxOffset) {
  2314. offset = maxOffset;
  2315. }
  2316. lastOffset += hint;
  2317. offset += hint;
  2318. }
  2319. else {
  2320. maxOffset = hint + 1;
  2321. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2322. lastOffset = offset;
  2323. offset = (offset << 1) + 1;
  2324. if (offset <= 0) {
  2325. offset = maxOffset;
  2326. }
  2327. }
  2328. if (offset > maxOffset) {
  2329. offset = maxOffset;
  2330. }
  2331. var tmp = lastOffset;
  2332. lastOffset = hint - offset;
  2333. offset = hint - tmp;
  2334. }
  2335. lastOffset++;
  2336. while (lastOffset < offset) {
  2337. var m = lastOffset + (offset - lastOffset >>> 1);
  2338. if (compare(value, array[start + m]) > 0) {
  2339. lastOffset = m + 1;
  2340. }
  2341. else {
  2342. offset = m;
  2343. }
  2344. }
  2345. return offset;
  2346. }
  2347. function gallopRight(value, array, start, length, hint, compare) {
  2348. var lastOffset = 0;
  2349. var maxOffset = 0;
  2350. var offset = 1;
  2351. if (compare(value, array[start + hint]) < 0) {
  2352. maxOffset = hint + 1;
  2353. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2354. lastOffset = offset;
  2355. offset = (offset << 1) + 1;
  2356. if (offset <= 0) {
  2357. offset = maxOffset;
  2358. }
  2359. }
  2360. if (offset > maxOffset) {
  2361. offset = maxOffset;
  2362. }
  2363. var tmp = lastOffset;
  2364. lastOffset = hint - offset;
  2365. offset = hint - tmp;
  2366. }
  2367. else {
  2368. maxOffset = length - hint;
  2369. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2370. lastOffset = offset;
  2371. offset = (offset << 1) + 1;
  2372. if (offset <= 0) {
  2373. offset = maxOffset;
  2374. }
  2375. }
  2376. if (offset > maxOffset) {
  2377. offset = maxOffset;
  2378. }
  2379. lastOffset += hint;
  2380. offset += hint;
  2381. }
  2382. lastOffset++;
  2383. while (lastOffset < offset) {
  2384. var m = lastOffset + (offset - lastOffset >>> 1);
  2385. if (compare(value, array[start + m]) < 0) {
  2386. offset = m;
  2387. }
  2388. else {
  2389. lastOffset = m + 1;
  2390. }
  2391. }
  2392. return offset;
  2393. }
  2394. function TimSort(array, compare) {
  2395. var minGallop = DEFAULT_MIN_GALLOPING;
  2396. var length = 0;
  2397. var runStart;
  2398. var runLength;
  2399. var stackSize = 0;
  2400. length = array.length;
  2401. var tmp = [];
  2402. runStart = [];
  2403. runLength = [];
  2404. function pushRun(_runStart, _runLength) {
  2405. runStart[stackSize] = _runStart;
  2406. runLength[stackSize] = _runLength;
  2407. stackSize += 1;
  2408. }
  2409. function mergeRuns() {
  2410. while (stackSize > 1) {
  2411. var n = stackSize - 2;
  2412. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2413. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2414. if (runLength[n - 1] < runLength[n + 1]) {
  2415. n--;
  2416. }
  2417. }
  2418. else if (runLength[n] > runLength[n + 1]) {
  2419. break;
  2420. }
  2421. mergeAt(n);
  2422. }
  2423. }
  2424. function forceMergeRuns() {
  2425. while (stackSize > 1) {
  2426. var n = stackSize - 2;
  2427. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2428. n--;
  2429. }
  2430. mergeAt(n);
  2431. }
  2432. }
  2433. function mergeAt(i) {
  2434. var start1 = runStart[i];
  2435. var length1 = runLength[i];
  2436. var start2 = runStart[i + 1];
  2437. var length2 = runLength[i + 1];
  2438. runLength[i] = length1 + length2;
  2439. if (i === stackSize - 3) {
  2440. runStart[i + 1] = runStart[i + 2];
  2441. runLength[i + 1] = runLength[i + 2];
  2442. }
  2443. stackSize--;
  2444. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2445. start1 += k;
  2446. length1 -= k;
  2447. if (length1 === 0) {
  2448. return;
  2449. }
  2450. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2451. if (length2 === 0) {
  2452. return;
  2453. }
  2454. if (length1 <= length2) {
  2455. mergeLow(start1, length1, start2, length2);
  2456. }
  2457. else {
  2458. mergeHigh(start1, length1, start2, length2);
  2459. }
  2460. }
  2461. function mergeLow(start1, length1, start2, length2) {
  2462. var i = 0;
  2463. for (i = 0; i < length1; i++) {
  2464. tmp[i] = array[start1 + i];
  2465. }
  2466. var cursor1 = 0;
  2467. var cursor2 = start2;
  2468. var dest = start1;
  2469. array[dest++] = array[cursor2++];
  2470. if (--length2 === 0) {
  2471. for (i = 0; i < length1; i++) {
  2472. array[dest + i] = tmp[cursor1 + i];
  2473. }
  2474. return;
  2475. }
  2476. if (length1 === 1) {
  2477. for (i = 0; i < length2; i++) {
  2478. array[dest + i] = array[cursor2 + i];
  2479. }
  2480. array[dest + length2] = tmp[cursor1];
  2481. return;
  2482. }
  2483. var _minGallop = minGallop;
  2484. var count1;
  2485. var count2;
  2486. var exit;
  2487. while (1) {
  2488. count1 = 0;
  2489. count2 = 0;
  2490. exit = false;
  2491. do {
  2492. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2493. array[dest++] = array[cursor2++];
  2494. count2++;
  2495. count1 = 0;
  2496. if (--length2 === 0) {
  2497. exit = true;
  2498. break;
  2499. }
  2500. }
  2501. else {
  2502. array[dest++] = tmp[cursor1++];
  2503. count1++;
  2504. count2 = 0;
  2505. if (--length1 === 1) {
  2506. exit = true;
  2507. break;
  2508. }
  2509. }
  2510. } while ((count1 | count2) < _minGallop);
  2511. if (exit) {
  2512. break;
  2513. }
  2514. do {
  2515. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2516. if (count1 !== 0) {
  2517. for (i = 0; i < count1; i++) {
  2518. array[dest + i] = tmp[cursor1 + i];
  2519. }
  2520. dest += count1;
  2521. cursor1 += count1;
  2522. length1 -= count1;
  2523. if (length1 <= 1) {
  2524. exit = true;
  2525. break;
  2526. }
  2527. }
  2528. array[dest++] = array[cursor2++];
  2529. if (--length2 === 0) {
  2530. exit = true;
  2531. break;
  2532. }
  2533. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2534. if (count2 !== 0) {
  2535. for (i = 0; i < count2; i++) {
  2536. array[dest + i] = array[cursor2 + i];
  2537. }
  2538. dest += count2;
  2539. cursor2 += count2;
  2540. length2 -= count2;
  2541. if (length2 === 0) {
  2542. exit = true;
  2543. break;
  2544. }
  2545. }
  2546. array[dest++] = tmp[cursor1++];
  2547. if (--length1 === 1) {
  2548. exit = true;
  2549. break;
  2550. }
  2551. _minGallop--;
  2552. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2553. if (exit) {
  2554. break;
  2555. }
  2556. if (_minGallop < 0) {
  2557. _minGallop = 0;
  2558. }
  2559. _minGallop += 2;
  2560. }
  2561. minGallop = _minGallop;
  2562. minGallop < 1 && (minGallop = 1);
  2563. if (length1 === 1) {
  2564. for (i = 0; i < length2; i++) {
  2565. array[dest + i] = array[cursor2 + i];
  2566. }
  2567. array[dest + length2] = tmp[cursor1];
  2568. }
  2569. else if (length1 === 0) {
  2570. throw new Error();
  2571. }
  2572. else {
  2573. for (i = 0; i < length1; i++) {
  2574. array[dest + i] = tmp[cursor1 + i];
  2575. }
  2576. }
  2577. }
  2578. function mergeHigh(start1, length1, start2, length2) {
  2579. var i = 0;
  2580. for (i = 0; i < length2; i++) {
  2581. tmp[i] = array[start2 + i];
  2582. }
  2583. var cursor1 = start1 + length1 - 1;
  2584. var cursor2 = length2 - 1;
  2585. var dest = start2 + length2 - 1;
  2586. var customCursor = 0;
  2587. var customDest = 0;
  2588. array[dest--] = array[cursor1--];
  2589. if (--length1 === 0) {
  2590. customCursor = dest - (length2 - 1);
  2591. for (i = 0; i < length2; i++) {
  2592. array[customCursor + i] = tmp[i];
  2593. }
  2594. return;
  2595. }
  2596. if (length2 === 1) {
  2597. dest -= length1;
  2598. cursor1 -= length1;
  2599. customDest = dest + 1;
  2600. customCursor = cursor1 + 1;
  2601. for (i = length1 - 1; i >= 0; i--) {
  2602. array[customDest + i] = array[customCursor + i];
  2603. }
  2604. array[dest] = tmp[cursor2];
  2605. return;
  2606. }
  2607. var _minGallop = minGallop;
  2608. while (true) {
  2609. var count1 = 0;
  2610. var count2 = 0;
  2611. var exit = false;
  2612. do {
  2613. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2614. array[dest--] = array[cursor1--];
  2615. count1++;
  2616. count2 = 0;
  2617. if (--length1 === 0) {
  2618. exit = true;
  2619. break;
  2620. }
  2621. }
  2622. else {
  2623. array[dest--] = tmp[cursor2--];
  2624. count2++;
  2625. count1 = 0;
  2626. if (--length2 === 1) {
  2627. exit = true;
  2628. break;
  2629. }
  2630. }
  2631. } while ((count1 | count2) < _minGallop);
  2632. if (exit) {
  2633. break;
  2634. }
  2635. do {
  2636. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2637. if (count1 !== 0) {
  2638. dest -= count1;
  2639. cursor1 -= count1;
  2640. length1 -= count1;
  2641. customDest = dest + 1;
  2642. customCursor = cursor1 + 1;
  2643. for (i = count1 - 1; i >= 0; i--) {
  2644. array[customDest + i] = array[customCursor + i];
  2645. }
  2646. if (length1 === 0) {
  2647. exit = true;
  2648. break;
  2649. }
  2650. }
  2651. array[dest--] = tmp[cursor2--];
  2652. if (--length2 === 1) {
  2653. exit = true;
  2654. break;
  2655. }
  2656. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2657. if (count2 !== 0) {
  2658. dest -= count2;
  2659. cursor2 -= count2;
  2660. length2 -= count2;
  2661. customDest = dest + 1;
  2662. customCursor = cursor2 + 1;
  2663. for (i = 0; i < count2; i++) {
  2664. array[customDest + i] = tmp[customCursor + i];
  2665. }
  2666. if (length2 <= 1) {
  2667. exit = true;
  2668. break;
  2669. }
  2670. }
  2671. array[dest--] = array[cursor1--];
  2672. if (--length1 === 0) {
  2673. exit = true;
  2674. break;
  2675. }
  2676. _minGallop--;
  2677. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2678. if (exit) {
  2679. break;
  2680. }
  2681. if (_minGallop < 0) {
  2682. _minGallop = 0;
  2683. }
  2684. _minGallop += 2;
  2685. }
  2686. minGallop = _minGallop;
  2687. if (minGallop < 1) {
  2688. minGallop = 1;
  2689. }
  2690. if (length2 === 1) {
  2691. dest -= length1;
  2692. cursor1 -= length1;
  2693. customDest = dest + 1;
  2694. customCursor = cursor1 + 1;
  2695. for (i = length1 - 1; i >= 0; i--) {
  2696. array[customDest + i] = array[customCursor + i];
  2697. }
  2698. array[dest] = tmp[cursor2];
  2699. }
  2700. else if (length2 === 0) {
  2701. throw new Error();
  2702. }
  2703. else {
  2704. customCursor = dest - (length2 - 1);
  2705. for (i = 0; i < length2; i++) {
  2706. array[customCursor + i] = tmp[i];
  2707. }
  2708. }
  2709. }
  2710. return {
  2711. mergeRuns: mergeRuns,
  2712. forceMergeRuns: forceMergeRuns,
  2713. pushRun: pushRun
  2714. };
  2715. }
  2716. function sort(array, compare, lo, hi) {
  2717. if (!lo) {
  2718. lo = 0;
  2719. }
  2720. if (!hi) {
  2721. hi = array.length;
  2722. }
  2723. var remaining = hi - lo;
  2724. if (remaining < 2) {
  2725. return;
  2726. }
  2727. var runLength = 0;
  2728. if (remaining < DEFAULT_MIN_MERGE) {
  2729. runLength = makeAscendingRun(array, lo, hi, compare);
  2730. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2731. return;
  2732. }
  2733. var ts = TimSort(array, compare);
  2734. var minRun = minRunLength(remaining);
  2735. do {
  2736. runLength = makeAscendingRun(array, lo, hi, compare);
  2737. if (runLength < minRun) {
  2738. var force = remaining;
  2739. if (force > minRun) {
  2740. force = minRun;
  2741. }
  2742. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2743. runLength = force;
  2744. }
  2745. ts.pushRun(lo, runLength);
  2746. ts.mergeRuns();
  2747. remaining -= runLength;
  2748. lo += runLength;
  2749. } while (remaining !== 0);
  2750. ts.forceMergeRuns();
  2751. }
  2752. var REDRAW_BIT = 1;
  2753. var STYLE_CHANGED_BIT = 2;
  2754. var SHAPE_CHANGED_BIT = 4;
  2755. var invalidZErrorLogged = false;
  2756. function logInvalidZError() {
  2757. if (invalidZErrorLogged) {
  2758. return;
  2759. }
  2760. invalidZErrorLogged = true;
  2761. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2762. }
  2763. function shapeCompareFunc(a, b) {
  2764. if (a.zlevel === b.zlevel) {
  2765. if (a.z === b.z) {
  2766. return a.z2 - b.z2;
  2767. }
  2768. return a.z - b.z;
  2769. }
  2770. return a.zlevel - b.zlevel;
  2771. }
  2772. var Storage = (function () {
  2773. function Storage() {
  2774. this._roots = [];
  2775. this._displayList = [];
  2776. this._displayListLen = 0;
  2777. this.displayableSortFunc = shapeCompareFunc;
  2778. }
  2779. Storage.prototype.traverse = function (cb, context) {
  2780. for (var i = 0; i < this._roots.length; i++) {
  2781. this._roots[i].traverse(cb, context);
  2782. }
  2783. };
  2784. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2785. includeIgnore = includeIgnore || false;
  2786. var displayList = this._displayList;
  2787. if (update || !displayList.length) {
  2788. this.updateDisplayList(includeIgnore);
  2789. }
  2790. return displayList;
  2791. };
  2792. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2793. this._displayListLen = 0;
  2794. var roots = this._roots;
  2795. var displayList = this._displayList;
  2796. for (var i = 0, len = roots.length; i < len; i++) {
  2797. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2798. }
  2799. displayList.length = this._displayListLen;
  2800. sort(displayList, shapeCompareFunc);
  2801. };
  2802. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2803. if (el.ignore && !includeIgnore) {
  2804. return;
  2805. }
  2806. el.beforeUpdate();
  2807. el.update();
  2808. el.afterUpdate();
  2809. var userSetClipPath = el.getClipPath();
  2810. if (el.ignoreClip) {
  2811. clipPaths = null;
  2812. }
  2813. else if (userSetClipPath) {
  2814. if (clipPaths) {
  2815. clipPaths = clipPaths.slice();
  2816. }
  2817. else {
  2818. clipPaths = [];
  2819. }
  2820. var currentClipPath = userSetClipPath;
  2821. var parentClipPath = el;
  2822. while (currentClipPath) {
  2823. currentClipPath.parent = parentClipPath;
  2824. currentClipPath.updateTransform();
  2825. clipPaths.push(currentClipPath);
  2826. parentClipPath = currentClipPath;
  2827. currentClipPath = currentClipPath.getClipPath();
  2828. }
  2829. }
  2830. if (el.childrenRef) {
  2831. var children = el.childrenRef();
  2832. for (var i = 0; i < children.length; i++) {
  2833. var child = children[i];
  2834. if (el.__dirty) {
  2835. child.__dirty |= REDRAW_BIT;
  2836. }
  2837. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2838. }
  2839. el.__dirty = 0;
  2840. }
  2841. else {
  2842. var disp = el;
  2843. if (clipPaths && clipPaths.length) {
  2844. disp.__clipPaths = clipPaths;
  2845. }
  2846. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2847. disp.__clipPaths = [];
  2848. }
  2849. if (isNaN(disp.z)) {
  2850. logInvalidZError();
  2851. disp.z = 0;
  2852. }
  2853. if (isNaN(disp.z2)) {
  2854. logInvalidZError();
  2855. disp.z2 = 0;
  2856. }
  2857. if (isNaN(disp.zlevel)) {
  2858. logInvalidZError();
  2859. disp.zlevel = 0;
  2860. }
  2861. this._displayList[this._displayListLen++] = disp;
  2862. }
  2863. var decalEl = el.getDecalElement && el.getDecalElement();
  2864. if (decalEl) {
  2865. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2866. }
  2867. var textGuide = el.getTextGuideLine();
  2868. if (textGuide) {
  2869. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2870. }
  2871. var textEl = el.getTextContent();
  2872. if (textEl) {
  2873. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2874. }
  2875. };
  2876. Storage.prototype.addRoot = function (el) {
  2877. if (el.__zr && el.__zr.storage === this) {
  2878. return;
  2879. }
  2880. this._roots.push(el);
  2881. };
  2882. Storage.prototype.delRoot = function (el) {
  2883. if (el instanceof Array) {
  2884. for (var i = 0, l = el.length; i < l; i++) {
  2885. this.delRoot(el[i]);
  2886. }
  2887. return;
  2888. }
  2889. var idx = indexOf(this._roots, el);
  2890. if (idx >= 0) {
  2891. this._roots.splice(idx, 1);
  2892. }
  2893. };
  2894. Storage.prototype.delAllRoots = function () {
  2895. this._roots = [];
  2896. this._displayList = [];
  2897. this._displayListLen = 0;
  2898. return;
  2899. };
  2900. Storage.prototype.getRoots = function () {
  2901. return this._roots;
  2902. };
  2903. Storage.prototype.dispose = function () {
  2904. this._displayList = null;
  2905. this._roots = null;
  2906. };
  2907. return Storage;
  2908. }());
  2909. var requestAnimationFrame;
  2910. requestAnimationFrame = (env.hasGlobalWindow
  2911. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2912. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2913. || window.mozRequestAnimationFrame
  2914. || window.webkitRequestAnimationFrame)) || function (func) {
  2915. return setTimeout(func, 16);
  2916. };
  2917. var requestAnimationFrame$1 = requestAnimationFrame;
  2918. var easingFuncs = {
  2919. linear: function (k) {
  2920. return k;
  2921. },
  2922. quadraticIn: function (k) {
  2923. return k * k;
  2924. },
  2925. quadraticOut: function (k) {
  2926. return k * (2 - k);
  2927. },
  2928. quadraticInOut: function (k) {
  2929. if ((k *= 2) < 1) {
  2930. return 0.5 * k * k;
  2931. }
  2932. return -0.5 * (--k * (k - 2) - 1);
  2933. },
  2934. cubicIn: function (k) {
  2935. return k * k * k;
  2936. },
  2937. cubicOut: function (k) {
  2938. return --k * k * k + 1;
  2939. },
  2940. cubicInOut: function (k) {
  2941. if ((k *= 2) < 1) {
  2942. return 0.5 * k * k * k;
  2943. }
  2944. return 0.5 * ((k -= 2) * k * k + 2);
  2945. },
  2946. quarticIn: function (k) {
  2947. return k * k * k * k;
  2948. },
  2949. quarticOut: function (k) {
  2950. return 1 - (--k * k * k * k);
  2951. },
  2952. quarticInOut: function (k) {
  2953. if ((k *= 2) < 1) {
  2954. return 0.5 * k * k * k * k;
  2955. }
  2956. return -0.5 * ((k -= 2) * k * k * k - 2);
  2957. },
  2958. quinticIn: function (k) {
  2959. return k * k * k * k * k;
  2960. },
  2961. quinticOut: function (k) {
  2962. return --k * k * k * k * k + 1;
  2963. },
  2964. quinticInOut: function (k) {
  2965. if ((k *= 2) < 1) {
  2966. return 0.5 * k * k * k * k * k;
  2967. }
  2968. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2969. },
  2970. sinusoidalIn: function (k) {
  2971. return 1 - Math.cos(k * Math.PI / 2);
  2972. },
  2973. sinusoidalOut: function (k) {
  2974. return Math.sin(k * Math.PI / 2);
  2975. },
  2976. sinusoidalInOut: function (k) {
  2977. return 0.5 * (1 - Math.cos(Math.PI * k));
  2978. },
  2979. exponentialIn: function (k) {
  2980. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2981. },
  2982. exponentialOut: function (k) {
  2983. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2984. },
  2985. exponentialInOut: function (k) {
  2986. if (k === 0) {
  2987. return 0;
  2988. }
  2989. if (k === 1) {
  2990. return 1;
  2991. }
  2992. if ((k *= 2) < 1) {
  2993. return 0.5 * Math.pow(1024, k - 1);
  2994. }
  2995. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2996. },
  2997. circularIn: function (k) {
  2998. return 1 - Math.sqrt(1 - k * k);
  2999. },
  3000. circularOut: function (k) {
  3001. return Math.sqrt(1 - (--k * k));
  3002. },
  3003. circularInOut: function (k) {
  3004. if ((k *= 2) < 1) {
  3005. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3006. }
  3007. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3008. },
  3009. elasticIn: function (k) {
  3010. var s;
  3011. var a = 0.1;
  3012. var p = 0.4;
  3013. if (k === 0) {
  3014. return 0;
  3015. }
  3016. if (k === 1) {
  3017. return 1;
  3018. }
  3019. if (!a || a < 1) {
  3020. a = 1;
  3021. s = p / 4;
  3022. }
  3023. else {
  3024. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3025. }
  3026. return -(a * Math.pow(2, 10 * (k -= 1))
  3027. * Math.sin((k - s) * (2 * Math.PI) / p));
  3028. },
  3029. elasticOut: function (k) {
  3030. var s;
  3031. var a = 0.1;
  3032. var p = 0.4;
  3033. if (k === 0) {
  3034. return 0;
  3035. }
  3036. if (k === 1) {
  3037. return 1;
  3038. }
  3039. if (!a || a < 1) {
  3040. a = 1;
  3041. s = p / 4;
  3042. }
  3043. else {
  3044. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3045. }
  3046. return (a * Math.pow(2, -10 * k)
  3047. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3048. },
  3049. elasticInOut: function (k) {
  3050. var s;
  3051. var a = 0.1;
  3052. var p = 0.4;
  3053. if (k === 0) {
  3054. return 0;
  3055. }
  3056. if (k === 1) {
  3057. return 1;
  3058. }
  3059. if (!a || a < 1) {
  3060. a = 1;
  3061. s = p / 4;
  3062. }
  3063. else {
  3064. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3065. }
  3066. if ((k *= 2) < 1) {
  3067. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3068. * Math.sin((k - s) * (2 * Math.PI) / p));
  3069. }
  3070. return a * Math.pow(2, -10 * (k -= 1))
  3071. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3072. },
  3073. backIn: function (k) {
  3074. var s = 1.70158;
  3075. return k * k * ((s + 1) * k - s);
  3076. },
  3077. backOut: function (k) {
  3078. var s = 1.70158;
  3079. return --k * k * ((s + 1) * k + s) + 1;
  3080. },
  3081. backInOut: function (k) {
  3082. var s = 1.70158 * 1.525;
  3083. if ((k *= 2) < 1) {
  3084. return 0.5 * (k * k * ((s + 1) * k - s));
  3085. }
  3086. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3087. },
  3088. bounceIn: function (k) {
  3089. return 1 - easingFuncs.bounceOut(1 - k);
  3090. },
  3091. bounceOut: function (k) {
  3092. if (k < (1 / 2.75)) {
  3093. return 7.5625 * k * k;
  3094. }
  3095. else if (k < (2 / 2.75)) {
  3096. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3097. }
  3098. else if (k < (2.5 / 2.75)) {
  3099. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3100. }
  3101. else {
  3102. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3103. }
  3104. },
  3105. bounceInOut: function (k) {
  3106. if (k < 0.5) {
  3107. return easingFuncs.bounceIn(k * 2) * 0.5;
  3108. }
  3109. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3110. }
  3111. };
  3112. var mathPow = Math.pow;
  3113. var mathSqrt = Math.sqrt;
  3114. var EPSILON = 1e-8;
  3115. var EPSILON_NUMERIC = 1e-4;
  3116. var THREE_SQRT = mathSqrt(3);
  3117. var ONE_THIRD = 1 / 3;
  3118. var _v0 = create();
  3119. var _v1 = create();
  3120. var _v2 = create();
  3121. function isAroundZero(val) {
  3122. return val > -EPSILON && val < EPSILON;
  3123. }
  3124. function isNotAroundZero(val) {
  3125. return val > EPSILON || val < -EPSILON;
  3126. }
  3127. function cubicAt(p0, p1, p2, p3, t) {
  3128. var onet = 1 - t;
  3129. return onet * onet * (onet * p0 + 3 * t * p1)
  3130. + t * t * (t * p3 + 3 * onet * p2);
  3131. }
  3132. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3133. var onet = 1 - t;
  3134. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3135. + (p3 - p2) * t * t);
  3136. }
  3137. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3138. var a = p3 + 3 * (p1 - p2) - p0;
  3139. var b = 3 * (p2 - p1 * 2 + p0);
  3140. var c = 3 * (p1 - p0);
  3141. var d = p0 - val;
  3142. var A = b * b - 3 * a * c;
  3143. var B = b * c - 9 * a * d;
  3144. var C = c * c - 3 * b * d;
  3145. var n = 0;
  3146. if (isAroundZero(A) && isAroundZero(B)) {
  3147. if (isAroundZero(b)) {
  3148. roots[0] = 0;
  3149. }
  3150. else {
  3151. var t1 = -c / b;
  3152. if (t1 >= 0 && t1 <= 1) {
  3153. roots[n++] = t1;
  3154. }
  3155. }
  3156. }
  3157. else {
  3158. var disc = B * B - 4 * A * C;
  3159. if (isAroundZero(disc)) {
  3160. var K = B / A;
  3161. var t1 = -b / a + K;
  3162. var t2 = -K / 2;
  3163. if (t1 >= 0 && t1 <= 1) {
  3164. roots[n++] = t1;
  3165. }
  3166. if (t2 >= 0 && t2 <= 1) {
  3167. roots[n++] = t2;
  3168. }
  3169. }
  3170. else if (disc > 0) {
  3171. var discSqrt = mathSqrt(disc);
  3172. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3173. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3174. if (Y1 < 0) {
  3175. Y1 = -mathPow(-Y1, ONE_THIRD);
  3176. }
  3177. else {
  3178. Y1 = mathPow(Y1, ONE_THIRD);
  3179. }
  3180. if (Y2 < 0) {
  3181. Y2 = -mathPow(-Y2, ONE_THIRD);
  3182. }
  3183. else {
  3184. Y2 = mathPow(Y2, ONE_THIRD);
  3185. }
  3186. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3187. if (t1 >= 0 && t1 <= 1) {
  3188. roots[n++] = t1;
  3189. }
  3190. }
  3191. else {
  3192. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3193. var theta = Math.acos(T) / 3;
  3194. var ASqrt = mathSqrt(A);
  3195. var tmp = Math.cos(theta);
  3196. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3197. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3198. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3199. if (t1 >= 0 && t1 <= 1) {
  3200. roots[n++] = t1;
  3201. }
  3202. if (t2 >= 0 && t2 <= 1) {
  3203. roots[n++] = t2;
  3204. }
  3205. if (t3 >= 0 && t3 <= 1) {
  3206. roots[n++] = t3;
  3207. }
  3208. }
  3209. }
  3210. return n;
  3211. }
  3212. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3213. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3214. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3215. var c = 3 * p1 - 3 * p0;
  3216. var n = 0;
  3217. if (isAroundZero(a)) {
  3218. if (isNotAroundZero(b)) {
  3219. var t1 = -c / b;
  3220. if (t1 >= 0 && t1 <= 1) {
  3221. extrema[n++] = t1;
  3222. }
  3223. }
  3224. }
  3225. else {
  3226. var disc = b * b - 4 * a * c;
  3227. if (isAroundZero(disc)) {
  3228. extrema[0] = -b / (2 * a);
  3229. }
  3230. else if (disc > 0) {
  3231. var discSqrt = mathSqrt(disc);
  3232. var t1 = (-b + discSqrt) / (2 * a);
  3233. var t2 = (-b - discSqrt) / (2 * a);
  3234. if (t1 >= 0 && t1 <= 1) {
  3235. extrema[n++] = t1;
  3236. }
  3237. if (t2 >= 0 && t2 <= 1) {
  3238. extrema[n++] = t2;
  3239. }
  3240. }
  3241. }
  3242. return n;
  3243. }
  3244. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3245. var p01 = (p1 - p0) * t + p0;
  3246. var p12 = (p2 - p1) * t + p1;
  3247. var p23 = (p3 - p2) * t + p2;
  3248. var p012 = (p12 - p01) * t + p01;
  3249. var p123 = (p23 - p12) * t + p12;
  3250. var p0123 = (p123 - p012) * t + p012;
  3251. out[0] = p0;
  3252. out[1] = p01;
  3253. out[2] = p012;
  3254. out[3] = p0123;
  3255. out[4] = p0123;
  3256. out[5] = p123;
  3257. out[6] = p23;
  3258. out[7] = p3;
  3259. }
  3260. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3261. var t;
  3262. var interval = 0.005;
  3263. var d = Infinity;
  3264. var prev;
  3265. var next;
  3266. var d1;
  3267. var d2;
  3268. _v0[0] = x;
  3269. _v0[1] = y;
  3270. for (var _t = 0; _t < 1; _t += 0.05) {
  3271. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3272. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3273. d1 = distSquare(_v0, _v1);
  3274. if (d1 < d) {
  3275. t = _t;
  3276. d = d1;
  3277. }
  3278. }
  3279. d = Infinity;
  3280. for (var i = 0; i < 32; i++) {
  3281. if (interval < EPSILON_NUMERIC) {
  3282. break;
  3283. }
  3284. prev = t - interval;
  3285. next = t + interval;
  3286. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3287. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3288. d1 = distSquare(_v1, _v0);
  3289. if (prev >= 0 && d1 < d) {
  3290. t = prev;
  3291. d = d1;
  3292. }
  3293. else {
  3294. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3295. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3296. d2 = distSquare(_v2, _v0);
  3297. if (next <= 1 && d2 < d) {
  3298. t = next;
  3299. d = d2;
  3300. }
  3301. else {
  3302. interval *= 0.5;
  3303. }
  3304. }
  3305. }
  3306. if (out) {
  3307. out[0] = cubicAt(x0, x1, x2, x3, t);
  3308. out[1] = cubicAt(y0, y1, y2, y3, t);
  3309. }
  3310. return mathSqrt(d);
  3311. }
  3312. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3313. var px = x0;
  3314. var py = y0;
  3315. var d = 0;
  3316. var step = 1 / iteration;
  3317. for (var i = 1; i <= iteration; i++) {
  3318. var t = i * step;
  3319. var x = cubicAt(x0, x1, x2, x3, t);
  3320. var y = cubicAt(y0, y1, y2, y3, t);
  3321. var dx = x - px;
  3322. var dy = y - py;
  3323. d += Math.sqrt(dx * dx + dy * dy);
  3324. px = x;
  3325. py = y;
  3326. }
  3327. return d;
  3328. }
  3329. function quadraticAt(p0, p1, p2, t) {
  3330. var onet = 1 - t;
  3331. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3332. }
  3333. function quadraticDerivativeAt(p0, p1, p2, t) {
  3334. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3335. }
  3336. function quadraticRootAt(p0, p1, p2, val, roots) {
  3337. var a = p0 - 2 * p1 + p2;
  3338. var b = 2 * (p1 - p0);
  3339. var c = p0 - val;
  3340. var n = 0;
  3341. if (isAroundZero(a)) {
  3342. if (isNotAroundZero(b)) {
  3343. var t1 = -c / b;
  3344. if (t1 >= 0 && t1 <= 1) {
  3345. roots[n++] = t1;
  3346. }
  3347. }
  3348. }
  3349. else {
  3350. var disc = b * b - 4 * a * c;
  3351. if (isAroundZero(disc)) {
  3352. var t1 = -b / (2 * a);
  3353. if (t1 >= 0 && t1 <= 1) {
  3354. roots[n++] = t1;
  3355. }
  3356. }
  3357. else if (disc > 0) {
  3358. var discSqrt = mathSqrt(disc);
  3359. var t1 = (-b + discSqrt) / (2 * a);
  3360. var t2 = (-b - discSqrt) / (2 * a);
  3361. if (t1 >= 0 && t1 <= 1) {
  3362. roots[n++] = t1;
  3363. }
  3364. if (t2 >= 0 && t2 <= 1) {
  3365. roots[n++] = t2;
  3366. }
  3367. }
  3368. }
  3369. return n;
  3370. }
  3371. function quadraticExtremum(p0, p1, p2) {
  3372. var divider = p0 + p2 - 2 * p1;
  3373. if (divider === 0) {
  3374. return 0.5;
  3375. }
  3376. else {
  3377. return (p0 - p1) / divider;
  3378. }
  3379. }
  3380. function quadraticSubdivide(p0, p1, p2, t, out) {
  3381. var p01 = (p1 - p0) * t + p0;
  3382. var p12 = (p2 - p1) * t + p1;
  3383. var p012 = (p12 - p01) * t + p01;
  3384. out[0] = p0;
  3385. out[1] = p01;
  3386. out[2] = p012;
  3387. out[3] = p012;
  3388. out[4] = p12;
  3389. out[5] = p2;
  3390. }
  3391. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3392. var t;
  3393. var interval = 0.005;
  3394. var d = Infinity;
  3395. _v0[0] = x;
  3396. _v0[1] = y;
  3397. for (var _t = 0; _t < 1; _t += 0.05) {
  3398. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3399. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3400. var d1 = distSquare(_v0, _v1);
  3401. if (d1 < d) {
  3402. t = _t;
  3403. d = d1;
  3404. }
  3405. }
  3406. d = Infinity;
  3407. for (var i = 0; i < 32; i++) {
  3408. if (interval < EPSILON_NUMERIC) {
  3409. break;
  3410. }
  3411. var prev = t - interval;
  3412. var next = t + interval;
  3413. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3414. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3415. var d1 = distSquare(_v1, _v0);
  3416. if (prev >= 0 && d1 < d) {
  3417. t = prev;
  3418. d = d1;
  3419. }
  3420. else {
  3421. _v2[0] = quadraticAt(x0, x1, x2, next);
  3422. _v2[1] = quadraticAt(y0, y1, y2, next);
  3423. var d2 = distSquare(_v2, _v0);
  3424. if (next <= 1 && d2 < d) {
  3425. t = next;
  3426. d = d2;
  3427. }
  3428. else {
  3429. interval *= 0.5;
  3430. }
  3431. }
  3432. }
  3433. if (out) {
  3434. out[0] = quadraticAt(x0, x1, x2, t);
  3435. out[1] = quadraticAt(y0, y1, y2, t);
  3436. }
  3437. return mathSqrt(d);
  3438. }
  3439. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3440. var px = x0;
  3441. var py = y0;
  3442. var d = 0;
  3443. var step = 1 / iteration;
  3444. for (var i = 1; i <= iteration; i++) {
  3445. var t = i * step;
  3446. var x = quadraticAt(x0, x1, x2, t);
  3447. var y = quadraticAt(y0, y1, y2, t);
  3448. var dx = x - px;
  3449. var dy = y - py;
  3450. d += Math.sqrt(dx * dx + dy * dy);
  3451. px = x;
  3452. py = y;
  3453. }
  3454. return d;
  3455. }
  3456. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3457. function createCubicEasingFunc(cubicEasingStr) {
  3458. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3459. if (cubic) {
  3460. var points = cubic[1].split(',');
  3461. var a_1 = +trim(points[0]);
  3462. var b_1 = +trim(points[1]);
  3463. var c_1 = +trim(points[2]);
  3464. var d_1 = +trim(points[3]);
  3465. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3466. return;
  3467. }
  3468. var roots_1 = [];
  3469. return function (p) {
  3470. return p <= 0
  3471. ? 0 : p >= 1
  3472. ? 1
  3473. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3474. };
  3475. }
  3476. }
  3477. var Clip = (function () {
  3478. function Clip(opts) {
  3479. this._inited = false;
  3480. this._startTime = 0;
  3481. this._pausedTime = 0;
  3482. this._paused = false;
  3483. this._life = opts.life || 1000;
  3484. this._delay = opts.delay || 0;
  3485. this.loop = opts.loop || false;
  3486. this.onframe = opts.onframe || noop;
  3487. this.ondestroy = opts.ondestroy || noop;
  3488. this.onrestart = opts.onrestart || noop;
  3489. opts.easing && this.setEasing(opts.easing);
  3490. }
  3491. Clip.prototype.step = function (globalTime, deltaTime) {
  3492. if (!this._inited) {
  3493. this._startTime = globalTime + this._delay;
  3494. this._inited = true;
  3495. }
  3496. if (this._paused) {
  3497. this._pausedTime += deltaTime;
  3498. return;
  3499. }
  3500. var life = this._life;
  3501. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3502. var percent = elapsedTime / life;
  3503. if (percent < 0) {
  3504. percent = 0;
  3505. }
  3506. percent = Math.min(percent, 1);
  3507. var easingFunc = this.easingFunc;
  3508. var schedule = easingFunc ? easingFunc(percent) : percent;
  3509. this.onframe(schedule);
  3510. if (percent === 1) {
  3511. if (this.loop) {
  3512. var remainder = elapsedTime % life;
  3513. this._startTime = globalTime - remainder;
  3514. this._pausedTime = 0;
  3515. this.onrestart();
  3516. }
  3517. else {
  3518. return true;
  3519. }
  3520. }
  3521. return false;
  3522. };
  3523. Clip.prototype.pause = function () {
  3524. this._paused = true;
  3525. };
  3526. Clip.prototype.resume = function () {
  3527. this._paused = false;
  3528. };
  3529. Clip.prototype.setEasing = function (easing) {
  3530. this.easing = easing;
  3531. this.easingFunc = isFunction(easing)
  3532. ? easing
  3533. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3534. };
  3535. return Clip;
  3536. }());
  3537. var Entry = (function () {
  3538. function Entry(val) {
  3539. this.value = val;
  3540. }
  3541. return Entry;
  3542. }());
  3543. var LinkedList = (function () {
  3544. function LinkedList() {
  3545. this._len = 0;
  3546. }
  3547. LinkedList.prototype.insert = function (val) {
  3548. var entry = new Entry(val);
  3549. this.insertEntry(entry);
  3550. return entry;
  3551. };
  3552. LinkedList.prototype.insertEntry = function (entry) {
  3553. if (!this.head) {
  3554. this.head = this.tail = entry;
  3555. }
  3556. else {
  3557. this.tail.next = entry;
  3558. entry.prev = this.tail;
  3559. entry.next = null;
  3560. this.tail = entry;
  3561. }
  3562. this._len++;
  3563. };
  3564. LinkedList.prototype.remove = function (entry) {
  3565. var prev = entry.prev;
  3566. var next = entry.next;
  3567. if (prev) {
  3568. prev.next = next;
  3569. }
  3570. else {
  3571. this.head = next;
  3572. }
  3573. if (next) {
  3574. next.prev = prev;
  3575. }
  3576. else {
  3577. this.tail = prev;
  3578. }
  3579. entry.next = entry.prev = null;
  3580. this._len--;
  3581. };
  3582. LinkedList.prototype.len = function () {
  3583. return this._len;
  3584. };
  3585. LinkedList.prototype.clear = function () {
  3586. this.head = this.tail = null;
  3587. this._len = 0;
  3588. };
  3589. return LinkedList;
  3590. }());
  3591. var LRU = (function () {
  3592. function LRU(maxSize) {
  3593. this._list = new LinkedList();
  3594. this._maxSize = 10;
  3595. this._map = {};
  3596. this._maxSize = maxSize;
  3597. }
  3598. LRU.prototype.put = function (key, value) {
  3599. var list = this._list;
  3600. var map = this._map;
  3601. var removed = null;
  3602. if (map[key] == null) {
  3603. var len = list.len();
  3604. var entry = this._lastRemovedEntry;
  3605. if (len >= this._maxSize && len > 0) {
  3606. var leastUsedEntry = list.head;
  3607. list.remove(leastUsedEntry);
  3608. delete map[leastUsedEntry.key];
  3609. removed = leastUsedEntry.value;
  3610. this._lastRemovedEntry = leastUsedEntry;
  3611. }
  3612. if (entry) {
  3613. entry.value = value;
  3614. }
  3615. else {
  3616. entry = new Entry(value);
  3617. }
  3618. entry.key = key;
  3619. list.insertEntry(entry);
  3620. map[key] = entry;
  3621. }
  3622. return removed;
  3623. };
  3624. LRU.prototype.get = function (key) {
  3625. var entry = this._map[key];
  3626. var list = this._list;
  3627. if (entry != null) {
  3628. if (entry !== list.tail) {
  3629. list.remove(entry);
  3630. list.insertEntry(entry);
  3631. }
  3632. return entry.value;
  3633. }
  3634. };
  3635. LRU.prototype.clear = function () {
  3636. this._list.clear();
  3637. this._map = {};
  3638. };
  3639. LRU.prototype.len = function () {
  3640. return this._list.len();
  3641. };
  3642. return LRU;
  3643. }());
  3644. var kCSSColorTable = {
  3645. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3646. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3647. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3648. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3649. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3650. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3651. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3652. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3653. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3654. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3655. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3656. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3657. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3658. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3659. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3660. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3661. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3662. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3663. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3664. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3665. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3666. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3667. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3668. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3669. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3670. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3671. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3672. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3673. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3674. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3675. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3676. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3677. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3678. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3679. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3680. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3681. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3682. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3683. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3684. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3685. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3686. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3687. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3688. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3689. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3690. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3691. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3692. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3693. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3694. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3695. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3696. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3697. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3698. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3699. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3700. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3701. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3702. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3703. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3704. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3705. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3706. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3707. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3708. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3709. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3710. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3711. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3712. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3713. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3714. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3715. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3716. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3717. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3718. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3719. };
  3720. function clampCssByte(i) {
  3721. i = Math.round(i);
  3722. return i < 0 ? 0 : i > 255 ? 255 : i;
  3723. }
  3724. function clampCssAngle(i) {
  3725. i = Math.round(i);
  3726. return i < 0 ? 0 : i > 360 ? 360 : i;
  3727. }
  3728. function clampCssFloat(f) {
  3729. return f < 0 ? 0 : f > 1 ? 1 : f;
  3730. }
  3731. function parseCssInt(val) {
  3732. var str = val;
  3733. if (str.length && str.charAt(str.length - 1) === '%') {
  3734. return clampCssByte(parseFloat(str) / 100 * 255);
  3735. }
  3736. return clampCssByte(parseInt(str, 10));
  3737. }
  3738. function parseCssFloat(val) {
  3739. var str = val;
  3740. if (str.length && str.charAt(str.length - 1) === '%') {
  3741. return clampCssFloat(parseFloat(str) / 100);
  3742. }
  3743. return clampCssFloat(parseFloat(str));
  3744. }
  3745. function cssHueToRgb(m1, m2, h) {
  3746. if (h < 0) {
  3747. h += 1;
  3748. }
  3749. else if (h > 1) {
  3750. h -= 1;
  3751. }
  3752. if (h * 6 < 1) {
  3753. return m1 + (m2 - m1) * h * 6;
  3754. }
  3755. if (h * 2 < 1) {
  3756. return m2;
  3757. }
  3758. if (h * 3 < 2) {
  3759. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3760. }
  3761. return m1;
  3762. }
  3763. function lerpNumber(a, b, p) {
  3764. return a + (b - a) * p;
  3765. }
  3766. function setRgba(out, r, g, b, a) {
  3767. out[0] = r;
  3768. out[1] = g;
  3769. out[2] = b;
  3770. out[3] = a;
  3771. return out;
  3772. }
  3773. function copyRgba(out, a) {
  3774. out[0] = a[0];
  3775. out[1] = a[1];
  3776. out[2] = a[2];
  3777. out[3] = a[3];
  3778. return out;
  3779. }
  3780. var colorCache = new LRU(20);
  3781. var lastRemovedArr = null;
  3782. function putToCache(colorStr, rgbaArr) {
  3783. if (lastRemovedArr) {
  3784. copyRgba(lastRemovedArr, rgbaArr);
  3785. }
  3786. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3787. }
  3788. function parse(colorStr, rgbaArr) {
  3789. if (!colorStr) {
  3790. return;
  3791. }
  3792. rgbaArr = rgbaArr || [];
  3793. var cached = colorCache.get(colorStr);
  3794. if (cached) {
  3795. return copyRgba(rgbaArr, cached);
  3796. }
  3797. colorStr = colorStr + '';
  3798. var str = colorStr.replace(/ /g, '').toLowerCase();
  3799. if (str in kCSSColorTable) {
  3800. copyRgba(rgbaArr, kCSSColorTable[str]);
  3801. putToCache(colorStr, rgbaArr);
  3802. return rgbaArr;
  3803. }
  3804. var strLen = str.length;
  3805. if (str.charAt(0) === '#') {
  3806. if (strLen === 4 || strLen === 5) {
  3807. var iv = parseInt(str.slice(1, 4), 16);
  3808. if (!(iv >= 0 && iv <= 0xfff)) {
  3809. setRgba(rgbaArr, 0, 0, 0, 1);
  3810. return;
  3811. }
  3812. 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);
  3813. putToCache(colorStr, rgbaArr);
  3814. return rgbaArr;
  3815. }
  3816. else if (strLen === 7 || strLen === 9) {
  3817. var iv = parseInt(str.slice(1, 7), 16);
  3818. if (!(iv >= 0 && iv <= 0xffffff)) {
  3819. setRgba(rgbaArr, 0, 0, 0, 1);
  3820. return;
  3821. }
  3822. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3823. putToCache(colorStr, rgbaArr);
  3824. return rgbaArr;
  3825. }
  3826. return;
  3827. }
  3828. var op = str.indexOf('(');
  3829. var ep = str.indexOf(')');
  3830. if (op !== -1 && ep + 1 === strLen) {
  3831. var fname = str.substr(0, op);
  3832. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3833. var alpha = 1;
  3834. switch (fname) {
  3835. case 'rgba':
  3836. if (params.length !== 4) {
  3837. return params.length === 3
  3838. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3839. : setRgba(rgbaArr, 0, 0, 0, 1);
  3840. }
  3841. alpha = parseCssFloat(params.pop());
  3842. case 'rgb':
  3843. if (params.length >= 3) {
  3844. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3845. putToCache(colorStr, rgbaArr);
  3846. return rgbaArr;
  3847. }
  3848. else {
  3849. setRgba(rgbaArr, 0, 0, 0, 1);
  3850. return;
  3851. }
  3852. case 'hsla':
  3853. if (params.length !== 4) {
  3854. setRgba(rgbaArr, 0, 0, 0, 1);
  3855. return;
  3856. }
  3857. params[3] = parseCssFloat(params[3]);
  3858. hsla2rgba(params, rgbaArr);
  3859. putToCache(colorStr, rgbaArr);
  3860. return rgbaArr;
  3861. case 'hsl':
  3862. if (params.length !== 3) {
  3863. setRgba(rgbaArr, 0, 0, 0, 1);
  3864. return;
  3865. }
  3866. hsla2rgba(params, rgbaArr);
  3867. putToCache(colorStr, rgbaArr);
  3868. return rgbaArr;
  3869. default:
  3870. return;
  3871. }
  3872. }
  3873. setRgba(rgbaArr, 0, 0, 0, 1);
  3874. return;
  3875. }
  3876. function hsla2rgba(hsla, rgba) {
  3877. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3878. var s = parseCssFloat(hsla[1]);
  3879. var l = parseCssFloat(hsla[2]);
  3880. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3881. var m1 = l * 2 - m2;
  3882. rgba = rgba || [];
  3883. 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);
  3884. if (hsla.length === 4) {
  3885. rgba[3] = hsla[3];
  3886. }
  3887. return rgba;
  3888. }
  3889. function rgba2hsla(rgba) {
  3890. if (!rgba) {
  3891. return;
  3892. }
  3893. var R = rgba[0] / 255;
  3894. var G = rgba[1] / 255;
  3895. var B = rgba[2] / 255;
  3896. var vMin = Math.min(R, G, B);
  3897. var vMax = Math.max(R, G, B);
  3898. var delta = vMax - vMin;
  3899. var L = (vMax + vMin) / 2;
  3900. var H;
  3901. var S;
  3902. if (delta === 0) {
  3903. H = 0;
  3904. S = 0;
  3905. }
  3906. else {
  3907. if (L < 0.5) {
  3908. S = delta / (vMax + vMin);
  3909. }
  3910. else {
  3911. S = delta / (2 - vMax - vMin);
  3912. }
  3913. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3914. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3915. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3916. if (R === vMax) {
  3917. H = deltaB - deltaG;
  3918. }
  3919. else if (G === vMax) {
  3920. H = (1 / 3) + deltaR - deltaB;
  3921. }
  3922. else if (B === vMax) {
  3923. H = (2 / 3) + deltaG - deltaR;
  3924. }
  3925. if (H < 0) {
  3926. H += 1;
  3927. }
  3928. if (H > 1) {
  3929. H -= 1;
  3930. }
  3931. }
  3932. var hsla = [H * 360, S, L];
  3933. if (rgba[3] != null) {
  3934. hsla.push(rgba[3]);
  3935. }
  3936. return hsla;
  3937. }
  3938. function lift(color, level) {
  3939. var colorArr = parse(color);
  3940. if (colorArr) {
  3941. for (var i = 0; i < 3; i++) {
  3942. if (level < 0) {
  3943. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3944. }
  3945. else {
  3946. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3947. }
  3948. if (colorArr[i] > 255) {
  3949. colorArr[i] = 255;
  3950. }
  3951. else if (colorArr[i] < 0) {
  3952. colorArr[i] = 0;
  3953. }
  3954. }
  3955. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3956. }
  3957. }
  3958. function toHex(color) {
  3959. var colorArr = parse(color);
  3960. if (colorArr) {
  3961. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3962. }
  3963. }
  3964. function fastLerp(normalizedValue, colors, out) {
  3965. if (!(colors && colors.length)
  3966. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3967. return;
  3968. }
  3969. out = out || [];
  3970. var value = normalizedValue * (colors.length - 1);
  3971. var leftIndex = Math.floor(value);
  3972. var rightIndex = Math.ceil(value);
  3973. var leftColor = colors[leftIndex];
  3974. var rightColor = colors[rightIndex];
  3975. var dv = value - leftIndex;
  3976. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3977. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3978. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3979. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3980. return out;
  3981. }
  3982. var fastMapToColor = fastLerp;
  3983. function lerp$1(normalizedValue, colors, fullOutput) {
  3984. if (!(colors && colors.length)
  3985. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3986. return;
  3987. }
  3988. var value = normalizedValue * (colors.length - 1);
  3989. var leftIndex = Math.floor(value);
  3990. var rightIndex = Math.ceil(value);
  3991. var leftColor = parse(colors[leftIndex]);
  3992. var rightColor = parse(colors[rightIndex]);
  3993. var dv = value - leftIndex;
  3994. var color = stringify([
  3995. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3996. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3997. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3998. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3999. ], 'rgba');
  4000. return fullOutput
  4001. ? {
  4002. color: color,
  4003. leftIndex: leftIndex,
  4004. rightIndex: rightIndex,
  4005. value: value
  4006. }
  4007. : color;
  4008. }
  4009. var mapToColor = lerp$1;
  4010. function modifyHSL(color, h, s, l) {
  4011. var colorArr = parse(color);
  4012. if (color) {
  4013. colorArr = rgba2hsla(colorArr);
  4014. h != null && (colorArr[0] = clampCssAngle(h));
  4015. s != null && (colorArr[1] = parseCssFloat(s));
  4016. l != null && (colorArr[2] = parseCssFloat(l));
  4017. return stringify(hsla2rgba(colorArr), 'rgba');
  4018. }
  4019. }
  4020. function modifyAlpha(color, alpha) {
  4021. var colorArr = parse(color);
  4022. if (colorArr && alpha != null) {
  4023. colorArr[3] = clampCssFloat(alpha);
  4024. return stringify(colorArr, 'rgba');
  4025. }
  4026. }
  4027. function stringify(arrColor, type) {
  4028. if (!arrColor || !arrColor.length) {
  4029. return;
  4030. }
  4031. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4032. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4033. colorStr += ',' + arrColor[3];
  4034. }
  4035. return type + '(' + colorStr + ')';
  4036. }
  4037. function lum(color, backgroundLum) {
  4038. var arr = parse(color);
  4039. return arr
  4040. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4041. + (1 - arr[3]) * backgroundLum
  4042. : 0;
  4043. }
  4044. function random() {
  4045. return stringify([
  4046. Math.round(Math.random() * 255),
  4047. Math.round(Math.random() * 255),
  4048. Math.round(Math.random() * 255)
  4049. ], 'rgb');
  4050. }
  4051. var color = /*#__PURE__*/Object.freeze({
  4052. __proto__: null,
  4053. parse: parse,
  4054. lift: lift,
  4055. toHex: toHex,
  4056. fastLerp: fastLerp,
  4057. fastMapToColor: fastMapToColor,
  4058. lerp: lerp$1,
  4059. mapToColor: mapToColor,
  4060. modifyHSL: modifyHSL,
  4061. modifyAlpha: modifyAlpha,
  4062. stringify: stringify,
  4063. lum: lum,
  4064. random: random
  4065. });
  4066. var mathRound = Math.round;
  4067. function normalizeColor(color) {
  4068. var opacity;
  4069. if (!color || color === 'transparent') {
  4070. color = 'none';
  4071. }
  4072. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4073. var arr = parse(color);
  4074. if (arr) {
  4075. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4076. opacity = arr[3];
  4077. }
  4078. }
  4079. return {
  4080. color: color,
  4081. opacity: opacity == null ? 1 : opacity
  4082. };
  4083. }
  4084. var EPSILON$1 = 1e-4;
  4085. function isAroundZero$1(transform) {
  4086. return transform < EPSILON$1 && transform > -EPSILON$1;
  4087. }
  4088. function round3(transform) {
  4089. return mathRound(transform * 1e3) / 1e3;
  4090. }
  4091. function round4(transform) {
  4092. return mathRound(transform * 1e4) / 1e4;
  4093. }
  4094. function getMatrixStr(m) {
  4095. return 'matrix('
  4096. + round3(m[0]) + ','
  4097. + round3(m[1]) + ','
  4098. + round3(m[2]) + ','
  4099. + round3(m[3]) + ','
  4100. + round4(m[4]) + ','
  4101. + round4(m[5])
  4102. + ')';
  4103. }
  4104. var TEXT_ALIGN_TO_ANCHOR = {
  4105. left: 'start',
  4106. right: 'end',
  4107. center: 'middle',
  4108. middle: 'middle'
  4109. };
  4110. function adjustTextY(y, lineHeight, textBaseline) {
  4111. if (textBaseline === 'top') {
  4112. y += lineHeight / 2;
  4113. }
  4114. else if (textBaseline === 'bottom') {
  4115. y -= lineHeight / 2;
  4116. }
  4117. return y;
  4118. }
  4119. function hasShadow(style) {
  4120. return style
  4121. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4122. }
  4123. function getShadowKey(displayable) {
  4124. var style = displayable.style;
  4125. var globalScale = displayable.getGlobalScale();
  4126. return [
  4127. style.shadowColor,
  4128. (style.shadowBlur || 0).toFixed(2),
  4129. (style.shadowOffsetX || 0).toFixed(2),
  4130. (style.shadowOffsetY || 0).toFixed(2),
  4131. globalScale[0],
  4132. globalScale[1]
  4133. ].join(',');
  4134. }
  4135. function isImagePattern(val) {
  4136. return val && (!!val.image);
  4137. }
  4138. function isSVGPattern(val) {
  4139. return val && (!!val.svgElement);
  4140. }
  4141. function isPattern(val) {
  4142. return isImagePattern(val) || isSVGPattern(val);
  4143. }
  4144. function isLinearGradient(val) {
  4145. return val.type === 'linear';
  4146. }
  4147. function isRadialGradient(val) {
  4148. return val.type === 'radial';
  4149. }
  4150. function isGradient(val) {
  4151. return val && (val.type === 'linear'
  4152. || val.type === 'radial');
  4153. }
  4154. function getIdURL(id) {
  4155. return "url(#" + id + ")";
  4156. }
  4157. function getPathPrecision(el) {
  4158. var scale = el.getGlobalScale();
  4159. var size = Math.max(scale[0], scale[1]);
  4160. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4161. }
  4162. function getSRTTransformString(transform) {
  4163. var x = transform.x || 0;
  4164. var y = transform.y || 0;
  4165. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4166. var scaleX = retrieve2(transform.scaleX, 1);
  4167. var scaleY = retrieve2(transform.scaleY, 1);
  4168. var skewX = transform.skewX || 0;
  4169. var skewY = transform.skewY || 0;
  4170. var res = [];
  4171. if (x || y) {
  4172. res.push("translate(" + x + "px," + y + "px)");
  4173. }
  4174. if (rotation) {
  4175. res.push("rotate(" + rotation + ")");
  4176. }
  4177. if (scaleX !== 1 || scaleY !== 1) {
  4178. res.push("scale(" + scaleX + "," + scaleY + ")");
  4179. }
  4180. if (skewX || skewY) {
  4181. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4182. }
  4183. return res.join(' ');
  4184. }
  4185. var encodeBase64 = (function () {
  4186. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4187. return function (str) {
  4188. return window.btoa(unescape(encodeURIComponent(str)));
  4189. };
  4190. }
  4191. if (typeof Buffer !== 'undefined') {
  4192. return function (str) {
  4193. return Buffer.from(str).toString('base64');
  4194. };
  4195. }
  4196. return function (str) {
  4197. if ("development" !== 'production') {
  4198. logError('Base64 isn\'t natively supported in the current environment.');
  4199. }
  4200. return null;
  4201. };
  4202. })();
  4203. var arraySlice = Array.prototype.slice;
  4204. function interpolateNumber(p0, p1, percent) {
  4205. return (p1 - p0) * percent + p0;
  4206. }
  4207. function interpolate1DArray(out, p0, p1, percent) {
  4208. var len = p0.length;
  4209. for (var i = 0; i < len; i++) {
  4210. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4211. }
  4212. return out;
  4213. }
  4214. function interpolate2DArray(out, p0, p1, percent) {
  4215. var len = p0.length;
  4216. var len2 = len && p0[0].length;
  4217. for (var i = 0; i < len; i++) {
  4218. if (!out[i]) {
  4219. out[i] = [];
  4220. }
  4221. for (var j = 0; j < len2; j++) {
  4222. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4223. }
  4224. }
  4225. return out;
  4226. }
  4227. function add1DArray(out, p0, p1, sign) {
  4228. var len = p0.length;
  4229. for (var i = 0; i < len; i++) {
  4230. out[i] = p0[i] + p1[i] * sign;
  4231. }
  4232. return out;
  4233. }
  4234. function add2DArray(out, p0, p1, sign) {
  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] = p0[i][j] + p1[i][j] * sign;
  4243. }
  4244. }
  4245. return out;
  4246. }
  4247. function fillColorStops(val0, val1) {
  4248. var len0 = val0.length;
  4249. var len1 = val1.length;
  4250. var shorterArr = len0 > len1 ? val1 : val0;
  4251. var shorterLen = Math.min(len0, len1);
  4252. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4253. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4254. shorterArr.push({
  4255. offset: last.offset,
  4256. color: last.color.slice()
  4257. });
  4258. }
  4259. }
  4260. function fillArray(val0, val1, arrDim) {
  4261. var arr0 = val0;
  4262. var arr1 = val1;
  4263. if (!arr0.push || !arr1.push) {
  4264. return;
  4265. }
  4266. var arr0Len = arr0.length;
  4267. var arr1Len = arr1.length;
  4268. if (arr0Len !== arr1Len) {
  4269. var isPreviousLarger = arr0Len > arr1Len;
  4270. if (isPreviousLarger) {
  4271. arr0.length = arr1Len;
  4272. }
  4273. else {
  4274. for (var i = arr0Len; i < arr1Len; i++) {
  4275. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4276. }
  4277. }
  4278. }
  4279. var len2 = arr0[0] && arr0[0].length;
  4280. for (var i = 0; i < arr0.length; i++) {
  4281. if (arrDim === 1) {
  4282. if (isNaN(arr0[i])) {
  4283. arr0[i] = arr1[i];
  4284. }
  4285. }
  4286. else {
  4287. for (var j = 0; j < len2; j++) {
  4288. if (isNaN(arr0[i][j])) {
  4289. arr0[i][j] = arr1[i][j];
  4290. }
  4291. }
  4292. }
  4293. }
  4294. }
  4295. function cloneValue(value) {
  4296. if (isArrayLike(value)) {
  4297. var len = value.length;
  4298. if (isArrayLike(value[0])) {
  4299. var ret = [];
  4300. for (var i = 0; i < len; i++) {
  4301. ret.push(arraySlice.call(value[i]));
  4302. }
  4303. return ret;
  4304. }
  4305. return arraySlice.call(value);
  4306. }
  4307. return value;
  4308. }
  4309. function rgba2String(rgba) {
  4310. rgba[0] = Math.floor(rgba[0]) || 0;
  4311. rgba[1] = Math.floor(rgba[1]) || 0;
  4312. rgba[2] = Math.floor(rgba[2]) || 0;
  4313. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4314. return 'rgba(' + rgba.join(',') + ')';
  4315. }
  4316. function guessArrayDim(value) {
  4317. return isArrayLike(value && value[0]) ? 2 : 1;
  4318. }
  4319. var VALUE_TYPE_NUMBER = 0;
  4320. var VALUE_TYPE_1D_ARRAY = 1;
  4321. var VALUE_TYPE_2D_ARRAY = 2;
  4322. var VALUE_TYPE_COLOR = 3;
  4323. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4324. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4325. var VALUE_TYPE_UNKOWN = 6;
  4326. function isGradientValueType(valType) {
  4327. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4328. }
  4329. function isArrayValueType(valType) {
  4330. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4331. }
  4332. var tmpRgba = [0, 0, 0, 0];
  4333. var Track = (function () {
  4334. function Track(propName) {
  4335. this.keyframes = [];
  4336. this.discrete = false;
  4337. this._invalid = false;
  4338. this._needsSort = false;
  4339. this._lastFr = 0;
  4340. this._lastFrP = 0;
  4341. this.propName = propName;
  4342. }
  4343. Track.prototype.isFinished = function () {
  4344. return this._finished;
  4345. };
  4346. Track.prototype.setFinished = function () {
  4347. this._finished = true;
  4348. if (this._additiveTrack) {
  4349. this._additiveTrack.setFinished();
  4350. }
  4351. };
  4352. Track.prototype.needsAnimate = function () {
  4353. return this.keyframes.length >= 1;
  4354. };
  4355. Track.prototype.getAdditiveTrack = function () {
  4356. return this._additiveTrack;
  4357. };
  4358. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4359. this._needsSort = true;
  4360. var keyframes = this.keyframes;
  4361. var len = keyframes.length;
  4362. var discrete = false;
  4363. var valType = VALUE_TYPE_UNKOWN;
  4364. var value = rawValue;
  4365. if (isArrayLike(rawValue)) {
  4366. var arrayDim = guessArrayDim(rawValue);
  4367. valType = arrayDim;
  4368. if (arrayDim === 1 && !isNumber(rawValue[0])
  4369. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4370. discrete = true;
  4371. }
  4372. }
  4373. else {
  4374. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4375. valType = VALUE_TYPE_NUMBER;
  4376. }
  4377. else if (isString(rawValue)) {
  4378. if (!isNaN(+rawValue)) {
  4379. valType = VALUE_TYPE_NUMBER;
  4380. }
  4381. else {
  4382. var colorArray = parse(rawValue);
  4383. if (colorArray) {
  4384. value = colorArray;
  4385. valType = VALUE_TYPE_COLOR;
  4386. }
  4387. }
  4388. }
  4389. else if (isGradientObject(rawValue)) {
  4390. var parsedGradient = extend({}, value);
  4391. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4392. offset: colorStop.offset,
  4393. color: parse(colorStop.color)
  4394. }); });
  4395. if (isLinearGradient(rawValue)) {
  4396. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4397. }
  4398. else if (isRadialGradient(rawValue)) {
  4399. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4400. }
  4401. value = parsedGradient;
  4402. }
  4403. }
  4404. if (len === 0) {
  4405. this.valType = valType;
  4406. }
  4407. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4408. discrete = true;
  4409. }
  4410. this.discrete = this.discrete || discrete;
  4411. var kf = {
  4412. time: time,
  4413. value: value,
  4414. rawValue: rawValue,
  4415. percent: 0
  4416. };
  4417. if (easing) {
  4418. kf.easing = easing;
  4419. kf.easingFunc = isFunction(easing)
  4420. ? easing
  4421. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4422. }
  4423. keyframes.push(kf);
  4424. return kf;
  4425. };
  4426. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4427. var kfs = this.keyframes;
  4428. if (this._needsSort) {
  4429. kfs.sort(function (a, b) {
  4430. return a.time - b.time;
  4431. });
  4432. }
  4433. var valType = this.valType;
  4434. var kfsLen = kfs.length;
  4435. var lastKf = kfs[kfsLen - 1];
  4436. var isDiscrete = this.discrete;
  4437. var isArr = isArrayValueType(valType);
  4438. var isGradient = isGradientValueType(valType);
  4439. for (var i = 0; i < kfsLen; i++) {
  4440. var kf = kfs[i];
  4441. var value = kf.value;
  4442. var lastValue = lastKf.value;
  4443. kf.percent = kf.time / maxTime;
  4444. if (!isDiscrete) {
  4445. if (isArr && i !== kfsLen - 1) {
  4446. fillArray(value, lastValue, valType);
  4447. }
  4448. else if (isGradient) {
  4449. fillColorStops(value.colorStops, lastValue.colorStops);
  4450. }
  4451. }
  4452. }
  4453. if (!isDiscrete
  4454. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4455. && additiveTrack
  4456. && this.needsAnimate()
  4457. && additiveTrack.needsAnimate()
  4458. && valType === additiveTrack.valType
  4459. && !additiveTrack._finished) {
  4460. this._additiveTrack = additiveTrack;
  4461. var startValue = kfs[0].value;
  4462. for (var i = 0; i < kfsLen; i++) {
  4463. if (valType === VALUE_TYPE_NUMBER) {
  4464. kfs[i].additiveValue = kfs[i].value - startValue;
  4465. }
  4466. else if (valType === VALUE_TYPE_COLOR) {
  4467. kfs[i].additiveValue =
  4468. add1DArray([], kfs[i].value, startValue, -1);
  4469. }
  4470. else if (isArrayValueType(valType)) {
  4471. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4472. ? add1DArray([], kfs[i].value, startValue, -1)
  4473. : add2DArray([], kfs[i].value, startValue, -1);
  4474. }
  4475. }
  4476. }
  4477. };
  4478. Track.prototype.step = function (target, percent) {
  4479. if (this._finished) {
  4480. return;
  4481. }
  4482. if (this._additiveTrack && this._additiveTrack._finished) {
  4483. this._additiveTrack = null;
  4484. }
  4485. var isAdditive = this._additiveTrack != null;
  4486. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4487. var valType = this.valType;
  4488. var keyframes = this.keyframes;
  4489. var kfsNum = keyframes.length;
  4490. var propName = this.propName;
  4491. var isValueColor = valType === VALUE_TYPE_COLOR;
  4492. var frameIdx;
  4493. var lastFrame = this._lastFr;
  4494. var mathMin = Math.min;
  4495. var frame;
  4496. var nextFrame;
  4497. if (kfsNum === 1) {
  4498. frame = nextFrame = keyframes[0];
  4499. }
  4500. else {
  4501. if (percent < 0) {
  4502. frameIdx = 0;
  4503. }
  4504. else if (percent < this._lastFrP) {
  4505. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4506. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4507. if (keyframes[frameIdx].percent <= percent) {
  4508. break;
  4509. }
  4510. }
  4511. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4512. }
  4513. else {
  4514. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4515. if (keyframes[frameIdx].percent > percent) {
  4516. break;
  4517. }
  4518. }
  4519. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4520. }
  4521. nextFrame = keyframes[frameIdx + 1];
  4522. frame = keyframes[frameIdx];
  4523. }
  4524. if (!(frame && nextFrame)) {
  4525. return;
  4526. }
  4527. this._lastFr = frameIdx;
  4528. this._lastFrP = percent;
  4529. var interval = (nextFrame.percent - frame.percent);
  4530. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4531. if (nextFrame.easingFunc) {
  4532. w = nextFrame.easingFunc(w);
  4533. }
  4534. var targetArr = isAdditive ? this._additiveValue
  4535. : (isValueColor ? tmpRgba : target[propName]);
  4536. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4537. targetArr = this._additiveValue = [];
  4538. }
  4539. if (this.discrete) {
  4540. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4541. }
  4542. else if (isArrayValueType(valType)) {
  4543. valType === VALUE_TYPE_1D_ARRAY
  4544. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4545. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4546. }
  4547. else if (isGradientValueType(valType)) {
  4548. var val = frame[valueKey];
  4549. var nextVal_1 = nextFrame[valueKey];
  4550. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4551. target[propName] = {
  4552. type: isLinearGradient_1 ? 'linear' : 'radial',
  4553. x: interpolateNumber(val.x, nextVal_1.x, w),
  4554. y: interpolateNumber(val.y, nextVal_1.y, w),
  4555. colorStops: map(val.colorStops, function (colorStop, idx) {
  4556. var nextColorStop = nextVal_1.colorStops[idx];
  4557. return {
  4558. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4559. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4560. };
  4561. }),
  4562. global: nextVal_1.global
  4563. };
  4564. if (isLinearGradient_1) {
  4565. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4566. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4567. }
  4568. else {
  4569. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4570. }
  4571. }
  4572. else if (isValueColor) {
  4573. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4574. if (!isAdditive) {
  4575. target[propName] = rgba2String(targetArr);
  4576. }
  4577. }
  4578. else {
  4579. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4580. if (isAdditive) {
  4581. this._additiveValue = value;
  4582. }
  4583. else {
  4584. target[propName] = value;
  4585. }
  4586. }
  4587. if (isAdditive) {
  4588. this._addToTarget(target);
  4589. }
  4590. };
  4591. Track.prototype._addToTarget = function (target) {
  4592. var valType = this.valType;
  4593. var propName = this.propName;
  4594. var additiveValue = this._additiveValue;
  4595. if (valType === VALUE_TYPE_NUMBER) {
  4596. target[propName] = target[propName] + additiveValue;
  4597. }
  4598. else if (valType === VALUE_TYPE_COLOR) {
  4599. parse(target[propName], tmpRgba);
  4600. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4601. target[propName] = rgba2String(tmpRgba);
  4602. }
  4603. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4604. add1DArray(target[propName], target[propName], additiveValue, 1);
  4605. }
  4606. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4607. add2DArray(target[propName], target[propName], additiveValue, 1);
  4608. }
  4609. };
  4610. return Track;
  4611. }());
  4612. var Animator = (function () {
  4613. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4614. this._tracks = {};
  4615. this._trackKeys = [];
  4616. this._maxTime = 0;
  4617. this._started = 0;
  4618. this._clip = null;
  4619. this._target = target;
  4620. this._loop = loop;
  4621. if (loop && additiveTo) {
  4622. logError('Can\' use additive animation on looped animation.');
  4623. return;
  4624. }
  4625. this._additiveAnimators = additiveTo;
  4626. this._allowDiscrete = allowDiscreteAnimation;
  4627. }
  4628. Animator.prototype.getMaxTime = function () {
  4629. return this._maxTime;
  4630. };
  4631. Animator.prototype.getDelay = function () {
  4632. return this._delay;
  4633. };
  4634. Animator.prototype.getLoop = function () {
  4635. return this._loop;
  4636. };
  4637. Animator.prototype.getTarget = function () {
  4638. return this._target;
  4639. };
  4640. Animator.prototype.changeTarget = function (target) {
  4641. this._target = target;
  4642. };
  4643. Animator.prototype.when = function (time, props, easing) {
  4644. return this.whenWithKeys(time, props, keys(props), easing);
  4645. };
  4646. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4647. var tracks = this._tracks;
  4648. for (var i = 0; i < propNames.length; i++) {
  4649. var propName = propNames[i];
  4650. var track = tracks[propName];
  4651. if (!track) {
  4652. track = tracks[propName] = new Track(propName);
  4653. var initialValue = void 0;
  4654. var additiveTrack = this._getAdditiveTrack(propName);
  4655. if (additiveTrack) {
  4656. var addtiveTrackKfs = additiveTrack.keyframes;
  4657. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4658. initialValue = lastFinalKf && lastFinalKf.value;
  4659. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4660. initialValue = rgba2String(initialValue);
  4661. }
  4662. }
  4663. else {
  4664. initialValue = this._target[propName];
  4665. }
  4666. if (initialValue == null) {
  4667. continue;
  4668. }
  4669. if (time > 0) {
  4670. track.addKeyframe(0, cloneValue(initialValue), easing);
  4671. }
  4672. this._trackKeys.push(propName);
  4673. }
  4674. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4675. }
  4676. this._maxTime = Math.max(this._maxTime, time);
  4677. return this;
  4678. };
  4679. Animator.prototype.pause = function () {
  4680. this._clip.pause();
  4681. this._paused = true;
  4682. };
  4683. Animator.prototype.resume = function () {
  4684. this._clip.resume();
  4685. this._paused = false;
  4686. };
  4687. Animator.prototype.isPaused = function () {
  4688. return !!this._paused;
  4689. };
  4690. Animator.prototype.duration = function (duration) {
  4691. this._maxTime = duration;
  4692. this._force = true;
  4693. return this;
  4694. };
  4695. Animator.prototype._doneCallback = function () {
  4696. this._setTracksFinished();
  4697. this._clip = null;
  4698. var doneList = this._doneCbs;
  4699. if (doneList) {
  4700. var len = doneList.length;
  4701. for (var i = 0; i < len; i++) {
  4702. doneList[i].call(this);
  4703. }
  4704. }
  4705. };
  4706. Animator.prototype._abortedCallback = function () {
  4707. this._setTracksFinished();
  4708. var animation = this.animation;
  4709. var abortedList = this._abortedCbs;
  4710. if (animation) {
  4711. animation.removeClip(this._clip);
  4712. }
  4713. this._clip = null;
  4714. if (abortedList) {
  4715. for (var i = 0; i < abortedList.length; i++) {
  4716. abortedList[i].call(this);
  4717. }
  4718. }
  4719. };
  4720. Animator.prototype._setTracksFinished = function () {
  4721. var tracks = this._tracks;
  4722. var tracksKeys = this._trackKeys;
  4723. for (var i = 0; i < tracksKeys.length; i++) {
  4724. tracks[tracksKeys[i]].setFinished();
  4725. }
  4726. };
  4727. Animator.prototype._getAdditiveTrack = function (trackName) {
  4728. var additiveTrack;
  4729. var additiveAnimators = this._additiveAnimators;
  4730. if (additiveAnimators) {
  4731. for (var i = 0; i < additiveAnimators.length; i++) {
  4732. var track = additiveAnimators[i].getTrack(trackName);
  4733. if (track) {
  4734. additiveTrack = track;
  4735. }
  4736. }
  4737. }
  4738. return additiveTrack;
  4739. };
  4740. Animator.prototype.start = function (easing) {
  4741. if (this._started > 0) {
  4742. return;
  4743. }
  4744. this._started = 1;
  4745. var self = this;
  4746. var tracks = [];
  4747. var maxTime = this._maxTime || 0;
  4748. for (var i = 0; i < this._trackKeys.length; i++) {
  4749. var propName = this._trackKeys[i];
  4750. var track = this._tracks[propName];
  4751. var additiveTrack = this._getAdditiveTrack(propName);
  4752. var kfs = track.keyframes;
  4753. var kfsNum = kfs.length;
  4754. track.prepare(maxTime, additiveTrack);
  4755. if (track.needsAnimate()) {
  4756. if (!this._allowDiscrete && track.discrete) {
  4757. var lastKf = kfs[kfsNum - 1];
  4758. if (lastKf) {
  4759. self._target[track.propName] = lastKf.rawValue;
  4760. }
  4761. track.setFinished();
  4762. }
  4763. else {
  4764. tracks.push(track);
  4765. }
  4766. }
  4767. }
  4768. if (tracks.length || this._force) {
  4769. var clip = new Clip({
  4770. life: maxTime,
  4771. loop: this._loop,
  4772. delay: this._delay || 0,
  4773. onframe: function (percent) {
  4774. self._started = 2;
  4775. var additiveAnimators = self._additiveAnimators;
  4776. if (additiveAnimators) {
  4777. var stillHasAdditiveAnimator = false;
  4778. for (var i = 0; i < additiveAnimators.length; i++) {
  4779. if (additiveAnimators[i]._clip) {
  4780. stillHasAdditiveAnimator = true;
  4781. break;
  4782. }
  4783. }
  4784. if (!stillHasAdditiveAnimator) {
  4785. self._additiveAnimators = null;
  4786. }
  4787. }
  4788. for (var i = 0; i < tracks.length; i++) {
  4789. tracks[i].step(self._target, percent);
  4790. }
  4791. var onframeList = self._onframeCbs;
  4792. if (onframeList) {
  4793. for (var i = 0; i < onframeList.length; i++) {
  4794. onframeList[i](self._target, percent);
  4795. }
  4796. }
  4797. },
  4798. ondestroy: function () {
  4799. self._doneCallback();
  4800. }
  4801. });
  4802. this._clip = clip;
  4803. if (this.animation) {
  4804. this.animation.addClip(clip);
  4805. }
  4806. if (easing) {
  4807. clip.setEasing(easing);
  4808. }
  4809. }
  4810. else {
  4811. this._doneCallback();
  4812. }
  4813. return this;
  4814. };
  4815. Animator.prototype.stop = function (forwardToLast) {
  4816. if (!this._clip) {
  4817. return;
  4818. }
  4819. var clip = this._clip;
  4820. if (forwardToLast) {
  4821. clip.onframe(1);
  4822. }
  4823. this._abortedCallback();
  4824. };
  4825. Animator.prototype.delay = function (time) {
  4826. this._delay = time;
  4827. return this;
  4828. };
  4829. Animator.prototype.during = function (cb) {
  4830. if (cb) {
  4831. if (!this._onframeCbs) {
  4832. this._onframeCbs = [];
  4833. }
  4834. this._onframeCbs.push(cb);
  4835. }
  4836. return this;
  4837. };
  4838. Animator.prototype.done = function (cb) {
  4839. if (cb) {
  4840. if (!this._doneCbs) {
  4841. this._doneCbs = [];
  4842. }
  4843. this._doneCbs.push(cb);
  4844. }
  4845. return this;
  4846. };
  4847. Animator.prototype.aborted = function (cb) {
  4848. if (cb) {
  4849. if (!this._abortedCbs) {
  4850. this._abortedCbs = [];
  4851. }
  4852. this._abortedCbs.push(cb);
  4853. }
  4854. return this;
  4855. };
  4856. Animator.prototype.getClip = function () {
  4857. return this._clip;
  4858. };
  4859. Animator.prototype.getTrack = function (propName) {
  4860. return this._tracks[propName];
  4861. };
  4862. Animator.prototype.getTracks = function () {
  4863. var _this = this;
  4864. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4865. };
  4866. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4867. if (!propNames.length || !this._clip) {
  4868. return true;
  4869. }
  4870. var tracks = this._tracks;
  4871. var tracksKeys = this._trackKeys;
  4872. for (var i = 0; i < propNames.length; i++) {
  4873. var track = tracks[propNames[i]];
  4874. if (track && !track.isFinished()) {
  4875. if (forwardToLast) {
  4876. track.step(this._target, 1);
  4877. }
  4878. else if (this._started === 1) {
  4879. track.step(this._target, 0);
  4880. }
  4881. track.setFinished();
  4882. }
  4883. }
  4884. var allAborted = true;
  4885. for (var i = 0; i < tracksKeys.length; i++) {
  4886. if (!tracks[tracksKeys[i]].isFinished()) {
  4887. allAborted = false;
  4888. break;
  4889. }
  4890. }
  4891. if (allAborted) {
  4892. this._abortedCallback();
  4893. }
  4894. return allAborted;
  4895. };
  4896. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4897. if (!target) {
  4898. return;
  4899. }
  4900. trackKeys = trackKeys || this._trackKeys;
  4901. for (var i = 0; i < trackKeys.length; i++) {
  4902. var propName = trackKeys[i];
  4903. var track = this._tracks[propName];
  4904. if (!track || track.isFinished()) {
  4905. continue;
  4906. }
  4907. var kfs = track.keyframes;
  4908. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4909. if (kf) {
  4910. target[propName] = cloneValue(kf.rawValue);
  4911. }
  4912. }
  4913. };
  4914. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4915. trackKeys = trackKeys || keys(finalProps);
  4916. for (var i = 0; i < trackKeys.length; i++) {
  4917. var propName = trackKeys[i];
  4918. var track = this._tracks[propName];
  4919. if (!track) {
  4920. continue;
  4921. }
  4922. var kfs = track.keyframes;
  4923. if (kfs.length > 1) {
  4924. var lastKf = kfs.pop();
  4925. track.addKeyframe(lastKf.time, finalProps[propName]);
  4926. track.prepare(this._maxTime, track.getAdditiveTrack());
  4927. }
  4928. }
  4929. };
  4930. return Animator;
  4931. }());
  4932. function getTime() {
  4933. return new Date().getTime();
  4934. }
  4935. var Animation = (function (_super) {
  4936. __extends(Animation, _super);
  4937. function Animation(opts) {
  4938. var _this = _super.call(this) || this;
  4939. _this._running = false;
  4940. _this._time = 0;
  4941. _this._pausedTime = 0;
  4942. _this._pauseStart = 0;
  4943. _this._paused = false;
  4944. opts = opts || {};
  4945. _this.stage = opts.stage || {};
  4946. return _this;
  4947. }
  4948. Animation.prototype.addClip = function (clip) {
  4949. if (clip.animation) {
  4950. this.removeClip(clip);
  4951. }
  4952. if (!this._head) {
  4953. this._head = this._tail = clip;
  4954. }
  4955. else {
  4956. this._tail.next = clip;
  4957. clip.prev = this._tail;
  4958. clip.next = null;
  4959. this._tail = clip;
  4960. }
  4961. clip.animation = this;
  4962. };
  4963. Animation.prototype.addAnimator = function (animator) {
  4964. animator.animation = this;
  4965. var clip = animator.getClip();
  4966. if (clip) {
  4967. this.addClip(clip);
  4968. }
  4969. };
  4970. Animation.prototype.removeClip = function (clip) {
  4971. if (!clip.animation) {
  4972. return;
  4973. }
  4974. var prev = clip.prev;
  4975. var next = clip.next;
  4976. if (prev) {
  4977. prev.next = next;
  4978. }
  4979. else {
  4980. this._head = next;
  4981. }
  4982. if (next) {
  4983. next.prev = prev;
  4984. }
  4985. else {
  4986. this._tail = prev;
  4987. }
  4988. clip.next = clip.prev = clip.animation = null;
  4989. };
  4990. Animation.prototype.removeAnimator = function (animator) {
  4991. var clip = animator.getClip();
  4992. if (clip) {
  4993. this.removeClip(clip);
  4994. }
  4995. animator.animation = null;
  4996. };
  4997. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4998. var time = getTime() - this._pausedTime;
  4999. var delta = time - this._time;
  5000. var clip = this._head;
  5001. while (clip) {
  5002. var nextClip = clip.next;
  5003. var finished = clip.step(time, delta);
  5004. if (finished) {
  5005. clip.ondestroy();
  5006. this.removeClip(clip);
  5007. clip = nextClip;
  5008. }
  5009. else {
  5010. clip = nextClip;
  5011. }
  5012. }
  5013. this._time = time;
  5014. if (!notTriggerFrameAndStageUpdate) {
  5015. this.trigger('frame', delta);
  5016. this.stage.update && this.stage.update();
  5017. }
  5018. };
  5019. Animation.prototype._startLoop = function () {
  5020. var self = this;
  5021. this._running = true;
  5022. function step() {
  5023. if (self._running) {
  5024. requestAnimationFrame$1(step);
  5025. !self._paused && self.update();
  5026. }
  5027. }
  5028. requestAnimationFrame$1(step);
  5029. };
  5030. Animation.prototype.start = function () {
  5031. if (this._running) {
  5032. return;
  5033. }
  5034. this._time = getTime();
  5035. this._pausedTime = 0;
  5036. this._startLoop();
  5037. };
  5038. Animation.prototype.stop = function () {
  5039. this._running = false;
  5040. };
  5041. Animation.prototype.pause = function () {
  5042. if (!this._paused) {
  5043. this._pauseStart = getTime();
  5044. this._paused = true;
  5045. }
  5046. };
  5047. Animation.prototype.resume = function () {
  5048. if (this._paused) {
  5049. this._pausedTime += getTime() - this._pauseStart;
  5050. this._paused = false;
  5051. }
  5052. };
  5053. Animation.prototype.clear = function () {
  5054. var clip = this._head;
  5055. while (clip) {
  5056. var nextClip = clip.next;
  5057. clip.prev = clip.next = clip.animation = null;
  5058. clip = nextClip;
  5059. }
  5060. this._head = this._tail = null;
  5061. };
  5062. Animation.prototype.isFinished = function () {
  5063. return this._head == null;
  5064. };
  5065. Animation.prototype.animate = function (target, options) {
  5066. options = options || {};
  5067. this.start();
  5068. var animator = new Animator(target, options.loop);
  5069. this.addAnimator(animator);
  5070. return animator;
  5071. };
  5072. return Animation;
  5073. }(Eventful));
  5074. var TOUCH_CLICK_DELAY = 300;
  5075. var globalEventSupported = env.domSupported;
  5076. var localNativeListenerNames = (function () {
  5077. var mouseHandlerNames = [
  5078. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5079. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5080. ];
  5081. var touchHandlerNames = [
  5082. 'touchstart', 'touchend', 'touchmove'
  5083. ];
  5084. var pointerEventNameMap = {
  5085. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5086. };
  5087. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5088. var nm = name.replace('mouse', 'pointer');
  5089. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5090. });
  5091. return {
  5092. mouse: mouseHandlerNames,
  5093. touch: touchHandlerNames,
  5094. pointer: pointerHandlerNames
  5095. };
  5096. })();
  5097. var globalNativeListenerNames = {
  5098. mouse: ['mousemove', 'mouseup'],
  5099. pointer: ['pointermove', 'pointerup']
  5100. };
  5101. var wheelEventSupported = false;
  5102. function isPointerFromTouch(event) {
  5103. var pointerType = event.pointerType;
  5104. return pointerType === 'pen' || pointerType === 'touch';
  5105. }
  5106. function setTouchTimer(scope) {
  5107. scope.touching = true;
  5108. if (scope.touchTimer != null) {
  5109. clearTimeout(scope.touchTimer);
  5110. scope.touchTimer = null;
  5111. }
  5112. scope.touchTimer = setTimeout(function () {
  5113. scope.touching = false;
  5114. scope.touchTimer = null;
  5115. }, 700);
  5116. }
  5117. function markTouch(event) {
  5118. event && (event.zrByTouch = true);
  5119. }
  5120. function normalizeGlobalEvent(instance, event) {
  5121. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5122. }
  5123. function isLocalEl(instance, el) {
  5124. var elTmp = el;
  5125. var isLocal = false;
  5126. while (elTmp && elTmp.nodeType !== 9
  5127. && !(isLocal = elTmp.domBelongToZr
  5128. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5129. elTmp = elTmp.parentNode;
  5130. }
  5131. return isLocal;
  5132. }
  5133. var FakeGlobalEvent = (function () {
  5134. function FakeGlobalEvent(instance, event) {
  5135. this.stopPropagation = noop;
  5136. this.stopImmediatePropagation = noop;
  5137. this.preventDefault = noop;
  5138. this.type = event.type;
  5139. this.target = this.currentTarget = instance.dom;
  5140. this.pointerType = event.pointerType;
  5141. this.clientX = event.clientX;
  5142. this.clientY = event.clientY;
  5143. }
  5144. return FakeGlobalEvent;
  5145. }());
  5146. var localDOMHandlers = {
  5147. mousedown: function (event) {
  5148. event = normalizeEvent(this.dom, event);
  5149. this.__mayPointerCapture = [event.zrX, event.zrY];
  5150. this.trigger('mousedown', event);
  5151. },
  5152. mousemove: function (event) {
  5153. event = normalizeEvent(this.dom, event);
  5154. var downPoint = this.__mayPointerCapture;
  5155. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5156. this.__togglePointerCapture(true);
  5157. }
  5158. this.trigger('mousemove', event);
  5159. },
  5160. mouseup: function (event) {
  5161. event = normalizeEvent(this.dom, event);
  5162. this.__togglePointerCapture(false);
  5163. this.trigger('mouseup', event);
  5164. },
  5165. mouseout: function (event) {
  5166. event = normalizeEvent(this.dom, event);
  5167. var element = event.toElement || event.relatedTarget;
  5168. if (!isLocalEl(this, element)) {
  5169. if (this.__pointerCapturing) {
  5170. event.zrEventControl = 'no_globalout';
  5171. }
  5172. this.trigger('mouseout', event);
  5173. }
  5174. },
  5175. wheel: function (event) {
  5176. wheelEventSupported = true;
  5177. event = normalizeEvent(this.dom, event);
  5178. this.trigger('mousewheel', event);
  5179. },
  5180. mousewheel: function (event) {
  5181. if (wheelEventSupported) {
  5182. return;
  5183. }
  5184. event = normalizeEvent(this.dom, event);
  5185. this.trigger('mousewheel', event);
  5186. },
  5187. touchstart: function (event) {
  5188. event = normalizeEvent(this.dom, event);
  5189. markTouch(event);
  5190. this.__lastTouchMoment = new Date();
  5191. this.handler.processGesture(event, 'start');
  5192. localDOMHandlers.mousemove.call(this, event);
  5193. localDOMHandlers.mousedown.call(this, event);
  5194. },
  5195. touchmove: function (event) {
  5196. event = normalizeEvent(this.dom, event);
  5197. markTouch(event);
  5198. this.handler.processGesture(event, 'change');
  5199. localDOMHandlers.mousemove.call(this, event);
  5200. },
  5201. touchend: function (event) {
  5202. event = normalizeEvent(this.dom, event);
  5203. markTouch(event);
  5204. this.handler.processGesture(event, 'end');
  5205. localDOMHandlers.mouseup.call(this, event);
  5206. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5207. localDOMHandlers.click.call(this, event);
  5208. }
  5209. },
  5210. pointerdown: function (event) {
  5211. localDOMHandlers.mousedown.call(this, event);
  5212. },
  5213. pointermove: function (event) {
  5214. if (!isPointerFromTouch(event)) {
  5215. localDOMHandlers.mousemove.call(this, event);
  5216. }
  5217. },
  5218. pointerup: function (event) {
  5219. localDOMHandlers.mouseup.call(this, event);
  5220. },
  5221. pointerout: function (event) {
  5222. if (!isPointerFromTouch(event)) {
  5223. localDOMHandlers.mouseout.call(this, event);
  5224. }
  5225. }
  5226. };
  5227. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5228. localDOMHandlers[name] = function (event) {
  5229. event = normalizeEvent(this.dom, event);
  5230. this.trigger(name, event);
  5231. };
  5232. });
  5233. var globalDOMHandlers = {
  5234. pointermove: function (event) {
  5235. if (!isPointerFromTouch(event)) {
  5236. globalDOMHandlers.mousemove.call(this, event);
  5237. }
  5238. },
  5239. pointerup: function (event) {
  5240. globalDOMHandlers.mouseup.call(this, event);
  5241. },
  5242. mousemove: function (event) {
  5243. this.trigger('mousemove', event);
  5244. },
  5245. mouseup: function (event) {
  5246. var pointerCaptureReleasing = this.__pointerCapturing;
  5247. this.__togglePointerCapture(false);
  5248. this.trigger('mouseup', event);
  5249. if (pointerCaptureReleasing) {
  5250. event.zrEventControl = 'only_globalout';
  5251. this.trigger('mouseout', event);
  5252. }
  5253. }
  5254. };
  5255. function mountLocalDOMEventListeners(instance, scope) {
  5256. var domHandlers = scope.domHandlers;
  5257. if (env.pointerEventsSupported) {
  5258. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5259. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5260. domHandlers[nativeEventName].call(instance, event);
  5261. });
  5262. });
  5263. }
  5264. else {
  5265. if (env.touchEventsSupported) {
  5266. each(localNativeListenerNames.touch, function (nativeEventName) {
  5267. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5268. domHandlers[nativeEventName].call(instance, event);
  5269. setTouchTimer(scope);
  5270. });
  5271. });
  5272. }
  5273. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5274. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5275. event = getNativeEvent(event);
  5276. if (!scope.touching) {
  5277. domHandlers[nativeEventName].call(instance, event);
  5278. }
  5279. });
  5280. });
  5281. }
  5282. }
  5283. function mountGlobalDOMEventListeners(instance, scope) {
  5284. if (env.pointerEventsSupported) {
  5285. each(globalNativeListenerNames.pointer, mount);
  5286. }
  5287. else if (!env.touchEventsSupported) {
  5288. each(globalNativeListenerNames.mouse, mount);
  5289. }
  5290. function mount(nativeEventName) {
  5291. function nativeEventListener(event) {
  5292. event = getNativeEvent(event);
  5293. if (!isLocalEl(instance, event.target)) {
  5294. event = normalizeGlobalEvent(instance, event);
  5295. scope.domHandlers[nativeEventName].call(instance, event);
  5296. }
  5297. }
  5298. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5299. }
  5300. }
  5301. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5302. scope.mounted[nativeEventName] = listener;
  5303. scope.listenerOpts[nativeEventName] = opt;
  5304. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5305. }
  5306. function unmountDOMEventListeners(scope) {
  5307. var mounted = scope.mounted;
  5308. for (var nativeEventName in mounted) {
  5309. if (mounted.hasOwnProperty(nativeEventName)) {
  5310. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5311. }
  5312. }
  5313. scope.mounted = {};
  5314. }
  5315. var DOMHandlerScope = (function () {
  5316. function DOMHandlerScope(domTarget, domHandlers) {
  5317. this.mounted = {};
  5318. this.listenerOpts = {};
  5319. this.touching = false;
  5320. this.domTarget = domTarget;
  5321. this.domHandlers = domHandlers;
  5322. }
  5323. return DOMHandlerScope;
  5324. }());
  5325. var HandlerDomProxy = (function (_super) {
  5326. __extends(HandlerDomProxy, _super);
  5327. function HandlerDomProxy(dom, painterRoot) {
  5328. var _this = _super.call(this) || this;
  5329. _this.__pointerCapturing = false;
  5330. _this.dom = dom;
  5331. _this.painterRoot = painterRoot;
  5332. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5333. if (globalEventSupported) {
  5334. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5335. }
  5336. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5337. return _this;
  5338. }
  5339. HandlerDomProxy.prototype.dispose = function () {
  5340. unmountDOMEventListeners(this._localHandlerScope);
  5341. if (globalEventSupported) {
  5342. unmountDOMEventListeners(this._globalHandlerScope);
  5343. }
  5344. };
  5345. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5346. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5347. };
  5348. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5349. this.__mayPointerCapture = null;
  5350. if (globalEventSupported
  5351. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5352. this.__pointerCapturing = isPointerCapturing;
  5353. var globalHandlerScope = this._globalHandlerScope;
  5354. isPointerCapturing
  5355. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5356. : unmountDOMEventListeners(globalHandlerScope);
  5357. }
  5358. };
  5359. return HandlerDomProxy;
  5360. }(Eventful));
  5361. var dpr = 1;
  5362. if (env.hasGlobalWindow) {
  5363. dpr = Math.max(window.devicePixelRatio
  5364. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5365. || 1, 1);
  5366. }
  5367. var devicePixelRatio = dpr;
  5368. var DARK_MODE_THRESHOLD = 0.4;
  5369. var DARK_LABEL_COLOR = '#333';
  5370. var LIGHT_LABEL_COLOR = '#ccc';
  5371. var LIGHTER_LABEL_COLOR = '#eee';
  5372. var mIdentity = identity;
  5373. var EPSILON$2 = 5e-5;
  5374. function isNotAroundZero$1(val) {
  5375. return val > EPSILON$2 || val < -EPSILON$2;
  5376. }
  5377. var scaleTmp = [];
  5378. var tmpTransform = [];
  5379. var originTransform = create$1();
  5380. var abs = Math.abs;
  5381. var Transformable = (function () {
  5382. function Transformable() {
  5383. }
  5384. Transformable.prototype.getLocalTransform = function (m) {
  5385. return Transformable.getLocalTransform(this, m);
  5386. };
  5387. Transformable.prototype.setPosition = function (arr) {
  5388. this.x = arr[0];
  5389. this.y = arr[1];
  5390. };
  5391. Transformable.prototype.setScale = function (arr) {
  5392. this.scaleX = arr[0];
  5393. this.scaleY = arr[1];
  5394. };
  5395. Transformable.prototype.setSkew = function (arr) {
  5396. this.skewX = arr[0];
  5397. this.skewY = arr[1];
  5398. };
  5399. Transformable.prototype.setOrigin = function (arr) {
  5400. this.originX = arr[0];
  5401. this.originY = arr[1];
  5402. };
  5403. Transformable.prototype.needLocalTransform = function () {
  5404. return isNotAroundZero$1(this.rotation)
  5405. || isNotAroundZero$1(this.x)
  5406. || isNotAroundZero$1(this.y)
  5407. || isNotAroundZero$1(this.scaleX - 1)
  5408. || isNotAroundZero$1(this.scaleY - 1)
  5409. || isNotAroundZero$1(this.skewX)
  5410. || isNotAroundZero$1(this.skewY);
  5411. };
  5412. Transformable.prototype.updateTransform = function () {
  5413. var parentTransform = this.parent && this.parent.transform;
  5414. var needLocalTransform = this.needLocalTransform();
  5415. var m = this.transform;
  5416. if (!(needLocalTransform || parentTransform)) {
  5417. m && mIdentity(m);
  5418. return;
  5419. }
  5420. m = m || create$1();
  5421. if (needLocalTransform) {
  5422. this.getLocalTransform(m);
  5423. }
  5424. else {
  5425. mIdentity(m);
  5426. }
  5427. if (parentTransform) {
  5428. if (needLocalTransform) {
  5429. mul$1(m, parentTransform, m);
  5430. }
  5431. else {
  5432. copy$1(m, parentTransform);
  5433. }
  5434. }
  5435. this.transform = m;
  5436. this._resolveGlobalScaleRatio(m);
  5437. };
  5438. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5439. var globalScaleRatio = this.globalScaleRatio;
  5440. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5441. this.getGlobalScale(scaleTmp);
  5442. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5443. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5444. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5445. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5446. m[0] *= sx;
  5447. m[1] *= sx;
  5448. m[2] *= sy;
  5449. m[3] *= sy;
  5450. }
  5451. this.invTransform = this.invTransform || create$1();
  5452. invert(this.invTransform, m);
  5453. };
  5454. Transformable.prototype.getComputedTransform = function () {
  5455. var transformNode = this;
  5456. var ancestors = [];
  5457. while (transformNode) {
  5458. ancestors.push(transformNode);
  5459. transformNode = transformNode.parent;
  5460. }
  5461. while (transformNode = ancestors.pop()) {
  5462. transformNode.updateTransform();
  5463. }
  5464. return this.transform;
  5465. };
  5466. Transformable.prototype.setLocalTransform = function (m) {
  5467. if (!m) {
  5468. return;
  5469. }
  5470. var sx = m[0] * m[0] + m[1] * m[1];
  5471. var sy = m[2] * m[2] + m[3] * m[3];
  5472. var rotation = Math.atan2(m[1], m[0]);
  5473. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5474. sy = Math.sqrt(sy) * Math.cos(shearX);
  5475. sx = Math.sqrt(sx);
  5476. this.skewX = shearX;
  5477. this.skewY = 0;
  5478. this.rotation = -rotation;
  5479. this.x = +m[4];
  5480. this.y = +m[5];
  5481. this.scaleX = sx;
  5482. this.scaleY = sy;
  5483. this.originX = 0;
  5484. this.originY = 0;
  5485. };
  5486. Transformable.prototype.decomposeTransform = function () {
  5487. if (!this.transform) {
  5488. return;
  5489. }
  5490. var parent = this.parent;
  5491. var m = this.transform;
  5492. if (parent && parent.transform) {
  5493. mul$1(tmpTransform, parent.invTransform, m);
  5494. m = tmpTransform;
  5495. }
  5496. var ox = this.originX;
  5497. var oy = this.originY;
  5498. if (ox || oy) {
  5499. originTransform[4] = ox;
  5500. originTransform[5] = oy;
  5501. mul$1(tmpTransform, m, originTransform);
  5502. tmpTransform[4] -= ox;
  5503. tmpTransform[5] -= oy;
  5504. m = tmpTransform;
  5505. }
  5506. this.setLocalTransform(m);
  5507. };
  5508. Transformable.prototype.getGlobalScale = function (out) {
  5509. var m = this.transform;
  5510. out = out || [];
  5511. if (!m) {
  5512. out[0] = 1;
  5513. out[1] = 1;
  5514. return out;
  5515. }
  5516. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5517. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5518. if (m[0] < 0) {
  5519. out[0] = -out[0];
  5520. }
  5521. if (m[3] < 0) {
  5522. out[1] = -out[1];
  5523. }
  5524. return out;
  5525. };
  5526. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5527. var v2 = [x, y];
  5528. var invTransform = this.invTransform;
  5529. if (invTransform) {
  5530. applyTransform(v2, v2, invTransform);
  5531. }
  5532. return v2;
  5533. };
  5534. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5535. var v2 = [x, y];
  5536. var transform = this.transform;
  5537. if (transform) {
  5538. applyTransform(v2, v2, transform);
  5539. }
  5540. return v2;
  5541. };
  5542. Transformable.prototype.getLineScale = function () {
  5543. var m = this.transform;
  5544. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5545. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5546. : 1;
  5547. };
  5548. Transformable.prototype.copyTransform = function (source) {
  5549. copyTransform(this, source);
  5550. };
  5551. Transformable.getLocalTransform = function (target, m) {
  5552. m = m || [];
  5553. var ox = target.originX || 0;
  5554. var oy = target.originY || 0;
  5555. var sx = target.scaleX;
  5556. var sy = target.scaleY;
  5557. var ax = target.anchorX;
  5558. var ay = target.anchorY;
  5559. var rotation = target.rotation || 0;
  5560. var x = target.x;
  5561. var y = target.y;
  5562. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5563. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5564. if (ox || oy || ax || ay) {
  5565. var dx = ox + ax;
  5566. var dy = oy + ay;
  5567. m[4] = -dx * sx - skewX * dy * sy;
  5568. m[5] = -dy * sy - skewY * dx * sx;
  5569. }
  5570. else {
  5571. m[4] = m[5] = 0;
  5572. }
  5573. m[0] = sx;
  5574. m[3] = sy;
  5575. m[1] = skewY * sx;
  5576. m[2] = skewX * sy;
  5577. rotation && rotate(m, m, rotation);
  5578. m[4] += ox + x;
  5579. m[5] += oy + y;
  5580. return m;
  5581. };
  5582. Transformable.initDefaultProps = (function () {
  5583. var proto = Transformable.prototype;
  5584. proto.scaleX =
  5585. proto.scaleY =
  5586. proto.globalScaleRatio = 1;
  5587. proto.x =
  5588. proto.y =
  5589. proto.originX =
  5590. proto.originY =
  5591. proto.skewX =
  5592. proto.skewY =
  5593. proto.rotation =
  5594. proto.anchorX =
  5595. proto.anchorY = 0;
  5596. })();
  5597. return Transformable;
  5598. }());
  5599. var TRANSFORMABLE_PROPS = [
  5600. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5601. ];
  5602. function copyTransform(target, source) {
  5603. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5604. var propName = TRANSFORMABLE_PROPS[i];
  5605. target[propName] = source[propName];
  5606. }
  5607. }
  5608. var textWidthCache = {};
  5609. function getWidth(text, font) {
  5610. font = font || DEFAULT_FONT;
  5611. var cacheOfFont = textWidthCache[font];
  5612. if (!cacheOfFont) {
  5613. cacheOfFont = textWidthCache[font] = new LRU(500);
  5614. }
  5615. var width = cacheOfFont.get(text);
  5616. if (width == null) {
  5617. width = platformApi.measureText(text, font).width;
  5618. cacheOfFont.put(text, width);
  5619. }
  5620. return width;
  5621. }
  5622. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5623. var width = getWidth(text, font);
  5624. var height = getLineHeight(font);
  5625. var x = adjustTextX(0, width, textAlign);
  5626. var y = adjustTextY$1(0, height, textBaseline);
  5627. var rect = new BoundingRect(x, y, width, height);
  5628. return rect;
  5629. }
  5630. function getBoundingRect(text, font, textAlign, textBaseline) {
  5631. var textLines = ((text || '') + '').split('\n');
  5632. var len = textLines.length;
  5633. if (len === 1) {
  5634. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5635. }
  5636. else {
  5637. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5638. for (var i = 0; i < textLines.length; i++) {
  5639. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5640. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5641. }
  5642. return uniondRect;
  5643. }
  5644. }
  5645. function adjustTextX(x, width, textAlign) {
  5646. if (textAlign === 'right') {
  5647. x -= width;
  5648. }
  5649. else if (textAlign === 'center') {
  5650. x -= width / 2;
  5651. }
  5652. return x;
  5653. }
  5654. function adjustTextY$1(y, height, verticalAlign) {
  5655. if (verticalAlign === 'middle') {
  5656. y -= height / 2;
  5657. }
  5658. else if (verticalAlign === 'bottom') {
  5659. y -= height;
  5660. }
  5661. return y;
  5662. }
  5663. function getLineHeight(font) {
  5664. return getWidth('国', font);
  5665. }
  5666. function parsePercent(value, maxValue) {
  5667. if (typeof value === 'string') {
  5668. if (value.lastIndexOf('%') >= 0) {
  5669. return parseFloat(value) / 100 * maxValue;
  5670. }
  5671. return parseFloat(value);
  5672. }
  5673. return value;
  5674. }
  5675. function calculateTextPosition(out, opts, rect) {
  5676. var textPosition = opts.position || 'inside';
  5677. var distance = opts.distance != null ? opts.distance : 5;
  5678. var height = rect.height;
  5679. var width = rect.width;
  5680. var halfHeight = height / 2;
  5681. var x = rect.x;
  5682. var y = rect.y;
  5683. var textAlign = 'left';
  5684. var textVerticalAlign = 'top';
  5685. if (textPosition instanceof Array) {
  5686. x += parsePercent(textPosition[0], rect.width);
  5687. y += parsePercent(textPosition[1], rect.height);
  5688. textAlign = null;
  5689. textVerticalAlign = null;
  5690. }
  5691. else {
  5692. switch (textPosition) {
  5693. case 'left':
  5694. x -= distance;
  5695. y += halfHeight;
  5696. textAlign = 'right';
  5697. textVerticalAlign = 'middle';
  5698. break;
  5699. case 'right':
  5700. x += distance + width;
  5701. y += halfHeight;
  5702. textVerticalAlign = 'middle';
  5703. break;
  5704. case 'top':
  5705. x += width / 2;
  5706. y -= distance;
  5707. textAlign = 'center';
  5708. textVerticalAlign = 'bottom';
  5709. break;
  5710. case 'bottom':
  5711. x += width / 2;
  5712. y += height + distance;
  5713. textAlign = 'center';
  5714. break;
  5715. case 'inside':
  5716. x += width / 2;
  5717. y += halfHeight;
  5718. textAlign = 'center';
  5719. textVerticalAlign = 'middle';
  5720. break;
  5721. case 'insideLeft':
  5722. x += distance;
  5723. y += halfHeight;
  5724. textVerticalAlign = 'middle';
  5725. break;
  5726. case 'insideRight':
  5727. x += width - distance;
  5728. y += halfHeight;
  5729. textAlign = 'right';
  5730. textVerticalAlign = 'middle';
  5731. break;
  5732. case 'insideTop':
  5733. x += width / 2;
  5734. y += distance;
  5735. textAlign = 'center';
  5736. break;
  5737. case 'insideBottom':
  5738. x += width / 2;
  5739. y += height - distance;
  5740. textAlign = 'center';
  5741. textVerticalAlign = 'bottom';
  5742. break;
  5743. case 'insideTopLeft':
  5744. x += distance;
  5745. y += distance;
  5746. break;
  5747. case 'insideTopRight':
  5748. x += width - distance;
  5749. y += distance;
  5750. textAlign = 'right';
  5751. break;
  5752. case 'insideBottomLeft':
  5753. x += distance;
  5754. y += height - distance;
  5755. textVerticalAlign = 'bottom';
  5756. break;
  5757. case 'insideBottomRight':
  5758. x += width - distance;
  5759. y += height - distance;
  5760. textAlign = 'right';
  5761. textVerticalAlign = 'bottom';
  5762. break;
  5763. }
  5764. }
  5765. out = out || {};
  5766. out.x = x;
  5767. out.y = y;
  5768. out.align = textAlign;
  5769. out.verticalAlign = textVerticalAlign;
  5770. return out;
  5771. }
  5772. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5773. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5774. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5775. obj[key] = true;
  5776. return obj;
  5777. }, { ignore: false });
  5778. var tmpTextPosCalcRes = {};
  5779. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5780. var Element = (function () {
  5781. function Element(props) {
  5782. this.id = guid();
  5783. this.animators = [];
  5784. this.currentStates = [];
  5785. this.states = {};
  5786. this._init(props);
  5787. }
  5788. Element.prototype._init = function (props) {
  5789. this.attr(props);
  5790. };
  5791. Element.prototype.drift = function (dx, dy, e) {
  5792. switch (this.draggable) {
  5793. case 'horizontal':
  5794. dy = 0;
  5795. break;
  5796. case 'vertical':
  5797. dx = 0;
  5798. break;
  5799. }
  5800. var m = this.transform;
  5801. if (!m) {
  5802. m = this.transform = [1, 0, 0, 1, 0, 0];
  5803. }
  5804. m[4] += dx;
  5805. m[5] += dy;
  5806. this.decomposeTransform();
  5807. this.markRedraw();
  5808. };
  5809. Element.prototype.beforeUpdate = function () { };
  5810. Element.prototype.afterUpdate = function () { };
  5811. Element.prototype.update = function () {
  5812. this.updateTransform();
  5813. if (this.__dirty) {
  5814. this.updateInnerText();
  5815. }
  5816. };
  5817. Element.prototype.updateInnerText = function (forceUpdate) {
  5818. var textEl = this._textContent;
  5819. if (textEl && (!textEl.ignore || forceUpdate)) {
  5820. if (!this.textConfig) {
  5821. this.textConfig = {};
  5822. }
  5823. var textConfig = this.textConfig;
  5824. var isLocal = textConfig.local;
  5825. var innerTransformable = textEl.innerTransformable;
  5826. var textAlign = void 0;
  5827. var textVerticalAlign = void 0;
  5828. var textStyleChanged = false;
  5829. innerTransformable.parent = isLocal ? this : null;
  5830. var innerOrigin = false;
  5831. innerTransformable.copyTransform(textEl);
  5832. if (textConfig.position != null) {
  5833. var layoutRect = tmpBoundingRect;
  5834. if (textConfig.layoutRect) {
  5835. layoutRect.copy(textConfig.layoutRect);
  5836. }
  5837. else {
  5838. layoutRect.copy(this.getBoundingRect());
  5839. }
  5840. if (!isLocal) {
  5841. layoutRect.applyTransform(this.transform);
  5842. }
  5843. if (this.calculateTextPosition) {
  5844. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5845. }
  5846. else {
  5847. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5848. }
  5849. innerTransformable.x = tmpTextPosCalcRes.x;
  5850. innerTransformable.y = tmpTextPosCalcRes.y;
  5851. textAlign = tmpTextPosCalcRes.align;
  5852. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5853. var textOrigin = textConfig.origin;
  5854. if (textOrigin && textConfig.rotation != null) {
  5855. var relOriginX = void 0;
  5856. var relOriginY = void 0;
  5857. if (textOrigin === 'center') {
  5858. relOriginX = layoutRect.width * 0.5;
  5859. relOriginY = layoutRect.height * 0.5;
  5860. }
  5861. else {
  5862. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5863. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5864. }
  5865. innerOrigin = true;
  5866. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5867. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5868. }
  5869. }
  5870. if (textConfig.rotation != null) {
  5871. innerTransformable.rotation = textConfig.rotation;
  5872. }
  5873. var textOffset = textConfig.offset;
  5874. if (textOffset) {
  5875. innerTransformable.x += textOffset[0];
  5876. innerTransformable.y += textOffset[1];
  5877. if (!innerOrigin) {
  5878. innerTransformable.originX = -textOffset[0];
  5879. innerTransformable.originY = -textOffset[1];
  5880. }
  5881. }
  5882. var isInside = textConfig.inside == null
  5883. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5884. : textConfig.inside;
  5885. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5886. var textFill = void 0;
  5887. var textStroke = void 0;
  5888. var autoStroke = void 0;
  5889. if (isInside && this.canBeInsideText()) {
  5890. textFill = textConfig.insideFill;
  5891. textStroke = textConfig.insideStroke;
  5892. if (textFill == null || textFill === 'auto') {
  5893. textFill = this.getInsideTextFill();
  5894. }
  5895. if (textStroke == null || textStroke === 'auto') {
  5896. textStroke = this.getInsideTextStroke(textFill);
  5897. autoStroke = true;
  5898. }
  5899. }
  5900. else {
  5901. textFill = textConfig.outsideFill;
  5902. textStroke = textConfig.outsideStroke;
  5903. if (textFill == null || textFill === 'auto') {
  5904. textFill = this.getOutsideFill();
  5905. }
  5906. if (textStroke == null || textStroke === 'auto') {
  5907. textStroke = this.getOutsideStroke(textFill);
  5908. autoStroke = true;
  5909. }
  5910. }
  5911. textFill = textFill || '#000';
  5912. if (textFill !== innerTextDefaultStyle.fill
  5913. || textStroke !== innerTextDefaultStyle.stroke
  5914. || autoStroke !== innerTextDefaultStyle.autoStroke
  5915. || textAlign !== innerTextDefaultStyle.align
  5916. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5917. textStyleChanged = true;
  5918. innerTextDefaultStyle.fill = textFill;
  5919. innerTextDefaultStyle.stroke = textStroke;
  5920. innerTextDefaultStyle.autoStroke = autoStroke;
  5921. innerTextDefaultStyle.align = textAlign;
  5922. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5923. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5924. }
  5925. textEl.__dirty |= REDRAW_BIT;
  5926. if (textStyleChanged) {
  5927. textEl.dirtyStyle(true);
  5928. }
  5929. }
  5930. };
  5931. Element.prototype.canBeInsideText = function () {
  5932. return true;
  5933. };
  5934. Element.prototype.getInsideTextFill = function () {
  5935. return '#fff';
  5936. };
  5937. Element.prototype.getInsideTextStroke = function (textFill) {
  5938. return '#000';
  5939. };
  5940. Element.prototype.getOutsideFill = function () {
  5941. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5942. };
  5943. Element.prototype.getOutsideStroke = function (textFill) {
  5944. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5945. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5946. if (!colorArr) {
  5947. colorArr = [255, 255, 255, 1];
  5948. }
  5949. var alpha = colorArr[3];
  5950. var isDark = this.__zr.isDarkMode();
  5951. for (var i = 0; i < 3; i++) {
  5952. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5953. }
  5954. colorArr[3] = 1;
  5955. return stringify(colorArr, 'rgba');
  5956. };
  5957. Element.prototype.traverse = function (cb, context) { };
  5958. Element.prototype.attrKV = function (key, value) {
  5959. if (key === 'textConfig') {
  5960. this.setTextConfig(value);
  5961. }
  5962. else if (key === 'textContent') {
  5963. this.setTextContent(value);
  5964. }
  5965. else if (key === 'clipPath') {
  5966. this.setClipPath(value);
  5967. }
  5968. else if (key === 'extra') {
  5969. this.extra = this.extra || {};
  5970. extend(this.extra, value);
  5971. }
  5972. else {
  5973. this[key] = value;
  5974. }
  5975. };
  5976. Element.prototype.hide = function () {
  5977. this.ignore = true;
  5978. this.markRedraw();
  5979. };
  5980. Element.prototype.show = function () {
  5981. this.ignore = false;
  5982. this.markRedraw();
  5983. };
  5984. Element.prototype.attr = function (keyOrObj, value) {
  5985. if (typeof keyOrObj === 'string') {
  5986. this.attrKV(keyOrObj, value);
  5987. }
  5988. else if (isObject(keyOrObj)) {
  5989. var obj = keyOrObj;
  5990. var keysArr = keys(obj);
  5991. for (var i = 0; i < keysArr.length; i++) {
  5992. var key = keysArr[i];
  5993. this.attrKV(key, keyOrObj[key]);
  5994. }
  5995. }
  5996. this.markRedraw();
  5997. return this;
  5998. };
  5999. Element.prototype.saveCurrentToNormalState = function (toState) {
  6000. this._innerSaveToNormal(toState);
  6001. var normalState = this._normalState;
  6002. for (var i = 0; i < this.animators.length; i++) {
  6003. var animator = this.animators[i];
  6004. var fromStateTransition = animator.__fromStateTransition;
  6005. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6006. continue;
  6007. }
  6008. var targetName = animator.targetName;
  6009. var target = targetName
  6010. ? normalState[targetName] : normalState;
  6011. animator.saveTo(target);
  6012. }
  6013. };
  6014. Element.prototype._innerSaveToNormal = function (toState) {
  6015. var normalState = this._normalState;
  6016. if (!normalState) {
  6017. normalState = this._normalState = {};
  6018. }
  6019. if (toState.textConfig && !normalState.textConfig) {
  6020. normalState.textConfig = this.textConfig;
  6021. }
  6022. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6023. };
  6024. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6025. for (var i = 0; i < primaryKeys.length; i++) {
  6026. var key = primaryKeys[i];
  6027. if (toState[key] != null && !(key in normalState)) {
  6028. normalState[key] = this[key];
  6029. }
  6030. }
  6031. };
  6032. Element.prototype.hasState = function () {
  6033. return this.currentStates.length > 0;
  6034. };
  6035. Element.prototype.getState = function (name) {
  6036. return this.states[name];
  6037. };
  6038. Element.prototype.ensureState = function (name) {
  6039. var states = this.states;
  6040. if (!states[name]) {
  6041. states[name] = {};
  6042. }
  6043. return states[name];
  6044. };
  6045. Element.prototype.clearStates = function (noAnimation) {
  6046. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6047. };
  6048. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6049. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6050. var hasStates = this.hasState();
  6051. if (!hasStates && toNormalState) {
  6052. return;
  6053. }
  6054. var currentStates = this.currentStates;
  6055. var animationCfg = this.stateTransition;
  6056. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6057. return;
  6058. }
  6059. var state;
  6060. if (this.stateProxy && !toNormalState) {
  6061. state = this.stateProxy(stateName);
  6062. }
  6063. if (!state) {
  6064. state = (this.states && this.states[stateName]);
  6065. }
  6066. if (!state && !toNormalState) {
  6067. logError("State " + stateName + " not exists.");
  6068. return;
  6069. }
  6070. if (!toNormalState) {
  6071. this.saveCurrentToNormalState(state);
  6072. }
  6073. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6074. if (useHoverLayer) {
  6075. this._toggleHoverLayerFlag(true);
  6076. }
  6077. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6078. var textContent = this._textContent;
  6079. var textGuide = this._textGuide;
  6080. if (textContent) {
  6081. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6082. }
  6083. if (textGuide) {
  6084. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6085. }
  6086. if (toNormalState) {
  6087. this.currentStates = [];
  6088. this._normalState = {};
  6089. }
  6090. else {
  6091. if (!keepCurrentStates) {
  6092. this.currentStates = [stateName];
  6093. }
  6094. else {
  6095. this.currentStates.push(stateName);
  6096. }
  6097. }
  6098. this._updateAnimationTargets();
  6099. this.markRedraw();
  6100. if (!useHoverLayer && this.__inHover) {
  6101. this._toggleHoverLayerFlag(false);
  6102. this.__dirty &= ~REDRAW_BIT;
  6103. }
  6104. return state;
  6105. };
  6106. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6107. if (!states.length) {
  6108. this.clearStates();
  6109. }
  6110. else {
  6111. var stateObjects = [];
  6112. var currentStates = this.currentStates;
  6113. var len = states.length;
  6114. var notChange = len === currentStates.length;
  6115. if (notChange) {
  6116. for (var i = 0; i < len; i++) {
  6117. if (states[i] !== currentStates[i]) {
  6118. notChange = false;
  6119. break;
  6120. }
  6121. }
  6122. }
  6123. if (notChange) {
  6124. return;
  6125. }
  6126. for (var i = 0; i < len; i++) {
  6127. var stateName = states[i];
  6128. var stateObj = void 0;
  6129. if (this.stateProxy) {
  6130. stateObj = this.stateProxy(stateName, states);
  6131. }
  6132. if (!stateObj) {
  6133. stateObj = this.states[stateName];
  6134. }
  6135. if (stateObj) {
  6136. stateObjects.push(stateObj);
  6137. }
  6138. }
  6139. var lastStateObj = stateObjects[len - 1];
  6140. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6141. if (useHoverLayer) {
  6142. this._toggleHoverLayerFlag(true);
  6143. }
  6144. var mergedState = this._mergeStates(stateObjects);
  6145. var animationCfg = this.stateTransition;
  6146. this.saveCurrentToNormalState(mergedState);
  6147. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6148. var textContent = this._textContent;
  6149. var textGuide = this._textGuide;
  6150. if (textContent) {
  6151. textContent.useStates(states, noAnimation, useHoverLayer);
  6152. }
  6153. if (textGuide) {
  6154. textGuide.useStates(states, noAnimation, useHoverLayer);
  6155. }
  6156. this._updateAnimationTargets();
  6157. this.currentStates = states.slice();
  6158. this.markRedraw();
  6159. if (!useHoverLayer && this.__inHover) {
  6160. this._toggleHoverLayerFlag(false);
  6161. this.__dirty &= ~REDRAW_BIT;
  6162. }
  6163. }
  6164. };
  6165. Element.prototype._updateAnimationTargets = function () {
  6166. for (var i = 0; i < this.animators.length; i++) {
  6167. var animator = this.animators[i];
  6168. if (animator.targetName) {
  6169. animator.changeTarget(this[animator.targetName]);
  6170. }
  6171. }
  6172. };
  6173. Element.prototype.removeState = function (state) {
  6174. var idx = indexOf(this.currentStates, state);
  6175. if (idx >= 0) {
  6176. var currentStates = this.currentStates.slice();
  6177. currentStates.splice(idx, 1);
  6178. this.useStates(currentStates);
  6179. }
  6180. };
  6181. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6182. var currentStates = this.currentStates.slice();
  6183. var idx = indexOf(currentStates, oldState);
  6184. var newStateExists = indexOf(currentStates, newState) >= 0;
  6185. if (idx >= 0) {
  6186. if (!newStateExists) {
  6187. currentStates[idx] = newState;
  6188. }
  6189. else {
  6190. currentStates.splice(idx, 1);
  6191. }
  6192. }
  6193. else if (forceAdd && !newStateExists) {
  6194. currentStates.push(newState);
  6195. }
  6196. this.useStates(currentStates);
  6197. };
  6198. Element.prototype.toggleState = function (state, enable) {
  6199. if (enable) {
  6200. this.useState(state, true);
  6201. }
  6202. else {
  6203. this.removeState(state);
  6204. }
  6205. };
  6206. Element.prototype._mergeStates = function (states) {
  6207. var mergedState = {};
  6208. var mergedTextConfig;
  6209. for (var i = 0; i < states.length; i++) {
  6210. var state = states[i];
  6211. extend(mergedState, state);
  6212. if (state.textConfig) {
  6213. mergedTextConfig = mergedTextConfig || {};
  6214. extend(mergedTextConfig, state.textConfig);
  6215. }
  6216. }
  6217. if (mergedTextConfig) {
  6218. mergedState.textConfig = mergedTextConfig;
  6219. }
  6220. return mergedState;
  6221. };
  6222. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6223. var needsRestoreToNormal = !(state && keepCurrentStates);
  6224. if (state && state.textConfig) {
  6225. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6226. extend(this.textConfig, state.textConfig);
  6227. }
  6228. else if (needsRestoreToNormal) {
  6229. if (normalState.textConfig) {
  6230. this.textConfig = normalState.textConfig;
  6231. }
  6232. }
  6233. var transitionTarget = {};
  6234. var hasTransition = false;
  6235. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6236. var key = PRIMARY_STATES_KEYS[i];
  6237. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6238. if (state && state[key] != null) {
  6239. if (propNeedsTransition) {
  6240. hasTransition = true;
  6241. transitionTarget[key] = state[key];
  6242. }
  6243. else {
  6244. this[key] = state[key];
  6245. }
  6246. }
  6247. else if (needsRestoreToNormal) {
  6248. if (normalState[key] != null) {
  6249. if (propNeedsTransition) {
  6250. hasTransition = true;
  6251. transitionTarget[key] = normalState[key];
  6252. }
  6253. else {
  6254. this[key] = normalState[key];
  6255. }
  6256. }
  6257. }
  6258. }
  6259. if (!transition) {
  6260. for (var i = 0; i < this.animators.length; i++) {
  6261. var animator = this.animators[i];
  6262. var targetName = animator.targetName;
  6263. if (!animator.getLoop()) {
  6264. animator.__changeFinalValue(targetName
  6265. ? (state || normalState)[targetName]
  6266. : (state || normalState));
  6267. }
  6268. }
  6269. }
  6270. if (hasTransition) {
  6271. this._transitionState(stateName, transitionTarget, animationCfg);
  6272. }
  6273. };
  6274. Element.prototype._attachComponent = function (componentEl) {
  6275. if (componentEl.__zr && !componentEl.__hostTarget) {
  6276. if ("development" !== 'production') {
  6277. throw new Error('Text element has been added to zrender.');
  6278. }
  6279. return;
  6280. }
  6281. if (componentEl === this) {
  6282. if ("development" !== 'production') {
  6283. throw new Error('Recursive component attachment.');
  6284. }
  6285. return;
  6286. }
  6287. var zr = this.__zr;
  6288. if (zr) {
  6289. componentEl.addSelfToZr(zr);
  6290. }
  6291. componentEl.__zr = zr;
  6292. componentEl.__hostTarget = this;
  6293. };
  6294. Element.prototype._detachComponent = function (componentEl) {
  6295. if (componentEl.__zr) {
  6296. componentEl.removeSelfFromZr(componentEl.__zr);
  6297. }
  6298. componentEl.__zr = null;
  6299. componentEl.__hostTarget = null;
  6300. };
  6301. Element.prototype.getClipPath = function () {
  6302. return this._clipPath;
  6303. };
  6304. Element.prototype.setClipPath = function (clipPath) {
  6305. if (this._clipPath && this._clipPath !== clipPath) {
  6306. this.removeClipPath();
  6307. }
  6308. this._attachComponent(clipPath);
  6309. this._clipPath = clipPath;
  6310. this.markRedraw();
  6311. };
  6312. Element.prototype.removeClipPath = function () {
  6313. var clipPath = this._clipPath;
  6314. if (clipPath) {
  6315. this._detachComponent(clipPath);
  6316. this._clipPath = null;
  6317. this.markRedraw();
  6318. }
  6319. };
  6320. Element.prototype.getTextContent = function () {
  6321. return this._textContent;
  6322. };
  6323. Element.prototype.setTextContent = function (textEl) {
  6324. var previousTextContent = this._textContent;
  6325. if (previousTextContent === textEl) {
  6326. return;
  6327. }
  6328. if (previousTextContent && previousTextContent !== textEl) {
  6329. this.removeTextContent();
  6330. }
  6331. if ("development" !== 'production') {
  6332. if (textEl.__zr && !textEl.__hostTarget) {
  6333. throw new Error('Text element has been added to zrender.');
  6334. }
  6335. }
  6336. textEl.innerTransformable = new Transformable();
  6337. this._attachComponent(textEl);
  6338. this._textContent = textEl;
  6339. this.markRedraw();
  6340. };
  6341. Element.prototype.setTextConfig = function (cfg) {
  6342. if (!this.textConfig) {
  6343. this.textConfig = {};
  6344. }
  6345. extend(this.textConfig, cfg);
  6346. this.markRedraw();
  6347. };
  6348. Element.prototype.removeTextConfig = function () {
  6349. this.textConfig = null;
  6350. this.markRedraw();
  6351. };
  6352. Element.prototype.removeTextContent = function () {
  6353. var textEl = this._textContent;
  6354. if (textEl) {
  6355. textEl.innerTransformable = null;
  6356. this._detachComponent(textEl);
  6357. this._textContent = null;
  6358. this._innerTextDefaultStyle = null;
  6359. this.markRedraw();
  6360. }
  6361. };
  6362. Element.prototype.getTextGuideLine = function () {
  6363. return this._textGuide;
  6364. };
  6365. Element.prototype.setTextGuideLine = function (guideLine) {
  6366. if (this._textGuide && this._textGuide !== guideLine) {
  6367. this.removeTextGuideLine();
  6368. }
  6369. this._attachComponent(guideLine);
  6370. this._textGuide = guideLine;
  6371. this.markRedraw();
  6372. };
  6373. Element.prototype.removeTextGuideLine = function () {
  6374. var textGuide = this._textGuide;
  6375. if (textGuide) {
  6376. this._detachComponent(textGuide);
  6377. this._textGuide = null;
  6378. this.markRedraw();
  6379. }
  6380. };
  6381. Element.prototype.markRedraw = function () {
  6382. this.__dirty |= REDRAW_BIT;
  6383. var zr = this.__zr;
  6384. if (zr) {
  6385. if (this.__inHover) {
  6386. zr.refreshHover();
  6387. }
  6388. else {
  6389. zr.refresh();
  6390. }
  6391. }
  6392. if (this.__hostTarget) {
  6393. this.__hostTarget.markRedraw();
  6394. }
  6395. };
  6396. Element.prototype.dirty = function () {
  6397. this.markRedraw();
  6398. };
  6399. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6400. this.__inHover = inHover;
  6401. var textContent = this._textContent;
  6402. var textGuide = this._textGuide;
  6403. if (textContent) {
  6404. textContent.__inHover = inHover;
  6405. }
  6406. if (textGuide) {
  6407. textGuide.__inHover = inHover;
  6408. }
  6409. };
  6410. Element.prototype.addSelfToZr = function (zr) {
  6411. if (this.__zr === zr) {
  6412. return;
  6413. }
  6414. this.__zr = zr;
  6415. var animators = this.animators;
  6416. if (animators) {
  6417. for (var i = 0; i < animators.length; i++) {
  6418. zr.animation.addAnimator(animators[i]);
  6419. }
  6420. }
  6421. if (this._clipPath) {
  6422. this._clipPath.addSelfToZr(zr);
  6423. }
  6424. if (this._textContent) {
  6425. this._textContent.addSelfToZr(zr);
  6426. }
  6427. if (this._textGuide) {
  6428. this._textGuide.addSelfToZr(zr);
  6429. }
  6430. };
  6431. Element.prototype.removeSelfFromZr = function (zr) {
  6432. if (!this.__zr) {
  6433. return;
  6434. }
  6435. this.__zr = null;
  6436. var animators = this.animators;
  6437. if (animators) {
  6438. for (var i = 0; i < animators.length; i++) {
  6439. zr.animation.removeAnimator(animators[i]);
  6440. }
  6441. }
  6442. if (this._clipPath) {
  6443. this._clipPath.removeSelfFromZr(zr);
  6444. }
  6445. if (this._textContent) {
  6446. this._textContent.removeSelfFromZr(zr);
  6447. }
  6448. if (this._textGuide) {
  6449. this._textGuide.removeSelfFromZr(zr);
  6450. }
  6451. };
  6452. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6453. var target = key ? this[key] : this;
  6454. if ("development" !== 'production') {
  6455. if (!target) {
  6456. logError('Property "'
  6457. + key
  6458. + '" is not existed in element '
  6459. + this.id);
  6460. return;
  6461. }
  6462. }
  6463. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6464. key && (animator.targetName = key);
  6465. this.addAnimator(animator, key);
  6466. return animator;
  6467. };
  6468. Element.prototype.addAnimator = function (animator, key) {
  6469. var zr = this.__zr;
  6470. var el = this;
  6471. animator.during(function () {
  6472. el.updateDuringAnimation(key);
  6473. }).done(function () {
  6474. var animators = el.animators;
  6475. var idx = indexOf(animators, animator);
  6476. if (idx >= 0) {
  6477. animators.splice(idx, 1);
  6478. }
  6479. });
  6480. this.animators.push(animator);
  6481. if (zr) {
  6482. zr.animation.addAnimator(animator);
  6483. }
  6484. zr && zr.wakeUp();
  6485. };
  6486. Element.prototype.updateDuringAnimation = function (key) {
  6487. this.markRedraw();
  6488. };
  6489. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6490. var animators = this.animators;
  6491. var len = animators.length;
  6492. var leftAnimators = [];
  6493. for (var i = 0; i < len; i++) {
  6494. var animator = animators[i];
  6495. if (!scope || scope === animator.scope) {
  6496. animator.stop(forwardToLast);
  6497. }
  6498. else {
  6499. leftAnimators.push(animator);
  6500. }
  6501. }
  6502. this.animators = leftAnimators;
  6503. return this;
  6504. };
  6505. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6506. animateTo(this, target, cfg, animationProps);
  6507. };
  6508. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6509. animateTo(this, target, cfg, animationProps, true);
  6510. };
  6511. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6512. var animators = animateTo(this, target, cfg, animationProps);
  6513. for (var i = 0; i < animators.length; i++) {
  6514. animators[i].__fromStateTransition = stateName;
  6515. }
  6516. };
  6517. Element.prototype.getBoundingRect = function () {
  6518. return null;
  6519. };
  6520. Element.prototype.getPaintRect = function () {
  6521. return null;
  6522. };
  6523. Element.initDefaultProps = (function () {
  6524. var elProto = Element.prototype;
  6525. elProto.type = 'element';
  6526. elProto.name = '';
  6527. elProto.ignore =
  6528. elProto.silent =
  6529. elProto.isGroup =
  6530. elProto.draggable =
  6531. elProto.dragging =
  6532. elProto.ignoreClip =
  6533. elProto.__inHover = false;
  6534. elProto.__dirty = REDRAW_BIT;
  6535. var logs = {};
  6536. function logDeprecatedError(key, xKey, yKey) {
  6537. if (!logs[key + xKey + yKey]) {
  6538. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6539. logs[key + xKey + yKey] = true;
  6540. }
  6541. }
  6542. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6543. Object.defineProperty(elProto, key, {
  6544. get: function () {
  6545. if ("development" !== 'production') {
  6546. logDeprecatedError(key, xKey, yKey);
  6547. }
  6548. if (!this[privateKey]) {
  6549. var pos = this[privateKey] = [];
  6550. enhanceArray(this, pos);
  6551. }
  6552. return this[privateKey];
  6553. },
  6554. set: function (pos) {
  6555. if ("development" !== 'production') {
  6556. logDeprecatedError(key, xKey, yKey);
  6557. }
  6558. this[xKey] = pos[0];
  6559. this[yKey] = pos[1];
  6560. this[privateKey] = pos;
  6561. enhanceArray(this, pos);
  6562. }
  6563. });
  6564. function enhanceArray(self, pos) {
  6565. Object.defineProperty(pos, 0, {
  6566. get: function () {
  6567. return self[xKey];
  6568. },
  6569. set: function (val) {
  6570. self[xKey] = val;
  6571. }
  6572. });
  6573. Object.defineProperty(pos, 1, {
  6574. get: function () {
  6575. return self[yKey];
  6576. },
  6577. set: function (val) {
  6578. self[yKey] = val;
  6579. }
  6580. });
  6581. }
  6582. }
  6583. if (Object.defineProperty) {
  6584. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6585. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6586. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6587. }
  6588. })();
  6589. return Element;
  6590. }());
  6591. mixin(Element, Eventful);
  6592. mixin(Element, Transformable);
  6593. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6594. cfg = cfg || {};
  6595. var animators = [];
  6596. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6597. var finishCount = animators.length;
  6598. var doneHappened = false;
  6599. var cfgDone = cfg.done;
  6600. var cfgAborted = cfg.aborted;
  6601. var doneCb = function () {
  6602. doneHappened = true;
  6603. finishCount--;
  6604. if (finishCount <= 0) {
  6605. doneHappened
  6606. ? (cfgDone && cfgDone())
  6607. : (cfgAborted && cfgAborted());
  6608. }
  6609. };
  6610. var abortedCb = function () {
  6611. finishCount--;
  6612. if (finishCount <= 0) {
  6613. doneHappened
  6614. ? (cfgDone && cfgDone())
  6615. : (cfgAborted && cfgAborted());
  6616. }
  6617. };
  6618. if (!finishCount) {
  6619. cfgDone && cfgDone();
  6620. }
  6621. if (animators.length > 0 && cfg.during) {
  6622. animators[0].during(function (target, percent) {
  6623. cfg.during(percent);
  6624. });
  6625. }
  6626. for (var i = 0; i < animators.length; i++) {
  6627. var animator = animators[i];
  6628. if (doneCb) {
  6629. animator.done(doneCb);
  6630. }
  6631. if (abortedCb) {
  6632. animator.aborted(abortedCb);
  6633. }
  6634. if (cfg.force) {
  6635. animator.duration(cfg.duration);
  6636. }
  6637. animator.start(cfg.easing);
  6638. }
  6639. return animators;
  6640. }
  6641. function copyArrShallow(source, target, len) {
  6642. for (var i = 0; i < len; i++) {
  6643. source[i] = target[i];
  6644. }
  6645. }
  6646. function is2DArray(value) {
  6647. return isArrayLike(value[0]);
  6648. }
  6649. function copyValue(target, source, key) {
  6650. if (isArrayLike(source[key])) {
  6651. if (!isArrayLike(target[key])) {
  6652. target[key] = [];
  6653. }
  6654. if (isTypedArray(source[key])) {
  6655. var len = source[key].length;
  6656. if (target[key].length !== len) {
  6657. target[key] = new (source[key].constructor)(len);
  6658. copyArrShallow(target[key], source[key], len);
  6659. }
  6660. }
  6661. else {
  6662. var sourceArr = source[key];
  6663. var targetArr = target[key];
  6664. var len0 = sourceArr.length;
  6665. if (is2DArray(sourceArr)) {
  6666. var len1 = sourceArr[0].length;
  6667. for (var i = 0; i < len0; i++) {
  6668. if (!targetArr[i]) {
  6669. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6670. }
  6671. else {
  6672. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6673. }
  6674. }
  6675. }
  6676. else {
  6677. copyArrShallow(targetArr, sourceArr, len0);
  6678. }
  6679. targetArr.length = sourceArr.length;
  6680. }
  6681. }
  6682. else {
  6683. target[key] = source[key];
  6684. }
  6685. }
  6686. function isValueSame(val1, val2) {
  6687. return val1 === val2
  6688. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6689. }
  6690. function is1DArraySame(arr0, arr1) {
  6691. var len = arr0.length;
  6692. if (len !== arr1.length) {
  6693. return false;
  6694. }
  6695. for (var i = 0; i < len; i++) {
  6696. if (arr0[i] !== arr1[i]) {
  6697. return false;
  6698. }
  6699. }
  6700. return true;
  6701. }
  6702. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6703. var targetKeys = keys(target);
  6704. var duration = cfg.duration;
  6705. var delay = cfg.delay;
  6706. var additive = cfg.additive;
  6707. var setToFinal = cfg.setToFinal;
  6708. var animateAll = !isObject(animationProps);
  6709. var existsAnimators = animatable.animators;
  6710. var animationKeys = [];
  6711. for (var k = 0; k < targetKeys.length; k++) {
  6712. var innerKey = targetKeys[k];
  6713. var targetVal = target[innerKey];
  6714. if (targetVal != null && animateObj[innerKey] != null
  6715. && (animateAll || animationProps[innerKey])) {
  6716. if (isObject(targetVal)
  6717. && !isArrayLike(targetVal)
  6718. && !isGradientObject(targetVal)) {
  6719. if (topKey) {
  6720. if (!reverse) {
  6721. animateObj[innerKey] = targetVal;
  6722. animatable.updateDuringAnimation(topKey);
  6723. }
  6724. continue;
  6725. }
  6726. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6727. }
  6728. else {
  6729. animationKeys.push(innerKey);
  6730. }
  6731. }
  6732. else if (!reverse) {
  6733. animateObj[innerKey] = targetVal;
  6734. animatable.updateDuringAnimation(topKey);
  6735. animationKeys.push(innerKey);
  6736. }
  6737. }
  6738. var keyLen = animationKeys.length;
  6739. if (!additive && keyLen) {
  6740. for (var i = 0; i < existsAnimators.length; i++) {
  6741. var animator = existsAnimators[i];
  6742. if (animator.targetName === topKey) {
  6743. var allAborted = animator.stopTracks(animationKeys);
  6744. if (allAborted) {
  6745. var idx = indexOf(existsAnimators, animator);
  6746. existsAnimators.splice(idx, 1);
  6747. }
  6748. }
  6749. }
  6750. }
  6751. if (!cfg.force) {
  6752. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6753. keyLen = animationKeys.length;
  6754. }
  6755. if (keyLen > 0
  6756. || (cfg.force && !animators.length)) {
  6757. var revertedSource = void 0;
  6758. var reversedTarget = void 0;
  6759. var sourceClone = void 0;
  6760. if (reverse) {
  6761. reversedTarget = {};
  6762. if (setToFinal) {
  6763. revertedSource = {};
  6764. }
  6765. for (var i = 0; i < keyLen; i++) {
  6766. var innerKey = animationKeys[i];
  6767. reversedTarget[innerKey] = animateObj[innerKey];
  6768. if (setToFinal) {
  6769. revertedSource[innerKey] = target[innerKey];
  6770. }
  6771. else {
  6772. animateObj[innerKey] = target[innerKey];
  6773. }
  6774. }
  6775. }
  6776. else if (setToFinal) {
  6777. sourceClone = {};
  6778. for (var i = 0; i < keyLen; i++) {
  6779. var innerKey = animationKeys[i];
  6780. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6781. copyValue(animateObj, target, innerKey);
  6782. }
  6783. }
  6784. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6785. animator.targetName = topKey;
  6786. if (cfg.scope) {
  6787. animator.scope = cfg.scope;
  6788. }
  6789. if (setToFinal && revertedSource) {
  6790. animator.whenWithKeys(0, revertedSource, animationKeys);
  6791. }
  6792. if (sourceClone) {
  6793. animator.whenWithKeys(0, sourceClone, animationKeys);
  6794. }
  6795. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6796. animatable.addAnimator(animator, topKey);
  6797. animators.push(animator);
  6798. }
  6799. }
  6800. var Group = (function (_super) {
  6801. __extends(Group, _super);
  6802. function Group(opts) {
  6803. var _this = _super.call(this) || this;
  6804. _this.isGroup = true;
  6805. _this._children = [];
  6806. _this.attr(opts);
  6807. return _this;
  6808. }
  6809. Group.prototype.childrenRef = function () {
  6810. return this._children;
  6811. };
  6812. Group.prototype.children = function () {
  6813. return this._children.slice();
  6814. };
  6815. Group.prototype.childAt = function (idx) {
  6816. return this._children[idx];
  6817. };
  6818. Group.prototype.childOfName = function (name) {
  6819. var children = this._children;
  6820. for (var i = 0; i < children.length; i++) {
  6821. if (children[i].name === name) {
  6822. return children[i];
  6823. }
  6824. }
  6825. };
  6826. Group.prototype.childCount = function () {
  6827. return this._children.length;
  6828. };
  6829. Group.prototype.add = function (child) {
  6830. if (child) {
  6831. if (child !== this && child.parent !== this) {
  6832. this._children.push(child);
  6833. this._doAdd(child);
  6834. }
  6835. if ("development" !== 'production') {
  6836. if (child.__hostTarget) {
  6837. throw 'This elemenet has been used as an attachment';
  6838. }
  6839. }
  6840. }
  6841. return this;
  6842. };
  6843. Group.prototype.addBefore = function (child, nextSibling) {
  6844. if (child && child !== this && child.parent !== this
  6845. && nextSibling && nextSibling.parent === this) {
  6846. var children = this._children;
  6847. var idx = children.indexOf(nextSibling);
  6848. if (idx >= 0) {
  6849. children.splice(idx, 0, child);
  6850. this._doAdd(child);
  6851. }
  6852. }
  6853. return this;
  6854. };
  6855. Group.prototype.replace = function (oldChild, newChild) {
  6856. var idx = indexOf(this._children, oldChild);
  6857. if (idx >= 0) {
  6858. this.replaceAt(newChild, idx);
  6859. }
  6860. return this;
  6861. };
  6862. Group.prototype.replaceAt = function (child, index) {
  6863. var children = this._children;
  6864. var old = children[index];
  6865. if (child && child !== this && child.parent !== this && child !== old) {
  6866. children[index] = child;
  6867. old.parent = null;
  6868. var zr = this.__zr;
  6869. if (zr) {
  6870. old.removeSelfFromZr(zr);
  6871. }
  6872. this._doAdd(child);
  6873. }
  6874. return this;
  6875. };
  6876. Group.prototype._doAdd = function (child) {
  6877. if (child.parent) {
  6878. child.parent.remove(child);
  6879. }
  6880. child.parent = this;
  6881. var zr = this.__zr;
  6882. if (zr && zr !== child.__zr) {
  6883. child.addSelfToZr(zr);
  6884. }
  6885. zr && zr.refresh();
  6886. };
  6887. Group.prototype.remove = function (child) {
  6888. var zr = this.__zr;
  6889. var children = this._children;
  6890. var idx = indexOf(children, child);
  6891. if (idx < 0) {
  6892. return this;
  6893. }
  6894. children.splice(idx, 1);
  6895. child.parent = null;
  6896. if (zr) {
  6897. child.removeSelfFromZr(zr);
  6898. }
  6899. zr && zr.refresh();
  6900. return this;
  6901. };
  6902. Group.prototype.removeAll = function () {
  6903. var children = this._children;
  6904. var zr = this.__zr;
  6905. for (var i = 0; i < children.length; i++) {
  6906. var child = children[i];
  6907. if (zr) {
  6908. child.removeSelfFromZr(zr);
  6909. }
  6910. child.parent = null;
  6911. }
  6912. children.length = 0;
  6913. return this;
  6914. };
  6915. Group.prototype.eachChild = function (cb, context) {
  6916. var children = this._children;
  6917. for (var i = 0; i < children.length; i++) {
  6918. var child = children[i];
  6919. cb.call(context, child, i);
  6920. }
  6921. return this;
  6922. };
  6923. Group.prototype.traverse = function (cb, context) {
  6924. for (var i = 0; i < this._children.length; i++) {
  6925. var child = this._children[i];
  6926. var stopped = cb.call(context, child);
  6927. if (child.isGroup && !stopped) {
  6928. child.traverse(cb, context);
  6929. }
  6930. }
  6931. return this;
  6932. };
  6933. Group.prototype.addSelfToZr = function (zr) {
  6934. _super.prototype.addSelfToZr.call(this, zr);
  6935. for (var i = 0; i < this._children.length; i++) {
  6936. var child = this._children[i];
  6937. child.addSelfToZr(zr);
  6938. }
  6939. };
  6940. Group.prototype.removeSelfFromZr = function (zr) {
  6941. _super.prototype.removeSelfFromZr.call(this, zr);
  6942. for (var i = 0; i < this._children.length; i++) {
  6943. var child = this._children[i];
  6944. child.removeSelfFromZr(zr);
  6945. }
  6946. };
  6947. Group.prototype.getBoundingRect = function (includeChildren) {
  6948. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6949. var children = includeChildren || this._children;
  6950. var tmpMat = [];
  6951. var rect = null;
  6952. for (var i = 0; i < children.length; i++) {
  6953. var child = children[i];
  6954. if (child.ignore || child.invisible) {
  6955. continue;
  6956. }
  6957. var childRect = child.getBoundingRect();
  6958. var transform = child.getLocalTransform(tmpMat);
  6959. if (transform) {
  6960. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6961. rect = rect || tmpRect.clone();
  6962. rect.union(tmpRect);
  6963. }
  6964. else {
  6965. rect = rect || childRect.clone();
  6966. rect.union(childRect);
  6967. }
  6968. }
  6969. return rect || tmpRect;
  6970. };
  6971. return Group;
  6972. }(Element));
  6973. Group.prototype.type = 'group';
  6974. /*!
  6975. * ZRender, a high performance 2d drawing library.
  6976. *
  6977. * Copyright (c) 2013, Baidu Inc.
  6978. * All rights reserved.
  6979. *
  6980. * LICENSE
  6981. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6982. */
  6983. var painterCtors = {};
  6984. var instances = {};
  6985. function delInstance(id) {
  6986. delete instances[id];
  6987. }
  6988. function isDarkMode(backgroundColor) {
  6989. if (!backgroundColor) {
  6990. return false;
  6991. }
  6992. if (typeof backgroundColor === 'string') {
  6993. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6994. }
  6995. else if (backgroundColor.colorStops) {
  6996. var colorStops = backgroundColor.colorStops;
  6997. var totalLum = 0;
  6998. var len = colorStops.length;
  6999. for (var i = 0; i < len; i++) {
  7000. totalLum += lum(colorStops[i].color, 1);
  7001. }
  7002. totalLum /= len;
  7003. return totalLum < DARK_MODE_THRESHOLD;
  7004. }
  7005. return false;
  7006. }
  7007. var ZRender = (function () {
  7008. function ZRender(id, dom, opts) {
  7009. var _this = this;
  7010. this._sleepAfterStill = 10;
  7011. this._stillFrameAccum = 0;
  7012. this._needsRefresh = true;
  7013. this._needsRefreshHover = true;
  7014. this._darkMode = false;
  7015. opts = opts || {};
  7016. this.dom = dom;
  7017. this.id = id;
  7018. var storage = new Storage();
  7019. var rendererType = opts.renderer || 'canvas';
  7020. if (!painterCtors[rendererType]) {
  7021. rendererType = keys(painterCtors)[0];
  7022. }
  7023. if ("development" !== 'production') {
  7024. if (!painterCtors[rendererType]) {
  7025. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7026. }
  7027. }
  7028. opts.useDirtyRect = opts.useDirtyRect == null
  7029. ? false
  7030. : opts.useDirtyRect;
  7031. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7032. var ssrMode = opts.ssr || painter.ssrOnly;
  7033. this.storage = storage;
  7034. this.painter = painter;
  7035. var handerProxy = (!env.node && !env.worker && !ssrMode)
  7036. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7037. : null;
  7038. var useCoarsePointer = opts.useCoarsePointer;
  7039. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7040. ? env.touchEventsSupported
  7041. : !!useCoarsePointer;
  7042. var defaultPointerSize = 44;
  7043. var pointerSize;
  7044. if (usePointerSize) {
  7045. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7046. }
  7047. this.handler = new Handler(storage, painter, handerProxy, painter.root, pointerSize);
  7048. this.animation = new Animation({
  7049. stage: {
  7050. update: ssrMode ? null : function () { return _this._flush(true); }
  7051. }
  7052. });
  7053. if (!ssrMode) {
  7054. this.animation.start();
  7055. }
  7056. }
  7057. ZRender.prototype.add = function (el) {
  7058. if (!el) {
  7059. return;
  7060. }
  7061. this.storage.addRoot(el);
  7062. el.addSelfToZr(this);
  7063. this.refresh();
  7064. };
  7065. ZRender.prototype.remove = function (el) {
  7066. if (!el) {
  7067. return;
  7068. }
  7069. this.storage.delRoot(el);
  7070. el.removeSelfFromZr(this);
  7071. this.refresh();
  7072. };
  7073. ZRender.prototype.configLayer = function (zLevel, config) {
  7074. if (this.painter.configLayer) {
  7075. this.painter.configLayer(zLevel, config);
  7076. }
  7077. this.refresh();
  7078. };
  7079. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7080. if (this.painter.setBackgroundColor) {
  7081. this.painter.setBackgroundColor(backgroundColor);
  7082. }
  7083. this.refresh();
  7084. this._backgroundColor = backgroundColor;
  7085. this._darkMode = isDarkMode(backgroundColor);
  7086. };
  7087. ZRender.prototype.getBackgroundColor = function () {
  7088. return this._backgroundColor;
  7089. };
  7090. ZRender.prototype.setDarkMode = function (darkMode) {
  7091. this._darkMode = darkMode;
  7092. };
  7093. ZRender.prototype.isDarkMode = function () {
  7094. return this._darkMode;
  7095. };
  7096. ZRender.prototype.refreshImmediately = function (fromInside) {
  7097. if (!fromInside) {
  7098. this.animation.update(true);
  7099. }
  7100. this._needsRefresh = false;
  7101. this.painter.refresh();
  7102. this._needsRefresh = false;
  7103. };
  7104. ZRender.prototype.refresh = function () {
  7105. this._needsRefresh = true;
  7106. this.animation.start();
  7107. };
  7108. ZRender.prototype.flush = function () {
  7109. this._flush(false);
  7110. };
  7111. ZRender.prototype._flush = function (fromInside) {
  7112. var triggerRendered;
  7113. var start = getTime();
  7114. if (this._needsRefresh) {
  7115. triggerRendered = true;
  7116. this.refreshImmediately(fromInside);
  7117. }
  7118. if (this._needsRefreshHover) {
  7119. triggerRendered = true;
  7120. this.refreshHoverImmediately();
  7121. }
  7122. var end = getTime();
  7123. if (triggerRendered) {
  7124. this._stillFrameAccum = 0;
  7125. this.trigger('rendered', {
  7126. elapsedTime: end - start
  7127. });
  7128. }
  7129. else if (this._sleepAfterStill > 0) {
  7130. this._stillFrameAccum++;
  7131. if (this._stillFrameAccum > this._sleepAfterStill) {
  7132. this.animation.stop();
  7133. }
  7134. }
  7135. };
  7136. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7137. this._sleepAfterStill = stillFramesCount;
  7138. };
  7139. ZRender.prototype.wakeUp = function () {
  7140. this.animation.start();
  7141. this._stillFrameAccum = 0;
  7142. };
  7143. ZRender.prototype.refreshHover = function () {
  7144. this._needsRefreshHover = true;
  7145. };
  7146. ZRender.prototype.refreshHoverImmediately = function () {
  7147. this._needsRefreshHover = false;
  7148. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7149. this.painter.refreshHover();
  7150. }
  7151. };
  7152. ZRender.prototype.resize = function (opts) {
  7153. opts = opts || {};
  7154. this.painter.resize(opts.width, opts.height);
  7155. this.handler.resize();
  7156. };
  7157. ZRender.prototype.clearAnimation = function () {
  7158. this.animation.clear();
  7159. };
  7160. ZRender.prototype.getWidth = function () {
  7161. return this.painter.getWidth();
  7162. };
  7163. ZRender.prototype.getHeight = function () {
  7164. return this.painter.getHeight();
  7165. };
  7166. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7167. this.handler.setCursorStyle(cursorStyle);
  7168. };
  7169. ZRender.prototype.findHover = function (x, y) {
  7170. return this.handler.findHover(x, y);
  7171. };
  7172. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7173. this.handler.on(eventName, eventHandler, context);
  7174. return this;
  7175. };
  7176. ZRender.prototype.off = function (eventName, eventHandler) {
  7177. this.handler.off(eventName, eventHandler);
  7178. };
  7179. ZRender.prototype.trigger = function (eventName, event) {
  7180. this.handler.trigger(eventName, event);
  7181. };
  7182. ZRender.prototype.clear = function () {
  7183. var roots = this.storage.getRoots();
  7184. for (var i = 0; i < roots.length; i++) {
  7185. if (roots[i] instanceof Group) {
  7186. roots[i].removeSelfFromZr(this);
  7187. }
  7188. }
  7189. this.storage.delAllRoots();
  7190. this.painter.clear();
  7191. };
  7192. ZRender.prototype.dispose = function () {
  7193. this.animation.stop();
  7194. this.clear();
  7195. this.storage.dispose();
  7196. this.painter.dispose();
  7197. this.handler.dispose();
  7198. this.animation =
  7199. this.storage =
  7200. this.painter =
  7201. this.handler = null;
  7202. delInstance(this.id);
  7203. };
  7204. return ZRender;
  7205. }());
  7206. function init(dom, opts) {
  7207. var zr = new ZRender(guid(), dom, opts);
  7208. instances[zr.id] = zr;
  7209. return zr;
  7210. }
  7211. function dispose(zr) {
  7212. zr.dispose();
  7213. }
  7214. function disposeAll() {
  7215. for (var key in instances) {
  7216. if (instances.hasOwnProperty(key)) {
  7217. instances[key].dispose();
  7218. }
  7219. }
  7220. instances = {};
  7221. }
  7222. function getInstance(id) {
  7223. return instances[id];
  7224. }
  7225. function registerPainter(name, Ctor) {
  7226. painterCtors[name] = Ctor;
  7227. }
  7228. var version = '5.4.3';
  7229. var zrender = /*#__PURE__*/Object.freeze({
  7230. __proto__: null,
  7231. init: init,
  7232. dispose: dispose,
  7233. disposeAll: disposeAll,
  7234. getInstance: getInstance,
  7235. registerPainter: registerPainter,
  7236. version: version
  7237. });
  7238. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  7239. // we sill follow the spec for compatibility.
  7240. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7241. function _trim(str) {
  7242. return str.replace(/^\s+|\s+$/g, '');
  7243. }
  7244. /**
  7245. * Linear mapping a value from domain to range
  7246. * @param val
  7247. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7248. * @param range Range extent range[0] can be bigger than range[1]
  7249. * @param clamp Default to be false
  7250. */
  7251. function linearMap(val, domain, range, clamp) {
  7252. var d0 = domain[0];
  7253. var d1 = domain[1];
  7254. var r0 = range[0];
  7255. var r1 = range[1];
  7256. var subDomain = d1 - d0;
  7257. var subRange = r1 - r0;
  7258. if (subDomain === 0) {
  7259. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7260. } // Avoid accuracy problem in edge, such as
  7261. // 146.39 - 62.83 === 83.55999999999999.
  7262. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7263. // It is a little verbose for efficiency considering this method
  7264. // is a hotspot.
  7265. if (clamp) {
  7266. if (subDomain > 0) {
  7267. if (val <= d0) {
  7268. return r0;
  7269. } else if (val >= d1) {
  7270. return r1;
  7271. }
  7272. } else {
  7273. if (val >= d0) {
  7274. return r0;
  7275. } else if (val <= d1) {
  7276. return r1;
  7277. }
  7278. }
  7279. } else {
  7280. if (val === d0) {
  7281. return r0;
  7282. }
  7283. if (val === d1) {
  7284. return r1;
  7285. }
  7286. }
  7287. return (val - d0) / subDomain * subRange + r0;
  7288. }
  7289. /**
  7290. * Convert a percent string to absolute number.
  7291. * Returns NaN if percent is not a valid string or number
  7292. */
  7293. function parsePercent$1(percent, all) {
  7294. switch (percent) {
  7295. case 'center':
  7296. case 'middle':
  7297. percent = '50%';
  7298. break;
  7299. case 'left':
  7300. case 'top':
  7301. percent = '0%';
  7302. break;
  7303. case 'right':
  7304. case 'bottom':
  7305. percent = '100%';
  7306. break;
  7307. }
  7308. if (isString(percent)) {
  7309. if (_trim(percent).match(/%$/)) {
  7310. return parseFloat(percent) / 100 * all;
  7311. }
  7312. return parseFloat(percent);
  7313. }
  7314. return percent == null ? NaN : +percent;
  7315. }
  7316. function round(x, precision, returnStr) {
  7317. if (precision == null) {
  7318. precision = 10;
  7319. } // Avoid range error
  7320. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7321. x = (+x).toFixed(precision);
  7322. return returnStr ? x : +x;
  7323. }
  7324. /**
  7325. * Inplacd asc sort arr.
  7326. * The input arr will be modified.
  7327. */
  7328. function asc(arr) {
  7329. arr.sort(function (a, b) {
  7330. return a - b;
  7331. });
  7332. return arr;
  7333. }
  7334. /**
  7335. * Get precision.
  7336. */
  7337. function getPrecision(val) {
  7338. val = +val;
  7339. if (isNaN(val)) {
  7340. return 0;
  7341. } // It is much faster than methods converting number to string as follows
  7342. // let tmp = val.toString();
  7343. // return tmp.length - 1 - tmp.indexOf('.');
  7344. // especially when precision is low
  7345. // Notice:
  7346. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7347. // (see https://jsbench.me/2vkpcekkvw/1)
  7348. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7349. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7350. if (val > 1e-14) {
  7351. var e = 1;
  7352. for (var i = 0; i < 15; i++, e *= 10) {
  7353. if (Math.round(val * e) / e === val) {
  7354. return i;
  7355. }
  7356. }
  7357. }
  7358. return getPrecisionSafe(val);
  7359. }
  7360. /**
  7361. * Get precision with slow but safe method
  7362. */
  7363. function getPrecisionSafe(val) {
  7364. // toLowerCase for: '3.4E-12'
  7365. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7366. var eIndex = str.indexOf('e');
  7367. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7368. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7369. var dotIndex = str.indexOf('.');
  7370. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7371. return Math.max(0, decimalPartLen - exp);
  7372. }
  7373. /**
  7374. * Minimal dicernible data precisioin according to a single pixel.
  7375. */
  7376. function getPixelPrecision(dataExtent, pixelExtent) {
  7377. var log = Math.log;
  7378. var LN10 = Math.LN10;
  7379. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7380. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7381. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7382. return !isFinite(precision) ? 20 : precision;
  7383. }
  7384. /**
  7385. * Get a data of given precision, assuring the sum of percentages
  7386. * in valueList is 1.
  7387. * The largest remainder method is used.
  7388. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7389. *
  7390. * @param valueList a list of all data
  7391. * @param idx index of the data to be processed in valueList
  7392. * @param precision integer number showing digits of precision
  7393. * @return percent ranging from 0 to 100
  7394. */
  7395. function getPercentWithPrecision(valueList, idx, precision) {
  7396. if (!valueList[idx]) {
  7397. return 0;
  7398. }
  7399. var seats = getPercentSeats(valueList, precision);
  7400. return seats[idx] || 0;
  7401. }
  7402. /**
  7403. * Get a data of given precision, assuring the sum of percentages
  7404. * in valueList is 1.
  7405. * The largest remainder method is used.
  7406. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7407. *
  7408. * @param valueList a list of all data
  7409. * @param precision integer number showing digits of precision
  7410. * @return {Array<number>}
  7411. */
  7412. function getPercentSeats(valueList, precision) {
  7413. var sum = reduce(valueList, function (acc, val) {
  7414. return acc + (isNaN(val) ? 0 : val);
  7415. }, 0);
  7416. if (sum === 0) {
  7417. return [];
  7418. }
  7419. var digits = Math.pow(10, precision);
  7420. var votesPerQuota = map(valueList, function (val) {
  7421. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7422. });
  7423. var targetSeats = digits * 100;
  7424. var seats = map(votesPerQuota, function (votes) {
  7425. // Assign automatic seats.
  7426. return Math.floor(votes);
  7427. });
  7428. var currentSum = reduce(seats, function (acc, val) {
  7429. return acc + val;
  7430. }, 0);
  7431. var remainder = map(votesPerQuota, function (votes, idx) {
  7432. return votes - seats[idx];
  7433. }); // Has remainding votes.
  7434. while (currentSum < targetSeats) {
  7435. // Find next largest remainder.
  7436. var max = Number.NEGATIVE_INFINITY;
  7437. var maxId = null;
  7438. for (var i = 0, len = remainder.length; i < len; ++i) {
  7439. if (remainder[i] > max) {
  7440. max = remainder[i];
  7441. maxId = i;
  7442. }
  7443. } // Add a vote to max remainder.
  7444. ++seats[maxId];
  7445. remainder[maxId] = 0;
  7446. ++currentSum;
  7447. }
  7448. return map(seats, function (seat) {
  7449. return seat / digits;
  7450. });
  7451. }
  7452. /**
  7453. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7454. * See <http://0.30000000000000004.com/>
  7455. */
  7456. function addSafe(val0, val1) {
  7457. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7458. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7459. var sum = val0 + val1; // // PENDING: support more?
  7460. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7461. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7462. var MAX_SAFE_INTEGER = 9007199254740991;
  7463. /**
  7464. * To 0 - 2 * PI, considering negative radian.
  7465. */
  7466. function remRadian(radian) {
  7467. var pi2 = Math.PI * 2;
  7468. return (radian % pi2 + pi2) % pi2;
  7469. }
  7470. /**
  7471. * @param {type} radian
  7472. * @return {boolean}
  7473. */
  7474. function isRadianAroundZero(val) {
  7475. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7476. } // eslint-disable-next-line
  7477. 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
  7478. /**
  7479. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7480. * These values can be accepted:
  7481. * + An instance of Date, represent a time in its own time zone.
  7482. * + Or string in a subset of ISO 8601, only including:
  7483. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7484. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7485. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7486. * all of which will be treated as local time if time zone is not specified
  7487. * (see <https://momentjs.com/>).
  7488. * + Or other string format, including (all of which will be treated as local time):
  7489. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7490. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7491. * + a timestamp, which represent a time in UTC.
  7492. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7493. */
  7494. function parseDate(value) {
  7495. if (value instanceof Date) {
  7496. return value;
  7497. } else if (isString(value)) {
  7498. // Different browsers parse date in different way, so we parse it manually.
  7499. // Some other issues:
  7500. // new Date('1970-01-01') is UTC,
  7501. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7502. // See issue #3623
  7503. var match = TIME_REG.exec(value);
  7504. if (!match) {
  7505. // return Invalid Date.
  7506. return new Date(NaN);
  7507. } // Use local time when no timezone offset is specified.
  7508. if (!match[8]) {
  7509. // match[n] can only be string or undefined.
  7510. // But take care of '12' + 1 => '121'.
  7511. 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);
  7512. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7513. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7514. // For example, system timezone is set as "Time Zone: America/Toronto",
  7515. // then these code will get different result:
  7516. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7517. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7518. // So we should not use `new Date`, but use `Date.UTC`.
  7519. else {
  7520. var hour = +match[4] || 0;
  7521. if (match[8].toUpperCase() !== 'Z') {
  7522. hour -= +match[8].slice(0, 3);
  7523. }
  7524. 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));
  7525. }
  7526. } else if (value == null) {
  7527. return new Date(NaN);
  7528. }
  7529. return new Date(Math.round(value));
  7530. }
  7531. /**
  7532. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7533. *
  7534. * @param val
  7535. * @return
  7536. */
  7537. function quantity(val) {
  7538. return Math.pow(10, quantityExponent(val));
  7539. }
  7540. /**
  7541. * Exponent of the quantity of a number
  7542. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7543. *
  7544. * @param val non-negative value
  7545. * @return
  7546. */
  7547. function quantityExponent(val) {
  7548. if (val === 0) {
  7549. return 0;
  7550. }
  7551. var exp = Math.floor(Math.log(val) / Math.LN10);
  7552. /**
  7553. * exp is expected to be the rounded-down result of the base-10 log of val.
  7554. * But due to the precision loss with Math.log(val), we need to restore it
  7555. * using 10^exp to make sure we can get val back from exp. #11249
  7556. */
  7557. if (val / Math.pow(10, exp) >= 10) {
  7558. exp++;
  7559. }
  7560. return exp;
  7561. }
  7562. /**
  7563. * find a “nice” number approximately equal to x. Round the number if round = true,
  7564. * take ceiling if round = false. The primary observation is that the “nicest”
  7565. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7566. *
  7567. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7568. *
  7569. * @param val Non-negative value.
  7570. * @param round
  7571. * @return Niced number
  7572. */
  7573. function nice(val, round) {
  7574. var exponent = quantityExponent(val);
  7575. var exp10 = Math.pow(10, exponent);
  7576. var f = val / exp10; // 1 <= f < 10
  7577. var nf;
  7578. if (round) {
  7579. if (f < 1.5) {
  7580. nf = 1;
  7581. } else if (f < 2.5) {
  7582. nf = 2;
  7583. } else if (f < 4) {
  7584. nf = 3;
  7585. } else if (f < 7) {
  7586. nf = 5;
  7587. } else {
  7588. nf = 10;
  7589. }
  7590. } else {
  7591. if (f < 1) {
  7592. nf = 1;
  7593. } else if (f < 2) {
  7594. nf = 2;
  7595. } else if (f < 3) {
  7596. nf = 3;
  7597. } else if (f < 5) {
  7598. nf = 5;
  7599. } else {
  7600. nf = 10;
  7601. }
  7602. }
  7603. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7604. // 20 is the uppper bound of toFixed.
  7605. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7606. }
  7607. /**
  7608. * This code was copied from "d3.js"
  7609. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7610. * See the license statement at the head of this file.
  7611. * @param ascArr
  7612. */
  7613. function quantile(ascArr, p) {
  7614. var H = (ascArr.length - 1) * p + 1;
  7615. var h = Math.floor(H);
  7616. var v = +ascArr[h - 1];
  7617. var e = H - h;
  7618. return e ? v + e * (ascArr[h] - v) : v;
  7619. }
  7620. /**
  7621. * Order intervals asc, and split them when overlap.
  7622. * expect(numberUtil.reformIntervals([
  7623. * {interval: [18, 62], close: [1, 1]},
  7624. * {interval: [-Infinity, -70], close: [0, 0]},
  7625. * {interval: [-70, -26], close: [1, 1]},
  7626. * {interval: [-26, 18], close: [1, 1]},
  7627. * {interval: [62, 150], close: [1, 1]},
  7628. * {interval: [106, 150], close: [1, 1]},
  7629. * {interval: [150, Infinity], close: [0, 0]}
  7630. * ])).toEqual([
  7631. * {interval: [-Infinity, -70], close: [0, 0]},
  7632. * {interval: [-70, -26], close: [1, 1]},
  7633. * {interval: [-26, 18], close: [0, 1]},
  7634. * {interval: [18, 62], close: [0, 1]},
  7635. * {interval: [62, 150], close: [0, 1]},
  7636. * {interval: [150, Infinity], close: [0, 0]}
  7637. * ]);
  7638. * @param list, where `close` mean open or close
  7639. * of the interval, and Infinity can be used.
  7640. * @return The origin list, which has been reformed.
  7641. */
  7642. function reformIntervals(list) {
  7643. list.sort(function (a, b) {
  7644. return littleThan(a, b, 0) ? -1 : 1;
  7645. });
  7646. var curr = -Infinity;
  7647. var currClose = 1;
  7648. for (var i = 0; i < list.length;) {
  7649. var interval = list[i].interval;
  7650. var close_1 = list[i].close;
  7651. for (var lg = 0; lg < 2; lg++) {
  7652. if (interval[lg] <= curr) {
  7653. interval[lg] = curr;
  7654. close_1[lg] = !lg ? 1 - currClose : 1;
  7655. }
  7656. curr = interval[lg];
  7657. currClose = close_1[lg];
  7658. }
  7659. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7660. list.splice(i, 1);
  7661. } else {
  7662. i++;
  7663. }
  7664. }
  7665. return list;
  7666. function littleThan(a, b, lg) {
  7667. 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));
  7668. }
  7669. }
  7670. /**
  7671. * [Numeric is defined as]:
  7672. * `parseFloat(val) == val`
  7673. * For example:
  7674. * numeric:
  7675. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7676. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7677. * not-numeric:
  7678. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7679. * empty string, string with only white-spaces or line-terminal (see es spec),
  7680. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7681. * non-string, ...
  7682. *
  7683. * @test See full test cases in `test/ut/spec/util/number.js`.
  7684. * @return Must be a typeof number. If not numeric, return NaN.
  7685. */
  7686. function numericToNumber(val) {
  7687. var valFloat = parseFloat(val);
  7688. return valFloat == val // eslint-disable-line eqeqeq
  7689. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7690. ? valFloat : NaN;
  7691. }
  7692. /**
  7693. * Definition of "numeric": see `numericToNumber`.
  7694. */
  7695. function isNumeric(val) {
  7696. return !isNaN(numericToNumber(val));
  7697. }
  7698. /**
  7699. * Use random base to prevent users hard code depending on
  7700. * this auto generated marker id.
  7701. * @return An positive integer.
  7702. */
  7703. function getRandomIdBase() {
  7704. return Math.round(Math.random() * 9);
  7705. }
  7706. /**
  7707. * Get the greatest common divisor.
  7708. *
  7709. * @param {number} a one number
  7710. * @param {number} b the other number
  7711. */
  7712. function getGreatestCommonDividor(a, b) {
  7713. if (b === 0) {
  7714. return a;
  7715. }
  7716. return getGreatestCommonDividor(b, a % b);
  7717. }
  7718. /**
  7719. * Get the least common multiple.
  7720. *
  7721. * @param {number} a one number
  7722. * @param {number} b the other number
  7723. */
  7724. function getLeastCommonMultiple(a, b) {
  7725. if (a == null) {
  7726. return b;
  7727. }
  7728. if (b == null) {
  7729. return a;
  7730. }
  7731. return a * b / getGreatestCommonDividor(a, b);
  7732. }
  7733. var ECHARTS_PREFIX = '[ECharts] ';
  7734. var storedLogs = {};
  7735. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7736. && console.warn && console.log;
  7737. function outputLog(type, str, onlyOnce) {
  7738. if (hasConsole) {
  7739. if (onlyOnce) {
  7740. if (storedLogs[str]) {
  7741. return;
  7742. }
  7743. storedLogs[str] = true;
  7744. } // eslint-disable-next-line
  7745. console[type](ECHARTS_PREFIX + str);
  7746. }
  7747. }
  7748. function log(str, onlyOnce) {
  7749. outputLog('log', str, onlyOnce);
  7750. }
  7751. function warn(str, onlyOnce) {
  7752. outputLog('warn', str, onlyOnce);
  7753. }
  7754. function error(str, onlyOnce) {
  7755. outputLog('error', str, onlyOnce);
  7756. }
  7757. function deprecateLog(str) {
  7758. if ("development" !== 'production') {
  7759. // Not display duplicate message.
  7760. outputLog('warn', 'DEPRECATED: ' + str, true);
  7761. }
  7762. }
  7763. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7764. if ("development" !== 'production') {
  7765. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7766. }
  7767. }
  7768. /**
  7769. * If in __DEV__ environment, get console printable message for users hint.
  7770. * Parameters are separated by ' '.
  7771. * @usage
  7772. * makePrintable('This is an error on', someVar, someObj);
  7773. *
  7774. * @param hintInfo anything about the current execution context to hint users.
  7775. * @throws Error
  7776. */
  7777. function makePrintable() {
  7778. var hintInfo = [];
  7779. for (var _i = 0; _i < arguments.length; _i++) {
  7780. hintInfo[_i] = arguments[_i];
  7781. }
  7782. var msg = '';
  7783. if ("development" !== 'production') {
  7784. // Fuzzy stringify for print.
  7785. // This code only exist in dev environment.
  7786. var makePrintableStringIfPossible_1 = function (val) {
  7787. 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;
  7788. };
  7789. msg = map(hintInfo, function (arg) {
  7790. if (isString(arg)) {
  7791. // Print without quotation mark for some statement.
  7792. return arg;
  7793. } else {
  7794. var printableStr = makePrintableStringIfPossible_1(arg);
  7795. if (printableStr != null) {
  7796. return printableStr;
  7797. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7798. try {
  7799. return JSON.stringify(arg, function (n, val) {
  7800. var printableStr = makePrintableStringIfPossible_1(val);
  7801. return printableStr == null ? val : printableStr;
  7802. }); // In most cases the info object is small, so do not line break.
  7803. } catch (err) {
  7804. return '?';
  7805. }
  7806. } else {
  7807. return '?';
  7808. }
  7809. }
  7810. }).join(' ');
  7811. }
  7812. return msg;
  7813. }
  7814. /**
  7815. * @throws Error
  7816. */
  7817. function throwError(msg) {
  7818. throw new Error(msg);
  7819. }
  7820. function interpolateNumber$1(p0, p1, percent) {
  7821. return (p1 - p0) * percent + p0;
  7822. }
  7823. /**
  7824. * Make the name displayable. But we should
  7825. * make sure it is not duplicated with user
  7826. * specified name, so use '\0';
  7827. */
  7828. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7829. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7830. /**
  7831. * If value is not array, then translate it to array.
  7832. * @param {*} value
  7833. * @return {Array} [value] or value
  7834. */
  7835. function normalizeToArray(value) {
  7836. return value instanceof Array ? value : value == null ? [] : [value];
  7837. }
  7838. /**
  7839. * Sync default option between normal and emphasis like `position` and `show`
  7840. * In case some one will write code like
  7841. * label: {
  7842. * show: false,
  7843. * position: 'outside',
  7844. * fontSize: 18
  7845. * },
  7846. * emphasis: {
  7847. * label: { show: true }
  7848. * }
  7849. */
  7850. function defaultEmphasis(opt, key, subOpts) {
  7851. // Caution: performance sensitive.
  7852. if (opt) {
  7853. opt[key] = opt[key] || {};
  7854. opt.emphasis = opt.emphasis || {};
  7855. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7856. for (var i = 0, len = subOpts.length; i < len; i++) {
  7857. var subOptName = subOpts[i];
  7858. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7859. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7860. }
  7861. }
  7862. }
  7863. }
  7864. 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']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7865. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7866. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7867. // // FIXME: deprecated, check and remove it.
  7868. // 'textStyle'
  7869. // ]);
  7870. /**
  7871. * The method does not ensure performance.
  7872. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7873. * This helper method retrieves value from data.
  7874. */
  7875. function getDataItemValue(dataItem) {
  7876. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7877. }
  7878. /**
  7879. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7880. * This helper method determine if dataItem has extra option besides value
  7881. */
  7882. function isDataItemOption(dataItem) {
  7883. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7884. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7885. }
  7886. /**
  7887. * Mapping to existings for merge.
  7888. *
  7889. * Mode "normalMege":
  7890. * The mapping result (merge result) will keep the order of the existing
  7891. * component, rather than the order of new option. Because we should ensure
  7892. * some specified index reference (like xAxisIndex) keep work.
  7893. * And in most cases, "merge option" is used to update partial option but not
  7894. * be expected to change the order.
  7895. *
  7896. * Mode "replaceMege":
  7897. * (1) Only the id mapped components will be merged.
  7898. * (2) Other existing components (except internal components) will be removed.
  7899. * (3) Other new options will be used to create new component.
  7900. * (4) The index of the existing components will not be modified.
  7901. * That means their might be "hole" after the removal.
  7902. * The new components are created first at those available index.
  7903. *
  7904. * Mode "replaceAll":
  7905. * This mode try to support that reproduce an echarts instance from another
  7906. * echarts instance (via `getOption`) in some simple cases.
  7907. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7908. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  7909. * the "hole" in `newCmptOptions` will also be kept.
  7910. * On the contrary, other modes try best to eliminate holes.
  7911. * PENDING: This is an experimental mode yet.
  7912. *
  7913. * @return See the comment of <MappingResult>.
  7914. */
  7915. function mappingToExists(existings, newCmptOptions, mode) {
  7916. var isNormalMergeMode = mode === 'normalMerge';
  7917. var isReplaceMergeMode = mode === 'replaceMerge';
  7918. var isReplaceAllMode = mode === 'replaceAll';
  7919. existings = existings || [];
  7920. newCmptOptions = (newCmptOptions || []).slice();
  7921. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7922. each(newCmptOptions, function (cmptOption, index) {
  7923. if (!isObject(cmptOption)) {
  7924. newCmptOptions[index] = null;
  7925. return;
  7926. }
  7927. if ("development" !== 'production') {
  7928. // There is some legacy case that name is set as `false`.
  7929. // But should work normally rather than throw error.
  7930. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7931. warnInvalidateIdOrName(cmptOption.id);
  7932. }
  7933. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7934. warnInvalidateIdOrName(cmptOption.name);
  7935. }
  7936. }
  7937. });
  7938. var result = prepareResult(existings, existingIdIdxMap, mode);
  7939. if (isNormalMergeMode || isReplaceMergeMode) {
  7940. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7941. }
  7942. if (isNormalMergeMode) {
  7943. mappingByName(result, newCmptOptions);
  7944. }
  7945. if (isNormalMergeMode || isReplaceMergeMode) {
  7946. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7947. } else if (isReplaceAllMode) {
  7948. mappingInReplaceAllMode(result, newCmptOptions);
  7949. }
  7950. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7951. // forEach will omit those items and result in incorrect result.
  7952. return result;
  7953. }
  7954. function prepareResult(existings, existingIdIdxMap, mode) {
  7955. var result = [];
  7956. if (mode === 'replaceAll') {
  7957. return result;
  7958. } // Do not use native `map` to in case that the array `existings`
  7959. // contains elided items, which will be omitted.
  7960. for (var index = 0; index < existings.length; index++) {
  7961. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7962. if (existing && existing.id != null) {
  7963. existingIdIdxMap.set(existing.id, index);
  7964. } // For non-internal-componnets:
  7965. // Mode "normalMerge": all existings kept.
  7966. // Mode "replaceMerge": all existing removed unless mapped by id.
  7967. // For internal-components:
  7968. // go with "replaceMerge" approach in both mode.
  7969. result.push({
  7970. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7971. newOption: null,
  7972. keyInfo: null,
  7973. brandNew: null
  7974. });
  7975. }
  7976. return result;
  7977. }
  7978. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7979. // Mapping by id if specified.
  7980. each(newCmptOptions, function (cmptOption, index) {
  7981. if (!cmptOption || cmptOption.id == null) {
  7982. return;
  7983. }
  7984. var optionId = makeComparableKey(cmptOption.id);
  7985. var existingIdx = existingIdIdxMap.get(optionId);
  7986. if (existingIdx != null) {
  7987. var resultItem = result[existingIdx];
  7988. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7989. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7990. // the existings rather than creating new component model.
  7991. resultItem.existing = existings[existingIdx];
  7992. newCmptOptions[index] = null;
  7993. }
  7994. });
  7995. }
  7996. function mappingByName(result, newCmptOptions) {
  7997. // Mapping by name if specified.
  7998. each(newCmptOptions, function (cmptOption, index) {
  7999. if (!cmptOption || cmptOption.name == null) {
  8000. return;
  8001. }
  8002. for (var i = 0; i < result.length; i++) {
  8003. var existing = result[i].existing;
  8004. if (!result[i].newOption // Consider name: two map to one.
  8005. // Can not match when both ids existing but different.
  8006. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8007. result[i].newOption = cmptOption;
  8008. newCmptOptions[index] = null;
  8009. return;
  8010. }
  8011. }
  8012. });
  8013. }
  8014. function mappingByIndex(result, newCmptOptions, brandNew) {
  8015. each(newCmptOptions, function (cmptOption) {
  8016. if (!cmptOption) {
  8017. return;
  8018. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  8019. var resultItem;
  8020. var nextIdx = 0;
  8021. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  8022. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  8023. // after mapping performed, model will always be assigned with an id if user not given.
  8024. // After that all models have id.
  8025. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8026. // not be merged to the existings with different id. Because id should not be overwritten.
  8027. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8028. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8029. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8030. nextIdx++;
  8031. }
  8032. if (resultItem) {
  8033. resultItem.newOption = cmptOption;
  8034. resultItem.brandNew = brandNew;
  8035. } else {
  8036. result.push({
  8037. newOption: cmptOption,
  8038. brandNew: brandNew,
  8039. existing: null,
  8040. keyInfo: null
  8041. });
  8042. }
  8043. nextIdx++;
  8044. });
  8045. }
  8046. function mappingInReplaceAllMode(result, newCmptOptions) {
  8047. each(newCmptOptions, function (cmptOption) {
  8048. // The feature "reproduce" requires "hole" will also reproduced
  8049. // in case that component index referring are broken.
  8050. result.push({
  8051. newOption: cmptOption,
  8052. brandNew: true,
  8053. existing: null,
  8054. keyInfo: null
  8055. });
  8056. });
  8057. }
  8058. /**
  8059. * Make id and name for mapping result (result of mappingToExists)
  8060. * into `keyInfo` field.
  8061. */
  8062. function makeIdAndName(mapResult) {
  8063. // We use this id to hash component models and view instances
  8064. // in echarts. id can be specified by user, or auto generated.
  8065. // The id generation rule ensures new view instance are able
  8066. // to mapped to old instance when setOption are called in
  8067. // no-merge mode. So we generate model id by name and plus
  8068. // type in view id.
  8069. // name can be duplicated among components, which is convenient
  8070. // to specify multi components (like series) by one name.
  8071. // Ensure that each id is distinct.
  8072. var idMap = createHashMap();
  8073. each(mapResult, function (item) {
  8074. var existing = item.existing;
  8075. existing && idMap.set(existing.id, item);
  8076. });
  8077. each(mapResult, function (item) {
  8078. var opt = item.newOption; // Force ensure id not duplicated.
  8079. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8080. opt && opt.id != null && idMap.set(opt.id, item);
  8081. !item.keyInfo && (item.keyInfo = {});
  8082. }); // Make name and id.
  8083. each(mapResult, function (item, index) {
  8084. var existing = item.existing;
  8085. var opt = item.newOption;
  8086. var keyInfo = item.keyInfo;
  8087. if (!isObject(opt)) {
  8088. return;
  8089. } // Name can be overwritten. Consider case: axis.name = '20km'.
  8090. // But id generated by name will not be changed, which affect
  8091. // only in that case: setOption with 'not merge mode' and view
  8092. // instance will be recreated, which can be accepted.
  8093. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid that different series has the same name,
  8094. // because name may be used like in color pallet.
  8095. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8096. if (existing) {
  8097. keyInfo.id = makeComparableKey(existing.id);
  8098. } else if (opt.id != null) {
  8099. keyInfo.id = makeComparableKey(opt.id);
  8100. } else {
  8101. // Consider this situatoin:
  8102. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8103. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8104. // Series with the same name between optionA and optionB
  8105. // should be mapped.
  8106. var idNum = 0;
  8107. do {
  8108. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8109. } while (idMap.get(keyInfo.id));
  8110. }
  8111. idMap.set(keyInfo.id, item);
  8112. });
  8113. }
  8114. function keyExistAndEqual(attr, obj1, obj2) {
  8115. var key1 = convertOptionIdName(obj1[attr], null);
  8116. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8117. return key1 != null && key2 != null && key1 === key2;
  8118. }
  8119. /**
  8120. * @return return null if not exist.
  8121. */
  8122. function makeComparableKey(val) {
  8123. if ("development" !== 'production') {
  8124. if (val == null) {
  8125. throw new Error();
  8126. }
  8127. }
  8128. return convertOptionIdName(val, '');
  8129. }
  8130. function convertOptionIdName(idOrName, defaultValue) {
  8131. if (idOrName == null) {
  8132. return defaultValue;
  8133. }
  8134. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8135. }
  8136. function warnInvalidateIdOrName(idOrName) {
  8137. if ("development" !== 'production') {
  8138. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8139. }
  8140. }
  8141. function isValidIdOrName(idOrName) {
  8142. return isStringSafe(idOrName) || isNumeric(idOrName);
  8143. }
  8144. function isNameSpecified(componentModel) {
  8145. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  8146. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8147. }
  8148. /**
  8149. * @public
  8150. * @param {Object} cmptOption
  8151. * @return {boolean}
  8152. */
  8153. function isComponentIdInternal(cmptOption) {
  8154. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8155. }
  8156. function makeInternalComponentId(idSuffix) {
  8157. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8158. }
  8159. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8160. // Set mainType and complete subType.
  8161. each(mappingResult, function (item) {
  8162. var newOption = item.newOption;
  8163. if (isObject(newOption)) {
  8164. item.keyInfo.mainType = mainType;
  8165. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8166. }
  8167. });
  8168. }
  8169. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8170. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  8171. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  8172. return subType;
  8173. }
  8174. /**
  8175. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8176. * each of which can be Array or primary type.
  8177. * @return dataIndex If not found, return undefined/null.
  8178. */
  8179. function queryDataIndex(data, payload) {
  8180. if (payload.dataIndexInside != null) {
  8181. return payload.dataIndexInside;
  8182. } else if (payload.dataIndex != null) {
  8183. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8184. return data.indexOfRawIndex(value);
  8185. }) : data.indexOfRawIndex(payload.dataIndex);
  8186. } else if (payload.name != null) {
  8187. return isArray(payload.name) ? map(payload.name, function (value) {
  8188. return data.indexOfName(value);
  8189. }) : data.indexOfName(payload.name);
  8190. }
  8191. }
  8192. /**
  8193. * Enable property storage to any host object.
  8194. * Notice: Serialization is not supported.
  8195. *
  8196. * For example:
  8197. * let inner = zrUitl.makeInner();
  8198. *
  8199. * function some1(hostObj) {
  8200. * inner(hostObj).someProperty = 1212;
  8201. * ...
  8202. * }
  8203. * function some2() {
  8204. * let fields = inner(this);
  8205. * fields.someProperty1 = 1212;
  8206. * fields.someProperty2 = 'xx';
  8207. * ...
  8208. * }
  8209. *
  8210. * @return {Function}
  8211. */
  8212. function makeInner() {
  8213. var key = '__ec_inner_' + innerUniqueIndex++;
  8214. return function (hostObj) {
  8215. return hostObj[key] || (hostObj[key] = {});
  8216. };
  8217. }
  8218. var innerUniqueIndex = getRandomIdBase();
  8219. /**
  8220. * The same behavior as `component.getReferringComponents`.
  8221. */
  8222. function parseFinder(ecModel, finderInput, opt) {
  8223. var _a = preParseFinder(finderInput, opt),
  8224. mainTypeSpecified = _a.mainTypeSpecified,
  8225. queryOptionMap = _a.queryOptionMap,
  8226. others = _a.others;
  8227. var result = others;
  8228. var defaultMainType = opt ? opt.defaultMainType : null;
  8229. if (!mainTypeSpecified && defaultMainType) {
  8230. queryOptionMap.set(defaultMainType, {});
  8231. }
  8232. queryOptionMap.each(function (queryOption, mainType) {
  8233. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8234. useDefault: defaultMainType === mainType,
  8235. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8236. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8237. });
  8238. result[mainType + 'Models'] = queryResult.models;
  8239. result[mainType + 'Model'] = queryResult.models[0];
  8240. });
  8241. return result;
  8242. }
  8243. function preParseFinder(finderInput, opt) {
  8244. var finder;
  8245. if (isString(finderInput)) {
  8246. var obj = {};
  8247. obj[finderInput + 'Index'] = 0;
  8248. finder = obj;
  8249. } else {
  8250. finder = finderInput;
  8251. }
  8252. var queryOptionMap = createHashMap();
  8253. var others = {};
  8254. var mainTypeSpecified = false;
  8255. each(finder, function (value, key) {
  8256. // Exclude 'dataIndex' and other illgal keys.
  8257. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8258. others[key] = value;
  8259. return;
  8260. }
  8261. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8262. var mainType = parsedKey[1];
  8263. var queryType = (parsedKey[2] || '').toLowerCase();
  8264. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8265. return;
  8266. }
  8267. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8268. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8269. queryOption[queryType] = value;
  8270. });
  8271. return {
  8272. mainTypeSpecified: mainTypeSpecified,
  8273. queryOptionMap: queryOptionMap,
  8274. others: others
  8275. };
  8276. }
  8277. var SINGLE_REFERRING = {
  8278. useDefault: true,
  8279. enableAll: false,
  8280. enableNone: false
  8281. };
  8282. var MULTIPLE_REFERRING = {
  8283. useDefault: false,
  8284. enableAll: true,
  8285. enableNone: true
  8286. };
  8287. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8288. opt = opt || SINGLE_REFERRING;
  8289. var indexOption = userOption.index;
  8290. var idOption = userOption.id;
  8291. var nameOption = userOption.name;
  8292. var result = {
  8293. models: null,
  8294. specified: indexOption != null || idOption != null || nameOption != null
  8295. };
  8296. if (!result.specified) {
  8297. // Use the first as default if `useDefault`.
  8298. var firstCmpt = void 0;
  8299. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8300. return result;
  8301. }
  8302. if (indexOption === 'none' || indexOption === false) {
  8303. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8304. result.models = [];
  8305. return result;
  8306. } // `queryComponents` will return all components if
  8307. // both all of index/id/name are null/undefined.
  8308. if (indexOption === 'all') {
  8309. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8310. indexOption = idOption = nameOption = null;
  8311. }
  8312. result.models = ecModel.queryComponents({
  8313. mainType: mainType,
  8314. index: indexOption,
  8315. id: idOption,
  8316. name: nameOption
  8317. });
  8318. return result;
  8319. }
  8320. function setAttribute(dom, key, value) {
  8321. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8322. }
  8323. function getAttribute(dom, key) {
  8324. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8325. }
  8326. function getTooltipRenderMode(renderModeOption) {
  8327. if (renderModeOption === 'auto') {
  8328. // Using html when `document` exists, use richText otherwise
  8329. return env.domSupported ? 'html' : 'richText';
  8330. } else {
  8331. return renderModeOption || 'html';
  8332. }
  8333. }
  8334. /**
  8335. * Interpolate raw values of a series with percent
  8336. *
  8337. * @param data data
  8338. * @param labelModel label model of the text element
  8339. * @param sourceValue start value. May be null/undefined when init.
  8340. * @param targetValue end value
  8341. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8342. * @return interpolated values
  8343. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8344. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8345. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8346. * Other cases do not supported.
  8347. */
  8348. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8349. var isAutoPrecision = precision == null || precision === 'auto';
  8350. if (targetValue == null) {
  8351. return targetValue;
  8352. }
  8353. if (isNumber(targetValue)) {
  8354. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8355. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8356. } else if (isString(targetValue)) {
  8357. return percent < 1 ? sourceValue : targetValue;
  8358. } else {
  8359. var interpolated = [];
  8360. var leftArr = sourceValue;
  8361. var rightArr = targetValue;
  8362. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8363. for (var i = 0; i < length_1; ++i) {
  8364. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8365. if (info && info.type === 'ordinal') {
  8366. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8367. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8368. } else {
  8369. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8370. var rightVal = rightArr[i];
  8371. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8372. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8373. }
  8374. }
  8375. return interpolated;
  8376. }
  8377. }
  8378. var TYPE_DELIMITER = '.';
  8379. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8380. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8381. /**
  8382. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8383. * @public
  8384. */
  8385. function parseClassType(componentType) {
  8386. var ret = {
  8387. main: '',
  8388. sub: ''
  8389. };
  8390. if (componentType) {
  8391. var typeArr = componentType.split(TYPE_DELIMITER);
  8392. ret.main = typeArr[0] || '';
  8393. ret.sub = typeArr[1] || '';
  8394. }
  8395. return ret;
  8396. }
  8397. /**
  8398. * @public
  8399. */
  8400. function checkClassType(componentType) {
  8401. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8402. }
  8403. function isExtendedClass(clz) {
  8404. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8405. }
  8406. /**
  8407. * Implements `ExtendableConstructor` for `rootClz`.
  8408. *
  8409. * @usage
  8410. * ```ts
  8411. * class Xxx {}
  8412. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8413. * enableClassExtend(Xxx as XxxConstructor);
  8414. * ```
  8415. */
  8416. function enableClassExtend(rootClz, mandatoryMethods) {
  8417. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8418. rootClz.extend = function (proto) {
  8419. if ("development" !== 'production') {
  8420. each(mandatoryMethods, function (method) {
  8421. if (!proto[method]) {
  8422. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8423. }
  8424. });
  8425. }
  8426. var superClass = this;
  8427. var ExtendedClass;
  8428. if (isESClass(superClass)) {
  8429. ExtendedClass =
  8430. /** @class */
  8431. function (_super) {
  8432. __extends(class_1, _super);
  8433. function class_1() {
  8434. return _super.apply(this, arguments) || this;
  8435. }
  8436. return class_1;
  8437. }(superClass);
  8438. } else {
  8439. // For backward compat, we both support ts class inheritance and this
  8440. // "extend" approach.
  8441. // The constructor should keep the same behavior as ts class inheritance:
  8442. // If this constructor/$constructor is not declared, auto invoke the super
  8443. // constructor.
  8444. // If this constructor/$constructor is declared, it is responsible for
  8445. // calling the super constructor.
  8446. ExtendedClass = function () {
  8447. (proto.$constructor || superClass).apply(this, arguments);
  8448. };
  8449. inherits(ExtendedClass, this);
  8450. }
  8451. extend(ExtendedClass.prototype, proto);
  8452. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8453. ExtendedClass.extend = this.extend;
  8454. ExtendedClass.superCall = superCall;
  8455. ExtendedClass.superApply = superApply;
  8456. ExtendedClass.superClass = superClass;
  8457. return ExtendedClass;
  8458. };
  8459. }
  8460. function isESClass(fn) {
  8461. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8462. }
  8463. /**
  8464. * A work around to both support ts extend and this extend mechanism.
  8465. * on sub-class.
  8466. * @usage
  8467. * ```ts
  8468. * class Component { ... }
  8469. * classUtil.enableClassExtend(Component);
  8470. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8471. *
  8472. * class Series extends Component { ... }
  8473. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8474. * Component.markExtend(Series);
  8475. * ```
  8476. */
  8477. function mountExtend(SubClz, SupperClz) {
  8478. SubClz.extend = SupperClz.extend;
  8479. } // A random offset.
  8480. var classBase = Math.round(Math.random() * 10);
  8481. /**
  8482. * Implements `CheckableConstructor` for `target`.
  8483. * Can not use instanceof, consider different scope by
  8484. * cross domain or es module import in ec extensions.
  8485. * Mount a method "isInstance()" to Clz.
  8486. *
  8487. * @usage
  8488. * ```ts
  8489. * class Xxx {}
  8490. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8491. * enableClassCheck(Xxx as XxxConstructor)
  8492. * ```
  8493. */
  8494. function enableClassCheck(target) {
  8495. var classAttr = ['__\0is_clz', classBase++].join('_');
  8496. target.prototype[classAttr] = true;
  8497. if ("development" !== 'production') {
  8498. assert(!target.isInstance, 'The method "is" can not be defined.');
  8499. }
  8500. target.isInstance = function (obj) {
  8501. return !!(obj && obj[classAttr]);
  8502. };
  8503. } // superCall should have class info, which can not be fetched from 'this'.
  8504. // Consider this case:
  8505. // class A has method f,
  8506. // class B inherits class A, overrides method f, f call superApply('f'),
  8507. // class C inherits class B, does not override method f,
  8508. // then when method of class C is called, dead loop occurred.
  8509. function superCall(context, methodName) {
  8510. var args = [];
  8511. for (var _i = 2; _i < arguments.length; _i++) {
  8512. args[_i - 2] = arguments[_i];
  8513. }
  8514. return this.superClass.prototype[methodName].apply(context, args);
  8515. }
  8516. function superApply(context, methodName, args) {
  8517. return this.superClass.prototype[methodName].apply(context, args);
  8518. }
  8519. /**
  8520. * Implements `ClassManager` for `target`
  8521. *
  8522. * @usage
  8523. * ```ts
  8524. * class Xxx {}
  8525. * type XxxConstructor = typeof Xxx & ClassManager
  8526. * enableClassManagement(Xxx as XxxConstructor);
  8527. * ```
  8528. */
  8529. function enableClassManagement(target) {
  8530. /**
  8531. * Component model classes
  8532. * key: componentType,
  8533. * value:
  8534. * componentClass, when componentType is 'a'
  8535. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8536. */
  8537. var storage = {};
  8538. target.registerClass = function (clz) {
  8539. // `type` should not be a "instance member".
  8540. // If using TS class, should better declared as `static type = 'series.pie'`.
  8541. // otherwise users have to mount `type` on prototype manually.
  8542. // For backward compat and enable instance visit type via `this.type`,
  8543. // we still support fetch `type` from prototype.
  8544. var componentFullType = clz.type || clz.prototype.type;
  8545. if (componentFullType) {
  8546. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8547. clz.prototype.type = componentFullType;
  8548. var componentTypeInfo = parseClassType(componentFullType);
  8549. if (!componentTypeInfo.sub) {
  8550. if ("development" !== 'production') {
  8551. if (storage[componentTypeInfo.main]) {
  8552. console.warn(componentTypeInfo.main + ' exists.');
  8553. }
  8554. }
  8555. storage[componentTypeInfo.main] = clz;
  8556. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8557. var container = makeContainer(componentTypeInfo);
  8558. container[componentTypeInfo.sub] = clz;
  8559. }
  8560. }
  8561. return clz;
  8562. };
  8563. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8564. var clz = storage[mainType];
  8565. if (clz && clz[IS_CONTAINER]) {
  8566. clz = subType ? clz[subType] : null;
  8567. }
  8568. if (throwWhenNotFound && !clz) {
  8569. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8570. }
  8571. return clz;
  8572. };
  8573. target.getClassesByMainType = function (componentType) {
  8574. var componentTypeInfo = parseClassType(componentType);
  8575. var result = [];
  8576. var obj = storage[componentTypeInfo.main];
  8577. if (obj && obj[IS_CONTAINER]) {
  8578. each(obj, function (o, type) {
  8579. type !== IS_CONTAINER && result.push(o);
  8580. });
  8581. } else {
  8582. result.push(obj);
  8583. }
  8584. return result;
  8585. };
  8586. target.hasClass = function (componentType) {
  8587. // Just consider componentType.main.
  8588. var componentTypeInfo = parseClassType(componentType);
  8589. return !!storage[componentTypeInfo.main];
  8590. };
  8591. /**
  8592. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8593. */
  8594. target.getAllClassMainTypes = function () {
  8595. var types = [];
  8596. each(storage, function (obj, type) {
  8597. types.push(type);
  8598. });
  8599. return types;
  8600. };
  8601. /**
  8602. * If a main type is container and has sub types
  8603. */
  8604. target.hasSubTypes = function (componentType) {
  8605. var componentTypeInfo = parseClassType(componentType);
  8606. var obj = storage[componentTypeInfo.main];
  8607. return obj && obj[IS_CONTAINER];
  8608. };
  8609. function makeContainer(componentTypeInfo) {
  8610. var container = storage[componentTypeInfo.main];
  8611. if (!container || !container[IS_CONTAINER]) {
  8612. container = storage[componentTypeInfo.main] = {};
  8613. container[IS_CONTAINER] = true;
  8614. }
  8615. return container;
  8616. }
  8617. } // /**
  8618. // * @param {string|Array.<string>} properties
  8619. // */
  8620. // export function setReadOnly(obj, properties) {
  8621. // FIXME It seems broken in IE8 simulation of IE11
  8622. // if (!zrUtil.isArray(properties)) {
  8623. // properties = properties != null ? [properties] : [];
  8624. // }
  8625. // zrUtil.each(properties, function (prop) {
  8626. // let value = obj[prop];
  8627. // Object.defineProperty
  8628. // && Object.defineProperty(obj, prop, {
  8629. // value: value, writable: false
  8630. // });
  8631. // zrUtil.isArray(obj[prop])
  8632. // && Object.freeze
  8633. // && Object.freeze(obj[prop]);
  8634. // });
  8635. // }
  8636. function makeStyleMapper(properties, ignoreParent) {
  8637. // Normalize
  8638. for (var i = 0; i < properties.length; i++) {
  8639. if (!properties[i][1]) {
  8640. properties[i][1] = properties[i][0];
  8641. }
  8642. }
  8643. ignoreParent = ignoreParent || false;
  8644. return function (model, excludes, includes) {
  8645. var style = {};
  8646. for (var i = 0; i < properties.length; i++) {
  8647. var propName = properties[i][1];
  8648. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8649. continue;
  8650. }
  8651. var val = model.getShallow(propName, ignoreParent);
  8652. if (val != null) {
  8653. style[properties[i][0]] = val;
  8654. }
  8655. } // TODO Text or image?
  8656. return style;
  8657. };
  8658. }
  8659. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8660. // So do not transfer decal directly.
  8661. ];
  8662. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8663. var AreaStyleMixin =
  8664. /** @class */
  8665. function () {
  8666. function AreaStyleMixin() {}
  8667. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8668. return getAreaStyle(this, excludes, includes);
  8669. };
  8670. return AreaStyleMixin;
  8671. }();
  8672. var globalImageCache = new LRU(50);
  8673. function findExistImage(newImageOrSrc) {
  8674. if (typeof newImageOrSrc === 'string') {
  8675. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8676. return cachedImgObj && cachedImgObj.image;
  8677. }
  8678. else {
  8679. return newImageOrSrc;
  8680. }
  8681. }
  8682. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8683. if (!newImageOrSrc) {
  8684. return image;
  8685. }
  8686. else if (typeof newImageOrSrc === 'string') {
  8687. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8688. return image;
  8689. }
  8690. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8691. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8692. if (cachedImgObj) {
  8693. image = cachedImgObj.image;
  8694. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8695. }
  8696. else {
  8697. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8698. image.__zrImageSrc = newImageOrSrc;
  8699. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8700. image: image,
  8701. pending: [pendingWrap]
  8702. });
  8703. }
  8704. return image;
  8705. }
  8706. else {
  8707. return newImageOrSrc;
  8708. }
  8709. }
  8710. function imageOnLoad() {
  8711. var cachedImgObj = this.__cachedImgObj;
  8712. this.onload = this.onerror = this.__cachedImgObj = null;
  8713. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8714. var pendingWrap = cachedImgObj.pending[i];
  8715. var cb = pendingWrap.cb;
  8716. cb && cb(this, pendingWrap.cbPayload);
  8717. pendingWrap.hostEl.dirty();
  8718. }
  8719. cachedImgObj.pending.length = 0;
  8720. }
  8721. function isImageReady(image) {
  8722. return image && image.width && image.height;
  8723. }
  8724. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8725. function truncateText(text, containerWidth, font, ellipsis, options) {
  8726. if (!containerWidth) {
  8727. return '';
  8728. }
  8729. var textLines = (text + '').split('\n');
  8730. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8731. for (var i = 0, len = textLines.length; i < len; i++) {
  8732. textLines[i] = truncateSingleLine(textLines[i], options);
  8733. }
  8734. return textLines.join('\n');
  8735. }
  8736. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8737. options = options || {};
  8738. var preparedOpts = extend({}, options);
  8739. preparedOpts.font = font;
  8740. ellipsis = retrieve2(ellipsis, '...');
  8741. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8742. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8743. preparedOpts.cnCharWidth = getWidth('国', font);
  8744. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8745. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8746. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8747. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8748. contentWidth -= ascCharWidth;
  8749. }
  8750. var ellipsisWidth = getWidth(ellipsis, font);
  8751. if (ellipsisWidth > contentWidth) {
  8752. ellipsis = '';
  8753. ellipsisWidth = 0;
  8754. }
  8755. contentWidth = containerWidth - ellipsisWidth;
  8756. preparedOpts.ellipsis = ellipsis;
  8757. preparedOpts.ellipsisWidth = ellipsisWidth;
  8758. preparedOpts.contentWidth = contentWidth;
  8759. preparedOpts.containerWidth = containerWidth;
  8760. return preparedOpts;
  8761. }
  8762. function truncateSingleLine(textLine, options) {
  8763. var containerWidth = options.containerWidth;
  8764. var font = options.font;
  8765. var contentWidth = options.contentWidth;
  8766. if (!containerWidth) {
  8767. return '';
  8768. }
  8769. var lineWidth = getWidth(textLine, font);
  8770. if (lineWidth <= containerWidth) {
  8771. return textLine;
  8772. }
  8773. for (var j = 0;; j++) {
  8774. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8775. textLine += options.ellipsis;
  8776. break;
  8777. }
  8778. var subLength = j === 0
  8779. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8780. : lineWidth > 0
  8781. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8782. : 0;
  8783. textLine = textLine.substr(0, subLength);
  8784. lineWidth = getWidth(textLine, font);
  8785. }
  8786. if (textLine === '') {
  8787. textLine = options.placeholder;
  8788. }
  8789. return textLine;
  8790. }
  8791. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8792. var width = 0;
  8793. var i = 0;
  8794. for (var len = text.length; i < len && width < contentWidth; i++) {
  8795. var charCode = text.charCodeAt(i);
  8796. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8797. }
  8798. return i;
  8799. }
  8800. function parsePlainText(text, style) {
  8801. text != null && (text += '');
  8802. var overflow = style.overflow;
  8803. var padding = style.padding;
  8804. var font = style.font;
  8805. var truncate = overflow === 'truncate';
  8806. var calculatedLineHeight = getLineHeight(font);
  8807. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8808. var bgColorDrawn = !!(style.backgroundColor);
  8809. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8810. var width = style.width;
  8811. var lines;
  8812. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8813. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8814. }
  8815. else {
  8816. lines = text ? text.split('\n') : [];
  8817. }
  8818. var contentHeight = lines.length * lineHeight;
  8819. var height = retrieve2(style.height, contentHeight);
  8820. if (contentHeight > height && truncateLineOverflow) {
  8821. var lineCount = Math.floor(height / lineHeight);
  8822. lines = lines.slice(0, lineCount);
  8823. }
  8824. if (text && truncate && width != null) {
  8825. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8826. minChar: style.truncateMinChar,
  8827. placeholder: style.placeholder
  8828. });
  8829. for (var i = 0; i < lines.length; i++) {
  8830. lines[i] = truncateSingleLine(lines[i], options);
  8831. }
  8832. }
  8833. var outerHeight = height;
  8834. var contentWidth = 0;
  8835. for (var i = 0; i < lines.length; i++) {
  8836. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8837. }
  8838. if (width == null) {
  8839. width = contentWidth;
  8840. }
  8841. var outerWidth = contentWidth;
  8842. if (padding) {
  8843. outerHeight += padding[0] + padding[2];
  8844. outerWidth += padding[1] + padding[3];
  8845. width += padding[1] + padding[3];
  8846. }
  8847. if (bgColorDrawn) {
  8848. outerWidth = width;
  8849. }
  8850. return {
  8851. lines: lines,
  8852. height: height,
  8853. outerWidth: outerWidth,
  8854. outerHeight: outerHeight,
  8855. lineHeight: lineHeight,
  8856. calculatedLineHeight: calculatedLineHeight,
  8857. contentWidth: contentWidth,
  8858. contentHeight: contentHeight,
  8859. width: width
  8860. };
  8861. }
  8862. var RichTextToken = (function () {
  8863. function RichTextToken() {
  8864. }
  8865. return RichTextToken;
  8866. }());
  8867. var RichTextLine = (function () {
  8868. function RichTextLine(tokens) {
  8869. this.tokens = [];
  8870. if (tokens) {
  8871. this.tokens = tokens;
  8872. }
  8873. }
  8874. return RichTextLine;
  8875. }());
  8876. var RichTextContentBlock = (function () {
  8877. function RichTextContentBlock() {
  8878. this.width = 0;
  8879. this.height = 0;
  8880. this.contentWidth = 0;
  8881. this.contentHeight = 0;
  8882. this.outerWidth = 0;
  8883. this.outerHeight = 0;
  8884. this.lines = [];
  8885. }
  8886. return RichTextContentBlock;
  8887. }());
  8888. function parseRichText(text, style) {
  8889. var contentBlock = new RichTextContentBlock();
  8890. text != null && (text += '');
  8891. if (!text) {
  8892. return contentBlock;
  8893. }
  8894. var topWidth = style.width;
  8895. var topHeight = style.height;
  8896. var overflow = style.overflow;
  8897. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8898. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8899. : null;
  8900. var lastIndex = STYLE_REG.lastIndex = 0;
  8901. var result;
  8902. while ((result = STYLE_REG.exec(text)) != null) {
  8903. var matchedIndex = result.index;
  8904. if (matchedIndex > lastIndex) {
  8905. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8906. }
  8907. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8908. lastIndex = STYLE_REG.lastIndex;
  8909. }
  8910. if (lastIndex < text.length) {
  8911. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8912. }
  8913. var pendingList = [];
  8914. var calculatedHeight = 0;
  8915. var calculatedWidth = 0;
  8916. var stlPadding = style.padding;
  8917. var truncate = overflow === 'truncate';
  8918. var truncateLine = style.lineOverflow === 'truncate';
  8919. function finishLine(line, lineWidth, lineHeight) {
  8920. line.width = lineWidth;
  8921. line.lineHeight = lineHeight;
  8922. calculatedHeight += lineHeight;
  8923. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8924. }
  8925. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8926. var line = contentBlock.lines[i];
  8927. var lineHeight = 0;
  8928. var lineWidth = 0;
  8929. for (var j = 0; j < line.tokens.length; j++) {
  8930. var token = line.tokens[j];
  8931. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8932. var textPadding = token.textPadding = tokenStyle.padding;
  8933. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8934. var font = token.font = tokenStyle.font || style.font;
  8935. token.contentHeight = getLineHeight(font);
  8936. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8937. token.innerHeight = tokenHeight;
  8938. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8939. token.height = tokenHeight;
  8940. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8941. token.align = tokenStyle && tokenStyle.align || style.align;
  8942. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8943. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8944. if (j > 0) {
  8945. line.tokens = line.tokens.slice(0, j);
  8946. finishLine(line, lineWidth, lineHeight);
  8947. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8948. }
  8949. else {
  8950. contentBlock.lines = contentBlock.lines.slice(0, i);
  8951. }
  8952. break outer;
  8953. }
  8954. var styleTokenWidth = tokenStyle.width;
  8955. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8956. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8957. token.percentWidth = styleTokenWidth;
  8958. pendingList.push(token);
  8959. token.contentWidth = getWidth(token.text, font);
  8960. }
  8961. else {
  8962. if (tokenWidthNotSpecified) {
  8963. var textBackgroundColor = tokenStyle.backgroundColor;
  8964. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8965. if (bgImg) {
  8966. bgImg = findExistImage(bgImg);
  8967. if (isImageReady(bgImg)) {
  8968. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8969. }
  8970. }
  8971. }
  8972. var remainTruncWidth = truncate && topWidth != null
  8973. ? topWidth - lineWidth : null;
  8974. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8975. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8976. token.text = '';
  8977. token.width = token.contentWidth = 0;
  8978. }
  8979. else {
  8980. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8981. token.width = token.contentWidth = getWidth(token.text, font);
  8982. }
  8983. }
  8984. else {
  8985. token.contentWidth = getWidth(token.text, font);
  8986. }
  8987. }
  8988. token.width += paddingH;
  8989. lineWidth += token.width;
  8990. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8991. }
  8992. finishLine(line, lineWidth, lineHeight);
  8993. }
  8994. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8995. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8996. contentBlock.contentHeight = calculatedHeight;
  8997. contentBlock.contentWidth = calculatedWidth;
  8998. if (stlPadding) {
  8999. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9000. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9001. }
  9002. for (var i = 0; i < pendingList.length; i++) {
  9003. var token = pendingList[i];
  9004. var percentWidth = token.percentWidth;
  9005. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9006. }
  9007. return contentBlock;
  9008. }
  9009. function pushTokens(block, str, style, wrapInfo, styleName) {
  9010. var isEmptyStr = str === '';
  9011. var tokenStyle = styleName && style.rich[styleName] || {};
  9012. var lines = block.lines;
  9013. var font = tokenStyle.font || style.font;
  9014. var newLine = false;
  9015. var strLines;
  9016. var linesWidths;
  9017. if (wrapInfo) {
  9018. var tokenPadding = tokenStyle.padding;
  9019. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9020. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9021. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9022. if (lines.length > 0) {
  9023. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9024. strLines = str.split('\n');
  9025. newLine = true;
  9026. }
  9027. }
  9028. wrapInfo.accumWidth = outerWidth_1;
  9029. }
  9030. else {
  9031. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9032. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9033. linesWidths = res.linesWidths;
  9034. strLines = res.lines;
  9035. }
  9036. }
  9037. else {
  9038. strLines = str.split('\n');
  9039. }
  9040. for (var i = 0; i < strLines.length; i++) {
  9041. var text = strLines[i];
  9042. var token = new RichTextToken();
  9043. token.styleName = styleName;
  9044. token.text = text;
  9045. token.isLineHolder = !text && !isEmptyStr;
  9046. if (typeof tokenStyle.width === 'number') {
  9047. token.width = tokenStyle.width;
  9048. }
  9049. else {
  9050. token.width = linesWidths
  9051. ? linesWidths[i]
  9052. : getWidth(text, font);
  9053. }
  9054. if (!i && !newLine) {
  9055. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9056. var tokensLen = tokens.length;
  9057. (tokensLen === 1 && tokens[0].isLineHolder)
  9058. ? (tokens[0] = token)
  9059. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9060. }
  9061. else {
  9062. lines.push(new RichTextLine([token]));
  9063. }
  9064. }
  9065. }
  9066. function isAlphabeticLetter(ch) {
  9067. var code = ch.charCodeAt(0);
  9068. return code >= 0x20 && code <= 0x24F
  9069. || code >= 0x370 && code <= 0x10FF
  9070. || code >= 0x1200 && code <= 0x13FF
  9071. || code >= 0x1E00 && code <= 0x206F;
  9072. }
  9073. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9074. obj[ch] = true;
  9075. return obj;
  9076. }, {});
  9077. function isWordBreakChar(ch) {
  9078. if (isAlphabeticLetter(ch)) {
  9079. if (breakCharMap[ch]) {
  9080. return true;
  9081. }
  9082. return false;
  9083. }
  9084. return true;
  9085. }
  9086. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9087. var lines = [];
  9088. var linesWidths = [];
  9089. var line = '';
  9090. var currentWord = '';
  9091. var currentWordWidth = 0;
  9092. var accumWidth = 0;
  9093. for (var i = 0; i < text.length; i++) {
  9094. var ch = text.charAt(i);
  9095. if (ch === '\n') {
  9096. if (currentWord) {
  9097. line += currentWord;
  9098. accumWidth += currentWordWidth;
  9099. }
  9100. lines.push(line);
  9101. linesWidths.push(accumWidth);
  9102. line = '';
  9103. currentWord = '';
  9104. currentWordWidth = 0;
  9105. accumWidth = 0;
  9106. continue;
  9107. }
  9108. var chWidth = getWidth(ch, font);
  9109. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9110. if (!lines.length
  9111. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9112. : accumWidth + chWidth > lineWidth) {
  9113. if (!accumWidth) {
  9114. if (inWord) {
  9115. lines.push(currentWord);
  9116. linesWidths.push(currentWordWidth);
  9117. currentWord = ch;
  9118. currentWordWidth = chWidth;
  9119. }
  9120. else {
  9121. lines.push(ch);
  9122. linesWidths.push(chWidth);
  9123. }
  9124. }
  9125. else if (line || currentWord) {
  9126. if (inWord) {
  9127. if (!line) {
  9128. line = currentWord;
  9129. currentWord = '';
  9130. currentWordWidth = 0;
  9131. accumWidth = currentWordWidth;
  9132. }
  9133. lines.push(line);
  9134. linesWidths.push(accumWidth - currentWordWidth);
  9135. currentWord += ch;
  9136. currentWordWidth += chWidth;
  9137. line = '';
  9138. accumWidth = currentWordWidth;
  9139. }
  9140. else {
  9141. if (currentWord) {
  9142. line += currentWord;
  9143. currentWord = '';
  9144. currentWordWidth = 0;
  9145. }
  9146. lines.push(line);
  9147. linesWidths.push(accumWidth);
  9148. line = ch;
  9149. accumWidth = chWidth;
  9150. }
  9151. }
  9152. continue;
  9153. }
  9154. accumWidth += chWidth;
  9155. if (inWord) {
  9156. currentWord += ch;
  9157. currentWordWidth += chWidth;
  9158. }
  9159. else {
  9160. if (currentWord) {
  9161. line += currentWord;
  9162. currentWord = '';
  9163. currentWordWidth = 0;
  9164. }
  9165. line += ch;
  9166. }
  9167. }
  9168. if (!lines.length && !line) {
  9169. line = text;
  9170. currentWord = '';
  9171. currentWordWidth = 0;
  9172. }
  9173. if (currentWord) {
  9174. line += currentWord;
  9175. }
  9176. if (line) {
  9177. lines.push(line);
  9178. linesWidths.push(accumWidth);
  9179. }
  9180. if (lines.length === 1) {
  9181. accumWidth += lastAccumWidth;
  9182. }
  9183. return {
  9184. accumWidth: accumWidth,
  9185. lines: lines,
  9186. linesWidths: linesWidths
  9187. };
  9188. }
  9189. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9190. var DEFAULT_COMMON_STYLE = {
  9191. shadowBlur: 0,
  9192. shadowOffsetX: 0,
  9193. shadowOffsetY: 0,
  9194. shadowColor: '#000',
  9195. opacity: 1,
  9196. blend: 'source-over'
  9197. };
  9198. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9199. style: {
  9200. shadowBlur: true,
  9201. shadowOffsetX: true,
  9202. shadowOffsetY: true,
  9203. shadowColor: true,
  9204. opacity: true
  9205. }
  9206. };
  9207. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9208. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9209. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9210. var Displayable = (function (_super) {
  9211. __extends(Displayable, _super);
  9212. function Displayable(props) {
  9213. return _super.call(this, props) || this;
  9214. }
  9215. Displayable.prototype._init = function (props) {
  9216. var keysArr = keys(props);
  9217. for (var i = 0; i < keysArr.length; i++) {
  9218. var key = keysArr[i];
  9219. if (key === 'style') {
  9220. this.useStyle(props[key]);
  9221. }
  9222. else {
  9223. _super.prototype.attrKV.call(this, key, props[key]);
  9224. }
  9225. }
  9226. if (!this.style) {
  9227. this.useStyle({});
  9228. }
  9229. };
  9230. Displayable.prototype.beforeBrush = function () { };
  9231. Displayable.prototype.afterBrush = function () { };
  9232. Displayable.prototype.innerBeforeBrush = function () { };
  9233. Displayable.prototype.innerAfterBrush = function () { };
  9234. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9235. var m = this.transform;
  9236. if (this.ignore
  9237. || this.invisible
  9238. || this.style.opacity === 0
  9239. || (this.culling
  9240. && isDisplayableCulled(this, viewWidth, viewHeight))
  9241. || (m && !m[0] && !m[3])) {
  9242. return false;
  9243. }
  9244. if (considerClipPath && this.__clipPaths) {
  9245. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9246. if (this.__clipPaths[i].isZeroArea()) {
  9247. return false;
  9248. }
  9249. }
  9250. }
  9251. if (considerAncestors && this.parent) {
  9252. var parent_1 = this.parent;
  9253. while (parent_1) {
  9254. if (parent_1.ignore) {
  9255. return false;
  9256. }
  9257. parent_1 = parent_1.parent;
  9258. }
  9259. }
  9260. return true;
  9261. };
  9262. Displayable.prototype.contain = function (x, y) {
  9263. return this.rectContain(x, y);
  9264. };
  9265. Displayable.prototype.traverse = function (cb, context) {
  9266. cb.call(context, this);
  9267. };
  9268. Displayable.prototype.rectContain = function (x, y) {
  9269. var coord = this.transformCoordToLocal(x, y);
  9270. var rect = this.getBoundingRect();
  9271. return rect.contain(coord[0], coord[1]);
  9272. };
  9273. Displayable.prototype.getPaintRect = function () {
  9274. var rect = this._paintRect;
  9275. if (!this._paintRect || this.__dirty) {
  9276. var transform = this.transform;
  9277. var elRect = this.getBoundingRect();
  9278. var style = this.style;
  9279. var shadowSize = style.shadowBlur || 0;
  9280. var shadowOffsetX = style.shadowOffsetX || 0;
  9281. var shadowOffsetY = style.shadowOffsetY || 0;
  9282. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9283. if (transform) {
  9284. BoundingRect.applyTransform(rect, elRect, transform);
  9285. }
  9286. else {
  9287. rect.copy(elRect);
  9288. }
  9289. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9290. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9291. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9292. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9293. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9294. }
  9295. var tolerance = this.dirtyRectTolerance;
  9296. if (!rect.isZero()) {
  9297. rect.x = Math.floor(rect.x - tolerance);
  9298. rect.y = Math.floor(rect.y - tolerance);
  9299. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9300. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9301. }
  9302. }
  9303. return rect;
  9304. };
  9305. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9306. if (paintRect) {
  9307. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9308. this._prevPaintRect.copy(paintRect);
  9309. }
  9310. else {
  9311. this._prevPaintRect = null;
  9312. }
  9313. };
  9314. Displayable.prototype.getPrevPaintRect = function () {
  9315. return this._prevPaintRect;
  9316. };
  9317. Displayable.prototype.animateStyle = function (loop) {
  9318. return this.animate('style', loop);
  9319. };
  9320. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9321. if (targetKey === 'style') {
  9322. this.dirtyStyle();
  9323. }
  9324. else {
  9325. this.markRedraw();
  9326. }
  9327. };
  9328. Displayable.prototype.attrKV = function (key, value) {
  9329. if (key !== 'style') {
  9330. _super.prototype.attrKV.call(this, key, value);
  9331. }
  9332. else {
  9333. if (!this.style) {
  9334. this.useStyle(value);
  9335. }
  9336. else {
  9337. this.setStyle(value);
  9338. }
  9339. }
  9340. };
  9341. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9342. if (typeof keyOrObj === 'string') {
  9343. this.style[keyOrObj] = value;
  9344. }
  9345. else {
  9346. extend(this.style, keyOrObj);
  9347. }
  9348. this.dirtyStyle();
  9349. return this;
  9350. };
  9351. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9352. if (!notRedraw) {
  9353. this.markRedraw();
  9354. }
  9355. this.__dirty |= STYLE_CHANGED_BIT;
  9356. if (this._rect) {
  9357. this._rect = null;
  9358. }
  9359. };
  9360. Displayable.prototype.dirty = function () {
  9361. this.dirtyStyle();
  9362. };
  9363. Displayable.prototype.styleChanged = function () {
  9364. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9365. };
  9366. Displayable.prototype.styleUpdated = function () {
  9367. this.__dirty &= ~STYLE_CHANGED_BIT;
  9368. };
  9369. Displayable.prototype.createStyle = function (obj) {
  9370. return createObject(DEFAULT_COMMON_STYLE, obj);
  9371. };
  9372. Displayable.prototype.useStyle = function (obj) {
  9373. if (!obj[STYLE_MAGIC_KEY]) {
  9374. obj = this.createStyle(obj);
  9375. }
  9376. if (this.__inHover) {
  9377. this.__hoverStyle = obj;
  9378. }
  9379. else {
  9380. this.style = obj;
  9381. }
  9382. this.dirtyStyle();
  9383. };
  9384. Displayable.prototype.isStyleObject = function (obj) {
  9385. return obj[STYLE_MAGIC_KEY];
  9386. };
  9387. Displayable.prototype._innerSaveToNormal = function (toState) {
  9388. _super.prototype._innerSaveToNormal.call(this, toState);
  9389. var normalState = this._normalState;
  9390. if (toState.style && !normalState.style) {
  9391. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9392. }
  9393. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9394. };
  9395. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9396. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9397. var needsRestoreToNormal = !(state && keepCurrentStates);
  9398. var targetStyle;
  9399. if (state && state.style) {
  9400. if (transition) {
  9401. if (keepCurrentStates) {
  9402. targetStyle = state.style;
  9403. }
  9404. else {
  9405. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9406. this._mergeStyle(targetStyle, state.style);
  9407. }
  9408. }
  9409. else {
  9410. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9411. this._mergeStyle(targetStyle, state.style);
  9412. }
  9413. }
  9414. else if (needsRestoreToNormal) {
  9415. targetStyle = normalState.style;
  9416. }
  9417. if (targetStyle) {
  9418. if (transition) {
  9419. var sourceStyle = this.style;
  9420. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9421. if (needsRestoreToNormal) {
  9422. var changedKeys = keys(sourceStyle);
  9423. for (var i = 0; i < changedKeys.length; i++) {
  9424. var key = changedKeys[i];
  9425. if (key in targetStyle) {
  9426. targetStyle[key] = targetStyle[key];
  9427. this.style[key] = sourceStyle[key];
  9428. }
  9429. }
  9430. }
  9431. var targetKeys = keys(targetStyle);
  9432. for (var i = 0; i < targetKeys.length; i++) {
  9433. var key = targetKeys[i];
  9434. this.style[key] = this.style[key];
  9435. }
  9436. this._transitionState(stateName, {
  9437. style: targetStyle
  9438. }, animationCfg, this.getAnimationStyleProps());
  9439. }
  9440. else {
  9441. this.useStyle(targetStyle);
  9442. }
  9443. }
  9444. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9445. for (var i = 0; i < statesKeys.length; i++) {
  9446. var key = statesKeys[i];
  9447. if (state && state[key] != null) {
  9448. this[key] = state[key];
  9449. }
  9450. else if (needsRestoreToNormal) {
  9451. if (normalState[key] != null) {
  9452. this[key] = normalState[key];
  9453. }
  9454. }
  9455. }
  9456. };
  9457. Displayable.prototype._mergeStates = function (states) {
  9458. var mergedState = _super.prototype._mergeStates.call(this, states);
  9459. var mergedStyle;
  9460. for (var i = 0; i < states.length; i++) {
  9461. var state = states[i];
  9462. if (state.style) {
  9463. mergedStyle = mergedStyle || {};
  9464. this._mergeStyle(mergedStyle, state.style);
  9465. }
  9466. }
  9467. if (mergedStyle) {
  9468. mergedState.style = mergedStyle;
  9469. }
  9470. return mergedState;
  9471. };
  9472. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9473. extend(targetStyle, sourceStyle);
  9474. return targetStyle;
  9475. };
  9476. Displayable.prototype.getAnimationStyleProps = function () {
  9477. return DEFAULT_COMMON_ANIMATION_PROPS;
  9478. };
  9479. Displayable.initDefaultProps = (function () {
  9480. var dispProto = Displayable.prototype;
  9481. dispProto.type = 'displayable';
  9482. dispProto.invisible = false;
  9483. dispProto.z = 0;
  9484. dispProto.z2 = 0;
  9485. dispProto.zlevel = 0;
  9486. dispProto.culling = false;
  9487. dispProto.cursor = 'pointer';
  9488. dispProto.rectHover = false;
  9489. dispProto.incremental = false;
  9490. dispProto._rect = null;
  9491. dispProto.dirtyRectTolerance = 0;
  9492. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9493. })();
  9494. return Displayable;
  9495. }(Element));
  9496. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9497. var viewRect = new BoundingRect(0, 0, 0, 0);
  9498. function isDisplayableCulled(el, width, height) {
  9499. tmpRect$1.copy(el.getBoundingRect());
  9500. if (el.transform) {
  9501. tmpRect$1.applyTransform(el.transform);
  9502. }
  9503. viewRect.width = width;
  9504. viewRect.height = height;
  9505. return !tmpRect$1.intersect(viewRect);
  9506. }
  9507. var mathMin$1 = Math.min;
  9508. var mathMax$1 = Math.max;
  9509. var mathSin = Math.sin;
  9510. var mathCos = Math.cos;
  9511. var PI2 = Math.PI * 2;
  9512. var start = create();
  9513. var end = create();
  9514. var extremity = create();
  9515. function fromLine(x0, y0, x1, y1, min, max) {
  9516. min[0] = mathMin$1(x0, x1);
  9517. min[1] = mathMin$1(y0, y1);
  9518. max[0] = mathMax$1(x0, x1);
  9519. max[1] = mathMax$1(y0, y1);
  9520. }
  9521. var xDim = [];
  9522. var yDim = [];
  9523. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9524. var cubicExtrema$1 = cubicExtrema;
  9525. var cubicAt$1 = cubicAt;
  9526. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9527. min[0] = Infinity;
  9528. min[1] = Infinity;
  9529. max[0] = -Infinity;
  9530. max[1] = -Infinity;
  9531. for (var i = 0; i < n; i++) {
  9532. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9533. min[0] = mathMin$1(x, min[0]);
  9534. max[0] = mathMax$1(x, max[0]);
  9535. }
  9536. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9537. for (var i = 0; i < n; i++) {
  9538. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9539. min[1] = mathMin$1(y, min[1]);
  9540. max[1] = mathMax$1(y, max[1]);
  9541. }
  9542. min[0] = mathMin$1(x0, min[0]);
  9543. max[0] = mathMax$1(x0, max[0]);
  9544. min[0] = mathMin$1(x3, min[0]);
  9545. max[0] = mathMax$1(x3, max[0]);
  9546. min[1] = mathMin$1(y0, min[1]);
  9547. max[1] = mathMax$1(y0, max[1]);
  9548. min[1] = mathMin$1(y3, min[1]);
  9549. max[1] = mathMax$1(y3, max[1]);
  9550. }
  9551. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9552. var quadraticExtremum$1 = quadraticExtremum;
  9553. var quadraticAt$1 = quadraticAt;
  9554. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9555. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9556. var x = quadraticAt$1(x0, x1, x2, tx);
  9557. var y = quadraticAt$1(y0, y1, y2, ty);
  9558. min[0] = mathMin$1(x0, x2, x);
  9559. min[1] = mathMin$1(y0, y2, y);
  9560. max[0] = mathMax$1(x0, x2, x);
  9561. max[1] = mathMax$1(y0, y2, y);
  9562. }
  9563. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9564. var vec2Min = min;
  9565. var vec2Max = max;
  9566. var diff = Math.abs(startAngle - endAngle);
  9567. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9568. min$1[0] = x - rx;
  9569. min$1[1] = y - ry;
  9570. max$1[0] = x + rx;
  9571. max$1[1] = y + ry;
  9572. return;
  9573. }
  9574. start[0] = mathCos(startAngle) * rx + x;
  9575. start[1] = mathSin(startAngle) * ry + y;
  9576. end[0] = mathCos(endAngle) * rx + x;
  9577. end[1] = mathSin(endAngle) * ry + y;
  9578. vec2Min(min$1, start, end);
  9579. vec2Max(max$1, start, end);
  9580. startAngle = startAngle % (PI2);
  9581. if (startAngle < 0) {
  9582. startAngle = startAngle + PI2;
  9583. }
  9584. endAngle = endAngle % (PI2);
  9585. if (endAngle < 0) {
  9586. endAngle = endAngle + PI2;
  9587. }
  9588. if (startAngle > endAngle && !anticlockwise) {
  9589. endAngle += PI2;
  9590. }
  9591. else if (startAngle < endAngle && anticlockwise) {
  9592. startAngle += PI2;
  9593. }
  9594. if (anticlockwise) {
  9595. var tmp = endAngle;
  9596. endAngle = startAngle;
  9597. startAngle = tmp;
  9598. }
  9599. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9600. if (angle > startAngle) {
  9601. extremity[0] = mathCos(angle) * rx + x;
  9602. extremity[1] = mathSin(angle) * ry + y;
  9603. vec2Min(min$1, extremity, min$1);
  9604. vec2Max(max$1, extremity, max$1);
  9605. }
  9606. }
  9607. }
  9608. var CMD = {
  9609. M: 1,
  9610. L: 2,
  9611. C: 3,
  9612. Q: 4,
  9613. A: 5,
  9614. Z: 6,
  9615. R: 7
  9616. };
  9617. var tmpOutX = [];
  9618. var tmpOutY = [];
  9619. var min$1 = [];
  9620. var max$1 = [];
  9621. var min2 = [];
  9622. var max2 = [];
  9623. var mathMin$2 = Math.min;
  9624. var mathMax$2 = Math.max;
  9625. var mathCos$1 = Math.cos;
  9626. var mathSin$1 = Math.sin;
  9627. var mathAbs = Math.abs;
  9628. var PI = Math.PI;
  9629. var PI2$1 = PI * 2;
  9630. var hasTypedArray = typeof Float32Array !== 'undefined';
  9631. var tmpAngles = [];
  9632. function modPI2(radian) {
  9633. var n = Math.round(radian / PI * 1e8) / 1e8;
  9634. return (n % 2) * PI;
  9635. }
  9636. function normalizeArcAngles(angles, anticlockwise) {
  9637. var newStartAngle = modPI2(angles[0]);
  9638. if (newStartAngle < 0) {
  9639. newStartAngle += PI2$1;
  9640. }
  9641. var delta = newStartAngle - angles[0];
  9642. var newEndAngle = angles[1];
  9643. newEndAngle += delta;
  9644. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9645. newEndAngle = newStartAngle + PI2$1;
  9646. }
  9647. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9648. newEndAngle = newStartAngle - PI2$1;
  9649. }
  9650. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9651. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9652. }
  9653. else if (anticlockwise && newStartAngle < newEndAngle) {
  9654. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9655. }
  9656. angles[0] = newStartAngle;
  9657. angles[1] = newEndAngle;
  9658. }
  9659. var PathProxy = (function () {
  9660. function PathProxy(notSaveData) {
  9661. this.dpr = 1;
  9662. this._xi = 0;
  9663. this._yi = 0;
  9664. this._x0 = 0;
  9665. this._y0 = 0;
  9666. this._len = 0;
  9667. if (notSaveData) {
  9668. this._saveData = false;
  9669. }
  9670. if (this._saveData) {
  9671. this.data = [];
  9672. }
  9673. }
  9674. PathProxy.prototype.increaseVersion = function () {
  9675. this._version++;
  9676. };
  9677. PathProxy.prototype.getVersion = function () {
  9678. return this._version;
  9679. };
  9680. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9681. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9682. if (segmentIgnoreThreshold > 0) {
  9683. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9684. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9685. }
  9686. };
  9687. PathProxy.prototype.setDPR = function (dpr) {
  9688. this.dpr = dpr;
  9689. };
  9690. PathProxy.prototype.setContext = function (ctx) {
  9691. this._ctx = ctx;
  9692. };
  9693. PathProxy.prototype.getContext = function () {
  9694. return this._ctx;
  9695. };
  9696. PathProxy.prototype.beginPath = function () {
  9697. this._ctx && this._ctx.beginPath();
  9698. this.reset();
  9699. return this;
  9700. };
  9701. PathProxy.prototype.reset = function () {
  9702. if (this._saveData) {
  9703. this._len = 0;
  9704. }
  9705. if (this._pathSegLen) {
  9706. this._pathSegLen = null;
  9707. this._pathLen = 0;
  9708. }
  9709. this._version++;
  9710. };
  9711. PathProxy.prototype.moveTo = function (x, y) {
  9712. this._drawPendingPt();
  9713. this.addData(CMD.M, x, y);
  9714. this._ctx && this._ctx.moveTo(x, y);
  9715. this._x0 = x;
  9716. this._y0 = y;
  9717. this._xi = x;
  9718. this._yi = y;
  9719. return this;
  9720. };
  9721. PathProxy.prototype.lineTo = function (x, y) {
  9722. var dx = mathAbs(x - this._xi);
  9723. var dy = mathAbs(y - this._yi);
  9724. var exceedUnit = dx > this._ux || dy > this._uy;
  9725. this.addData(CMD.L, x, y);
  9726. if (this._ctx && exceedUnit) {
  9727. this._ctx.lineTo(x, y);
  9728. }
  9729. if (exceedUnit) {
  9730. this._xi = x;
  9731. this._yi = y;
  9732. this._pendingPtDist = 0;
  9733. }
  9734. else {
  9735. var d2 = dx * dx + dy * dy;
  9736. if (d2 > this._pendingPtDist) {
  9737. this._pendingPtX = x;
  9738. this._pendingPtY = y;
  9739. this._pendingPtDist = d2;
  9740. }
  9741. }
  9742. return this;
  9743. };
  9744. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9745. this._drawPendingPt();
  9746. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9747. if (this._ctx) {
  9748. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9749. }
  9750. this._xi = x3;
  9751. this._yi = y3;
  9752. return this;
  9753. };
  9754. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9755. this._drawPendingPt();
  9756. this.addData(CMD.Q, x1, y1, x2, y2);
  9757. if (this._ctx) {
  9758. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9759. }
  9760. this._xi = x2;
  9761. this._yi = y2;
  9762. return this;
  9763. };
  9764. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9765. this._drawPendingPt();
  9766. tmpAngles[0] = startAngle;
  9767. tmpAngles[1] = endAngle;
  9768. normalizeArcAngles(tmpAngles, anticlockwise);
  9769. startAngle = tmpAngles[0];
  9770. endAngle = tmpAngles[1];
  9771. var delta = endAngle - startAngle;
  9772. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9773. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9774. this._xi = mathCos$1(endAngle) * r + cx;
  9775. this._yi = mathSin$1(endAngle) * r + cy;
  9776. return this;
  9777. };
  9778. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9779. this._drawPendingPt();
  9780. if (this._ctx) {
  9781. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9782. }
  9783. return this;
  9784. };
  9785. PathProxy.prototype.rect = function (x, y, w, h) {
  9786. this._drawPendingPt();
  9787. this._ctx && this._ctx.rect(x, y, w, h);
  9788. this.addData(CMD.R, x, y, w, h);
  9789. return this;
  9790. };
  9791. PathProxy.prototype.closePath = function () {
  9792. this._drawPendingPt();
  9793. this.addData(CMD.Z);
  9794. var ctx = this._ctx;
  9795. var x0 = this._x0;
  9796. var y0 = this._y0;
  9797. if (ctx) {
  9798. ctx.closePath();
  9799. }
  9800. this._xi = x0;
  9801. this._yi = y0;
  9802. return this;
  9803. };
  9804. PathProxy.prototype.fill = function (ctx) {
  9805. ctx && ctx.fill();
  9806. this.toStatic();
  9807. };
  9808. PathProxy.prototype.stroke = function (ctx) {
  9809. ctx && ctx.stroke();
  9810. this.toStatic();
  9811. };
  9812. PathProxy.prototype.len = function () {
  9813. return this._len;
  9814. };
  9815. PathProxy.prototype.setData = function (data) {
  9816. var len = data.length;
  9817. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9818. this.data = new Float32Array(len);
  9819. }
  9820. for (var i = 0; i < len; i++) {
  9821. this.data[i] = data[i];
  9822. }
  9823. this._len = len;
  9824. };
  9825. PathProxy.prototype.appendPath = function (path) {
  9826. if (!(path instanceof Array)) {
  9827. path = [path];
  9828. }
  9829. var len = path.length;
  9830. var appendSize = 0;
  9831. var offset = this._len;
  9832. for (var i = 0; i < len; i++) {
  9833. appendSize += path[i].len();
  9834. }
  9835. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9836. this.data = new Float32Array(offset + appendSize);
  9837. }
  9838. for (var i = 0; i < len; i++) {
  9839. var appendPathData = path[i].data;
  9840. for (var k = 0; k < appendPathData.length; k++) {
  9841. this.data[offset++] = appendPathData[k];
  9842. }
  9843. }
  9844. this._len = offset;
  9845. };
  9846. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9847. if (!this._saveData) {
  9848. return;
  9849. }
  9850. var data = this.data;
  9851. if (this._len + arguments.length > data.length) {
  9852. this._expandData();
  9853. data = this.data;
  9854. }
  9855. for (var i = 0; i < arguments.length; i++) {
  9856. data[this._len++] = arguments[i];
  9857. }
  9858. };
  9859. PathProxy.prototype._drawPendingPt = function () {
  9860. if (this._pendingPtDist > 0) {
  9861. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9862. this._pendingPtDist = 0;
  9863. }
  9864. };
  9865. PathProxy.prototype._expandData = function () {
  9866. if (!(this.data instanceof Array)) {
  9867. var newData = [];
  9868. for (var i = 0; i < this._len; i++) {
  9869. newData[i] = this.data[i];
  9870. }
  9871. this.data = newData;
  9872. }
  9873. };
  9874. PathProxy.prototype.toStatic = function () {
  9875. if (!this._saveData) {
  9876. return;
  9877. }
  9878. this._drawPendingPt();
  9879. var data = this.data;
  9880. if (data instanceof Array) {
  9881. data.length = this._len;
  9882. if (hasTypedArray && this._len > 11) {
  9883. this.data = new Float32Array(data);
  9884. }
  9885. }
  9886. };
  9887. PathProxy.prototype.getBoundingRect = function () {
  9888. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9889. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9890. var data = this.data;
  9891. var xi = 0;
  9892. var yi = 0;
  9893. var x0 = 0;
  9894. var y0 = 0;
  9895. var i;
  9896. for (i = 0; i < this._len;) {
  9897. var cmd = data[i++];
  9898. var isFirst = i === 1;
  9899. if (isFirst) {
  9900. xi = data[i];
  9901. yi = data[i + 1];
  9902. x0 = xi;
  9903. y0 = yi;
  9904. }
  9905. switch (cmd) {
  9906. case CMD.M:
  9907. xi = x0 = data[i++];
  9908. yi = y0 = data[i++];
  9909. min2[0] = x0;
  9910. min2[1] = y0;
  9911. max2[0] = x0;
  9912. max2[1] = y0;
  9913. break;
  9914. case CMD.L:
  9915. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9916. xi = data[i++];
  9917. yi = data[i++];
  9918. break;
  9919. case CMD.C:
  9920. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9921. xi = data[i++];
  9922. yi = data[i++];
  9923. break;
  9924. case CMD.Q:
  9925. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9926. xi = data[i++];
  9927. yi = data[i++];
  9928. break;
  9929. case CMD.A:
  9930. var cx = data[i++];
  9931. var cy = data[i++];
  9932. var rx = data[i++];
  9933. var ry = data[i++];
  9934. var startAngle = data[i++];
  9935. var endAngle = data[i++] + startAngle;
  9936. i += 1;
  9937. var anticlockwise = !data[i++];
  9938. if (isFirst) {
  9939. x0 = mathCos$1(startAngle) * rx + cx;
  9940. y0 = mathSin$1(startAngle) * ry + cy;
  9941. }
  9942. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9943. xi = mathCos$1(endAngle) * rx + cx;
  9944. yi = mathSin$1(endAngle) * ry + cy;
  9945. break;
  9946. case CMD.R:
  9947. x0 = xi = data[i++];
  9948. y0 = yi = data[i++];
  9949. var width = data[i++];
  9950. var height = data[i++];
  9951. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9952. break;
  9953. case CMD.Z:
  9954. xi = x0;
  9955. yi = y0;
  9956. break;
  9957. }
  9958. min(min$1, min$1, min2);
  9959. max(max$1, max$1, max2);
  9960. }
  9961. if (i === 0) {
  9962. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9963. }
  9964. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9965. };
  9966. PathProxy.prototype._calculateLength = function () {
  9967. var data = this.data;
  9968. var len = this._len;
  9969. var ux = this._ux;
  9970. var uy = this._uy;
  9971. var xi = 0;
  9972. var yi = 0;
  9973. var x0 = 0;
  9974. var y0 = 0;
  9975. if (!this._pathSegLen) {
  9976. this._pathSegLen = [];
  9977. }
  9978. var pathSegLen = this._pathSegLen;
  9979. var pathTotalLen = 0;
  9980. var segCount = 0;
  9981. for (var i = 0; i < len;) {
  9982. var cmd = data[i++];
  9983. var isFirst = i === 1;
  9984. if (isFirst) {
  9985. xi = data[i];
  9986. yi = data[i + 1];
  9987. x0 = xi;
  9988. y0 = yi;
  9989. }
  9990. var l = -1;
  9991. switch (cmd) {
  9992. case CMD.M:
  9993. xi = x0 = data[i++];
  9994. yi = y0 = data[i++];
  9995. break;
  9996. case CMD.L: {
  9997. var x2 = data[i++];
  9998. var y2 = data[i++];
  9999. var dx = x2 - xi;
  10000. var dy = y2 - yi;
  10001. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10002. l = Math.sqrt(dx * dx + dy * dy);
  10003. xi = x2;
  10004. yi = y2;
  10005. }
  10006. break;
  10007. }
  10008. case CMD.C: {
  10009. var x1 = data[i++];
  10010. var y1 = data[i++];
  10011. var x2 = data[i++];
  10012. var y2 = data[i++];
  10013. var x3 = data[i++];
  10014. var y3 = data[i++];
  10015. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10016. xi = x3;
  10017. yi = y3;
  10018. break;
  10019. }
  10020. case CMD.Q: {
  10021. var x1 = data[i++];
  10022. var y1 = data[i++];
  10023. var x2 = data[i++];
  10024. var y2 = data[i++];
  10025. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10026. xi = x2;
  10027. yi = y2;
  10028. break;
  10029. }
  10030. case CMD.A:
  10031. var cx = data[i++];
  10032. var cy = data[i++];
  10033. var rx = data[i++];
  10034. var ry = data[i++];
  10035. var startAngle = data[i++];
  10036. var delta = data[i++];
  10037. var endAngle = delta + startAngle;
  10038. i += 1;
  10039. var anticlockwise = !data[i++];
  10040. if (isFirst) {
  10041. x0 = mathCos$1(startAngle) * rx + cx;
  10042. y0 = mathSin$1(startAngle) * ry + cy;
  10043. }
  10044. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10045. xi = mathCos$1(endAngle) * rx + cx;
  10046. yi = mathSin$1(endAngle) * ry + cy;
  10047. break;
  10048. case CMD.R: {
  10049. x0 = xi = data[i++];
  10050. y0 = yi = data[i++];
  10051. var width = data[i++];
  10052. var height = data[i++];
  10053. l = width * 2 + height * 2;
  10054. break;
  10055. }
  10056. case CMD.Z: {
  10057. var dx = x0 - xi;
  10058. var dy = y0 - yi;
  10059. l = Math.sqrt(dx * dx + dy * dy);
  10060. xi = x0;
  10061. yi = y0;
  10062. break;
  10063. }
  10064. }
  10065. if (l >= 0) {
  10066. pathSegLen[segCount++] = l;
  10067. pathTotalLen += l;
  10068. }
  10069. }
  10070. this._pathLen = pathTotalLen;
  10071. return pathTotalLen;
  10072. };
  10073. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10074. var d = this.data;
  10075. var ux = this._ux;
  10076. var uy = this._uy;
  10077. var len = this._len;
  10078. var x0;
  10079. var y0;
  10080. var xi;
  10081. var yi;
  10082. var x;
  10083. var y;
  10084. var drawPart = percent < 1;
  10085. var pathSegLen;
  10086. var pathTotalLen;
  10087. var accumLength = 0;
  10088. var segCount = 0;
  10089. var displayedLength;
  10090. var pendingPtDist = 0;
  10091. var pendingPtX;
  10092. var pendingPtY;
  10093. if (drawPart) {
  10094. if (!this._pathSegLen) {
  10095. this._calculateLength();
  10096. }
  10097. pathSegLen = this._pathSegLen;
  10098. pathTotalLen = this._pathLen;
  10099. displayedLength = percent * pathTotalLen;
  10100. if (!displayedLength) {
  10101. return;
  10102. }
  10103. }
  10104. lo: for (var i = 0; i < len;) {
  10105. var cmd = d[i++];
  10106. var isFirst = i === 1;
  10107. if (isFirst) {
  10108. xi = d[i];
  10109. yi = d[i + 1];
  10110. x0 = xi;
  10111. y0 = yi;
  10112. }
  10113. if (cmd !== CMD.L && pendingPtDist > 0) {
  10114. ctx.lineTo(pendingPtX, pendingPtY);
  10115. pendingPtDist = 0;
  10116. }
  10117. switch (cmd) {
  10118. case CMD.M:
  10119. x0 = xi = d[i++];
  10120. y0 = yi = d[i++];
  10121. ctx.moveTo(xi, yi);
  10122. break;
  10123. case CMD.L: {
  10124. x = d[i++];
  10125. y = d[i++];
  10126. var dx = mathAbs(x - xi);
  10127. var dy = mathAbs(y - yi);
  10128. if (dx > ux || dy > uy) {
  10129. if (drawPart) {
  10130. var l = pathSegLen[segCount++];
  10131. if (accumLength + l > displayedLength) {
  10132. var t = (displayedLength - accumLength) / l;
  10133. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10134. break lo;
  10135. }
  10136. accumLength += l;
  10137. }
  10138. ctx.lineTo(x, y);
  10139. xi = x;
  10140. yi = y;
  10141. pendingPtDist = 0;
  10142. }
  10143. else {
  10144. var d2 = dx * dx + dy * dy;
  10145. if (d2 > pendingPtDist) {
  10146. pendingPtX = x;
  10147. pendingPtY = y;
  10148. pendingPtDist = d2;
  10149. }
  10150. }
  10151. break;
  10152. }
  10153. case CMD.C: {
  10154. var x1 = d[i++];
  10155. var y1 = d[i++];
  10156. var x2 = d[i++];
  10157. var y2 = d[i++];
  10158. var x3 = d[i++];
  10159. var y3 = d[i++];
  10160. if (drawPart) {
  10161. var l = pathSegLen[segCount++];
  10162. if (accumLength + l > displayedLength) {
  10163. var t = (displayedLength - accumLength) / l;
  10164. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10165. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10166. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10167. break lo;
  10168. }
  10169. accumLength += l;
  10170. }
  10171. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10172. xi = x3;
  10173. yi = y3;
  10174. break;
  10175. }
  10176. case CMD.Q: {
  10177. var x1 = d[i++];
  10178. var y1 = d[i++];
  10179. var x2 = d[i++];
  10180. var y2 = d[i++];
  10181. if (drawPart) {
  10182. var l = pathSegLen[segCount++];
  10183. if (accumLength + l > displayedLength) {
  10184. var t = (displayedLength - accumLength) / l;
  10185. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10186. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10187. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10188. break lo;
  10189. }
  10190. accumLength += l;
  10191. }
  10192. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10193. xi = x2;
  10194. yi = y2;
  10195. break;
  10196. }
  10197. case CMD.A:
  10198. var cx = d[i++];
  10199. var cy = d[i++];
  10200. var rx = d[i++];
  10201. var ry = d[i++];
  10202. var startAngle = d[i++];
  10203. var delta = d[i++];
  10204. var psi = d[i++];
  10205. var anticlockwise = !d[i++];
  10206. var r = (rx > ry) ? rx : ry;
  10207. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10208. var endAngle = startAngle + delta;
  10209. var breakBuild = false;
  10210. if (drawPart) {
  10211. var l = pathSegLen[segCount++];
  10212. if (accumLength + l > displayedLength) {
  10213. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10214. breakBuild = true;
  10215. }
  10216. accumLength += l;
  10217. }
  10218. if (isEllipse && ctx.ellipse) {
  10219. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10220. }
  10221. else {
  10222. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10223. }
  10224. if (breakBuild) {
  10225. break lo;
  10226. }
  10227. if (isFirst) {
  10228. x0 = mathCos$1(startAngle) * rx + cx;
  10229. y0 = mathSin$1(startAngle) * ry + cy;
  10230. }
  10231. xi = mathCos$1(endAngle) * rx + cx;
  10232. yi = mathSin$1(endAngle) * ry + cy;
  10233. break;
  10234. case CMD.R:
  10235. x0 = xi = d[i];
  10236. y0 = yi = d[i + 1];
  10237. x = d[i++];
  10238. y = d[i++];
  10239. var width = d[i++];
  10240. var height = d[i++];
  10241. if (drawPart) {
  10242. var l = pathSegLen[segCount++];
  10243. if (accumLength + l > displayedLength) {
  10244. var d_1 = displayedLength - accumLength;
  10245. ctx.moveTo(x, y);
  10246. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10247. d_1 -= width;
  10248. if (d_1 > 0) {
  10249. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10250. }
  10251. d_1 -= height;
  10252. if (d_1 > 0) {
  10253. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10254. }
  10255. d_1 -= width;
  10256. if (d_1 > 0) {
  10257. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10258. }
  10259. break lo;
  10260. }
  10261. accumLength += l;
  10262. }
  10263. ctx.rect(x, y, width, height);
  10264. break;
  10265. case CMD.Z:
  10266. if (drawPart) {
  10267. var l = pathSegLen[segCount++];
  10268. if (accumLength + l > displayedLength) {
  10269. var t = (displayedLength - accumLength) / l;
  10270. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10271. break lo;
  10272. }
  10273. accumLength += l;
  10274. }
  10275. ctx.closePath();
  10276. xi = x0;
  10277. yi = y0;
  10278. }
  10279. }
  10280. };
  10281. PathProxy.prototype.clone = function () {
  10282. var newProxy = new PathProxy();
  10283. var data = this.data;
  10284. newProxy.data = data.slice ? data.slice()
  10285. : Array.prototype.slice.call(data);
  10286. newProxy._len = this._len;
  10287. return newProxy;
  10288. };
  10289. PathProxy.CMD = CMD;
  10290. PathProxy.initDefaultProps = (function () {
  10291. var proto = PathProxy.prototype;
  10292. proto._saveData = true;
  10293. proto._ux = 0;
  10294. proto._uy = 0;
  10295. proto._pendingPtDist = 0;
  10296. proto._version = 0;
  10297. })();
  10298. return PathProxy;
  10299. }());
  10300. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10301. if (lineWidth === 0) {
  10302. return false;
  10303. }
  10304. var _l = lineWidth;
  10305. var _a = 0;
  10306. var _b = x0;
  10307. if ((y > y0 + _l && y > y1 + _l)
  10308. || (y < y0 - _l && y < y1 - _l)
  10309. || (x > x0 + _l && x > x1 + _l)
  10310. || (x < x0 - _l && x < x1 - _l)) {
  10311. return false;
  10312. }
  10313. if (x0 !== x1) {
  10314. _a = (y0 - y1) / (x0 - x1);
  10315. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10316. }
  10317. else {
  10318. return Math.abs(x - x0) <= _l / 2;
  10319. }
  10320. var tmp = _a * x - y + _b;
  10321. var _s = tmp * tmp / (_a * _a + 1);
  10322. return _s <= _l / 2 * _l / 2;
  10323. }
  10324. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10325. if (lineWidth === 0) {
  10326. return false;
  10327. }
  10328. var _l = lineWidth;
  10329. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10330. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10331. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10332. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10333. return false;
  10334. }
  10335. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10336. return d <= _l / 2;
  10337. }
  10338. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10339. if (lineWidth === 0) {
  10340. return false;
  10341. }
  10342. var _l = lineWidth;
  10343. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10344. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10345. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10346. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10347. return false;
  10348. }
  10349. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10350. return d <= _l / 2;
  10351. }
  10352. var PI2$2 = Math.PI * 2;
  10353. function normalizeRadian(angle) {
  10354. angle %= PI2$2;
  10355. if (angle < 0) {
  10356. angle += PI2$2;
  10357. }
  10358. return angle;
  10359. }
  10360. var PI2$3 = Math.PI * 2;
  10361. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10362. if (lineWidth === 0) {
  10363. return false;
  10364. }
  10365. var _l = lineWidth;
  10366. x -= cx;
  10367. y -= cy;
  10368. var d = Math.sqrt(x * x + y * y);
  10369. if ((d - _l > r) || (d + _l < r)) {
  10370. return false;
  10371. }
  10372. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10373. return true;
  10374. }
  10375. if (anticlockwise) {
  10376. var tmp = startAngle;
  10377. startAngle = normalizeRadian(endAngle);
  10378. endAngle = normalizeRadian(tmp);
  10379. }
  10380. else {
  10381. startAngle = normalizeRadian(startAngle);
  10382. endAngle = normalizeRadian(endAngle);
  10383. }
  10384. if (startAngle > endAngle) {
  10385. endAngle += PI2$3;
  10386. }
  10387. var angle = Math.atan2(y, x);
  10388. if (angle < 0) {
  10389. angle += PI2$3;
  10390. }
  10391. return (angle >= startAngle && angle <= endAngle)
  10392. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10393. }
  10394. function windingLine(x0, y0, x1, y1, x, y) {
  10395. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10396. return 0;
  10397. }
  10398. if (y1 === y0) {
  10399. return 0;
  10400. }
  10401. var t = (y - y0) / (y1 - y0);
  10402. var dir = y1 < y0 ? 1 : -1;
  10403. if (t === 1 || t === 0) {
  10404. dir = y1 < y0 ? 0.5 : -0.5;
  10405. }
  10406. var x_ = t * (x1 - x0) + x0;
  10407. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10408. }
  10409. var CMD$1 = PathProxy.CMD;
  10410. var PI2$4 = Math.PI * 2;
  10411. var EPSILON$3 = 1e-4;
  10412. function isAroundEqual(a, b) {
  10413. return Math.abs(a - b) < EPSILON$3;
  10414. }
  10415. var roots = [-1, -1, -1];
  10416. var extrema = [-1, -1];
  10417. function swapExtrema() {
  10418. var tmp = extrema[0];
  10419. extrema[0] = extrema[1];
  10420. extrema[1] = tmp;
  10421. }
  10422. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10423. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10424. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10425. return 0;
  10426. }
  10427. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10428. if (nRoots === 0) {
  10429. return 0;
  10430. }
  10431. else {
  10432. var w = 0;
  10433. var nExtrema = -1;
  10434. var y0_ = void 0;
  10435. var y1_ = void 0;
  10436. for (var i = 0; i < nRoots; i++) {
  10437. var t = roots[i];
  10438. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10439. var x_ = cubicAt(x0, x1, x2, x3, t);
  10440. if (x_ < x) {
  10441. continue;
  10442. }
  10443. if (nExtrema < 0) {
  10444. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10445. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10446. swapExtrema();
  10447. }
  10448. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10449. if (nExtrema > 1) {
  10450. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10451. }
  10452. }
  10453. if (nExtrema === 2) {
  10454. if (t < extrema[0]) {
  10455. w += y0_ < y0 ? unit : -unit;
  10456. }
  10457. else if (t < extrema[1]) {
  10458. w += y1_ < y0_ ? unit : -unit;
  10459. }
  10460. else {
  10461. w += y3 < y1_ ? unit : -unit;
  10462. }
  10463. }
  10464. else {
  10465. if (t < extrema[0]) {
  10466. w += y0_ < y0 ? unit : -unit;
  10467. }
  10468. else {
  10469. w += y3 < y0_ ? unit : -unit;
  10470. }
  10471. }
  10472. }
  10473. return w;
  10474. }
  10475. }
  10476. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10477. if ((y > y0 && y > y1 && y > y2)
  10478. || (y < y0 && y < y1 && y < y2)) {
  10479. return 0;
  10480. }
  10481. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10482. if (nRoots === 0) {
  10483. return 0;
  10484. }
  10485. else {
  10486. var t = quadraticExtremum(y0, y1, y2);
  10487. if (t >= 0 && t <= 1) {
  10488. var w = 0;
  10489. var y_ = quadraticAt(y0, y1, y2, t);
  10490. for (var i = 0; i < nRoots; i++) {
  10491. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10492. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10493. if (x_ < x) {
  10494. continue;
  10495. }
  10496. if (roots[i] < t) {
  10497. w += y_ < y0 ? unit : -unit;
  10498. }
  10499. else {
  10500. w += y2 < y_ ? unit : -unit;
  10501. }
  10502. }
  10503. return w;
  10504. }
  10505. else {
  10506. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10507. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10508. if (x_ < x) {
  10509. return 0;
  10510. }
  10511. return y2 < y0 ? unit : -unit;
  10512. }
  10513. }
  10514. }
  10515. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10516. y -= cy;
  10517. if (y > r || y < -r) {
  10518. return 0;
  10519. }
  10520. var tmp = Math.sqrt(r * r - y * y);
  10521. roots[0] = -tmp;
  10522. roots[1] = tmp;
  10523. var dTheta = Math.abs(startAngle - endAngle);
  10524. if (dTheta < 1e-4) {
  10525. return 0;
  10526. }
  10527. if (dTheta >= PI2$4 - 1e-4) {
  10528. startAngle = 0;
  10529. endAngle = PI2$4;
  10530. var dir = anticlockwise ? 1 : -1;
  10531. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10532. return dir;
  10533. }
  10534. else {
  10535. return 0;
  10536. }
  10537. }
  10538. if (startAngle > endAngle) {
  10539. var tmp_1 = startAngle;
  10540. startAngle = endAngle;
  10541. endAngle = tmp_1;
  10542. }
  10543. if (startAngle < 0) {
  10544. startAngle += PI2$4;
  10545. endAngle += PI2$4;
  10546. }
  10547. var w = 0;
  10548. for (var i = 0; i < 2; i++) {
  10549. var x_ = roots[i];
  10550. if (x_ + cx > x) {
  10551. var angle = Math.atan2(y, x_);
  10552. var dir = anticlockwise ? 1 : -1;
  10553. if (angle < 0) {
  10554. angle = PI2$4 + angle;
  10555. }
  10556. if ((angle >= startAngle && angle <= endAngle)
  10557. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10558. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10559. dir = -dir;
  10560. }
  10561. w += dir;
  10562. }
  10563. }
  10564. }
  10565. return w;
  10566. }
  10567. function containPath(path, lineWidth, isStroke, x, y) {
  10568. var data = path.data;
  10569. var len = path.len();
  10570. var w = 0;
  10571. var xi = 0;
  10572. var yi = 0;
  10573. var x0 = 0;
  10574. var y0 = 0;
  10575. var x1;
  10576. var y1;
  10577. for (var i = 0; i < len;) {
  10578. var cmd = data[i++];
  10579. var isFirst = i === 1;
  10580. if (cmd === CMD$1.M && i > 1) {
  10581. if (!isStroke) {
  10582. w += windingLine(xi, yi, x0, y0, x, y);
  10583. }
  10584. }
  10585. if (isFirst) {
  10586. xi = data[i];
  10587. yi = data[i + 1];
  10588. x0 = xi;
  10589. y0 = yi;
  10590. }
  10591. switch (cmd) {
  10592. case CMD$1.M:
  10593. x0 = data[i++];
  10594. y0 = data[i++];
  10595. xi = x0;
  10596. yi = y0;
  10597. break;
  10598. case CMD$1.L:
  10599. if (isStroke) {
  10600. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10601. return true;
  10602. }
  10603. }
  10604. else {
  10605. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10606. }
  10607. xi = data[i++];
  10608. yi = data[i++];
  10609. break;
  10610. case CMD$1.C:
  10611. if (isStroke) {
  10612. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10613. return true;
  10614. }
  10615. }
  10616. else {
  10617. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10618. }
  10619. xi = data[i++];
  10620. yi = data[i++];
  10621. break;
  10622. case CMD$1.Q:
  10623. if (isStroke) {
  10624. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10625. return true;
  10626. }
  10627. }
  10628. else {
  10629. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10630. }
  10631. xi = data[i++];
  10632. yi = data[i++];
  10633. break;
  10634. case CMD$1.A:
  10635. var cx = data[i++];
  10636. var cy = data[i++];
  10637. var rx = data[i++];
  10638. var ry = data[i++];
  10639. var theta = data[i++];
  10640. var dTheta = data[i++];
  10641. i += 1;
  10642. var anticlockwise = !!(1 - data[i++]);
  10643. x1 = Math.cos(theta) * rx + cx;
  10644. y1 = Math.sin(theta) * ry + cy;
  10645. if (!isFirst) {
  10646. w += windingLine(xi, yi, x1, y1, x, y);
  10647. }
  10648. else {
  10649. x0 = x1;
  10650. y0 = y1;
  10651. }
  10652. var _x = (x - cx) * ry / rx + cx;
  10653. if (isStroke) {
  10654. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10655. return true;
  10656. }
  10657. }
  10658. else {
  10659. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10660. }
  10661. xi = Math.cos(theta + dTheta) * rx + cx;
  10662. yi = Math.sin(theta + dTheta) * ry + cy;
  10663. break;
  10664. case CMD$1.R:
  10665. x0 = xi = data[i++];
  10666. y0 = yi = data[i++];
  10667. var width = data[i++];
  10668. var height = data[i++];
  10669. x1 = x0 + width;
  10670. y1 = y0 + height;
  10671. if (isStroke) {
  10672. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10673. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10674. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10675. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10676. return true;
  10677. }
  10678. }
  10679. else {
  10680. w += windingLine(x1, y0, x1, y1, x, y);
  10681. w += windingLine(x0, y1, x0, y0, x, y);
  10682. }
  10683. break;
  10684. case CMD$1.Z:
  10685. if (isStroke) {
  10686. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10687. return true;
  10688. }
  10689. }
  10690. else {
  10691. w += windingLine(xi, yi, x0, y0, x, y);
  10692. }
  10693. xi = x0;
  10694. yi = y0;
  10695. break;
  10696. }
  10697. }
  10698. if (!isStroke && !isAroundEqual(yi, y0)) {
  10699. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10700. }
  10701. return w !== 0;
  10702. }
  10703. function contain(pathProxy, x, y) {
  10704. return containPath(pathProxy, 0, false, x, y);
  10705. }
  10706. function containStroke$4(pathProxy, lineWidth, x, y) {
  10707. return containPath(pathProxy, lineWidth, true, x, y);
  10708. }
  10709. var DEFAULT_PATH_STYLE = defaults({
  10710. fill: '#000',
  10711. stroke: null,
  10712. strokePercent: 1,
  10713. fillOpacity: 1,
  10714. strokeOpacity: 1,
  10715. lineDashOffset: 0,
  10716. lineWidth: 1,
  10717. lineCap: 'butt',
  10718. miterLimit: 10,
  10719. strokeNoScale: false,
  10720. strokeFirst: false
  10721. }, DEFAULT_COMMON_STYLE);
  10722. var DEFAULT_PATH_ANIMATION_PROPS = {
  10723. style: defaults({
  10724. fill: true,
  10725. stroke: true,
  10726. strokePercent: true,
  10727. fillOpacity: true,
  10728. strokeOpacity: true,
  10729. lineDashOffset: true,
  10730. lineWidth: true,
  10731. miterLimit: true
  10732. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10733. };
  10734. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10735. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10736. ]);
  10737. var Path = (function (_super) {
  10738. __extends(Path, _super);
  10739. function Path(opts) {
  10740. return _super.call(this, opts) || this;
  10741. }
  10742. Path.prototype.update = function () {
  10743. var _this = this;
  10744. _super.prototype.update.call(this);
  10745. var style = this.style;
  10746. if (style.decal) {
  10747. var decalEl = this._decalEl = this._decalEl || new Path();
  10748. if (decalEl.buildPath === Path.prototype.buildPath) {
  10749. decalEl.buildPath = function (ctx) {
  10750. _this.buildPath(ctx, _this.shape);
  10751. };
  10752. }
  10753. decalEl.silent = true;
  10754. var decalElStyle = decalEl.style;
  10755. for (var key in style) {
  10756. if (decalElStyle[key] !== style[key]) {
  10757. decalElStyle[key] = style[key];
  10758. }
  10759. }
  10760. decalElStyle.fill = style.fill ? style.decal : null;
  10761. decalElStyle.decal = null;
  10762. decalElStyle.shadowColor = null;
  10763. style.strokeFirst && (decalElStyle.stroke = null);
  10764. for (var i = 0; i < pathCopyParams.length; ++i) {
  10765. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10766. }
  10767. decalEl.__dirty |= REDRAW_BIT;
  10768. }
  10769. else if (this._decalEl) {
  10770. this._decalEl = null;
  10771. }
  10772. };
  10773. Path.prototype.getDecalElement = function () {
  10774. return this._decalEl;
  10775. };
  10776. Path.prototype._init = function (props) {
  10777. var keysArr = keys(props);
  10778. this.shape = this.getDefaultShape();
  10779. var defaultStyle = this.getDefaultStyle();
  10780. if (defaultStyle) {
  10781. this.useStyle(defaultStyle);
  10782. }
  10783. for (var i = 0; i < keysArr.length; i++) {
  10784. var key = keysArr[i];
  10785. var value = props[key];
  10786. if (key === 'style') {
  10787. if (!this.style) {
  10788. this.useStyle(value);
  10789. }
  10790. else {
  10791. extend(this.style, value);
  10792. }
  10793. }
  10794. else if (key === 'shape') {
  10795. extend(this.shape, value);
  10796. }
  10797. else {
  10798. _super.prototype.attrKV.call(this, key, value);
  10799. }
  10800. }
  10801. if (!this.style) {
  10802. this.useStyle({});
  10803. }
  10804. };
  10805. Path.prototype.getDefaultStyle = function () {
  10806. return null;
  10807. };
  10808. Path.prototype.getDefaultShape = function () {
  10809. return {};
  10810. };
  10811. Path.prototype.canBeInsideText = function () {
  10812. return this.hasFill();
  10813. };
  10814. Path.prototype.getInsideTextFill = function () {
  10815. var pathFill = this.style.fill;
  10816. if (pathFill !== 'none') {
  10817. if (isString(pathFill)) {
  10818. var fillLum = lum(pathFill, 0);
  10819. if (fillLum > 0.5) {
  10820. return DARK_LABEL_COLOR;
  10821. }
  10822. else if (fillLum > 0.2) {
  10823. return LIGHTER_LABEL_COLOR;
  10824. }
  10825. return LIGHT_LABEL_COLOR;
  10826. }
  10827. else if (pathFill) {
  10828. return LIGHT_LABEL_COLOR;
  10829. }
  10830. }
  10831. return DARK_LABEL_COLOR;
  10832. };
  10833. Path.prototype.getInsideTextStroke = function (textFill) {
  10834. var pathFill = this.style.fill;
  10835. if (isString(pathFill)) {
  10836. var zr = this.__zr;
  10837. var isDarkMode = !!(zr && zr.isDarkMode());
  10838. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10839. if (isDarkMode === isDarkLabel) {
  10840. return pathFill;
  10841. }
  10842. }
  10843. };
  10844. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10845. Path.prototype.pathUpdated = function () {
  10846. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10847. };
  10848. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10849. !this.path && this.createPathProxy();
  10850. this.path.beginPath();
  10851. this.buildPath(this.path, this.shape, inBatch);
  10852. return this.path;
  10853. };
  10854. Path.prototype.createPathProxy = function () {
  10855. this.path = new PathProxy(false);
  10856. };
  10857. Path.prototype.hasStroke = function () {
  10858. var style = this.style;
  10859. var stroke = style.stroke;
  10860. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10861. };
  10862. Path.prototype.hasFill = function () {
  10863. var style = this.style;
  10864. var fill = style.fill;
  10865. return fill != null && fill !== 'none';
  10866. };
  10867. Path.prototype.getBoundingRect = function () {
  10868. var rect = this._rect;
  10869. var style = this.style;
  10870. var needsUpdateRect = !rect;
  10871. if (needsUpdateRect) {
  10872. var firstInvoke = false;
  10873. if (!this.path) {
  10874. firstInvoke = true;
  10875. this.createPathProxy();
  10876. }
  10877. var path = this.path;
  10878. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10879. path.beginPath();
  10880. this.buildPath(path, this.shape, false);
  10881. this.pathUpdated();
  10882. }
  10883. rect = path.getBoundingRect();
  10884. }
  10885. this._rect = rect;
  10886. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10887. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10888. if (this.__dirty || needsUpdateRect) {
  10889. rectStroke.copy(rect);
  10890. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10891. var w = style.lineWidth;
  10892. if (!this.hasFill()) {
  10893. var strokeContainThreshold = this.strokeContainThreshold;
  10894. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10895. }
  10896. if (lineScale > 1e-10) {
  10897. rectStroke.width += w / lineScale;
  10898. rectStroke.height += w / lineScale;
  10899. rectStroke.x -= w / lineScale / 2;
  10900. rectStroke.y -= w / lineScale / 2;
  10901. }
  10902. }
  10903. return rectStroke;
  10904. }
  10905. return rect;
  10906. };
  10907. Path.prototype.contain = function (x, y) {
  10908. var localPos = this.transformCoordToLocal(x, y);
  10909. var rect = this.getBoundingRect();
  10910. var style = this.style;
  10911. x = localPos[0];
  10912. y = localPos[1];
  10913. if (rect.contain(x, y)) {
  10914. var pathProxy = this.path;
  10915. if (this.hasStroke()) {
  10916. var lineWidth = style.lineWidth;
  10917. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10918. if (lineScale > 1e-10) {
  10919. if (!this.hasFill()) {
  10920. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10921. }
  10922. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10923. return true;
  10924. }
  10925. }
  10926. }
  10927. if (this.hasFill()) {
  10928. return contain(pathProxy, x, y);
  10929. }
  10930. }
  10931. return false;
  10932. };
  10933. Path.prototype.dirtyShape = function () {
  10934. this.__dirty |= SHAPE_CHANGED_BIT;
  10935. if (this._rect) {
  10936. this._rect = null;
  10937. }
  10938. if (this._decalEl) {
  10939. this._decalEl.dirtyShape();
  10940. }
  10941. this.markRedraw();
  10942. };
  10943. Path.prototype.dirty = function () {
  10944. this.dirtyStyle();
  10945. this.dirtyShape();
  10946. };
  10947. Path.prototype.animateShape = function (loop) {
  10948. return this.animate('shape', loop);
  10949. };
  10950. Path.prototype.updateDuringAnimation = function (targetKey) {
  10951. if (targetKey === 'style') {
  10952. this.dirtyStyle();
  10953. }
  10954. else if (targetKey === 'shape') {
  10955. this.dirtyShape();
  10956. }
  10957. else {
  10958. this.markRedraw();
  10959. }
  10960. };
  10961. Path.prototype.attrKV = function (key, value) {
  10962. if (key === 'shape') {
  10963. this.setShape(value);
  10964. }
  10965. else {
  10966. _super.prototype.attrKV.call(this, key, value);
  10967. }
  10968. };
  10969. Path.prototype.setShape = function (keyOrObj, value) {
  10970. var shape = this.shape;
  10971. if (!shape) {
  10972. shape = this.shape = {};
  10973. }
  10974. if (typeof keyOrObj === 'string') {
  10975. shape[keyOrObj] = value;
  10976. }
  10977. else {
  10978. extend(shape, keyOrObj);
  10979. }
  10980. this.dirtyShape();
  10981. return this;
  10982. };
  10983. Path.prototype.shapeChanged = function () {
  10984. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  10985. };
  10986. Path.prototype.createStyle = function (obj) {
  10987. return createObject(DEFAULT_PATH_STYLE, obj);
  10988. };
  10989. Path.prototype._innerSaveToNormal = function (toState) {
  10990. _super.prototype._innerSaveToNormal.call(this, toState);
  10991. var normalState = this._normalState;
  10992. if (toState.shape && !normalState.shape) {
  10993. normalState.shape = extend({}, this.shape);
  10994. }
  10995. };
  10996. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10997. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10998. var needsRestoreToNormal = !(state && keepCurrentStates);
  10999. var targetShape;
  11000. if (state && state.shape) {
  11001. if (transition) {
  11002. if (keepCurrentStates) {
  11003. targetShape = state.shape;
  11004. }
  11005. else {
  11006. targetShape = extend({}, normalState.shape);
  11007. extend(targetShape, state.shape);
  11008. }
  11009. }
  11010. else {
  11011. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11012. extend(targetShape, state.shape);
  11013. }
  11014. }
  11015. else if (needsRestoreToNormal) {
  11016. targetShape = normalState.shape;
  11017. }
  11018. if (targetShape) {
  11019. if (transition) {
  11020. this.shape = extend({}, this.shape);
  11021. var targetShapePrimaryProps = {};
  11022. var shapeKeys = keys(targetShape);
  11023. for (var i = 0; i < shapeKeys.length; i++) {
  11024. var key = shapeKeys[i];
  11025. if (typeof targetShape[key] === 'object') {
  11026. this.shape[key] = targetShape[key];
  11027. }
  11028. else {
  11029. targetShapePrimaryProps[key] = targetShape[key];
  11030. }
  11031. }
  11032. this._transitionState(stateName, {
  11033. shape: targetShapePrimaryProps
  11034. }, animationCfg);
  11035. }
  11036. else {
  11037. this.shape = targetShape;
  11038. this.dirtyShape();
  11039. }
  11040. }
  11041. };
  11042. Path.prototype._mergeStates = function (states) {
  11043. var mergedState = _super.prototype._mergeStates.call(this, states);
  11044. var mergedShape;
  11045. for (var i = 0; i < states.length; i++) {
  11046. var state = states[i];
  11047. if (state.shape) {
  11048. mergedShape = mergedShape || {};
  11049. this._mergeStyle(mergedShape, state.shape);
  11050. }
  11051. }
  11052. if (mergedShape) {
  11053. mergedState.shape = mergedShape;
  11054. }
  11055. return mergedState;
  11056. };
  11057. Path.prototype.getAnimationStyleProps = function () {
  11058. return DEFAULT_PATH_ANIMATION_PROPS;
  11059. };
  11060. Path.prototype.isZeroArea = function () {
  11061. return false;
  11062. };
  11063. Path.extend = function (defaultProps) {
  11064. var Sub = (function (_super) {
  11065. __extends(Sub, _super);
  11066. function Sub(opts) {
  11067. var _this = _super.call(this, opts) || this;
  11068. defaultProps.init && defaultProps.init.call(_this, opts);
  11069. return _this;
  11070. }
  11071. Sub.prototype.getDefaultStyle = function () {
  11072. return clone(defaultProps.style);
  11073. };
  11074. Sub.prototype.getDefaultShape = function () {
  11075. return clone(defaultProps.shape);
  11076. };
  11077. return Sub;
  11078. }(Path));
  11079. for (var key in defaultProps) {
  11080. if (typeof defaultProps[key] === 'function') {
  11081. Sub.prototype[key] = defaultProps[key];
  11082. }
  11083. }
  11084. return Sub;
  11085. };
  11086. Path.initDefaultProps = (function () {
  11087. var pathProto = Path.prototype;
  11088. pathProto.type = 'path';
  11089. pathProto.strokeContainThreshold = 5;
  11090. pathProto.segmentIgnoreThreshold = 0;
  11091. pathProto.subPixelOptimize = false;
  11092. pathProto.autoBatch = false;
  11093. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11094. })();
  11095. return Path;
  11096. }(Displayable));
  11097. var DEFAULT_TSPAN_STYLE = defaults({
  11098. strokeFirst: true,
  11099. font: DEFAULT_FONT,
  11100. x: 0,
  11101. y: 0,
  11102. textAlign: 'left',
  11103. textBaseline: 'top',
  11104. miterLimit: 2
  11105. }, DEFAULT_PATH_STYLE);
  11106. var TSpan = (function (_super) {
  11107. __extends(TSpan, _super);
  11108. function TSpan() {
  11109. return _super !== null && _super.apply(this, arguments) || this;
  11110. }
  11111. TSpan.prototype.hasStroke = function () {
  11112. var style = this.style;
  11113. var stroke = style.stroke;
  11114. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11115. };
  11116. TSpan.prototype.hasFill = function () {
  11117. var style = this.style;
  11118. var fill = style.fill;
  11119. return fill != null && fill !== 'none';
  11120. };
  11121. TSpan.prototype.createStyle = function (obj) {
  11122. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11123. };
  11124. TSpan.prototype.setBoundingRect = function (rect) {
  11125. this._rect = rect;
  11126. };
  11127. TSpan.prototype.getBoundingRect = function () {
  11128. var style = this.style;
  11129. if (!this._rect) {
  11130. var text = style.text;
  11131. text != null ? (text += '') : (text = '');
  11132. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11133. rect.x += style.x || 0;
  11134. rect.y += style.y || 0;
  11135. if (this.hasStroke()) {
  11136. var w = style.lineWidth;
  11137. rect.x -= w / 2;
  11138. rect.y -= w / 2;
  11139. rect.width += w;
  11140. rect.height += w;
  11141. }
  11142. this._rect = rect;
  11143. }
  11144. return this._rect;
  11145. };
  11146. TSpan.initDefaultProps = (function () {
  11147. var tspanProto = TSpan.prototype;
  11148. tspanProto.dirtyRectTolerance = 10;
  11149. })();
  11150. return TSpan;
  11151. }(Displayable));
  11152. TSpan.prototype.type = 'tspan';
  11153. var DEFAULT_IMAGE_STYLE = defaults({
  11154. x: 0,
  11155. y: 0
  11156. }, DEFAULT_COMMON_STYLE);
  11157. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11158. style: defaults({
  11159. x: true,
  11160. y: true,
  11161. width: true,
  11162. height: true,
  11163. sx: true,
  11164. sy: true,
  11165. sWidth: true,
  11166. sHeight: true
  11167. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11168. };
  11169. function isImageLike(source) {
  11170. return !!(source
  11171. && typeof source !== 'string'
  11172. && source.width && source.height);
  11173. }
  11174. var ZRImage = (function (_super) {
  11175. __extends(ZRImage, _super);
  11176. function ZRImage() {
  11177. return _super !== null && _super.apply(this, arguments) || this;
  11178. }
  11179. ZRImage.prototype.createStyle = function (obj) {
  11180. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11181. };
  11182. ZRImage.prototype._getSize = function (dim) {
  11183. var style = this.style;
  11184. var size = style[dim];
  11185. if (size != null) {
  11186. return size;
  11187. }
  11188. var imageSource = isImageLike(style.image)
  11189. ? style.image : this.__image;
  11190. if (!imageSource) {
  11191. return 0;
  11192. }
  11193. var otherDim = dim === 'width' ? 'height' : 'width';
  11194. var otherDimSize = style[otherDim];
  11195. if (otherDimSize == null) {
  11196. return imageSource[dim];
  11197. }
  11198. else {
  11199. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11200. }
  11201. };
  11202. ZRImage.prototype.getWidth = function () {
  11203. return this._getSize('width');
  11204. };
  11205. ZRImage.prototype.getHeight = function () {
  11206. return this._getSize('height');
  11207. };
  11208. ZRImage.prototype.getAnimationStyleProps = function () {
  11209. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11210. };
  11211. ZRImage.prototype.getBoundingRect = function () {
  11212. var style = this.style;
  11213. if (!this._rect) {
  11214. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11215. }
  11216. return this._rect;
  11217. };
  11218. return ZRImage;
  11219. }(Displayable));
  11220. ZRImage.prototype.type = 'image';
  11221. function buildPath(ctx, shape) {
  11222. var x = shape.x;
  11223. var y = shape.y;
  11224. var width = shape.width;
  11225. var height = shape.height;
  11226. var r = shape.r;
  11227. var r1;
  11228. var r2;
  11229. var r3;
  11230. var r4;
  11231. if (width < 0) {
  11232. x = x + width;
  11233. width = -width;
  11234. }
  11235. if (height < 0) {
  11236. y = y + height;
  11237. height = -height;
  11238. }
  11239. if (typeof r === 'number') {
  11240. r1 = r2 = r3 = r4 = r;
  11241. }
  11242. else if (r instanceof Array) {
  11243. if (r.length === 1) {
  11244. r1 = r2 = r3 = r4 = r[0];
  11245. }
  11246. else if (r.length === 2) {
  11247. r1 = r3 = r[0];
  11248. r2 = r4 = r[1];
  11249. }
  11250. else if (r.length === 3) {
  11251. r1 = r[0];
  11252. r2 = r4 = r[1];
  11253. r3 = r[2];
  11254. }
  11255. else {
  11256. r1 = r[0];
  11257. r2 = r[1];
  11258. r3 = r[2];
  11259. r4 = r[3];
  11260. }
  11261. }
  11262. else {
  11263. r1 = r2 = r3 = r4 = 0;
  11264. }
  11265. var total;
  11266. if (r1 + r2 > width) {
  11267. total = r1 + r2;
  11268. r1 *= width / total;
  11269. r2 *= width / total;
  11270. }
  11271. if (r3 + r4 > width) {
  11272. total = r3 + r4;
  11273. r3 *= width / total;
  11274. r4 *= width / total;
  11275. }
  11276. if (r2 + r3 > height) {
  11277. total = r2 + r3;
  11278. r2 *= height / total;
  11279. r3 *= height / total;
  11280. }
  11281. if (r1 + r4 > height) {
  11282. total = r1 + r4;
  11283. r1 *= height / total;
  11284. r4 *= height / total;
  11285. }
  11286. ctx.moveTo(x + r1, y);
  11287. ctx.lineTo(x + width - r2, y);
  11288. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11289. ctx.lineTo(x + width, y + height - r3);
  11290. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11291. ctx.lineTo(x + r4, y + height);
  11292. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11293. ctx.lineTo(x, y + r1);
  11294. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11295. }
  11296. var round$1 = Math.round;
  11297. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11298. if (!inputShape) {
  11299. return;
  11300. }
  11301. var x1 = inputShape.x1;
  11302. var x2 = inputShape.x2;
  11303. var y1 = inputShape.y1;
  11304. var y2 = inputShape.y2;
  11305. outputShape.x1 = x1;
  11306. outputShape.x2 = x2;
  11307. outputShape.y1 = y1;
  11308. outputShape.y2 = y2;
  11309. var lineWidth = style && style.lineWidth;
  11310. if (!lineWidth) {
  11311. return outputShape;
  11312. }
  11313. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11314. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11315. }
  11316. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11317. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11318. }
  11319. return outputShape;
  11320. }
  11321. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11322. if (!inputShape) {
  11323. return;
  11324. }
  11325. var originX = inputShape.x;
  11326. var originY = inputShape.y;
  11327. var originWidth = inputShape.width;
  11328. var originHeight = inputShape.height;
  11329. outputShape.x = originX;
  11330. outputShape.y = originY;
  11331. outputShape.width = originWidth;
  11332. outputShape.height = originHeight;
  11333. var lineWidth = style && style.lineWidth;
  11334. if (!lineWidth) {
  11335. return outputShape;
  11336. }
  11337. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11338. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11339. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11340. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11341. return outputShape;
  11342. }
  11343. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11344. if (!lineWidth) {
  11345. return position;
  11346. }
  11347. var doubledPosition = round$1(position * 2);
  11348. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11349. ? doubledPosition / 2
  11350. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11351. }
  11352. var RectShape = (function () {
  11353. function RectShape() {
  11354. this.x = 0;
  11355. this.y = 0;
  11356. this.width = 0;
  11357. this.height = 0;
  11358. }
  11359. return RectShape;
  11360. }());
  11361. var subPixelOptimizeOutputShape = {};
  11362. var Rect = (function (_super) {
  11363. __extends(Rect, _super);
  11364. function Rect(opts) {
  11365. return _super.call(this, opts) || this;
  11366. }
  11367. Rect.prototype.getDefaultShape = function () {
  11368. return new RectShape();
  11369. };
  11370. Rect.prototype.buildPath = function (ctx, shape) {
  11371. var x;
  11372. var y;
  11373. var width;
  11374. var height;
  11375. if (this.subPixelOptimize) {
  11376. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11377. x = optimizedShape.x;
  11378. y = optimizedShape.y;
  11379. width = optimizedShape.width;
  11380. height = optimizedShape.height;
  11381. optimizedShape.r = shape.r;
  11382. shape = optimizedShape;
  11383. }
  11384. else {
  11385. x = shape.x;
  11386. y = shape.y;
  11387. width = shape.width;
  11388. height = shape.height;
  11389. }
  11390. if (!shape.r) {
  11391. ctx.rect(x, y, width, height);
  11392. }
  11393. else {
  11394. buildPath(ctx, shape);
  11395. }
  11396. };
  11397. Rect.prototype.isZeroArea = function () {
  11398. return !this.shape.width || !this.shape.height;
  11399. };
  11400. return Rect;
  11401. }(Path));
  11402. Rect.prototype.type = 'rect';
  11403. var DEFAULT_RICH_TEXT_COLOR = {
  11404. fill: '#000'
  11405. };
  11406. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11407. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11408. style: defaults({
  11409. fill: true,
  11410. stroke: true,
  11411. fillOpacity: true,
  11412. strokeOpacity: true,
  11413. lineWidth: true,
  11414. fontSize: true,
  11415. lineHeight: true,
  11416. width: true,
  11417. height: true,
  11418. textShadowColor: true,
  11419. textShadowBlur: true,
  11420. textShadowOffsetX: true,
  11421. textShadowOffsetY: true,
  11422. backgroundColor: true,
  11423. padding: true,
  11424. borderColor: true,
  11425. borderWidth: true,
  11426. borderRadius: true
  11427. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11428. };
  11429. var ZRText = (function (_super) {
  11430. __extends(ZRText, _super);
  11431. function ZRText(opts) {
  11432. var _this = _super.call(this) || this;
  11433. _this.type = 'text';
  11434. _this._children = [];
  11435. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11436. _this.attr(opts);
  11437. return _this;
  11438. }
  11439. ZRText.prototype.childrenRef = function () {
  11440. return this._children;
  11441. };
  11442. ZRText.prototype.update = function () {
  11443. _super.prototype.update.call(this);
  11444. if (this.styleChanged()) {
  11445. this._updateSubTexts();
  11446. }
  11447. for (var i = 0; i < this._children.length; i++) {
  11448. var child = this._children[i];
  11449. child.zlevel = this.zlevel;
  11450. child.z = this.z;
  11451. child.z2 = this.z2;
  11452. child.culling = this.culling;
  11453. child.cursor = this.cursor;
  11454. child.invisible = this.invisible;
  11455. }
  11456. };
  11457. ZRText.prototype.updateTransform = function () {
  11458. var innerTransformable = this.innerTransformable;
  11459. if (innerTransformable) {
  11460. innerTransformable.updateTransform();
  11461. if (innerTransformable.transform) {
  11462. this.transform = innerTransformable.transform;
  11463. }
  11464. }
  11465. else {
  11466. _super.prototype.updateTransform.call(this);
  11467. }
  11468. };
  11469. ZRText.prototype.getLocalTransform = function (m) {
  11470. var innerTransformable = this.innerTransformable;
  11471. return innerTransformable
  11472. ? innerTransformable.getLocalTransform(m)
  11473. : _super.prototype.getLocalTransform.call(this, m);
  11474. };
  11475. ZRText.prototype.getComputedTransform = function () {
  11476. if (this.__hostTarget) {
  11477. this.__hostTarget.getComputedTransform();
  11478. this.__hostTarget.updateInnerText(true);
  11479. }
  11480. return _super.prototype.getComputedTransform.call(this);
  11481. };
  11482. ZRText.prototype._updateSubTexts = function () {
  11483. this._childCursor = 0;
  11484. normalizeTextStyle(this.style);
  11485. this.style.rich
  11486. ? this._updateRichTexts()
  11487. : this._updatePlainTexts();
  11488. this._children.length = this._childCursor;
  11489. this.styleUpdated();
  11490. };
  11491. ZRText.prototype.addSelfToZr = function (zr) {
  11492. _super.prototype.addSelfToZr.call(this, zr);
  11493. for (var i = 0; i < this._children.length; i++) {
  11494. this._children[i].__zr = zr;
  11495. }
  11496. };
  11497. ZRText.prototype.removeSelfFromZr = function (zr) {
  11498. _super.prototype.removeSelfFromZr.call(this, zr);
  11499. for (var i = 0; i < this._children.length; i++) {
  11500. this._children[i].__zr = null;
  11501. }
  11502. };
  11503. ZRText.prototype.getBoundingRect = function () {
  11504. if (this.styleChanged()) {
  11505. this._updateSubTexts();
  11506. }
  11507. if (!this._rect) {
  11508. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11509. var children = this._children;
  11510. var tmpMat = [];
  11511. var rect = null;
  11512. for (var i = 0; i < children.length; i++) {
  11513. var child = children[i];
  11514. var childRect = child.getBoundingRect();
  11515. var transform = child.getLocalTransform(tmpMat);
  11516. if (transform) {
  11517. tmpRect.copy(childRect);
  11518. tmpRect.applyTransform(transform);
  11519. rect = rect || tmpRect.clone();
  11520. rect.union(tmpRect);
  11521. }
  11522. else {
  11523. rect = rect || childRect.clone();
  11524. rect.union(childRect);
  11525. }
  11526. }
  11527. this._rect = rect || tmpRect;
  11528. }
  11529. return this._rect;
  11530. };
  11531. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11532. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11533. };
  11534. ZRText.prototype.setTextContent = function (textContent) {
  11535. if ("development" !== 'production') {
  11536. throw new Error('Can\'t attach text on another text');
  11537. }
  11538. };
  11539. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11540. if (!sourceStyle) {
  11541. return targetStyle;
  11542. }
  11543. var sourceRich = sourceStyle.rich;
  11544. var targetRich = targetStyle.rich || (sourceRich && {});
  11545. extend(targetStyle, sourceStyle);
  11546. if (sourceRich && targetRich) {
  11547. this._mergeRich(targetRich, sourceRich);
  11548. targetStyle.rich = targetRich;
  11549. }
  11550. else if (targetRich) {
  11551. targetStyle.rich = targetRich;
  11552. }
  11553. return targetStyle;
  11554. };
  11555. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11556. var richNames = keys(sourceRich);
  11557. for (var i = 0; i < richNames.length; i++) {
  11558. var richName = richNames[i];
  11559. targetRich[richName] = targetRich[richName] || {};
  11560. extend(targetRich[richName], sourceRich[richName]);
  11561. }
  11562. };
  11563. ZRText.prototype.getAnimationStyleProps = function () {
  11564. return DEFAULT_TEXT_ANIMATION_PROPS;
  11565. };
  11566. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11567. var child = this._children[this._childCursor];
  11568. if (!child || !(child instanceof Ctor)) {
  11569. child = new Ctor();
  11570. }
  11571. this._children[this._childCursor++] = child;
  11572. child.__zr = this.__zr;
  11573. child.parent = this;
  11574. return child;
  11575. };
  11576. ZRText.prototype._updatePlainTexts = function () {
  11577. var style = this.style;
  11578. var textFont = style.font || DEFAULT_FONT;
  11579. var textPadding = style.padding;
  11580. var text = getStyleText(style);
  11581. var contentBlock = parsePlainText(text, style);
  11582. var needDrawBg = needDrawBackground(style);
  11583. var bgColorDrawn = !!(style.backgroundColor);
  11584. var outerHeight = contentBlock.outerHeight;
  11585. var outerWidth = contentBlock.outerWidth;
  11586. var contentWidth = contentBlock.contentWidth;
  11587. var textLines = contentBlock.lines;
  11588. var lineHeight = contentBlock.lineHeight;
  11589. var defaultStyle = this._defaultStyle;
  11590. var baseX = style.x || 0;
  11591. var baseY = style.y || 0;
  11592. var textAlign = style.align || defaultStyle.align || 'left';
  11593. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11594. var textX = baseX;
  11595. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11596. if (needDrawBg || textPadding) {
  11597. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11598. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11599. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11600. }
  11601. textY += lineHeight / 2;
  11602. if (textPadding) {
  11603. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11604. if (verticalAlign === 'top') {
  11605. textY += textPadding[0];
  11606. }
  11607. else if (verticalAlign === 'bottom') {
  11608. textY -= textPadding[2];
  11609. }
  11610. }
  11611. var defaultLineWidth = 0;
  11612. var useDefaultFill = false;
  11613. var textFill = getFill('fill' in style
  11614. ? style.fill
  11615. : (useDefaultFill = true, defaultStyle.fill));
  11616. var textStroke = getStroke('stroke' in style
  11617. ? style.stroke
  11618. : (!bgColorDrawn
  11619. && (!defaultStyle.autoStroke || useDefaultFill))
  11620. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11621. : null);
  11622. var hasShadow = style.textShadowBlur > 0;
  11623. var fixedBoundingRect = style.width != null
  11624. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11625. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11626. for (var i = 0; i < textLines.length; i++) {
  11627. var el = this._getOrCreateChild(TSpan);
  11628. var subElStyle = el.createStyle();
  11629. el.useStyle(subElStyle);
  11630. subElStyle.text = textLines[i];
  11631. subElStyle.x = textX;
  11632. subElStyle.y = textY;
  11633. if (textAlign) {
  11634. subElStyle.textAlign = textAlign;
  11635. }
  11636. subElStyle.textBaseline = 'middle';
  11637. subElStyle.opacity = style.opacity;
  11638. subElStyle.strokeFirst = true;
  11639. if (hasShadow) {
  11640. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11641. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11642. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11643. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11644. }
  11645. subElStyle.stroke = textStroke;
  11646. subElStyle.fill = textFill;
  11647. if (textStroke) {
  11648. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11649. subElStyle.lineDash = style.lineDash;
  11650. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11651. }
  11652. subElStyle.font = textFont;
  11653. setSeparateFont(subElStyle, style);
  11654. textY += lineHeight;
  11655. if (fixedBoundingRect) {
  11656. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11657. }
  11658. }
  11659. };
  11660. ZRText.prototype._updateRichTexts = function () {
  11661. var style = this.style;
  11662. var text = getStyleText(style);
  11663. var contentBlock = parseRichText(text, style);
  11664. var contentWidth = contentBlock.width;
  11665. var outerWidth = contentBlock.outerWidth;
  11666. var outerHeight = contentBlock.outerHeight;
  11667. var textPadding = style.padding;
  11668. var baseX = style.x || 0;
  11669. var baseY = style.y || 0;
  11670. var defaultStyle = this._defaultStyle;
  11671. var textAlign = style.align || defaultStyle.align;
  11672. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11673. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11674. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11675. var xLeft = boxX;
  11676. var lineTop = boxY;
  11677. if (textPadding) {
  11678. xLeft += textPadding[3];
  11679. lineTop += textPadding[0];
  11680. }
  11681. var xRight = xLeft + contentWidth;
  11682. if (needDrawBackground(style)) {
  11683. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11684. }
  11685. var bgColorDrawn = !!(style.backgroundColor);
  11686. for (var i = 0; i < contentBlock.lines.length; i++) {
  11687. var line = contentBlock.lines[i];
  11688. var tokens = line.tokens;
  11689. var tokenCount = tokens.length;
  11690. var lineHeight = line.lineHeight;
  11691. var remainedWidth = line.width;
  11692. var leftIndex = 0;
  11693. var lineXLeft = xLeft;
  11694. var lineXRight = xRight;
  11695. var rightIndex = tokenCount - 1;
  11696. var token = void 0;
  11697. while (leftIndex < tokenCount
  11698. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11699. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11700. remainedWidth -= token.width;
  11701. lineXLeft += token.width;
  11702. leftIndex++;
  11703. }
  11704. while (rightIndex >= 0
  11705. && (token = tokens[rightIndex], token.align === 'right')) {
  11706. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11707. remainedWidth -= token.width;
  11708. lineXRight -= token.width;
  11709. rightIndex--;
  11710. }
  11711. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11712. while (leftIndex <= rightIndex) {
  11713. token = tokens[leftIndex];
  11714. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11715. lineXLeft += token.width;
  11716. leftIndex++;
  11717. }
  11718. lineTop += lineHeight;
  11719. }
  11720. };
  11721. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11722. var tokenStyle = style.rich[token.styleName] || {};
  11723. tokenStyle.text = token.text;
  11724. var verticalAlign = token.verticalAlign;
  11725. var y = lineTop + lineHeight / 2;
  11726. if (verticalAlign === 'top') {
  11727. y = lineTop + token.height / 2;
  11728. }
  11729. else if (verticalAlign === 'bottom') {
  11730. y = lineTop + lineHeight - token.height / 2;
  11731. }
  11732. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11733. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11734. ? x - token.width
  11735. : textAlign === 'center'
  11736. ? x - token.width / 2
  11737. : x, y - token.height / 2, token.width, token.height);
  11738. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11739. var textPadding = token.textPadding;
  11740. if (textPadding) {
  11741. x = getTextXForPadding(x, textAlign, textPadding);
  11742. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11743. }
  11744. var el = this._getOrCreateChild(TSpan);
  11745. var subElStyle = el.createStyle();
  11746. el.useStyle(subElStyle);
  11747. var defaultStyle = this._defaultStyle;
  11748. var useDefaultFill = false;
  11749. var defaultLineWidth = 0;
  11750. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11751. : 'fill' in style ? style.fill
  11752. : (useDefaultFill = true, defaultStyle.fill));
  11753. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11754. : 'stroke' in style ? style.stroke
  11755. : (!bgColorDrawn
  11756. && !parentBgColorDrawn
  11757. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11758. : null);
  11759. var hasShadow = tokenStyle.textShadowBlur > 0
  11760. || style.textShadowBlur > 0;
  11761. subElStyle.text = token.text;
  11762. subElStyle.x = x;
  11763. subElStyle.y = y;
  11764. if (hasShadow) {
  11765. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11766. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11767. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11768. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11769. }
  11770. subElStyle.textAlign = textAlign;
  11771. subElStyle.textBaseline = 'middle';
  11772. subElStyle.font = token.font || DEFAULT_FONT;
  11773. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11774. setSeparateFont(subElStyle, tokenStyle);
  11775. if (textStroke) {
  11776. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11777. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11778. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11779. subElStyle.stroke = textStroke;
  11780. }
  11781. if (textFill) {
  11782. subElStyle.fill = textFill;
  11783. }
  11784. var textWidth = token.contentWidth;
  11785. var textHeight = token.contentHeight;
  11786. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11787. };
  11788. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11789. var textBackgroundColor = style.backgroundColor;
  11790. var textBorderWidth = style.borderWidth;
  11791. var textBorderColor = style.borderColor;
  11792. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11793. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11794. var textBorderRadius = style.borderRadius;
  11795. var self = this;
  11796. var rectEl;
  11797. var imgEl;
  11798. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11799. rectEl = this._getOrCreateChild(Rect);
  11800. rectEl.useStyle(rectEl.createStyle());
  11801. rectEl.style.fill = null;
  11802. var rectShape = rectEl.shape;
  11803. rectShape.x = x;
  11804. rectShape.y = y;
  11805. rectShape.width = width;
  11806. rectShape.height = height;
  11807. rectShape.r = textBorderRadius;
  11808. rectEl.dirtyShape();
  11809. }
  11810. if (isPlainOrGradientBg) {
  11811. var rectStyle = rectEl.style;
  11812. rectStyle.fill = textBackgroundColor || null;
  11813. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11814. }
  11815. else if (isImageBg) {
  11816. imgEl = this._getOrCreateChild(ZRImage);
  11817. imgEl.onload = function () {
  11818. self.dirtyStyle();
  11819. };
  11820. var imgStyle = imgEl.style;
  11821. imgStyle.image = textBackgroundColor.image;
  11822. imgStyle.x = x;
  11823. imgStyle.y = y;
  11824. imgStyle.width = width;
  11825. imgStyle.height = height;
  11826. }
  11827. if (textBorderWidth && textBorderColor) {
  11828. var rectStyle = rectEl.style;
  11829. rectStyle.lineWidth = textBorderWidth;
  11830. rectStyle.stroke = textBorderColor;
  11831. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11832. rectStyle.lineDash = style.borderDash;
  11833. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11834. rectEl.strokeContainThreshold = 0;
  11835. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11836. rectStyle.strokeFirst = true;
  11837. rectStyle.lineWidth *= 2;
  11838. }
  11839. }
  11840. var commonStyle = (rectEl || imgEl).style;
  11841. commonStyle.shadowBlur = style.shadowBlur || 0;
  11842. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11843. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11844. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11845. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11846. };
  11847. ZRText.makeFont = function (style) {
  11848. var font = '';
  11849. if (hasSeparateFont(style)) {
  11850. font = [
  11851. style.fontStyle,
  11852. style.fontWeight,
  11853. parseFontSize(style.fontSize),
  11854. style.fontFamily || 'sans-serif'
  11855. ].join(' ');
  11856. }
  11857. return font && trim(font) || style.textFont || style.font;
  11858. };
  11859. return ZRText;
  11860. }(Displayable));
  11861. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11862. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11863. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11864. function parseFontSize(fontSize) {
  11865. if (typeof fontSize === 'string'
  11866. && (fontSize.indexOf('px') !== -1
  11867. || fontSize.indexOf('rem') !== -1
  11868. || fontSize.indexOf('em') !== -1)) {
  11869. return fontSize;
  11870. }
  11871. else if (!isNaN(+fontSize)) {
  11872. return fontSize + 'px';
  11873. }
  11874. else {
  11875. return DEFAULT_FONT_SIZE + 'px';
  11876. }
  11877. }
  11878. function setSeparateFont(targetStyle, sourceStyle) {
  11879. for (var i = 0; i < FONT_PARTS.length; i++) {
  11880. var fontProp = FONT_PARTS[i];
  11881. var val = sourceStyle[fontProp];
  11882. if (val != null) {
  11883. targetStyle[fontProp] = val;
  11884. }
  11885. }
  11886. }
  11887. function hasSeparateFont(style) {
  11888. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11889. }
  11890. function normalizeTextStyle(style) {
  11891. normalizeStyle(style);
  11892. each(style.rich, normalizeStyle);
  11893. return style;
  11894. }
  11895. function normalizeStyle(style) {
  11896. if (style) {
  11897. style.font = ZRText.makeFont(style);
  11898. var textAlign = style.align;
  11899. textAlign === 'middle' && (textAlign = 'center');
  11900. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11901. var verticalAlign = style.verticalAlign;
  11902. verticalAlign === 'center' && (verticalAlign = 'middle');
  11903. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11904. var textPadding = style.padding;
  11905. if (textPadding) {
  11906. style.padding = normalizeCssArray(style.padding);
  11907. }
  11908. }
  11909. }
  11910. function getStroke(stroke, lineWidth) {
  11911. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11912. ? null
  11913. : (stroke.image || stroke.colorStops)
  11914. ? '#000'
  11915. : stroke;
  11916. }
  11917. function getFill(fill) {
  11918. return (fill == null || fill === 'none')
  11919. ? null
  11920. : (fill.image || fill.colorStops)
  11921. ? '#000'
  11922. : fill;
  11923. }
  11924. function getTextXForPadding(x, textAlign, textPadding) {
  11925. return textAlign === 'right'
  11926. ? (x - textPadding[1])
  11927. : textAlign === 'center'
  11928. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11929. : (x + textPadding[3]);
  11930. }
  11931. function getStyleText(style) {
  11932. var text = style.text;
  11933. text != null && (text += '');
  11934. return text;
  11935. }
  11936. function needDrawBackground(style) {
  11937. return !!(style.backgroundColor
  11938. || style.lineHeight
  11939. || (style.borderWidth && style.borderColor));
  11940. }
  11941. var getECData = makeInner();
  11942. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  11943. if (el) {
  11944. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  11945. // Useful in tooltip
  11946. ecData.dataIndex = dataIdx;
  11947. ecData.dataType = dataType;
  11948. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  11949. if (el.type === 'group') {
  11950. el.traverse(function (child) {
  11951. var childECData = getECData(child);
  11952. childECData.seriesIndex = seriesIndex;
  11953. childECData.dataIndex = dataIdx;
  11954. childECData.dataType = dataType;
  11955. });
  11956. }
  11957. }
  11958. };
  11959. var _highlightNextDigit = 1;
  11960. var _highlightKeyMap = {};
  11961. var getSavedStates = makeInner();
  11962. var getComponentStates = makeInner();
  11963. var HOVER_STATE_NORMAL = 0;
  11964. var HOVER_STATE_BLUR = 1;
  11965. var HOVER_STATE_EMPHASIS = 2;
  11966. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11967. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11968. var Z2_EMPHASIS_LIFT = 10;
  11969. var Z2_SELECT_LIFT = 9;
  11970. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11971. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11972. var SELECT_ACTION_TYPE = 'select';
  11973. var UNSELECT_ACTION_TYPE = 'unselect';
  11974. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11975. function hasFillOrStroke(fillOrStroke) {
  11976. return fillOrStroke != null && fillOrStroke !== 'none';
  11977. } // Most lifted color are duplicated.
  11978. var liftedColorCache = new LRU(100);
  11979. function liftColor(color$1) {
  11980. if (isString(color$1)) {
  11981. var liftedColor = liftedColorCache.get(color$1);
  11982. if (!liftedColor) {
  11983. liftedColor = lift(color$1, -0.1);
  11984. liftedColorCache.put(color$1, liftedColor);
  11985. }
  11986. return liftedColor;
  11987. } else if (isGradientObject(color$1)) {
  11988. var ret = extend({}, color$1);
  11989. ret.colorStops = map(color$1.colorStops, function (stop) {
  11990. return {
  11991. offset: stop.offset,
  11992. color: lift(stop.color, -0.1)
  11993. };
  11994. });
  11995. return ret;
  11996. } // Change nothing.
  11997. return color$1;
  11998. }
  11999. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12000. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12001. el.onHoverStateChange(stateName);
  12002. }
  12003. el.hoverState = hoverStateEnum;
  12004. }
  12005. function singleEnterEmphasis(el) {
  12006. // Only mark the flag.
  12007. // States will be applied in the echarts.ts in next frame.
  12008. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12009. }
  12010. function singleLeaveEmphasis(el) {
  12011. // Only mark the flag.
  12012. // States will be applied in the echarts.ts in next frame.
  12013. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12014. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12015. }
  12016. }
  12017. function singleEnterBlur(el) {
  12018. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12019. }
  12020. function singleLeaveBlur(el) {
  12021. if (el.hoverState === HOVER_STATE_BLUR) {
  12022. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12023. }
  12024. }
  12025. function singleEnterSelect(el) {
  12026. el.selected = true;
  12027. }
  12028. function singleLeaveSelect(el) {
  12029. el.selected = false;
  12030. }
  12031. function updateElementState(el, updater, commonParam) {
  12032. updater(el, commonParam);
  12033. }
  12034. function traverseUpdateState(el, updater, commonParam) {
  12035. updateElementState(el, updater, commonParam);
  12036. el.isGroup && el.traverse(function (child) {
  12037. updateElementState(child, updater, commonParam);
  12038. });
  12039. }
  12040. function setStatesFlag(el, stateName) {
  12041. switch (stateName) {
  12042. case 'emphasis':
  12043. el.hoverState = HOVER_STATE_EMPHASIS;
  12044. break;
  12045. case 'normal':
  12046. el.hoverState = HOVER_STATE_NORMAL;
  12047. break;
  12048. case 'blur':
  12049. el.hoverState = HOVER_STATE_BLUR;
  12050. break;
  12051. case 'select':
  12052. el.selected = true;
  12053. }
  12054. }
  12055. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12056. var style = el.style;
  12057. var fromState = {};
  12058. for (var i = 0; i < props.length; i++) {
  12059. var propName = props[i];
  12060. var val = style[propName];
  12061. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12062. }
  12063. for (var i = 0; i < el.animators.length; i++) {
  12064. var animator = el.animators[i];
  12065. if (animator.__fromStateTransition // Don't consider the animation to emphasis state.
  12066. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12067. animator.saveTo(fromState, props);
  12068. }
  12069. }
  12070. return fromState;
  12071. }
  12072. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12073. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12074. var cloned = false;
  12075. if (el instanceof Path) {
  12076. var store = getSavedStates(el);
  12077. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12078. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12079. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12080. state = state || {};
  12081. var emphasisStyle = state.style || {}; // inherit case
  12082. if (emphasisStyle.fill === 'inherit') {
  12083. cloned = true;
  12084. state = extend({}, state);
  12085. emphasisStyle = extend({}, emphasisStyle);
  12086. emphasisStyle.fill = fromFill;
  12087. } // Apply default color lift
  12088. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12089. cloned = true; // Not modify the original value.
  12090. state = extend({}, state);
  12091. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  12092. emphasisStyle.fill = liftColor(fromFill);
  12093. } // Not highlight stroke if fill has been highlighted.
  12094. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12095. if (!cloned) {
  12096. state = extend({}, state);
  12097. emphasisStyle = extend({}, emphasisStyle);
  12098. }
  12099. emphasisStyle.stroke = liftColor(fromStroke);
  12100. }
  12101. state.style = emphasisStyle;
  12102. }
  12103. }
  12104. if (state) {
  12105. // TODO Share with textContent?
  12106. if (state.z2 == null) {
  12107. if (!cloned) {
  12108. state = extend({}, state);
  12109. }
  12110. var z2EmphasisLift = el.z2EmphasisLift;
  12111. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12112. }
  12113. }
  12114. return state;
  12115. }
  12116. function createSelectDefaultState(el, stateName, state) {
  12117. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12118. if (state) {
  12119. // TODO Share with textContent?
  12120. if (state.z2 == null) {
  12121. state = extend({}, state);
  12122. var z2SelectLift = el.z2SelectLift;
  12123. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12124. }
  12125. }
  12126. return state;
  12127. }
  12128. function createBlurDefaultState(el, stateName, state) {
  12129. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12130. var currentOpacity = el.style.opacity;
  12131. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12132. opacity: 1
  12133. }) : null;
  12134. state = state || {};
  12135. var blurStyle = state.style || {};
  12136. if (blurStyle.opacity == null) {
  12137. // clone state
  12138. state = extend({}, state);
  12139. blurStyle = extend({
  12140. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12141. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12142. }, blurStyle);
  12143. state.style = blurStyle;
  12144. }
  12145. return state;
  12146. }
  12147. function elementStateProxy(stateName, targetStates) {
  12148. var state = this.states[stateName];
  12149. if (this.style) {
  12150. if (stateName === 'emphasis') {
  12151. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12152. } else if (stateName === 'blur') {
  12153. return createBlurDefaultState(this, stateName, state);
  12154. } else if (stateName === 'select') {
  12155. return createSelectDefaultState(this, stateName, state);
  12156. }
  12157. }
  12158. return state;
  12159. }
  12160. /**
  12161. * Set hover style (namely "emphasis style") of element.
  12162. * @param el Should not be `zrender/graphic/Group`.
  12163. * @param focus 'self' | 'selfInSeries' | 'series'
  12164. */
  12165. function setDefaultStateProxy(el) {
  12166. el.stateProxy = elementStateProxy;
  12167. var textContent = el.getTextContent();
  12168. var textGuide = el.getTextGuideLine();
  12169. if (textContent) {
  12170. textContent.stateProxy = elementStateProxy;
  12171. }
  12172. if (textGuide) {
  12173. textGuide.stateProxy = elementStateProxy;
  12174. }
  12175. }
  12176. function enterEmphasisWhenMouseOver(el, e) {
  12177. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12178. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12179. }
  12180. function leaveEmphasisWhenMouseOut(el, e) {
  12181. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12182. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12183. }
  12184. function enterEmphasis(el, highlightDigit) {
  12185. el.__highByOuter |= 1 << (highlightDigit || 0);
  12186. traverseUpdateState(el, singleEnterEmphasis);
  12187. }
  12188. function leaveEmphasis(el, highlightDigit) {
  12189. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12190. }
  12191. function enterBlur(el) {
  12192. traverseUpdateState(el, singleEnterBlur);
  12193. }
  12194. function leaveBlur(el) {
  12195. traverseUpdateState(el, singleLeaveBlur);
  12196. }
  12197. function enterSelect(el) {
  12198. traverseUpdateState(el, singleEnterSelect);
  12199. }
  12200. function leaveSelect(el) {
  12201. traverseUpdateState(el, singleLeaveSelect);
  12202. }
  12203. function shouldSilent(el, e) {
  12204. return el.__highDownSilentOnTouch && e.zrByTouch;
  12205. }
  12206. function allLeaveBlur(api) {
  12207. var model = api.getModel();
  12208. var leaveBlurredSeries = [];
  12209. var allComponentViews = [];
  12210. model.eachComponent(function (componentType, componentModel) {
  12211. var componentStates = getComponentStates(componentModel);
  12212. var isSeries = componentType === 'series';
  12213. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12214. !isSeries && allComponentViews.push(view);
  12215. if (componentStates.isBlured) {
  12216. // Leave blur anyway
  12217. view.group.traverse(function (child) {
  12218. singleLeaveBlur(child);
  12219. });
  12220. isSeries && leaveBlurredSeries.push(componentModel);
  12221. }
  12222. componentStates.isBlured = false;
  12223. });
  12224. each(allComponentViews, function (view) {
  12225. if (view && view.toggleBlurSeries) {
  12226. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12227. }
  12228. });
  12229. }
  12230. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12231. var ecModel = api.getModel();
  12232. blurScope = blurScope || 'coordinateSystem';
  12233. function leaveBlurOfIndices(data, dataIndices) {
  12234. for (var i = 0; i < dataIndices.length; i++) {
  12235. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12236. itemEl && leaveBlur(itemEl);
  12237. }
  12238. }
  12239. if (targetSeriesIndex == null) {
  12240. return;
  12241. }
  12242. if (!focus || focus === 'none') {
  12243. return;
  12244. }
  12245. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12246. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12247. if (targetCoordSys && targetCoordSys.master) {
  12248. targetCoordSys = targetCoordSys.master;
  12249. }
  12250. var blurredSeries = [];
  12251. ecModel.eachSeries(function (seriesModel) {
  12252. var sameSeries = targetSeriesModel === seriesModel;
  12253. var coordSys = seriesModel.coordinateSystem;
  12254. if (coordSys && coordSys.master) {
  12255. coordSys = coordSys.master;
  12256. }
  12257. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12258. if (!( // Not blur other series if blurScope series
  12259. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12260. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12261. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12262. )) {
  12263. var view = api.getViewOfSeriesModel(seriesModel);
  12264. view.group.traverse(function (child) {
  12265. singleEnterBlur(child);
  12266. });
  12267. if (isArrayLike(focus)) {
  12268. leaveBlurOfIndices(seriesModel.getData(), focus);
  12269. } else if (isObject(focus)) {
  12270. var dataTypes = keys(focus);
  12271. for (var d = 0; d < dataTypes.length; d++) {
  12272. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12273. }
  12274. }
  12275. blurredSeries.push(seriesModel);
  12276. getComponentStates(seriesModel).isBlured = true;
  12277. }
  12278. });
  12279. ecModel.eachComponent(function (componentType, componentModel) {
  12280. if (componentType === 'series') {
  12281. return;
  12282. }
  12283. var view = api.getViewOfComponentModel(componentModel);
  12284. if (view && view.toggleBlurSeries) {
  12285. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12286. }
  12287. });
  12288. }
  12289. function blurComponent(componentMainType, componentIndex, api) {
  12290. if (componentMainType == null || componentIndex == null) {
  12291. return;
  12292. }
  12293. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12294. if (!componentModel) {
  12295. return;
  12296. }
  12297. getComponentStates(componentModel).isBlured = true;
  12298. var view = api.getViewOfComponentModel(componentModel);
  12299. if (!view || !view.focusBlurEnabled) {
  12300. return;
  12301. }
  12302. view.group.traverse(function (child) {
  12303. singleEnterBlur(child);
  12304. });
  12305. }
  12306. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12307. var seriesIndex = seriesModel.seriesIndex;
  12308. var data = seriesModel.getData(payload.dataType);
  12309. if (!data) {
  12310. if ("development" !== 'production') {
  12311. error("Unknown dataType " + payload.dataType);
  12312. }
  12313. return;
  12314. }
  12315. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12316. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12317. var el = data.getItemGraphicEl(dataIndex);
  12318. if (!el) {
  12319. var count = data.count();
  12320. var current = 0; // If data on dataIndex is NaN.
  12321. while (!el && current < count) {
  12322. el = data.getItemGraphicEl(current++);
  12323. }
  12324. }
  12325. if (el) {
  12326. var ecData = getECData(el);
  12327. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12328. } else {
  12329. // If there is no element put on the data. Try getting it from raw option
  12330. // TODO Should put it on seriesModel?
  12331. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12332. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12333. if (focus_1 != null) {
  12334. blurSeries(seriesIndex, focus_1, blurScope, api);
  12335. }
  12336. }
  12337. }
  12338. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12339. var ret = {
  12340. focusSelf: false,
  12341. dispatchers: null
  12342. };
  12343. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12344. return ret;
  12345. }
  12346. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12347. if (!componentModel) {
  12348. return ret;
  12349. }
  12350. var view = api.getViewOfComponentModel(componentModel);
  12351. if (!view || !view.findHighDownDispatchers) {
  12352. return ret;
  12353. }
  12354. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12355. // So we do not use `blurScope` in component.
  12356. var focusSelf;
  12357. for (var i = 0; i < dispatchers.length; i++) {
  12358. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12359. error('param should be highDownDispatcher');
  12360. }
  12361. if (getECData(dispatchers[i]).focus === 'self') {
  12362. focusSelf = true;
  12363. break;
  12364. }
  12365. }
  12366. return {
  12367. focusSelf: focusSelf,
  12368. dispatchers: dispatchers
  12369. };
  12370. }
  12371. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12372. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12373. error('param should be highDownDispatcher');
  12374. }
  12375. var ecData = getECData(dispatcher);
  12376. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12377. dispatchers = _a.dispatchers,
  12378. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12379. // highlight/downplay elements with the same name.
  12380. if (dispatchers) {
  12381. if (focusSelf) {
  12382. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12383. }
  12384. each(dispatchers, function (dispatcher) {
  12385. return enterEmphasisWhenMouseOver(dispatcher, e);
  12386. });
  12387. } else {
  12388. // Try blur all in the related series. Then emphasis the hoverred.
  12389. // TODO. progressive mode.
  12390. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12391. if (ecData.focus === 'self') {
  12392. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12393. } // Other than series, component that not support `findHighDownDispatcher` will
  12394. // also use it. But in this case, highlight/downplay are only supported in
  12395. // mouse hover but not in dispatchAction.
  12396. enterEmphasisWhenMouseOver(dispatcher, e);
  12397. }
  12398. }
  12399. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12400. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12401. error('param should be highDownDispatcher');
  12402. }
  12403. allLeaveBlur(api);
  12404. var ecData = getECData(dispatcher);
  12405. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12406. if (dispatchers) {
  12407. each(dispatchers, function (dispatcher) {
  12408. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12409. });
  12410. } else {
  12411. leaveEmphasisWhenMouseOut(dispatcher, e);
  12412. }
  12413. }
  12414. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12415. if (!isSelectChangePayload(payload)) {
  12416. return;
  12417. }
  12418. var dataType = payload.dataType;
  12419. var data = seriesModel.getData(dataType);
  12420. var dataIndex = queryDataIndex(data, payload);
  12421. if (!isArray(dataIndex)) {
  12422. dataIndex = [dataIndex];
  12423. }
  12424. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12425. }
  12426. function updateSeriesElementSelection(seriesModel) {
  12427. var allData = seriesModel.getAllData();
  12428. each(allData, function (_a) {
  12429. var data = _a.data,
  12430. type = _a.type;
  12431. data.eachItemGraphicEl(function (el, idx) {
  12432. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12433. });
  12434. });
  12435. }
  12436. function getAllSelectedIndices(ecModel) {
  12437. var ret = [];
  12438. ecModel.eachSeries(function (seriesModel) {
  12439. var allData = seriesModel.getAllData();
  12440. each(allData, function (_a) {
  12441. var data = _a.data,
  12442. type = _a.type;
  12443. var dataIndices = seriesModel.getSelectedDataIndices();
  12444. if (dataIndices.length > 0) {
  12445. var item = {
  12446. dataIndex: dataIndices,
  12447. seriesIndex: seriesModel.seriesIndex
  12448. };
  12449. if (type != null) {
  12450. item.dataType = type;
  12451. }
  12452. ret.push(item);
  12453. }
  12454. });
  12455. });
  12456. return ret;
  12457. }
  12458. /**
  12459. * Enable the function that mouseover will trigger the emphasis state.
  12460. *
  12461. * NOTE:
  12462. * This function should be used on the element with dataIndex, seriesIndex.
  12463. *
  12464. */
  12465. function enableHoverEmphasis(el, focus, blurScope) {
  12466. setAsHighDownDispatcher(el, true);
  12467. traverseUpdateState(el, setDefaultStateProxy);
  12468. enableHoverFocus(el, focus, blurScope);
  12469. }
  12470. function disableHoverEmphasis(el) {
  12471. setAsHighDownDispatcher(el, false);
  12472. }
  12473. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12474. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12475. }
  12476. function enableHoverFocus(el, focus, blurScope) {
  12477. var ecData = getECData(el);
  12478. if (focus != null) {
  12479. // TODO dataIndex may be set after this function. This check is not useful.
  12480. // if (ecData.dataIndex == null) {
  12481. // if (__DEV__) {
  12482. // console.warn('focus can only been set on element with dataIndex');
  12483. // }
  12484. // }
  12485. // else {
  12486. ecData.focus = focus;
  12487. ecData.blurScope = blurScope; // }
  12488. } else if (ecData.focus) {
  12489. ecData.focus = null;
  12490. }
  12491. }
  12492. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12493. var defaultStyleGetterMap = {
  12494. itemStyle: 'getItemStyle',
  12495. lineStyle: 'getLineStyle',
  12496. areaStyle: 'getAreaStyle'
  12497. };
  12498. /**
  12499. * Set emphasis/blur/selected states of element.
  12500. */
  12501. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12502. getter) {
  12503. styleType = styleType || 'itemStyle';
  12504. for (var i = 0; i < OTHER_STATES.length; i++) {
  12505. var stateName = OTHER_STATES[i];
  12506. var model = itemModel.getModel([stateName, styleType]);
  12507. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12508. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12509. }
  12510. }
  12511. /**
  12512. *
  12513. * Set element as highlight / downplay dispatcher.
  12514. * It will be checked when element received mouseover event or from highlight action.
  12515. * It's in change of all highlight/downplay behavior of it's children.
  12516. *
  12517. * @param el
  12518. * @param el.highDownSilentOnTouch
  12519. * In touch device, mouseover event will be trigger on touchstart event
  12520. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12521. * conveniently use hoverStyle when tap on touch screen without additional
  12522. * code for compatibility.
  12523. * But if the chart/component has select feature, which usually also use
  12524. * hoverStyle, there might be conflict between 'select-highlight' and
  12525. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12526. * In this case, `highDownSilentOnTouch` should be used to disable
  12527. * hover-highlight on touch device.
  12528. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12529. */
  12530. function setAsHighDownDispatcher(el, asDispatcher) {
  12531. var disable = asDispatcher === false;
  12532. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12533. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12534. if (el.highDownSilentOnTouch) {
  12535. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12536. } // Simple optimize, since this method might be
  12537. // called for each elements of a group in some cases.
  12538. if (!disable || extendedEl.__highDownDispatcher) {
  12539. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12540. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12541. // Also keep previous record.
  12542. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12543. extendedEl.__highDownDispatcher = !disable;
  12544. }
  12545. }
  12546. function isHighDownDispatcher(el) {
  12547. return !!(el && el.__highDownDispatcher);
  12548. }
  12549. /**
  12550. * Support highlight/downplay record on each elements.
  12551. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12552. * user triggered highlight/downplay should not conflict.
  12553. * Only all of the highlightDigit cleared, return to normal.
  12554. * @param {string} highlightKey
  12555. * @return {number} highlightDigit
  12556. */
  12557. function getHighlightDigit(highlightKey) {
  12558. var highlightDigit = _highlightKeyMap[highlightKey];
  12559. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12560. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12561. }
  12562. return highlightDigit;
  12563. }
  12564. function isSelectChangePayload(payload) {
  12565. var payloadType = payload.type;
  12566. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12567. }
  12568. function isHighDownPayload(payload) {
  12569. var payloadType = payload.type;
  12570. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12571. }
  12572. function savePathStates(el) {
  12573. var store = getSavedStates(el);
  12574. store.normalFill = el.style.fill;
  12575. store.normalStroke = el.style.stroke;
  12576. var selectState = el.states.select || {};
  12577. store.selectFill = selectState.style && selectState.style.fill || null;
  12578. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12579. }
  12580. var CMD$2 = PathProxy.CMD;
  12581. var points = [[], [], []];
  12582. var mathSqrt$1 = Math.sqrt;
  12583. var mathAtan2 = Math.atan2;
  12584. function transformPath(path, m) {
  12585. if (!m) {
  12586. return;
  12587. }
  12588. var data = path.data;
  12589. var len = path.len();
  12590. var cmd;
  12591. var nPoint;
  12592. var i;
  12593. var j;
  12594. var k;
  12595. var p;
  12596. var M = CMD$2.M;
  12597. var C = CMD$2.C;
  12598. var L = CMD$2.L;
  12599. var R = CMD$2.R;
  12600. var A = CMD$2.A;
  12601. var Q = CMD$2.Q;
  12602. for (i = 0, j = 0; i < len;) {
  12603. cmd = data[i++];
  12604. j = i;
  12605. nPoint = 0;
  12606. switch (cmd) {
  12607. case M:
  12608. nPoint = 1;
  12609. break;
  12610. case L:
  12611. nPoint = 1;
  12612. break;
  12613. case C:
  12614. nPoint = 3;
  12615. break;
  12616. case Q:
  12617. nPoint = 2;
  12618. break;
  12619. case A:
  12620. var x = m[4];
  12621. var y = m[5];
  12622. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12623. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12624. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12625. data[i] *= sx;
  12626. data[i++] += x;
  12627. data[i] *= sy;
  12628. data[i++] += y;
  12629. data[i++] *= sx;
  12630. data[i++] *= sy;
  12631. data[i++] += angle;
  12632. data[i++] += angle;
  12633. i += 2;
  12634. j = i;
  12635. break;
  12636. case R:
  12637. p[0] = data[i++];
  12638. p[1] = data[i++];
  12639. applyTransform(p, p, m);
  12640. data[j++] = p[0];
  12641. data[j++] = p[1];
  12642. p[0] += data[i++];
  12643. p[1] += data[i++];
  12644. applyTransform(p, p, m);
  12645. data[j++] = p[0];
  12646. data[j++] = p[1];
  12647. }
  12648. for (k = 0; k < nPoint; k++) {
  12649. var p_1 = points[k];
  12650. p_1[0] = data[i++];
  12651. p_1[1] = data[i++];
  12652. applyTransform(p_1, p_1, m);
  12653. data[j++] = p_1[0];
  12654. data[j++] = p_1[1];
  12655. }
  12656. }
  12657. path.increaseVersion();
  12658. }
  12659. var mathSqrt$2 = Math.sqrt;
  12660. var mathSin$2 = Math.sin;
  12661. var mathCos$2 = Math.cos;
  12662. var PI$1 = Math.PI;
  12663. function vMag(v) {
  12664. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12665. }
  12666. function vRatio(u, v) {
  12667. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12668. }
  12669. function vAngle(u, v) {
  12670. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12671. * Math.acos(vRatio(u, v));
  12672. }
  12673. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12674. var psi = psiDeg * (PI$1 / 180.0);
  12675. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12676. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12677. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12678. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12679. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12680. if (lambda > 1) {
  12681. rx *= mathSqrt$2(lambda);
  12682. ry *= mathSqrt$2(lambda);
  12683. }
  12684. var f = (fa === fs ? -1 : 1)
  12685. * mathSqrt$2((((rx * rx) * (ry * ry))
  12686. - ((rx * rx) * (yp * yp))
  12687. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12688. + (ry * ry) * (xp * xp))) || 0;
  12689. var cxp = f * rx * yp / ry;
  12690. var cyp = f * -ry * xp / rx;
  12691. var cx = (x1 + x2) / 2.0
  12692. + mathCos$2(psi) * cxp
  12693. - mathSin$2(psi) * cyp;
  12694. var cy = (y1 + y2) / 2.0
  12695. + mathSin$2(psi) * cxp
  12696. + mathCos$2(psi) * cyp;
  12697. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12698. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12699. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12700. var dTheta = vAngle(u, v);
  12701. if (vRatio(u, v) <= -1) {
  12702. dTheta = PI$1;
  12703. }
  12704. if (vRatio(u, v) >= 1) {
  12705. dTheta = 0;
  12706. }
  12707. if (dTheta < 0) {
  12708. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12709. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12710. }
  12711. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12712. }
  12713. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12714. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12715. function createPathProxyFromString(data) {
  12716. var path = new PathProxy();
  12717. if (!data) {
  12718. return path;
  12719. }
  12720. var cpx = 0;
  12721. var cpy = 0;
  12722. var subpathX = cpx;
  12723. var subpathY = cpy;
  12724. var prevCmd;
  12725. var CMD = PathProxy.CMD;
  12726. var cmdList = data.match(commandReg);
  12727. if (!cmdList) {
  12728. return path;
  12729. }
  12730. for (var l = 0; l < cmdList.length; l++) {
  12731. var cmdText = cmdList[l];
  12732. var cmdStr = cmdText.charAt(0);
  12733. var cmd = void 0;
  12734. var p = cmdText.match(numberReg) || [];
  12735. var pLen = p.length;
  12736. for (var i = 0; i < pLen; i++) {
  12737. p[i] = parseFloat(p[i]);
  12738. }
  12739. var off = 0;
  12740. while (off < pLen) {
  12741. var ctlPtx = void 0;
  12742. var ctlPty = void 0;
  12743. var rx = void 0;
  12744. var ry = void 0;
  12745. var psi = void 0;
  12746. var fa = void 0;
  12747. var fs = void 0;
  12748. var x1 = cpx;
  12749. var y1 = cpy;
  12750. var len = void 0;
  12751. var pathData = void 0;
  12752. switch (cmdStr) {
  12753. case 'l':
  12754. cpx += p[off++];
  12755. cpy += p[off++];
  12756. cmd = CMD.L;
  12757. path.addData(cmd, cpx, cpy);
  12758. break;
  12759. case 'L':
  12760. cpx = p[off++];
  12761. cpy = p[off++];
  12762. cmd = CMD.L;
  12763. path.addData(cmd, cpx, cpy);
  12764. break;
  12765. case 'm':
  12766. cpx += p[off++];
  12767. cpy += p[off++];
  12768. cmd = CMD.M;
  12769. path.addData(cmd, cpx, cpy);
  12770. subpathX = cpx;
  12771. subpathY = cpy;
  12772. cmdStr = 'l';
  12773. break;
  12774. case 'M':
  12775. cpx = p[off++];
  12776. cpy = p[off++];
  12777. cmd = CMD.M;
  12778. path.addData(cmd, cpx, cpy);
  12779. subpathX = cpx;
  12780. subpathY = cpy;
  12781. cmdStr = 'L';
  12782. break;
  12783. case 'h':
  12784. cpx += p[off++];
  12785. cmd = CMD.L;
  12786. path.addData(cmd, cpx, cpy);
  12787. break;
  12788. case 'H':
  12789. cpx = p[off++];
  12790. cmd = CMD.L;
  12791. path.addData(cmd, cpx, cpy);
  12792. break;
  12793. case 'v':
  12794. cpy += p[off++];
  12795. cmd = CMD.L;
  12796. path.addData(cmd, cpx, cpy);
  12797. break;
  12798. case 'V':
  12799. cpy = p[off++];
  12800. cmd = CMD.L;
  12801. path.addData(cmd, cpx, cpy);
  12802. break;
  12803. case 'C':
  12804. cmd = CMD.C;
  12805. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12806. cpx = p[off - 2];
  12807. cpy = p[off - 1];
  12808. break;
  12809. case 'c':
  12810. cmd = CMD.C;
  12811. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12812. cpx += p[off - 2];
  12813. cpy += p[off - 1];
  12814. break;
  12815. case 'S':
  12816. ctlPtx = cpx;
  12817. ctlPty = cpy;
  12818. len = path.len();
  12819. pathData = path.data;
  12820. if (prevCmd === CMD.C) {
  12821. ctlPtx += cpx - pathData[len - 4];
  12822. ctlPty += cpy - pathData[len - 3];
  12823. }
  12824. cmd = CMD.C;
  12825. x1 = p[off++];
  12826. y1 = p[off++];
  12827. cpx = p[off++];
  12828. cpy = p[off++];
  12829. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12830. break;
  12831. case 's':
  12832. ctlPtx = cpx;
  12833. ctlPty = cpy;
  12834. len = path.len();
  12835. pathData = path.data;
  12836. if (prevCmd === CMD.C) {
  12837. ctlPtx += cpx - pathData[len - 4];
  12838. ctlPty += cpy - pathData[len - 3];
  12839. }
  12840. cmd = CMD.C;
  12841. x1 = cpx + p[off++];
  12842. y1 = cpy + p[off++];
  12843. cpx += p[off++];
  12844. cpy += p[off++];
  12845. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12846. break;
  12847. case 'Q':
  12848. x1 = p[off++];
  12849. y1 = p[off++];
  12850. cpx = p[off++];
  12851. cpy = p[off++];
  12852. cmd = CMD.Q;
  12853. path.addData(cmd, x1, y1, cpx, cpy);
  12854. break;
  12855. case 'q':
  12856. x1 = p[off++] + cpx;
  12857. y1 = p[off++] + cpy;
  12858. cpx += p[off++];
  12859. cpy += p[off++];
  12860. cmd = CMD.Q;
  12861. path.addData(cmd, x1, y1, cpx, cpy);
  12862. break;
  12863. case 'T':
  12864. ctlPtx = cpx;
  12865. ctlPty = cpy;
  12866. len = path.len();
  12867. pathData = path.data;
  12868. if (prevCmd === CMD.Q) {
  12869. ctlPtx += cpx - pathData[len - 4];
  12870. ctlPty += cpy - pathData[len - 3];
  12871. }
  12872. cpx = p[off++];
  12873. cpy = p[off++];
  12874. cmd = CMD.Q;
  12875. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12876. break;
  12877. case 't':
  12878. ctlPtx = cpx;
  12879. ctlPty = cpy;
  12880. len = path.len();
  12881. pathData = path.data;
  12882. if (prevCmd === CMD.Q) {
  12883. ctlPtx += cpx - pathData[len - 4];
  12884. ctlPty += cpy - pathData[len - 3];
  12885. }
  12886. cpx += p[off++];
  12887. cpy += p[off++];
  12888. cmd = CMD.Q;
  12889. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12890. break;
  12891. case 'A':
  12892. rx = p[off++];
  12893. ry = p[off++];
  12894. psi = p[off++];
  12895. fa = p[off++];
  12896. fs = p[off++];
  12897. x1 = cpx, y1 = cpy;
  12898. cpx = p[off++];
  12899. cpy = p[off++];
  12900. cmd = CMD.A;
  12901. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12902. break;
  12903. case 'a':
  12904. rx = p[off++];
  12905. ry = p[off++];
  12906. psi = p[off++];
  12907. fa = p[off++];
  12908. fs = p[off++];
  12909. x1 = cpx, y1 = cpy;
  12910. cpx += p[off++];
  12911. cpy += p[off++];
  12912. cmd = CMD.A;
  12913. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12914. break;
  12915. }
  12916. }
  12917. if (cmdStr === 'z' || cmdStr === 'Z') {
  12918. cmd = CMD.Z;
  12919. path.addData(cmd);
  12920. cpx = subpathX;
  12921. cpy = subpathY;
  12922. }
  12923. prevCmd = cmd;
  12924. }
  12925. path.toStatic();
  12926. return path;
  12927. }
  12928. var SVGPath = (function (_super) {
  12929. __extends(SVGPath, _super);
  12930. function SVGPath() {
  12931. return _super !== null && _super.apply(this, arguments) || this;
  12932. }
  12933. SVGPath.prototype.applyTransform = function (m) { };
  12934. return SVGPath;
  12935. }(Path));
  12936. function isPathProxy(path) {
  12937. return path.setData != null;
  12938. }
  12939. function createPathOptions(str, opts) {
  12940. var pathProxy = createPathProxyFromString(str);
  12941. var innerOpts = extend({}, opts);
  12942. innerOpts.buildPath = function (path) {
  12943. if (isPathProxy(path)) {
  12944. path.setData(pathProxy.data);
  12945. var ctx = path.getContext();
  12946. if (ctx) {
  12947. path.rebuildPath(ctx, 1);
  12948. }
  12949. }
  12950. else {
  12951. var ctx = path;
  12952. pathProxy.rebuildPath(ctx, 1);
  12953. }
  12954. };
  12955. innerOpts.applyTransform = function (m) {
  12956. transformPath(pathProxy, m);
  12957. this.dirtyShape();
  12958. };
  12959. return innerOpts;
  12960. }
  12961. function createFromString(str, opts) {
  12962. return new SVGPath(createPathOptions(str, opts));
  12963. }
  12964. function extendFromString(str, defaultOpts) {
  12965. var innerOpts = createPathOptions(str, defaultOpts);
  12966. var Sub = (function (_super) {
  12967. __extends(Sub, _super);
  12968. function Sub(opts) {
  12969. var _this = _super.call(this, opts) || this;
  12970. _this.applyTransform = innerOpts.applyTransform;
  12971. _this.buildPath = innerOpts.buildPath;
  12972. return _this;
  12973. }
  12974. return Sub;
  12975. }(SVGPath));
  12976. return Sub;
  12977. }
  12978. function mergePath(pathEls, opts) {
  12979. var pathList = [];
  12980. var len = pathEls.length;
  12981. for (var i = 0; i < len; i++) {
  12982. var pathEl = pathEls[i];
  12983. pathList.push(pathEl.getUpdatedPathProxy(true));
  12984. }
  12985. var pathBundle = new Path(opts);
  12986. pathBundle.createPathProxy();
  12987. pathBundle.buildPath = function (path) {
  12988. if (isPathProxy(path)) {
  12989. path.appendPath(pathList);
  12990. var ctx = path.getContext();
  12991. if (ctx) {
  12992. path.rebuildPath(ctx, 1);
  12993. }
  12994. }
  12995. };
  12996. return pathBundle;
  12997. }
  12998. var CircleShape = (function () {
  12999. function CircleShape() {
  13000. this.cx = 0;
  13001. this.cy = 0;
  13002. this.r = 0;
  13003. }
  13004. return CircleShape;
  13005. }());
  13006. var Circle = (function (_super) {
  13007. __extends(Circle, _super);
  13008. function Circle(opts) {
  13009. return _super.call(this, opts) || this;
  13010. }
  13011. Circle.prototype.getDefaultShape = function () {
  13012. return new CircleShape();
  13013. };
  13014. Circle.prototype.buildPath = function (ctx, shape) {
  13015. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13016. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13017. };
  13018. return Circle;
  13019. }(Path));
  13020. Circle.prototype.type = 'circle';
  13021. var EllipseShape = (function () {
  13022. function EllipseShape() {
  13023. this.cx = 0;
  13024. this.cy = 0;
  13025. this.rx = 0;
  13026. this.ry = 0;
  13027. }
  13028. return EllipseShape;
  13029. }());
  13030. var Ellipse = (function (_super) {
  13031. __extends(Ellipse, _super);
  13032. function Ellipse(opts) {
  13033. return _super.call(this, opts) || this;
  13034. }
  13035. Ellipse.prototype.getDefaultShape = function () {
  13036. return new EllipseShape();
  13037. };
  13038. Ellipse.prototype.buildPath = function (ctx, shape) {
  13039. var k = 0.5522848;
  13040. var x = shape.cx;
  13041. var y = shape.cy;
  13042. var a = shape.rx;
  13043. var b = shape.ry;
  13044. var ox = a * k;
  13045. var oy = b * k;
  13046. ctx.moveTo(x - a, y);
  13047. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13048. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13049. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13050. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13051. ctx.closePath();
  13052. };
  13053. return Ellipse;
  13054. }(Path));
  13055. Ellipse.prototype.type = 'ellipse';
  13056. var PI$2 = Math.PI;
  13057. var PI2$5 = PI$2 * 2;
  13058. var mathSin$3 = Math.sin;
  13059. var mathCos$3 = Math.cos;
  13060. var mathACos = Math.acos;
  13061. var mathATan2 = Math.atan2;
  13062. var mathAbs$1 = Math.abs;
  13063. var mathSqrt$3 = Math.sqrt;
  13064. var mathMax$3 = Math.max;
  13065. var mathMin$3 = Math.min;
  13066. var e = 1e-4;
  13067. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13068. var dx10 = x1 - x0;
  13069. var dy10 = y1 - y0;
  13070. var dx32 = x3 - x2;
  13071. var dy32 = y3 - y2;
  13072. var t = dy32 * dx10 - dx32 * dy10;
  13073. if (t * t < e) {
  13074. return;
  13075. }
  13076. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13077. return [x0 + t * dx10, y0 + t * dy10];
  13078. }
  13079. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13080. var x01 = x0 - x1;
  13081. var y01 = y0 - y1;
  13082. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13083. var ox = lo * y01;
  13084. var oy = -lo * x01;
  13085. var x11 = x0 + ox;
  13086. var y11 = y0 + oy;
  13087. var x10 = x1 + ox;
  13088. var y10 = y1 + oy;
  13089. var x00 = (x11 + x10) / 2;
  13090. var y00 = (y11 + y10) / 2;
  13091. var dx = x10 - x11;
  13092. var dy = y10 - y11;
  13093. var d2 = dx * dx + dy * dy;
  13094. var r = radius - cr;
  13095. var s = x11 * y10 - x10 * y11;
  13096. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13097. var cx0 = (s * dy - dx * d) / d2;
  13098. var cy0 = (-s * dx - dy * d) / d2;
  13099. var cx1 = (s * dy + dx * d) / d2;
  13100. var cy1 = (-s * dx + dy * d) / d2;
  13101. var dx0 = cx0 - x00;
  13102. var dy0 = cy0 - y00;
  13103. var dx1 = cx1 - x00;
  13104. var dy1 = cy1 - y00;
  13105. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13106. cx0 = cx1;
  13107. cy0 = cy1;
  13108. }
  13109. return {
  13110. cx: cx0,
  13111. cy: cy0,
  13112. x0: -ox,
  13113. y0: -oy,
  13114. x1: cx0 * (radius / r - 1),
  13115. y1: cy0 * (radius / r - 1)
  13116. };
  13117. }
  13118. function normalizeCornerRadius(cr) {
  13119. var arr;
  13120. if (isArray(cr)) {
  13121. var len = cr.length;
  13122. if (!len) {
  13123. return cr;
  13124. }
  13125. if (len === 1) {
  13126. arr = [cr[0], cr[0], 0, 0];
  13127. }
  13128. else if (len === 2) {
  13129. arr = [cr[0], cr[0], cr[1], cr[1]];
  13130. }
  13131. else if (len === 3) {
  13132. arr = cr.concat(cr[2]);
  13133. }
  13134. else {
  13135. arr = cr;
  13136. }
  13137. }
  13138. else {
  13139. arr = [cr, cr, cr, cr];
  13140. }
  13141. return arr;
  13142. }
  13143. function buildPath$1(ctx, shape) {
  13144. var _a;
  13145. var radius = mathMax$3(shape.r, 0);
  13146. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13147. var hasRadius = radius > 0;
  13148. var hasInnerRadius = innerRadius > 0;
  13149. if (!hasRadius && !hasInnerRadius) {
  13150. return;
  13151. }
  13152. if (!hasRadius) {
  13153. radius = innerRadius;
  13154. innerRadius = 0;
  13155. }
  13156. if (innerRadius > radius) {
  13157. var tmp = radius;
  13158. radius = innerRadius;
  13159. innerRadius = tmp;
  13160. }
  13161. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13162. if (isNaN(startAngle) || isNaN(endAngle)) {
  13163. return;
  13164. }
  13165. var cx = shape.cx, cy = shape.cy;
  13166. var clockwise = !!shape.clockwise;
  13167. var arc = mathAbs$1(endAngle - startAngle);
  13168. var mod = arc > PI2$5 && arc % PI2$5;
  13169. mod > e && (arc = mod);
  13170. if (!(radius > e)) {
  13171. ctx.moveTo(cx, cy);
  13172. }
  13173. else if (arc > PI2$5 - e) {
  13174. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13175. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13176. if (innerRadius > e) {
  13177. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13178. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13179. }
  13180. }
  13181. else {
  13182. var icrStart = void 0;
  13183. var icrEnd = void 0;
  13184. var ocrStart = void 0;
  13185. var ocrEnd = void 0;
  13186. var ocrs = void 0;
  13187. var ocre = void 0;
  13188. var icrs = void 0;
  13189. var icre = void 0;
  13190. var ocrMax = void 0;
  13191. var icrMax = void 0;
  13192. var limitedOcrMax = void 0;
  13193. var limitedIcrMax = void 0;
  13194. var xre = void 0;
  13195. var yre = void 0;
  13196. var xirs = void 0;
  13197. var yirs = void 0;
  13198. var xrs = radius * mathCos$3(startAngle);
  13199. var yrs = radius * mathSin$3(startAngle);
  13200. var xire = innerRadius * mathCos$3(endAngle);
  13201. var yire = innerRadius * mathSin$3(endAngle);
  13202. var hasArc = arc > e;
  13203. if (hasArc) {
  13204. var cornerRadius = shape.cornerRadius;
  13205. if (cornerRadius) {
  13206. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13207. }
  13208. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13209. ocrs = mathMin$3(halfRd, ocrStart);
  13210. ocre = mathMin$3(halfRd, ocrEnd);
  13211. icrs = mathMin$3(halfRd, icrStart);
  13212. icre = mathMin$3(halfRd, icrEnd);
  13213. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13214. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13215. if (ocrMax > e || icrMax > e) {
  13216. xre = radius * mathCos$3(endAngle);
  13217. yre = radius * mathSin$3(endAngle);
  13218. xirs = innerRadius * mathCos$3(startAngle);
  13219. yirs = innerRadius * mathSin$3(startAngle);
  13220. if (arc < PI$2) {
  13221. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13222. if (it_1) {
  13223. var x0 = xrs - it_1[0];
  13224. var y0 = yrs - it_1[1];
  13225. var x1 = xre - it_1[0];
  13226. var y1 = yre - it_1[1];
  13227. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13228. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13229. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13230. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13231. }
  13232. }
  13233. }
  13234. }
  13235. if (!hasArc) {
  13236. ctx.moveTo(cx + xrs, cy + yrs);
  13237. }
  13238. else if (limitedOcrMax > e) {
  13239. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13240. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13241. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13242. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13243. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13244. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13245. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13246. }
  13247. else {
  13248. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13249. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13250. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13251. }
  13252. }
  13253. else {
  13254. ctx.moveTo(cx + xrs, cy + yrs);
  13255. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13256. }
  13257. if (!(innerRadius > e) || !hasArc) {
  13258. ctx.lineTo(cx + xire, cy + yire);
  13259. }
  13260. else if (limitedIcrMax > e) {
  13261. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13262. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13263. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13264. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13265. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13266. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13267. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13268. }
  13269. else {
  13270. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13271. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13272. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13273. }
  13274. }
  13275. else {
  13276. ctx.lineTo(cx + xire, cy + yire);
  13277. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13278. }
  13279. }
  13280. ctx.closePath();
  13281. }
  13282. var SectorShape = (function () {
  13283. function SectorShape() {
  13284. this.cx = 0;
  13285. this.cy = 0;
  13286. this.r0 = 0;
  13287. this.r = 0;
  13288. this.startAngle = 0;
  13289. this.endAngle = Math.PI * 2;
  13290. this.clockwise = true;
  13291. this.cornerRadius = 0;
  13292. }
  13293. return SectorShape;
  13294. }());
  13295. var Sector = (function (_super) {
  13296. __extends(Sector, _super);
  13297. function Sector(opts) {
  13298. return _super.call(this, opts) || this;
  13299. }
  13300. Sector.prototype.getDefaultShape = function () {
  13301. return new SectorShape();
  13302. };
  13303. Sector.prototype.buildPath = function (ctx, shape) {
  13304. buildPath$1(ctx, shape);
  13305. };
  13306. Sector.prototype.isZeroArea = function () {
  13307. return this.shape.startAngle === this.shape.endAngle
  13308. || this.shape.r === this.shape.r0;
  13309. };
  13310. return Sector;
  13311. }(Path));
  13312. Sector.prototype.type = 'sector';
  13313. var RingShape = (function () {
  13314. function RingShape() {
  13315. this.cx = 0;
  13316. this.cy = 0;
  13317. this.r = 0;
  13318. this.r0 = 0;
  13319. }
  13320. return RingShape;
  13321. }());
  13322. var Ring = (function (_super) {
  13323. __extends(Ring, _super);
  13324. function Ring(opts) {
  13325. return _super.call(this, opts) || this;
  13326. }
  13327. Ring.prototype.getDefaultShape = function () {
  13328. return new RingShape();
  13329. };
  13330. Ring.prototype.buildPath = function (ctx, shape) {
  13331. var x = shape.cx;
  13332. var y = shape.cy;
  13333. var PI2 = Math.PI * 2;
  13334. ctx.moveTo(x + shape.r, y);
  13335. ctx.arc(x, y, shape.r, 0, PI2, false);
  13336. ctx.moveTo(x + shape.r0, y);
  13337. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13338. };
  13339. return Ring;
  13340. }(Path));
  13341. Ring.prototype.type = 'ring';
  13342. function smoothBezier(points, smooth, isLoop, constraint) {
  13343. var cps = [];
  13344. var v = [];
  13345. var v1 = [];
  13346. var v2 = [];
  13347. var prevPoint;
  13348. var nextPoint;
  13349. var min$1;
  13350. var max$1;
  13351. if (constraint) {
  13352. min$1 = [Infinity, Infinity];
  13353. max$1 = [-Infinity, -Infinity];
  13354. for (var i = 0, len = points.length; i < len; i++) {
  13355. min(min$1, min$1, points[i]);
  13356. max(max$1, max$1, points[i]);
  13357. }
  13358. min(min$1, min$1, constraint[0]);
  13359. max(max$1, max$1, constraint[1]);
  13360. }
  13361. for (var i = 0, len = points.length; i < len; i++) {
  13362. var point = points[i];
  13363. if (isLoop) {
  13364. prevPoint = points[i ? i - 1 : len - 1];
  13365. nextPoint = points[(i + 1) % len];
  13366. }
  13367. else {
  13368. if (i === 0 || i === len - 1) {
  13369. cps.push(clone$1(points[i]));
  13370. continue;
  13371. }
  13372. else {
  13373. prevPoint = points[i - 1];
  13374. nextPoint = points[i + 1];
  13375. }
  13376. }
  13377. sub(v, nextPoint, prevPoint);
  13378. scale(v, v, smooth);
  13379. var d0 = distance(point, prevPoint);
  13380. var d1 = distance(point, nextPoint);
  13381. var sum = d0 + d1;
  13382. if (sum !== 0) {
  13383. d0 /= sum;
  13384. d1 /= sum;
  13385. }
  13386. scale(v1, v, -d0);
  13387. scale(v2, v, d1);
  13388. var cp0 = add([], point, v1);
  13389. var cp1 = add([], point, v2);
  13390. if (constraint) {
  13391. max(cp0, cp0, min$1);
  13392. min(cp0, cp0, max$1);
  13393. max(cp1, cp1, min$1);
  13394. min(cp1, cp1, max$1);
  13395. }
  13396. cps.push(cp0);
  13397. cps.push(cp1);
  13398. }
  13399. if (isLoop) {
  13400. cps.push(cps.shift());
  13401. }
  13402. return cps;
  13403. }
  13404. function buildPath$2(ctx, shape, closePath) {
  13405. var smooth = shape.smooth;
  13406. var points = shape.points;
  13407. if (points && points.length >= 2) {
  13408. if (smooth) {
  13409. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13410. ctx.moveTo(points[0][0], points[0][1]);
  13411. var len = points.length;
  13412. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13413. var cp1 = controlPoints[i * 2];
  13414. var cp2 = controlPoints[i * 2 + 1];
  13415. var p = points[(i + 1) % len];
  13416. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13417. }
  13418. }
  13419. else {
  13420. ctx.moveTo(points[0][0], points[0][1]);
  13421. for (var i = 1, l = points.length; i < l; i++) {
  13422. ctx.lineTo(points[i][0], points[i][1]);
  13423. }
  13424. }
  13425. closePath && ctx.closePath();
  13426. }
  13427. }
  13428. var PolygonShape = (function () {
  13429. function PolygonShape() {
  13430. this.points = null;
  13431. this.smooth = 0;
  13432. this.smoothConstraint = null;
  13433. }
  13434. return PolygonShape;
  13435. }());
  13436. var Polygon = (function (_super) {
  13437. __extends(Polygon, _super);
  13438. function Polygon(opts) {
  13439. return _super.call(this, opts) || this;
  13440. }
  13441. Polygon.prototype.getDefaultShape = function () {
  13442. return new PolygonShape();
  13443. };
  13444. Polygon.prototype.buildPath = function (ctx, shape) {
  13445. buildPath$2(ctx, shape, true);
  13446. };
  13447. return Polygon;
  13448. }(Path));
  13449. Polygon.prototype.type = 'polygon';
  13450. var PolylineShape = (function () {
  13451. function PolylineShape() {
  13452. this.points = null;
  13453. this.percent = 1;
  13454. this.smooth = 0;
  13455. this.smoothConstraint = null;
  13456. }
  13457. return PolylineShape;
  13458. }());
  13459. var Polyline = (function (_super) {
  13460. __extends(Polyline, _super);
  13461. function Polyline(opts) {
  13462. return _super.call(this, opts) || this;
  13463. }
  13464. Polyline.prototype.getDefaultStyle = function () {
  13465. return {
  13466. stroke: '#000',
  13467. fill: null
  13468. };
  13469. };
  13470. Polyline.prototype.getDefaultShape = function () {
  13471. return new PolylineShape();
  13472. };
  13473. Polyline.prototype.buildPath = function (ctx, shape) {
  13474. buildPath$2(ctx, shape, false);
  13475. };
  13476. return Polyline;
  13477. }(Path));
  13478. Polyline.prototype.type = 'polyline';
  13479. var subPixelOptimizeOutputShape$1 = {};
  13480. var LineShape = (function () {
  13481. function LineShape() {
  13482. this.x1 = 0;
  13483. this.y1 = 0;
  13484. this.x2 = 0;
  13485. this.y2 = 0;
  13486. this.percent = 1;
  13487. }
  13488. return LineShape;
  13489. }());
  13490. var Line = (function (_super) {
  13491. __extends(Line, _super);
  13492. function Line(opts) {
  13493. return _super.call(this, opts) || this;
  13494. }
  13495. Line.prototype.getDefaultStyle = function () {
  13496. return {
  13497. stroke: '#000',
  13498. fill: null
  13499. };
  13500. };
  13501. Line.prototype.getDefaultShape = function () {
  13502. return new LineShape();
  13503. };
  13504. Line.prototype.buildPath = function (ctx, shape) {
  13505. var x1;
  13506. var y1;
  13507. var x2;
  13508. var y2;
  13509. if (this.subPixelOptimize) {
  13510. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13511. x1 = optimizedShape.x1;
  13512. y1 = optimizedShape.y1;
  13513. x2 = optimizedShape.x2;
  13514. y2 = optimizedShape.y2;
  13515. }
  13516. else {
  13517. x1 = shape.x1;
  13518. y1 = shape.y1;
  13519. x2 = shape.x2;
  13520. y2 = shape.y2;
  13521. }
  13522. var percent = shape.percent;
  13523. if (percent === 0) {
  13524. return;
  13525. }
  13526. ctx.moveTo(x1, y1);
  13527. if (percent < 1) {
  13528. x2 = x1 * (1 - percent) + x2 * percent;
  13529. y2 = y1 * (1 - percent) + y2 * percent;
  13530. }
  13531. ctx.lineTo(x2, y2);
  13532. };
  13533. Line.prototype.pointAt = function (p) {
  13534. var shape = this.shape;
  13535. return [
  13536. shape.x1 * (1 - p) + shape.x2 * p,
  13537. shape.y1 * (1 - p) + shape.y2 * p
  13538. ];
  13539. };
  13540. return Line;
  13541. }(Path));
  13542. Line.prototype.type = 'line';
  13543. var out = [];
  13544. var BezierCurveShape = (function () {
  13545. function BezierCurveShape() {
  13546. this.x1 = 0;
  13547. this.y1 = 0;
  13548. this.x2 = 0;
  13549. this.y2 = 0;
  13550. this.cpx1 = 0;
  13551. this.cpy1 = 0;
  13552. this.percent = 1;
  13553. }
  13554. return BezierCurveShape;
  13555. }());
  13556. function someVectorAt(shape, t, isTangent) {
  13557. var cpx2 = shape.cpx2;
  13558. var cpy2 = shape.cpy2;
  13559. if (cpx2 != null || cpy2 != null) {
  13560. return [
  13561. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13562. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13563. ];
  13564. }
  13565. else {
  13566. return [
  13567. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13568. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13569. ];
  13570. }
  13571. }
  13572. var BezierCurve = (function (_super) {
  13573. __extends(BezierCurve, _super);
  13574. function BezierCurve(opts) {
  13575. return _super.call(this, opts) || this;
  13576. }
  13577. BezierCurve.prototype.getDefaultStyle = function () {
  13578. return {
  13579. stroke: '#000',
  13580. fill: null
  13581. };
  13582. };
  13583. BezierCurve.prototype.getDefaultShape = function () {
  13584. return new BezierCurveShape();
  13585. };
  13586. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13587. var x1 = shape.x1;
  13588. var y1 = shape.y1;
  13589. var x2 = shape.x2;
  13590. var y2 = shape.y2;
  13591. var cpx1 = shape.cpx1;
  13592. var cpy1 = shape.cpy1;
  13593. var cpx2 = shape.cpx2;
  13594. var cpy2 = shape.cpy2;
  13595. var percent = shape.percent;
  13596. if (percent === 0) {
  13597. return;
  13598. }
  13599. ctx.moveTo(x1, y1);
  13600. if (cpx2 == null || cpy2 == null) {
  13601. if (percent < 1) {
  13602. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13603. cpx1 = out[1];
  13604. x2 = out[2];
  13605. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13606. cpy1 = out[1];
  13607. y2 = out[2];
  13608. }
  13609. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13610. }
  13611. else {
  13612. if (percent < 1) {
  13613. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13614. cpx1 = out[1];
  13615. cpx2 = out[2];
  13616. x2 = out[3];
  13617. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13618. cpy1 = out[1];
  13619. cpy2 = out[2];
  13620. y2 = out[3];
  13621. }
  13622. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13623. }
  13624. };
  13625. BezierCurve.prototype.pointAt = function (t) {
  13626. return someVectorAt(this.shape, t, false);
  13627. };
  13628. BezierCurve.prototype.tangentAt = function (t) {
  13629. var p = someVectorAt(this.shape, t, true);
  13630. return normalize(p, p);
  13631. };
  13632. return BezierCurve;
  13633. }(Path));
  13634. BezierCurve.prototype.type = 'bezier-curve';
  13635. var ArcShape = (function () {
  13636. function ArcShape() {
  13637. this.cx = 0;
  13638. this.cy = 0;
  13639. this.r = 0;
  13640. this.startAngle = 0;
  13641. this.endAngle = Math.PI * 2;
  13642. this.clockwise = true;
  13643. }
  13644. return ArcShape;
  13645. }());
  13646. var Arc = (function (_super) {
  13647. __extends(Arc, _super);
  13648. function Arc(opts) {
  13649. return _super.call(this, opts) || this;
  13650. }
  13651. Arc.prototype.getDefaultStyle = function () {
  13652. return {
  13653. stroke: '#000',
  13654. fill: null
  13655. };
  13656. };
  13657. Arc.prototype.getDefaultShape = function () {
  13658. return new ArcShape();
  13659. };
  13660. Arc.prototype.buildPath = function (ctx, shape) {
  13661. var x = shape.cx;
  13662. var y = shape.cy;
  13663. var r = Math.max(shape.r, 0);
  13664. var startAngle = shape.startAngle;
  13665. var endAngle = shape.endAngle;
  13666. var clockwise = shape.clockwise;
  13667. var unitX = Math.cos(startAngle);
  13668. var unitY = Math.sin(startAngle);
  13669. ctx.moveTo(unitX * r + x, unitY * r + y);
  13670. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13671. };
  13672. return Arc;
  13673. }(Path));
  13674. Arc.prototype.type = 'arc';
  13675. var CompoundPath = (function (_super) {
  13676. __extends(CompoundPath, _super);
  13677. function CompoundPath() {
  13678. var _this = _super !== null && _super.apply(this, arguments) || this;
  13679. _this.type = 'compound';
  13680. return _this;
  13681. }
  13682. CompoundPath.prototype._updatePathDirty = function () {
  13683. var paths = this.shape.paths;
  13684. var dirtyPath = this.shapeChanged();
  13685. for (var i = 0; i < paths.length; i++) {
  13686. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13687. }
  13688. if (dirtyPath) {
  13689. this.dirtyShape();
  13690. }
  13691. };
  13692. CompoundPath.prototype.beforeBrush = function () {
  13693. this._updatePathDirty();
  13694. var paths = this.shape.paths || [];
  13695. var scale = this.getGlobalScale();
  13696. for (var i = 0; i < paths.length; i++) {
  13697. if (!paths[i].path) {
  13698. paths[i].createPathProxy();
  13699. }
  13700. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13701. }
  13702. };
  13703. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13704. var paths = shape.paths || [];
  13705. for (var i = 0; i < paths.length; i++) {
  13706. paths[i].buildPath(ctx, paths[i].shape, true);
  13707. }
  13708. };
  13709. CompoundPath.prototype.afterBrush = function () {
  13710. var paths = this.shape.paths || [];
  13711. for (var i = 0; i < paths.length; i++) {
  13712. paths[i].pathUpdated();
  13713. }
  13714. };
  13715. CompoundPath.prototype.getBoundingRect = function () {
  13716. this._updatePathDirty.call(this);
  13717. return Path.prototype.getBoundingRect.call(this);
  13718. };
  13719. return CompoundPath;
  13720. }(Path));
  13721. var Gradient = (function () {
  13722. function Gradient(colorStops) {
  13723. this.colorStops = colorStops || [];
  13724. }
  13725. Gradient.prototype.addColorStop = function (offset, color) {
  13726. this.colorStops.push({
  13727. offset: offset,
  13728. color: color
  13729. });
  13730. };
  13731. return Gradient;
  13732. }());
  13733. var LinearGradient = (function (_super) {
  13734. __extends(LinearGradient, _super);
  13735. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13736. var _this = _super.call(this, colorStops) || this;
  13737. _this.x = x == null ? 0 : x;
  13738. _this.y = y == null ? 0 : y;
  13739. _this.x2 = x2 == null ? 1 : x2;
  13740. _this.y2 = y2 == null ? 0 : y2;
  13741. _this.type = 'linear';
  13742. _this.global = globalCoord || false;
  13743. return _this;
  13744. }
  13745. return LinearGradient;
  13746. }(Gradient));
  13747. var RadialGradient = (function (_super) {
  13748. __extends(RadialGradient, _super);
  13749. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13750. var _this = _super.call(this, colorStops) || this;
  13751. _this.x = x == null ? 0.5 : x;
  13752. _this.y = y == null ? 0.5 : y;
  13753. _this.r = r == null ? 0.5 : r;
  13754. _this.type = 'radial';
  13755. _this.global = globalCoord || false;
  13756. return _this;
  13757. }
  13758. return RadialGradient;
  13759. }(Gradient));
  13760. var extent = [0, 0];
  13761. var extent2 = [0, 0];
  13762. var minTv$1 = new Point();
  13763. var maxTv$1 = new Point();
  13764. var OrientedBoundingRect = (function () {
  13765. function OrientedBoundingRect(rect, transform) {
  13766. this._corners = [];
  13767. this._axes = [];
  13768. this._origin = [0, 0];
  13769. for (var i = 0; i < 4; i++) {
  13770. this._corners[i] = new Point();
  13771. }
  13772. for (var i = 0; i < 2; i++) {
  13773. this._axes[i] = new Point();
  13774. }
  13775. if (rect) {
  13776. this.fromBoundingRect(rect, transform);
  13777. }
  13778. }
  13779. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13780. var corners = this._corners;
  13781. var axes = this._axes;
  13782. var x = rect.x;
  13783. var y = rect.y;
  13784. var x2 = x + rect.width;
  13785. var y2 = y + rect.height;
  13786. corners[0].set(x, y);
  13787. corners[1].set(x2, y);
  13788. corners[2].set(x2, y2);
  13789. corners[3].set(x, y2);
  13790. if (transform) {
  13791. for (var i = 0; i < 4; i++) {
  13792. corners[i].transform(transform);
  13793. }
  13794. }
  13795. Point.sub(axes[0], corners[1], corners[0]);
  13796. Point.sub(axes[1], corners[3], corners[0]);
  13797. axes[0].normalize();
  13798. axes[1].normalize();
  13799. for (var i = 0; i < 2; i++) {
  13800. this._origin[i] = axes[i].dot(corners[0]);
  13801. }
  13802. };
  13803. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13804. var overlapped = true;
  13805. var noMtv = !mtv;
  13806. minTv$1.set(Infinity, Infinity);
  13807. maxTv$1.set(0, 0);
  13808. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13809. overlapped = false;
  13810. if (noMtv) {
  13811. return overlapped;
  13812. }
  13813. }
  13814. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13815. overlapped = false;
  13816. if (noMtv) {
  13817. return overlapped;
  13818. }
  13819. }
  13820. if (!noMtv) {
  13821. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13822. }
  13823. return overlapped;
  13824. };
  13825. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13826. var overlapped = true;
  13827. for (var i = 0; i < 2; i++) {
  13828. var axis = this._axes[i];
  13829. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13830. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13831. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13832. overlapped = false;
  13833. if (noMtv) {
  13834. return overlapped;
  13835. }
  13836. var dist0 = Math.abs(extent2[0] - extent[1]);
  13837. var dist1 = Math.abs(extent[0] - extent2[1]);
  13838. if (Math.min(dist0, dist1) > maxTv.len()) {
  13839. if (dist0 < dist1) {
  13840. Point.scale(maxTv, axis, -dist0 * inverse);
  13841. }
  13842. else {
  13843. Point.scale(maxTv, axis, dist1 * inverse);
  13844. }
  13845. }
  13846. }
  13847. else if (minTv) {
  13848. var dist0 = Math.abs(extent2[0] - extent[1]);
  13849. var dist1 = Math.abs(extent[0] - extent2[1]);
  13850. if (Math.min(dist0, dist1) < minTv.len()) {
  13851. if (dist0 < dist1) {
  13852. Point.scale(minTv, axis, dist0 * inverse);
  13853. }
  13854. else {
  13855. Point.scale(minTv, axis, -dist1 * inverse);
  13856. }
  13857. }
  13858. }
  13859. }
  13860. return overlapped;
  13861. };
  13862. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13863. var axis = this._axes[dim];
  13864. var origin = this._origin;
  13865. var proj = corners[0].dot(axis) + origin[dim];
  13866. var min = proj;
  13867. var max = proj;
  13868. for (var i = 1; i < corners.length; i++) {
  13869. var proj_1 = corners[i].dot(axis) + origin[dim];
  13870. min = Math.min(proj_1, min);
  13871. max = Math.max(proj_1, max);
  13872. }
  13873. out[0] = min;
  13874. out[1] = max;
  13875. };
  13876. return OrientedBoundingRect;
  13877. }());
  13878. var m = [];
  13879. var IncrementalDisplayable = (function (_super) {
  13880. __extends(IncrementalDisplayable, _super);
  13881. function IncrementalDisplayable() {
  13882. var _this = _super !== null && _super.apply(this, arguments) || this;
  13883. _this.notClear = true;
  13884. _this.incremental = true;
  13885. _this._displayables = [];
  13886. _this._temporaryDisplayables = [];
  13887. _this._cursor = 0;
  13888. return _this;
  13889. }
  13890. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13891. cb.call(context, this);
  13892. };
  13893. IncrementalDisplayable.prototype.useStyle = function () {
  13894. this.style = {};
  13895. };
  13896. IncrementalDisplayable.prototype.getCursor = function () {
  13897. return this._cursor;
  13898. };
  13899. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13900. this._cursor = this._displayables.length;
  13901. };
  13902. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13903. this._displayables = [];
  13904. this._temporaryDisplayables = [];
  13905. this._cursor = 0;
  13906. this.markRedraw();
  13907. this.notClear = false;
  13908. };
  13909. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13910. this._temporaryDisplayables = [];
  13911. };
  13912. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13913. if (notPersistent) {
  13914. this._temporaryDisplayables.push(displayable);
  13915. }
  13916. else {
  13917. this._displayables.push(displayable);
  13918. }
  13919. this.markRedraw();
  13920. };
  13921. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13922. notPersistent = notPersistent || false;
  13923. for (var i = 0; i < displayables.length; i++) {
  13924. this.addDisplayable(displayables[i], notPersistent);
  13925. }
  13926. };
  13927. IncrementalDisplayable.prototype.getDisplayables = function () {
  13928. return this._displayables;
  13929. };
  13930. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13931. return this._temporaryDisplayables;
  13932. };
  13933. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13934. for (var i = this._cursor; i < this._displayables.length; i++) {
  13935. cb && cb(this._displayables[i]);
  13936. }
  13937. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13938. cb && cb(this._temporaryDisplayables[i]);
  13939. }
  13940. };
  13941. IncrementalDisplayable.prototype.update = function () {
  13942. this.updateTransform();
  13943. for (var i = this._cursor; i < this._displayables.length; i++) {
  13944. var displayable = this._displayables[i];
  13945. displayable.parent = this;
  13946. displayable.update();
  13947. displayable.parent = null;
  13948. }
  13949. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13950. var displayable = this._temporaryDisplayables[i];
  13951. displayable.parent = this;
  13952. displayable.update();
  13953. displayable.parent = null;
  13954. }
  13955. };
  13956. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13957. if (!this._rect) {
  13958. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13959. for (var i = 0; i < this._displayables.length; i++) {
  13960. var displayable = this._displayables[i];
  13961. var childRect = displayable.getBoundingRect().clone();
  13962. if (displayable.needLocalTransform()) {
  13963. childRect.applyTransform(displayable.getLocalTransform(m));
  13964. }
  13965. rect.union(childRect);
  13966. }
  13967. this._rect = rect;
  13968. }
  13969. return this._rect;
  13970. };
  13971. IncrementalDisplayable.prototype.contain = function (x, y) {
  13972. var localPos = this.transformCoordToLocal(x, y);
  13973. var rect = this.getBoundingRect();
  13974. if (rect.contain(localPos[0], localPos[1])) {
  13975. for (var i = 0; i < this._displayables.length; i++) {
  13976. var displayable = this._displayables[i];
  13977. if (displayable.contain(x, y)) {
  13978. return true;
  13979. }
  13980. }
  13981. }
  13982. return false;
  13983. };
  13984. return IncrementalDisplayable;
  13985. }(Displayable));
  13986. var transitionStore = makeInner();
  13987. /**
  13988. * Return null if animation is disabled.
  13989. */
  13990. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  13991. extraOpts, // TODO It's only for pictorial bar now.
  13992. extraDelayParams) {
  13993. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13994. // If animation is enabled. Will use this animation config in payload.
  13995. // If animation is disabled. Just ignore it.
  13996. if (animatableModel && animatableModel.ecModel) {
  13997. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13998. animationPayload = updatePayload && updatePayload.animation;
  13999. }
  14000. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14001. var isUpdate = animationType === 'update';
  14002. if (animationEnabled) {
  14003. var duration = void 0;
  14004. var easing = void 0;
  14005. var delay = void 0;
  14006. if (extraOpts) {
  14007. duration = retrieve2(extraOpts.duration, 200);
  14008. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14009. delay = 0;
  14010. } else {
  14011. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14012. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14013. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14014. } // animation from payload has highest priority.
  14015. if (animationPayload) {
  14016. animationPayload.duration != null && (duration = animationPayload.duration);
  14017. animationPayload.easing != null && (easing = animationPayload.easing);
  14018. animationPayload.delay != null && (delay = animationPayload.delay);
  14019. }
  14020. if (isFunction(delay)) {
  14021. delay = delay(dataIndex, extraDelayParams);
  14022. }
  14023. if (isFunction(duration)) {
  14024. duration = duration(dataIndex);
  14025. }
  14026. var config = {
  14027. duration: duration || 0,
  14028. delay: delay,
  14029. easing: easing
  14030. };
  14031. return config;
  14032. } else {
  14033. return null;
  14034. }
  14035. }
  14036. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14037. var isFrom = false;
  14038. var removeOpt;
  14039. if (isFunction(dataIndex)) {
  14040. during = cb;
  14041. cb = dataIndex;
  14042. dataIndex = null;
  14043. } else if (isObject(dataIndex)) {
  14044. cb = dataIndex.cb;
  14045. during = dataIndex.during;
  14046. isFrom = dataIndex.isFrom;
  14047. removeOpt = dataIndex.removeOpt;
  14048. dataIndex = dataIndex.dataIndex;
  14049. }
  14050. var isRemove = animationType === 'leave';
  14051. if (!isRemove) {
  14052. // Must stop the remove animation.
  14053. el.stopAnimation('leave');
  14054. }
  14055. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14056. if (animationConfig && animationConfig.duration > 0) {
  14057. var duration = animationConfig.duration;
  14058. var animationDelay = animationConfig.delay;
  14059. var animationEasing = animationConfig.easing;
  14060. var animateConfig = {
  14061. duration: duration,
  14062. delay: animationDelay || 0,
  14063. easing: animationEasing,
  14064. done: cb,
  14065. force: !!cb || !!during,
  14066. // Set to final state in update/init animation.
  14067. // So the post processing based on the path shape can be done correctly.
  14068. setToFinal: !isRemove,
  14069. scope: animationType,
  14070. during: during
  14071. };
  14072. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14073. } else {
  14074. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  14075. !isFrom && el.attr(props); // Call during at least once.
  14076. during && during(1);
  14077. cb && cb();
  14078. }
  14079. }
  14080. /**
  14081. * Update graphic element properties with or without animation according to the
  14082. * configuration in series.
  14083. *
  14084. * Caution: this method will stop previous animation.
  14085. * So do not use this method to one element twice before
  14086. * animation starts, unless you know what you are doing.
  14087. * @example
  14088. * graphic.updateProps(el, {
  14089. * position: [100, 100]
  14090. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14091. * // Or
  14092. * graphic.updateProps(el, {
  14093. * position: [100, 100]
  14094. * }, seriesModel, function () { console.log('Animation done!'); });
  14095. */
  14096. function updateProps(el, props, // TODO: TYPE AnimatableModel
  14097. animatableModel, dataIndex, cb, during) {
  14098. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14099. }
  14100. /**
  14101. * Init graphic element properties with or without animation according to the
  14102. * configuration in series.
  14103. *
  14104. * Caution: this method will stop previous animation.
  14105. * So do not use this method to one element twice before
  14106. * animation starts, unless you know what you are doing.
  14107. */
  14108. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14109. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14110. }
  14111. /**
  14112. * If element is removed.
  14113. * It can determine if element is having remove animation.
  14114. */
  14115. function isElementRemoved(el) {
  14116. if (!el.__zr) {
  14117. return true;
  14118. }
  14119. for (var i = 0; i < el.animators.length; i++) {
  14120. var animator = el.animators[i];
  14121. if (animator.scope === 'leave') {
  14122. return true;
  14123. }
  14124. }
  14125. return false;
  14126. }
  14127. /**
  14128. * Remove graphic element
  14129. */
  14130. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14131. // Don't do remove animation twice.
  14132. if (isElementRemoved(el)) {
  14133. return;
  14134. }
  14135. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14136. }
  14137. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14138. el.removeTextContent();
  14139. el.removeTextGuideLine();
  14140. removeElement(el, {
  14141. style: {
  14142. opacity: 0
  14143. }
  14144. }, animatableModel, dataIndex, done);
  14145. }
  14146. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14147. function doRemove() {
  14148. el.parent && el.parent.remove(el);
  14149. } // Hide label and labelLine first
  14150. // TODO Also use fade out animation?
  14151. if (!el.isGroup) {
  14152. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14153. } else {
  14154. el.traverse(function (disp) {
  14155. if (!disp.isGroup) {
  14156. // Can invoke doRemove multiple times.
  14157. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14158. }
  14159. });
  14160. }
  14161. }
  14162. /**
  14163. * Save old style for style transition in universalTransition module.
  14164. * It's used when element will be reused in each render.
  14165. * For chart like map, heatmap, which will always create new element.
  14166. * We don't need to save this because universalTransition can get old style from the old element
  14167. */
  14168. function saveOldStyle(el) {
  14169. transitionStore(el).oldStyle = el.style;
  14170. }
  14171. var mathMax$4 = Math.max;
  14172. var mathMin$4 = Math.min;
  14173. var _customShapeMap = {};
  14174. /**
  14175. * Extend shape with parameters
  14176. */
  14177. function extendShape(opts) {
  14178. return Path.extend(opts);
  14179. }
  14180. var extendPathFromString = extendFromString;
  14181. /**
  14182. * Extend path
  14183. */
  14184. function extendPath(pathData, opts) {
  14185. return extendPathFromString(pathData, opts);
  14186. }
  14187. /**
  14188. * Register a user defined shape.
  14189. * The shape class can be fetched by `getShapeClass`
  14190. * This method will overwrite the registered shapes, including
  14191. * the registered built-in shapes, if using the same `name`.
  14192. * The shape can be used in `custom series` and
  14193. * `graphic component` by declaring `{type: name}`.
  14194. *
  14195. * @param name
  14196. * @param ShapeClass Can be generated by `extendShape`.
  14197. */
  14198. function registerShape(name, ShapeClass) {
  14199. _customShapeMap[name] = ShapeClass;
  14200. }
  14201. /**
  14202. * Find shape class registered by `registerShape`. Usually used in
  14203. * fetching user defined shape.
  14204. *
  14205. * [Caution]:
  14206. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14207. * to use user registered shapes.
  14208. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14209. * `registerShape` by default. That enables users to get both built-in
  14210. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14211. * the built-in shapes by using names like 'circle', 'rect' via calling
  14212. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14213. * in case that it is overwritten by users, except that some features, like
  14214. * `custom series`, `graphic component`, do it deliberately.
  14215. *
  14216. * (2) In the features like `custom series`, `graphic component`, the user input
  14217. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14218. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14219. * are reserved names, that is, if some user registers a shape named `'image'`,
  14220. * the shape will not be used. If we intending to add some more reserved names
  14221. * in feature, that might bring break changes (disable some existing user shape
  14222. * names). But that case probably rarely happens. So we don't make more mechanism
  14223. * to resolve this issue here.
  14224. *
  14225. * @param name
  14226. * @return The shape class. If not found, return nothing.
  14227. */
  14228. function getShapeClass(name) {
  14229. if (_customShapeMap.hasOwnProperty(name)) {
  14230. return _customShapeMap[name];
  14231. }
  14232. }
  14233. /**
  14234. * Create a path element from path data string
  14235. * @param pathData
  14236. * @param opts
  14237. * @param rect
  14238. * @param layout 'center' or 'cover' default to be cover
  14239. */
  14240. function makePath(pathData, opts, rect, layout) {
  14241. var path = createFromString(pathData, opts);
  14242. if (rect) {
  14243. if (layout === 'center') {
  14244. rect = centerGraphic(rect, path.getBoundingRect());
  14245. }
  14246. resizePath(path, rect);
  14247. }
  14248. return path;
  14249. }
  14250. /**
  14251. * Create a image element from image url
  14252. * @param imageUrl image url
  14253. * @param opts options
  14254. * @param rect constrain rect
  14255. * @param layout 'center' or 'cover'. Default to be 'cover'
  14256. */
  14257. function makeImage(imageUrl, rect, layout) {
  14258. var zrImg = new ZRImage({
  14259. style: {
  14260. image: imageUrl,
  14261. x: rect.x,
  14262. y: rect.y,
  14263. width: rect.width,
  14264. height: rect.height
  14265. },
  14266. onload: function (img) {
  14267. if (layout === 'center') {
  14268. var boundingRect = {
  14269. width: img.width,
  14270. height: img.height
  14271. };
  14272. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14273. }
  14274. }
  14275. });
  14276. return zrImg;
  14277. }
  14278. /**
  14279. * Get position of centered element in bounding box.
  14280. *
  14281. * @param rect element local bounding box
  14282. * @param boundingRect constraint bounding box
  14283. * @return element position containing x, y, width, and height
  14284. */
  14285. function centerGraphic(rect, boundingRect) {
  14286. // Set rect to center, keep width / height ratio.
  14287. var aspect = boundingRect.width / boundingRect.height;
  14288. var width = rect.height * aspect;
  14289. var height;
  14290. if (width <= rect.width) {
  14291. height = rect.height;
  14292. } else {
  14293. width = rect.width;
  14294. height = width / aspect;
  14295. }
  14296. var cx = rect.x + rect.width / 2;
  14297. var cy = rect.y + rect.height / 2;
  14298. return {
  14299. x: cx - width / 2,
  14300. y: cy - height / 2,
  14301. width: width,
  14302. height: height
  14303. };
  14304. }
  14305. var mergePath$1 = mergePath;
  14306. /**
  14307. * Resize a path to fit the rect
  14308. * @param path
  14309. * @param rect
  14310. */
  14311. function resizePath(path, rect) {
  14312. if (!path.applyTransform) {
  14313. return;
  14314. }
  14315. var pathRect = path.getBoundingRect();
  14316. var m = pathRect.calculateTransform(rect);
  14317. path.applyTransform(m);
  14318. }
  14319. /**
  14320. * Sub pixel optimize line for canvas
  14321. */
  14322. function subPixelOptimizeLine$1(shape, lineWidth) {
  14323. subPixelOptimizeLine(shape, shape, {
  14324. lineWidth: lineWidth
  14325. });
  14326. return shape;
  14327. }
  14328. /**
  14329. * Sub pixel optimize rect for canvas
  14330. */
  14331. function subPixelOptimizeRect$1(param) {
  14332. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14333. return param;
  14334. }
  14335. /**
  14336. * Sub pixel optimize for canvas
  14337. *
  14338. * @param position Coordinate, such as x, y
  14339. * @param lineWidth Should be nonnegative integer.
  14340. * @param positiveOrNegative Default false (negative).
  14341. * @return Optimized position.
  14342. */
  14343. var subPixelOptimize$1 = subPixelOptimize;
  14344. /**
  14345. * Get transform matrix of target (param target),
  14346. * in coordinate of its ancestor (param ancestor)
  14347. *
  14348. * @param target
  14349. * @param [ancestor]
  14350. */
  14351. function getTransform(target, ancestor) {
  14352. var mat = identity([]);
  14353. while (target && target !== ancestor) {
  14354. mul$1(mat, target.getLocalTransform(), mat);
  14355. target = target.parent;
  14356. }
  14357. return mat;
  14358. }
  14359. /**
  14360. * Apply transform to an vertex.
  14361. * @param target [x, y]
  14362. * @param transform Can be:
  14363. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14364. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14365. * @param invert Whether use invert matrix.
  14366. * @return [x, y]
  14367. */
  14368. function applyTransform$1(target, transform, invert$1) {
  14369. if (transform && !isArrayLike(transform)) {
  14370. transform = Transformable.getLocalTransform(transform);
  14371. }
  14372. if (invert$1) {
  14373. transform = invert([], transform);
  14374. }
  14375. return applyTransform([], target, transform);
  14376. }
  14377. /**
  14378. * @param direction 'left' 'right' 'top' 'bottom'
  14379. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14380. * @param invert Whether use invert matrix.
  14381. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14382. */
  14383. function transformDirection(direction, transform, invert) {
  14384. // Pick a base, ensure that transform result will not be (0, 0).
  14385. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14386. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14387. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14388. vertex = applyTransform$1(vertex, transform, invert);
  14389. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14390. }
  14391. function isNotGroup(el) {
  14392. return !el.isGroup;
  14393. }
  14394. function isPath(el) {
  14395. return el.shape != null;
  14396. }
  14397. /**
  14398. * Apply group transition animation from g1 to g2.
  14399. * If no animatableModel, no animation.
  14400. */
  14401. function groupTransition(g1, g2, animatableModel) {
  14402. if (!g1 || !g2) {
  14403. return;
  14404. }
  14405. function getElMap(g) {
  14406. var elMap = {};
  14407. g.traverse(function (el) {
  14408. if (isNotGroup(el) && el.anid) {
  14409. elMap[el.anid] = el;
  14410. }
  14411. });
  14412. return elMap;
  14413. }
  14414. function getAnimatableProps(el) {
  14415. var obj = {
  14416. x: el.x,
  14417. y: el.y,
  14418. rotation: el.rotation
  14419. };
  14420. if (isPath(el)) {
  14421. obj.shape = extend({}, el.shape);
  14422. }
  14423. return obj;
  14424. }
  14425. var elMap1 = getElMap(g1);
  14426. g2.traverse(function (el) {
  14427. if (isNotGroup(el) && el.anid) {
  14428. var oldEl = elMap1[el.anid];
  14429. if (oldEl) {
  14430. var newProp = getAnimatableProps(el);
  14431. el.attr(getAnimatableProps(oldEl));
  14432. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14433. }
  14434. }
  14435. });
  14436. }
  14437. function clipPointsByRect(points, rect) {
  14438. // FIXME: This way might be incorrect when graphic clipped by a corner
  14439. // and when element has a border.
  14440. return map(points, function (point) {
  14441. var x = point[0];
  14442. x = mathMax$4(x, rect.x);
  14443. x = mathMin$4(x, rect.x + rect.width);
  14444. var y = point[1];
  14445. y = mathMax$4(y, rect.y);
  14446. y = mathMin$4(y, rect.y + rect.height);
  14447. return [x, y];
  14448. });
  14449. }
  14450. /**
  14451. * Return a new clipped rect. If rect size are negative, return undefined.
  14452. */
  14453. function clipRectByRect(targetRect, rect) {
  14454. var x = mathMax$4(targetRect.x, rect.x);
  14455. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14456. var y = mathMax$4(targetRect.y, rect.y);
  14457. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14458. // should be painted. So return undefined.
  14459. if (x2 >= x && y2 >= y) {
  14460. return {
  14461. x: x,
  14462. y: y,
  14463. width: x2 - x,
  14464. height: y2 - y
  14465. };
  14466. }
  14467. }
  14468. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14469. opt, rect) {
  14470. var innerOpts = extend({
  14471. rectHover: true
  14472. }, opt);
  14473. var style = innerOpts.style = {
  14474. strokeNoScale: true
  14475. };
  14476. rect = rect || {
  14477. x: -1,
  14478. y: -1,
  14479. width: 2,
  14480. height: 2
  14481. };
  14482. if (iconStr) {
  14483. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14484. }
  14485. }
  14486. /**
  14487. * Return `true` if the given line (line `a`) and the given polygon
  14488. * are intersect.
  14489. * Note that we do not count colinear as intersect here because no
  14490. * requirement for that. We could do that if required in future.
  14491. */
  14492. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14493. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14494. var p = points[i];
  14495. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14496. return true;
  14497. }
  14498. p2 = p;
  14499. }
  14500. }
  14501. /**
  14502. * Return `true` if the given two lines (line `a` and line `b`)
  14503. * are intersect.
  14504. * Note that we do not count colinear as intersect here because no
  14505. * requirement for that. We could do that if required in future.
  14506. */
  14507. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14508. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14509. var mx = a2x - a1x;
  14510. var my = a2y - a1y;
  14511. var nx = b2x - b1x;
  14512. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14513. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14514. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14515. if (nearZero(nmCrossProduct)) {
  14516. return false;
  14517. } // `vec_m` and `vec_n` are intersect iff
  14518. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14519. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14520. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14521. var b1a1x = a1x - b1x;
  14522. var b1a1y = a1y - b1y;
  14523. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14524. if (q < 0 || q > 1) {
  14525. return false;
  14526. }
  14527. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14528. if (p < 0 || p > 1) {
  14529. return false;
  14530. }
  14531. return true;
  14532. }
  14533. /**
  14534. * Cross product of 2-dimension vector.
  14535. */
  14536. function crossProduct2d(x1, y1, x2, y2) {
  14537. return x1 * y2 - x2 * y1;
  14538. }
  14539. function nearZero(val) {
  14540. return val <= 1e-6 && val >= -1e-6;
  14541. }
  14542. function setTooltipConfig(opt) {
  14543. var itemTooltipOption = opt.itemTooltipOption;
  14544. var componentModel = opt.componentModel;
  14545. var itemName = opt.itemName;
  14546. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14547. formatter: itemTooltipOption
  14548. } : itemTooltipOption;
  14549. var mainType = componentModel.mainType;
  14550. var componentIndex = componentModel.componentIndex;
  14551. var formatterParams = {
  14552. componentType: mainType,
  14553. name: itemName,
  14554. $vars: ['name']
  14555. };
  14556. formatterParams[mainType + 'Index'] = componentIndex;
  14557. var formatterParamsExtra = opt.formatterParamsExtra;
  14558. if (formatterParamsExtra) {
  14559. each(keys(formatterParamsExtra), function (key) {
  14560. if (!hasOwn(formatterParams, key)) {
  14561. formatterParams[key] = formatterParamsExtra[key];
  14562. formatterParams.$vars.push(key);
  14563. }
  14564. });
  14565. }
  14566. var ecData = getECData(opt.el);
  14567. ecData.componentMainType = mainType;
  14568. ecData.componentIndex = componentIndex;
  14569. ecData.tooltipConfig = {
  14570. name: itemName,
  14571. option: defaults({
  14572. content: itemName,
  14573. formatterParams: formatterParams
  14574. }, itemTooltipOptionObj)
  14575. };
  14576. }
  14577. function traverseElement(el, cb) {
  14578. var stopped; // TODO
  14579. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14580. if (el.isGroup) {
  14581. stopped = cb(el);
  14582. }
  14583. if (!stopped) {
  14584. el.traverse(cb);
  14585. }
  14586. }
  14587. function traverseElements(els, cb) {
  14588. if (els) {
  14589. if (isArray(els)) {
  14590. for (var i = 0; i < els.length; i++) {
  14591. traverseElement(els[i], cb);
  14592. }
  14593. } else {
  14594. traverseElement(els, cb);
  14595. }
  14596. }
  14597. } // Register built-in shapes. These shapes might be overwritten
  14598. // by users, although we do not recommend that.
  14599. registerShape('circle', Circle);
  14600. registerShape('ellipse', Ellipse);
  14601. registerShape('sector', Sector);
  14602. registerShape('ring', Ring);
  14603. registerShape('polygon', Polygon);
  14604. registerShape('polyline', Polyline);
  14605. registerShape('rect', Rect);
  14606. registerShape('line', Line);
  14607. registerShape('bezierCurve', BezierCurve);
  14608. registerShape('arc', Arc);
  14609. var graphic = /*#__PURE__*/Object.freeze({
  14610. __proto__: null,
  14611. updateProps: updateProps,
  14612. initProps: initProps,
  14613. removeElement: removeElement,
  14614. removeElementWithFadeOut: removeElementWithFadeOut,
  14615. isElementRemoved: isElementRemoved,
  14616. extendShape: extendShape,
  14617. extendPath: extendPath,
  14618. registerShape: registerShape,
  14619. getShapeClass: getShapeClass,
  14620. makePath: makePath,
  14621. makeImage: makeImage,
  14622. mergePath: mergePath$1,
  14623. resizePath: resizePath,
  14624. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14625. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14626. subPixelOptimize: subPixelOptimize$1,
  14627. getTransform: getTransform,
  14628. applyTransform: applyTransform$1,
  14629. transformDirection: transformDirection,
  14630. groupTransition: groupTransition,
  14631. clipPointsByRect: clipPointsByRect,
  14632. clipRectByRect: clipRectByRect,
  14633. createIcon: createIcon,
  14634. linePolygonIntersect: linePolygonIntersect,
  14635. lineLineIntersect: lineLineIntersect,
  14636. setTooltipConfig: setTooltipConfig,
  14637. traverseElements: traverseElements,
  14638. Group: Group,
  14639. Image: ZRImage,
  14640. Text: ZRText,
  14641. Circle: Circle,
  14642. Ellipse: Ellipse,
  14643. Sector: Sector,
  14644. Ring: Ring,
  14645. Polygon: Polygon,
  14646. Polyline: Polyline,
  14647. Rect: Rect,
  14648. Line: Line,
  14649. BezierCurve: BezierCurve,
  14650. Arc: Arc,
  14651. IncrementalDisplayable: IncrementalDisplayable,
  14652. CompoundPath: CompoundPath,
  14653. LinearGradient: LinearGradient,
  14654. RadialGradient: RadialGradient,
  14655. BoundingRect: BoundingRect,
  14656. OrientedBoundingRect: OrientedBoundingRect,
  14657. Point: Point,
  14658. Path: Path
  14659. });
  14660. var EMPTY_OBJ = {};
  14661. function setLabelText(label, labelTexts) {
  14662. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14663. var stateName = SPECIAL_STATES[i];
  14664. var text = labelTexts[stateName];
  14665. var state = label.ensureState(stateName);
  14666. state.style = state.style || {};
  14667. state.style.text = text;
  14668. }
  14669. var oldStates = label.currentStates.slice();
  14670. label.clearStates(true);
  14671. label.setStyle({
  14672. text: labelTexts.normal
  14673. });
  14674. label.useStates(oldStates, true);
  14675. }
  14676. function getLabelText(opt, stateModels, interpolatedValue) {
  14677. var labelFetcher = opt.labelFetcher;
  14678. var labelDataIndex = opt.labelDataIndex;
  14679. var labelDimIndex = opt.labelDimIndex;
  14680. var normalModel = stateModels.normal;
  14681. var baseText;
  14682. if (labelFetcher) {
  14683. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14684. interpolatedValue: interpolatedValue
  14685. } : null);
  14686. }
  14687. if (baseText == null) {
  14688. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14689. }
  14690. var statesText = {
  14691. normal: baseText
  14692. };
  14693. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14694. var stateName = SPECIAL_STATES[i];
  14695. var stateModel = stateModels[stateName];
  14696. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14697. }
  14698. return statesText;
  14699. }
  14700. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14701. ) {
  14702. opt = opt || EMPTY_OBJ;
  14703. var isSetOnText = targetEl instanceof ZRText;
  14704. var needsCreateText = false;
  14705. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14706. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14707. if (stateModel && stateModel.getShallow('show')) {
  14708. needsCreateText = true;
  14709. break;
  14710. }
  14711. }
  14712. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14713. if (needsCreateText) {
  14714. if (!isSetOnText) {
  14715. // Reuse the previous
  14716. if (!textContent) {
  14717. textContent = new ZRText();
  14718. targetEl.setTextContent(textContent);
  14719. } // Use same state proxy
  14720. if (targetEl.stateProxy) {
  14721. textContent.stateProxy = targetEl.stateProxy;
  14722. }
  14723. }
  14724. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14725. var normalModel = labelStatesModels.normal;
  14726. var showNormal = !!normalModel.getShallow('show');
  14727. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14728. normalStyle.text = labelStatesTexts.normal;
  14729. if (!isSetOnText) {
  14730. // Always create new
  14731. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14732. }
  14733. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14734. var stateName = SPECIAL_STATES[i];
  14735. var stateModel = labelStatesModels[stateName];
  14736. if (stateModel) {
  14737. var stateObj = textContent.ensureState(stateName);
  14738. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14739. if (stateShow !== showNormal) {
  14740. stateObj.ignore = !stateShow;
  14741. }
  14742. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14743. stateObj.style.text = labelStatesTexts[stateName];
  14744. if (!isSetOnText) {
  14745. var targetElEmphasisState = targetEl.ensureState(stateName);
  14746. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14747. }
  14748. }
  14749. } // PENDING: if there is many requirements that emphasis position
  14750. // need to be different from normal position, we might consider
  14751. // auto silent is those cases.
  14752. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14753. if (textContent.style.x != null) {
  14754. normalStyle.x = textContent.style.x;
  14755. }
  14756. if (textContent.style.y != null) {
  14757. normalStyle.y = textContent.style.y;
  14758. }
  14759. textContent.ignore = !showNormal; // Always create new style.
  14760. textContent.useStyle(normalStyle);
  14761. textContent.dirty();
  14762. if (opt.enableTextSetter) {
  14763. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14764. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14765. setLabelText(textContent, labelStatesTexts);
  14766. };
  14767. }
  14768. } else if (textContent) {
  14769. // Not display rich text.
  14770. textContent.ignore = true;
  14771. }
  14772. targetEl.dirty();
  14773. }
  14774. function getLabelStatesModels(itemModel, labelName) {
  14775. labelName = labelName || 'label';
  14776. var statesModels = {
  14777. normal: itemModel.getModel(labelName)
  14778. };
  14779. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14780. var stateName = SPECIAL_STATES[i];
  14781. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14782. }
  14783. return statesModels;
  14784. }
  14785. /**
  14786. * Set basic textStyle properties.
  14787. */
  14788. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14789. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14790. ) {
  14791. var textStyle = {};
  14792. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14793. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14794. return textStyle;
  14795. }
  14796. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14797. opt = opt || {};
  14798. var textConfig = {};
  14799. var labelPosition;
  14800. var labelRotate = textStyleModel.getShallow('rotate');
  14801. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14802. var labelOffset = textStyleModel.getShallow('offset');
  14803. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14804. // in bar series, and magric type should be considered.
  14805. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14806. if (labelPosition != null) {
  14807. textConfig.position = labelPosition;
  14808. }
  14809. if (labelOffset != null) {
  14810. textConfig.offset = labelOffset;
  14811. }
  14812. if (labelRotate != null) {
  14813. labelRotate *= Math.PI / 180;
  14814. textConfig.rotation = labelRotate;
  14815. }
  14816. if (labelDistance != null) {
  14817. textConfig.distance = labelDistance;
  14818. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14819. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14820. return textConfig;
  14821. }
  14822. /**
  14823. * The uniform entry of set text style, that is, retrieve style definitions
  14824. * from `model` and set to `textStyle` object.
  14825. *
  14826. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14827. * properties will be set. (Consider the states of normal and emphasis and
  14828. * default value can be adopted, merge would make the logic too complicated
  14829. * to manage.)
  14830. */
  14831. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14832. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14833. opt = opt || EMPTY_OBJ;
  14834. var ecModel = textStyleModel.ecModel;
  14835. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14836. // {
  14837. // data: [{
  14838. // value: 12,
  14839. // label: {
  14840. // rich: {
  14841. // // no 'a' here but using parent 'a'.
  14842. // }
  14843. // }
  14844. // }],
  14845. // rich: {
  14846. // a: { ... }
  14847. // }
  14848. // }
  14849. var richItemNames = getRichItemNames(textStyleModel);
  14850. var richResult;
  14851. if (richItemNames) {
  14852. richResult = {};
  14853. for (var name_1 in richItemNames) {
  14854. if (richItemNames.hasOwnProperty(name_1)) {
  14855. // Cascade is supported in rich.
  14856. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14857. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14858. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14859. // That might confuses users. So probably we should put `textStyleModel` as the
  14860. // root ancestor of the `richTextStyle`. But that would be a break change.
  14861. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14862. }
  14863. }
  14864. }
  14865. if (richResult) {
  14866. textStyle.rich = richResult;
  14867. }
  14868. var overflow = textStyleModel.get('overflow');
  14869. if (overflow) {
  14870. textStyle.overflow = overflow;
  14871. }
  14872. var margin = textStyleModel.get('minMargin');
  14873. if (margin != null) {
  14874. textStyle.margin = margin;
  14875. }
  14876. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14877. } // Consider case:
  14878. // {
  14879. // data: [{
  14880. // value: 12,
  14881. // label: {
  14882. // rich: {
  14883. // // no 'a' here but using parent 'a'.
  14884. // }
  14885. // }
  14886. // }],
  14887. // rich: {
  14888. // a: { ... }
  14889. // }
  14890. // }
  14891. // TODO TextStyleModel
  14892. function getRichItemNames(textStyleModel) {
  14893. // Use object to remove duplicated names.
  14894. var richItemNameMap;
  14895. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14896. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14897. if (rich) {
  14898. richItemNameMap = richItemNameMap || {};
  14899. var richKeys = keys(rich);
  14900. for (var i = 0; i < richKeys.length; i++) {
  14901. var richKey = richKeys[i];
  14902. richItemNameMap[richKey] = 1;
  14903. }
  14904. }
  14905. textStyleModel = textStyleModel.parentModel;
  14906. }
  14907. return richItemNameMap;
  14908. }
  14909. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14910. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14911. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14912. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14913. // In merge mode, default value should not be given.
  14914. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14915. var inheritColor = opt && opt.inheritColor;
  14916. var fillColor = textStyleModel.getShallow('color');
  14917. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14918. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14919. if (fillColor === 'inherit' || fillColor === 'auto') {
  14920. if ("development" !== 'production') {
  14921. if (fillColor === 'auto') {
  14922. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14923. }
  14924. }
  14925. if (inheritColor) {
  14926. fillColor = inheritColor;
  14927. } else {
  14928. fillColor = null;
  14929. }
  14930. }
  14931. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14932. if ("development" !== 'production') {
  14933. if (strokeColor === 'auto') {
  14934. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14935. }
  14936. }
  14937. if (inheritColor) {
  14938. strokeColor = inheritColor;
  14939. } else {
  14940. strokeColor = null;
  14941. }
  14942. }
  14943. if (!isAttached) {
  14944. // Only use default global textStyle.color if text is individual.
  14945. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14946. fillColor = fillColor || globalTextStyle.color;
  14947. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14948. }
  14949. if (fillColor != null) {
  14950. textStyle.fill = fillColor;
  14951. }
  14952. if (strokeColor != null) {
  14953. textStyle.stroke = strokeColor;
  14954. }
  14955. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14956. if (textBorderWidth != null) {
  14957. textStyle.lineWidth = textBorderWidth;
  14958. }
  14959. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14960. if (textBorderType != null) {
  14961. textStyle.lineDash = textBorderType;
  14962. }
  14963. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14964. if (textBorderDashOffset != null) {
  14965. textStyle.lineDashOffset = textBorderDashOffset;
  14966. }
  14967. if (!isNotNormal && opacity == null && !inRich) {
  14968. opacity = opt && opt.defaultOpacity;
  14969. }
  14970. if (opacity != null) {
  14971. textStyle.opacity = opacity;
  14972. } // TODO
  14973. if (!isNotNormal && !isAttached) {
  14974. // Set default finally.
  14975. if (textStyle.fill == null && opt.inheritColor) {
  14976. textStyle.fill = opt.inheritColor;
  14977. }
  14978. } // Do not use `getFont` here, because merge should be supported, where
  14979. // part of these properties may be changed in emphasis style, and the
  14980. // others should remain their original value got from normal style.
  14981. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14982. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14983. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14984. if (val != null) {
  14985. textStyle[key] = val;
  14986. }
  14987. }
  14988. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14989. var key = TEXT_PROPS_SELF[i];
  14990. var val = textStyleModel.getShallow(key);
  14991. if (val != null) {
  14992. textStyle[key] = val;
  14993. }
  14994. }
  14995. if (textStyle.verticalAlign == null) {
  14996. var baseline = textStyleModel.getShallow('baseline');
  14997. if (baseline != null) {
  14998. textStyle.verticalAlign = baseline;
  14999. }
  15000. }
  15001. if (!isBlock || !opt.disableBox) {
  15002. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15003. var key = TEXT_PROPS_BOX[i];
  15004. var val = textStyleModel.getShallow(key);
  15005. if (val != null) {
  15006. textStyle[key] = val;
  15007. }
  15008. }
  15009. var borderType = textStyleModel.getShallow('borderType');
  15010. if (borderType != null) {
  15011. textStyle.borderDash = borderType;
  15012. }
  15013. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15014. if ("development" !== 'production') {
  15015. if (textStyle.backgroundColor === 'auto') {
  15016. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15017. }
  15018. }
  15019. textStyle.backgroundColor = inheritColor;
  15020. }
  15021. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15022. if ("development" !== 'production') {
  15023. if (textStyle.borderColor === 'auto') {
  15024. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15025. }
  15026. }
  15027. textStyle.borderColor = inheritColor;
  15028. }
  15029. }
  15030. }
  15031. function getFont(opt, ecModel) {
  15032. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15033. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  15034. 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(' '));
  15035. }
  15036. var labelInner = makeInner();
  15037. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15038. if (!label) {
  15039. return;
  15040. }
  15041. var obj = labelInner(label);
  15042. obj.prevValue = obj.value;
  15043. obj.value = value;
  15044. var normalLabelModel = labelStatesModels.normal;
  15045. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15046. if (obj.valueAnimation) {
  15047. obj.precision = normalLabelModel.get('precision');
  15048. obj.defaultInterpolatedText = getDefaultText;
  15049. obj.statesModels = labelStatesModels;
  15050. }
  15051. }
  15052. var PATH_COLOR = ['textStyle', 'color'];
  15053. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  15054. var tmpText = new ZRText();
  15055. var TextStyleMixin =
  15056. /** @class */
  15057. function () {
  15058. function TextStyleMixin() {}
  15059. /**
  15060. * Get color property or get color from option.textStyle.color
  15061. */
  15062. // TODO Callback
  15063. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15064. var ecModel = this.ecModel;
  15065. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15066. };
  15067. /**
  15068. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15069. * @return {string}
  15070. */
  15071. TextStyleMixin.prototype.getFont = function () {
  15072. return getFont({
  15073. fontStyle: this.getShallow('fontStyle'),
  15074. fontWeight: this.getShallow('fontWeight'),
  15075. fontSize: this.getShallow('fontSize'),
  15076. fontFamily: this.getShallow('fontFamily')
  15077. }, this.ecModel);
  15078. };
  15079. TextStyleMixin.prototype.getTextRect = function (text) {
  15080. var style = {
  15081. text: text,
  15082. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15083. };
  15084. for (var i = 0; i < textStyleParams.length; i++) {
  15085. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15086. }
  15087. tmpText.useStyle(style);
  15088. tmpText.update();
  15089. return tmpText.getBoundingRect();
  15090. };
  15091. return TextStyleMixin;
  15092. }();
  15093. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15094. // So do not transfer decal directly.
  15095. ];
  15096. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15097. var LineStyleMixin =
  15098. /** @class */
  15099. function () {
  15100. function LineStyleMixin() {}
  15101. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15102. return getLineStyle(this, excludes);
  15103. };
  15104. return LineStyleMixin;
  15105. }();
  15106. 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'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15107. // So do not transfer decal directly.
  15108. ];
  15109. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15110. var ItemStyleMixin =
  15111. /** @class */
  15112. function () {
  15113. function ItemStyleMixin() {}
  15114. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15115. return getItemStyle(this, excludes, includes);
  15116. };
  15117. return ItemStyleMixin;
  15118. }();
  15119. var Model =
  15120. /** @class */
  15121. function () {
  15122. function Model(option, parentModel, ecModel) {
  15123. this.parentModel = parentModel;
  15124. this.ecModel = ecModel;
  15125. this.option = option; // Simple optimization
  15126. // if (this.init) {
  15127. // if (arguments.length <= 4) {
  15128. // this.init(option, parentModel, ecModel, extraOpt);
  15129. // }
  15130. // else {
  15131. // this.init.apply(this, arguments);
  15132. // }
  15133. // }
  15134. }
  15135. Model.prototype.init = function (option, parentModel, ecModel) {
  15136. var rest = [];
  15137. for (var _i = 3; _i < arguments.length; _i++) {
  15138. rest[_i - 3] = arguments[_i];
  15139. }
  15140. };
  15141. /**
  15142. * Merge the input option to me.
  15143. */
  15144. Model.prototype.mergeOption = function (option, ecModel) {
  15145. merge(this.option, option, true);
  15146. }; // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15147. // TODO: TYPE strict key check?
  15148. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15149. Model.prototype.get = function (path, ignoreParent) {
  15150. if (path == null) {
  15151. return this.option;
  15152. }
  15153. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15154. };
  15155. Model.prototype.getShallow = function (key, ignoreParent) {
  15156. var option = this.option;
  15157. var val = option == null ? option : option[key];
  15158. if (val == null && !ignoreParent) {
  15159. var parentModel = this.parentModel;
  15160. if (parentModel) {
  15161. // FIXME:TS do not know how to make it works
  15162. val = parentModel.getShallow(key);
  15163. }
  15164. }
  15165. return val;
  15166. }; // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15167. // getModel(path: string | string[], parentModel?: Model): Model;
  15168. // TODO 'a.b.c' is deprecated
  15169. Model.prototype.getModel = function (path, parentModel) {
  15170. var hasPath = path != null;
  15171. var pathFinal = hasPath ? this.parsePath(path) : null;
  15172. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15173. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15174. return new Model(obj, parentModel, this.ecModel);
  15175. };
  15176. /**
  15177. * If model has option
  15178. */
  15179. Model.prototype.isEmpty = function () {
  15180. return this.option == null;
  15181. };
  15182. Model.prototype.restoreData = function () {}; // Pending
  15183. Model.prototype.clone = function () {
  15184. var Ctor = this.constructor;
  15185. return new Ctor(clone(this.option));
  15186. }; // setReadOnly(properties): void {
  15187. // clazzUtil.setReadOnly(this, properties);
  15188. // }
  15189. // If path is null/undefined, return null/undefined.
  15190. Model.prototype.parsePath = function (path) {
  15191. if (typeof path === 'string') {
  15192. return path.split('.');
  15193. }
  15194. return path;
  15195. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15196. // Default to be a identity resolver.
  15197. // Can be modified to a different resolver.
  15198. Model.prototype.resolveParentPath = function (path) {
  15199. return path;
  15200. }; // FIXME:TS check whether put this method here
  15201. Model.prototype.isAnimationEnabled = function () {
  15202. if (!env.node && this.option) {
  15203. if (this.option.animation != null) {
  15204. return !!this.option.animation;
  15205. } else if (this.parentModel) {
  15206. return this.parentModel.isAnimationEnabled();
  15207. }
  15208. }
  15209. };
  15210. Model.prototype._doGet = function (pathArr, parentModel) {
  15211. var obj = this.option;
  15212. if (!pathArr) {
  15213. return obj;
  15214. }
  15215. for (var i = 0; i < pathArr.length; i++) {
  15216. // Ignore empty
  15217. if (!pathArr[i]) {
  15218. continue;
  15219. } // obj could be number/string/... (like 0)
  15220. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15221. if (obj == null) {
  15222. break;
  15223. }
  15224. }
  15225. if (obj == null && parentModel) {
  15226. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15227. }
  15228. return obj;
  15229. };
  15230. return Model;
  15231. }();
  15232. enableClassExtend(Model);
  15233. enableClassCheck(Model);
  15234. mixin(Model, LineStyleMixin);
  15235. mixin(Model, ItemStyleMixin);
  15236. mixin(Model, AreaStyleMixin);
  15237. mixin(Model, TextStyleMixin);
  15238. var base = Math.round(Math.random() * 10);
  15239. /**
  15240. * @public
  15241. * @param {string} type
  15242. * @return {string}
  15243. */
  15244. function getUID(type) {
  15245. // Considering the case of crossing js context,
  15246. // use Math.random to make id as unique as possible.
  15247. return [type || '', base++].join('_');
  15248. }
  15249. /**
  15250. * Implements `SubTypeDefaulterManager` for `target`.
  15251. */
  15252. function enableSubTypeDefaulter(target) {
  15253. var subTypeDefaulters = {};
  15254. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15255. var componentTypeInfo = parseClassType(componentType);
  15256. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15257. };
  15258. target.determineSubType = function (componentType, option) {
  15259. var type = option.type;
  15260. if (!type) {
  15261. var componentTypeMain = parseClassType(componentType).main;
  15262. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15263. type = subTypeDefaulters[componentTypeMain](option);
  15264. }
  15265. }
  15266. return type;
  15267. };
  15268. }
  15269. /**
  15270. * Implements `TopologicalTravelable<any>` for `entity`.
  15271. *
  15272. * Topological travel on Activity Network (Activity On Vertices).
  15273. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15274. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15275. * If there is circular dependencey, Error will be thrown.
  15276. */
  15277. function enableTopologicalTravel(entity, dependencyGetter) {
  15278. /**
  15279. * @param targetNameList Target Component type list.
  15280. * Can be ['aa', 'bb', 'aa.xx']
  15281. * @param fullNameList By which we can build dependency graph.
  15282. * @param callback Params: componentType, dependencies.
  15283. * @param context Scope of callback.
  15284. */
  15285. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15286. if (!targetNameList.length) {
  15287. return;
  15288. }
  15289. var result = makeDepndencyGraph(fullNameList);
  15290. var graph = result.graph;
  15291. var noEntryList = result.noEntryList;
  15292. var targetNameSet = {};
  15293. each(targetNameList, function (name) {
  15294. targetNameSet[name] = true;
  15295. });
  15296. while (noEntryList.length) {
  15297. var currComponentType = noEntryList.pop();
  15298. var currVertex = graph[currComponentType];
  15299. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15300. if (isInTargetNameSet) {
  15301. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15302. delete targetNameSet[currComponentType];
  15303. }
  15304. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15305. }
  15306. each(targetNameSet, function () {
  15307. var errMsg = '';
  15308. if ("development" !== 'production') {
  15309. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15310. }
  15311. throw new Error(errMsg);
  15312. });
  15313. function removeEdge(succComponentType) {
  15314. graph[succComponentType].entryCount--;
  15315. if (graph[succComponentType].entryCount === 0) {
  15316. noEntryList.push(succComponentType);
  15317. }
  15318. } // Consider this case: legend depends on series, and we call
  15319. // chart.setOption({series: [...]}), where only series is in option.
  15320. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15321. // not be called, but only sereis.mergeOption is called. Thus legend
  15322. // have no chance to update its local record about series (like which
  15323. // name of series is available in legend).
  15324. function removeEdgeAndAdd(succComponentType) {
  15325. targetNameSet[succComponentType] = true;
  15326. removeEdge(succComponentType);
  15327. }
  15328. };
  15329. function makeDepndencyGraph(fullNameList) {
  15330. var graph = {};
  15331. var noEntryList = [];
  15332. each(fullNameList, function (name) {
  15333. var thisItem = createDependencyGraphItem(graph, name);
  15334. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15335. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15336. thisItem.entryCount = availableDeps.length;
  15337. if (thisItem.entryCount === 0) {
  15338. noEntryList.push(name);
  15339. }
  15340. each(availableDeps, function (dependentName) {
  15341. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15342. thisItem.predecessor.push(dependentName);
  15343. }
  15344. var thatItem = createDependencyGraphItem(graph, dependentName);
  15345. if (indexOf(thatItem.successor, dependentName) < 0) {
  15346. thatItem.successor.push(name);
  15347. }
  15348. });
  15349. });
  15350. return {
  15351. graph: graph,
  15352. noEntryList: noEntryList
  15353. };
  15354. }
  15355. function createDependencyGraphItem(graph, name) {
  15356. if (!graph[name]) {
  15357. graph[name] = {
  15358. predecessor: [],
  15359. successor: []
  15360. };
  15361. }
  15362. return graph[name];
  15363. }
  15364. function getAvailableDependencies(originalDeps, fullNameList) {
  15365. var availableDeps = [];
  15366. each(originalDeps, function (dep) {
  15367. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15368. });
  15369. return availableDeps;
  15370. }
  15371. }
  15372. function inheritDefaultOption(superOption, subOption) {
  15373. // See also `model/Component.ts#getDefaultOption`
  15374. return merge(merge({}, superOption, true), subOption, true);
  15375. }
  15376. /*
  15377. * Licensed to the Apache Software Foundation (ASF) under one
  15378. * or more contributor license agreements. See the NOTICE file
  15379. * distributed with this work for additional information
  15380. * regarding copyright ownership. The ASF licenses this file
  15381. * to you under the Apache License, Version 2.0 (the
  15382. * "License"); you may not use this file except in compliance
  15383. * with the License. You may obtain a copy of the License at
  15384. *
  15385. * http://www.apache.org/licenses/LICENSE-2.0
  15386. *
  15387. * Unless required by applicable law or agreed to in writing,
  15388. * software distributed under the License is distributed on an
  15389. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15390. * KIND, either express or implied. See the License for the
  15391. * specific language governing permissions and limitations
  15392. * under the License.
  15393. */
  15394. /**
  15395. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15396. */
  15397. /*
  15398. * Licensed to the Apache Software Foundation (ASF) under one
  15399. * or more contributor license agreements. See the NOTICE file
  15400. * distributed with this work for additional information
  15401. * regarding copyright ownership. The ASF licenses this file
  15402. * to you under the Apache License, Version 2.0 (the
  15403. * "License"); you may not use this file except in compliance
  15404. * with the License. You may obtain a copy of the License at
  15405. *
  15406. * http://www.apache.org/licenses/LICENSE-2.0
  15407. *
  15408. * Unless required by applicable law or agreed to in writing,
  15409. * software distributed under the License is distributed on an
  15410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15411. * KIND, either express or implied. See the License for the
  15412. * specific language governing permissions and limitations
  15413. * under the License.
  15414. */
  15415. /**
  15416. * Language: English.
  15417. */
  15418. var langEN = {
  15419. time: {
  15420. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15421. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15422. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15423. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15424. },
  15425. legend: {
  15426. selector: {
  15427. all: 'All',
  15428. inverse: 'Inv'
  15429. }
  15430. },
  15431. toolbox: {
  15432. brush: {
  15433. title: {
  15434. rect: 'Box Select',
  15435. polygon: 'Lasso Select',
  15436. lineX: 'Horizontally Select',
  15437. lineY: 'Vertically Select',
  15438. keep: 'Keep Selections',
  15439. clear: 'Clear Selections'
  15440. }
  15441. },
  15442. dataView: {
  15443. title: 'Data View',
  15444. lang: ['Data View', 'Close', 'Refresh']
  15445. },
  15446. dataZoom: {
  15447. title: {
  15448. zoom: 'Zoom',
  15449. back: 'Zoom Reset'
  15450. }
  15451. },
  15452. magicType: {
  15453. title: {
  15454. line: 'Switch to Line Chart',
  15455. bar: 'Switch to Bar Chart',
  15456. stack: 'Stack',
  15457. tiled: 'Tile'
  15458. }
  15459. },
  15460. restore: {
  15461. title: 'Restore'
  15462. },
  15463. saveAsImage: {
  15464. title: 'Save as Image',
  15465. lang: ['Right Click to Save Image']
  15466. }
  15467. },
  15468. series: {
  15469. typeNames: {
  15470. pie: 'Pie chart',
  15471. bar: 'Bar chart',
  15472. line: 'Line chart',
  15473. scatter: 'Scatter plot',
  15474. effectScatter: 'Ripple scatter plot',
  15475. radar: 'Radar chart',
  15476. tree: 'Tree',
  15477. treemap: 'Treemap',
  15478. boxplot: 'Boxplot',
  15479. candlestick: 'Candlestick',
  15480. k: 'K line chart',
  15481. heatmap: 'Heat map',
  15482. map: 'Map',
  15483. parallel: 'Parallel coordinate map',
  15484. lines: 'Line graph',
  15485. graph: 'Relationship graph',
  15486. sankey: 'Sankey diagram',
  15487. funnel: 'Funnel chart',
  15488. gauge: 'Gauge',
  15489. pictorialBar: 'Pictorial bar',
  15490. themeRiver: 'Theme River Map',
  15491. sunburst: 'Sunburst'
  15492. }
  15493. },
  15494. aria: {
  15495. general: {
  15496. withTitle: 'This is a chart about "{title}"',
  15497. withoutTitle: 'This is a chart'
  15498. },
  15499. series: {
  15500. single: {
  15501. prefix: '',
  15502. withName: ' with type {seriesType} named {seriesName}.',
  15503. withoutName: ' with type {seriesType}.'
  15504. },
  15505. multiple: {
  15506. prefix: '. It consists of {seriesCount} series count.',
  15507. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15508. withoutName: ' The {seriesId} series is a {seriesType}.',
  15509. separator: {
  15510. middle: '',
  15511. end: ''
  15512. }
  15513. }
  15514. },
  15515. data: {
  15516. allData: 'The data is as follows: ',
  15517. partialData: 'The first {displayCnt} items are: ',
  15518. withName: 'the data for {name} is {value}',
  15519. withoutName: '{value}',
  15520. separator: {
  15521. middle: ', ',
  15522. end: '. '
  15523. }
  15524. }
  15525. }
  15526. };
  15527. /*
  15528. * Licensed to the Apache Software Foundation (ASF) under one
  15529. * or more contributor license agreements. See the NOTICE file
  15530. * distributed with this work for additional information
  15531. * regarding copyright ownership. The ASF licenses this file
  15532. * to you under the Apache License, Version 2.0 (the
  15533. * "License"); you may not use this file except in compliance
  15534. * with the License. You may obtain a copy of the License at
  15535. *
  15536. * http://www.apache.org/licenses/LICENSE-2.0
  15537. *
  15538. * Unless required by applicable law or agreed to in writing,
  15539. * software distributed under the License is distributed on an
  15540. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15541. * KIND, either express or implied. See the License for the
  15542. * specific language governing permissions and limitations
  15543. * under the License.
  15544. */
  15545. /**
  15546. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15547. */
  15548. /*
  15549. * Licensed to the Apache Software Foundation (ASF) under one
  15550. * or more contributor license agreements. See the NOTICE file
  15551. * distributed with this work for additional information
  15552. * regarding copyright ownership. The ASF licenses this file
  15553. * to you under the Apache License, Version 2.0 (the
  15554. * "License"); you may not use this file except in compliance
  15555. * with the License. You may obtain a copy of the License at
  15556. *
  15557. * http://www.apache.org/licenses/LICENSE-2.0
  15558. *
  15559. * Unless required by applicable law or agreed to in writing,
  15560. * software distributed under the License is distributed on an
  15561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15562. * KIND, either express or implied. See the License for the
  15563. * specific language governing permissions and limitations
  15564. * under the License.
  15565. */
  15566. var langZH = {
  15567. time: {
  15568. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15569. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15570. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15571. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15572. },
  15573. legend: {
  15574. selector: {
  15575. all: '全选',
  15576. inverse: '反选'
  15577. }
  15578. },
  15579. toolbox: {
  15580. brush: {
  15581. title: {
  15582. rect: '矩形选择',
  15583. polygon: '圈选',
  15584. lineX: '横向选择',
  15585. lineY: '纵向选择',
  15586. keep: '保持选择',
  15587. clear: '清除选择'
  15588. }
  15589. },
  15590. dataView: {
  15591. title: '数据视图',
  15592. lang: ['数据视图', '关闭', '刷新']
  15593. },
  15594. dataZoom: {
  15595. title: {
  15596. zoom: '区域缩放',
  15597. back: '区域缩放还原'
  15598. }
  15599. },
  15600. magicType: {
  15601. title: {
  15602. line: '切换为折线图',
  15603. bar: '切换为柱状图',
  15604. stack: '切换为堆叠',
  15605. tiled: '切换为平铺'
  15606. }
  15607. },
  15608. restore: {
  15609. title: '还原'
  15610. },
  15611. saveAsImage: {
  15612. title: '保存为图片',
  15613. lang: ['右键另存为图片']
  15614. }
  15615. },
  15616. series: {
  15617. typeNames: {
  15618. pie: '饼图',
  15619. bar: '柱状图',
  15620. line: '折线图',
  15621. scatter: '散点图',
  15622. effectScatter: '涟漪散点图',
  15623. radar: '雷达图',
  15624. tree: '树图',
  15625. treemap: '矩形树图',
  15626. boxplot: '箱型图',
  15627. candlestick: 'K线图',
  15628. k: 'K线图',
  15629. heatmap: '热力图',
  15630. map: '地图',
  15631. parallel: '平行坐标图',
  15632. lines: '线图',
  15633. graph: '关系图',
  15634. sankey: '桑基图',
  15635. funnel: '漏斗图',
  15636. gauge: '仪表盘图',
  15637. pictorialBar: '象形柱图',
  15638. themeRiver: '主题河流图',
  15639. sunburst: '旭日图'
  15640. }
  15641. },
  15642. aria: {
  15643. general: {
  15644. withTitle: '这是一个关于“{title}”的图表。',
  15645. withoutTitle: '这是一个图表,'
  15646. },
  15647. series: {
  15648. single: {
  15649. prefix: '',
  15650. withName: '图表类型是{seriesType},表示{seriesName}。',
  15651. withoutName: '图表类型是{seriesType}。'
  15652. },
  15653. multiple: {
  15654. prefix: '它由{seriesCount}个图表系列组成。',
  15655. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15656. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15657. separator: {
  15658. middle: ';',
  15659. end: '。'
  15660. }
  15661. }
  15662. },
  15663. data: {
  15664. allData: '其数据是——',
  15665. partialData: '其中,前{displayCnt}项是——',
  15666. withName: '{name}的数据是{value}',
  15667. withoutName: '{value}',
  15668. separator: {
  15669. middle: ',',
  15670. end: ''
  15671. }
  15672. }
  15673. }
  15674. };
  15675. var LOCALE_ZH = 'ZH';
  15676. var LOCALE_EN = 'EN';
  15677. var DEFAULT_LOCALE = LOCALE_EN;
  15678. var localeStorage = {};
  15679. var localeModels = {};
  15680. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15681. var langStr = (
  15682. /* eslint-disable-next-line */
  15683. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15684. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15685. }();
  15686. function registerLocale(locale, localeObj) {
  15687. locale = locale.toUpperCase();
  15688. localeModels[locale] = new Model(localeObj);
  15689. localeStorage[locale] = localeObj;
  15690. } // export function getLocale(locale: string) {
  15691. // return localeStorage[locale];
  15692. // }
  15693. function createLocaleObject(locale) {
  15694. if (isString(locale)) {
  15695. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15696. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15697. return clone(localeObj);
  15698. } else {
  15699. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15700. }
  15701. } else {
  15702. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15703. }
  15704. }
  15705. function getLocaleModel(lang) {
  15706. return localeModels[lang];
  15707. }
  15708. function getDefaultLocaleModel() {
  15709. return localeModels[DEFAULT_LOCALE];
  15710. } // Default locale
  15711. registerLocale(LOCALE_EN, langEN);
  15712. registerLocale(LOCALE_ZH, langZH);
  15713. var ONE_SECOND = 1000;
  15714. var ONE_MINUTE = ONE_SECOND * 60;
  15715. var ONE_HOUR = ONE_MINUTE * 60;
  15716. var ONE_DAY = ONE_HOUR * 24;
  15717. var ONE_YEAR = ONE_DAY * 365;
  15718. var defaultLeveledFormatter = {
  15719. year: '{yyyy}',
  15720. month: '{MMM}',
  15721. day: '{d}',
  15722. hour: '{HH}:{mm}',
  15723. minute: '{HH}:{mm}',
  15724. second: '{HH}:{mm}:{ss}',
  15725. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15726. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15727. };
  15728. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15729. var fullLeveledFormatter = {
  15730. year: '{yyyy}',
  15731. month: '{yyyy}-{MM}',
  15732. day: fullDayFormatter,
  15733. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15734. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15735. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15736. millisecond: defaultLeveledFormatter.none
  15737. };
  15738. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15739. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15740. function pad(str, len) {
  15741. str += '';
  15742. return '0000'.substr(0, len - str.length) + str;
  15743. }
  15744. function getPrimaryTimeUnit(timeUnit) {
  15745. switch (timeUnit) {
  15746. case 'half-year':
  15747. case 'quarter':
  15748. return 'month';
  15749. case 'week':
  15750. case 'half-week':
  15751. return 'day';
  15752. case 'half-day':
  15753. case 'quarter-day':
  15754. return 'hour';
  15755. default:
  15756. // year, minutes, second, milliseconds
  15757. return timeUnit;
  15758. }
  15759. }
  15760. function isPrimaryTimeUnit(timeUnit) {
  15761. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15762. }
  15763. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15764. switch (timeUnit) {
  15765. case 'year':
  15766. case 'month':
  15767. return 'day';
  15768. case 'millisecond':
  15769. return 'millisecond';
  15770. default:
  15771. // Also for day, hour, minute, second
  15772. return 'second';
  15773. }
  15774. }
  15775. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15776. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15777. time, template, isUTC, lang) {
  15778. var date = parseDate(time);
  15779. var y = date[fullYearGetterName(isUTC)]();
  15780. var M = date[monthGetterName(isUTC)]() + 1;
  15781. var q = Math.floor((M - 1) / 3) + 1;
  15782. var d = date[dateGetterName(isUTC)]();
  15783. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15784. var H = date[hoursGetterName(isUTC)]();
  15785. var h = (H - 1) % 12 + 1;
  15786. var m = date[minutesGetterName(isUTC)]();
  15787. var s = date[secondsGetterName(isUTC)]();
  15788. var S = date[millisecondsGetterName(isUTC)]();
  15789. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15790. var timeModel = localeModel.getModel('time');
  15791. var month = timeModel.get('month');
  15792. var monthAbbr = timeModel.get('monthAbbr');
  15793. var dayOfWeek = timeModel.get('dayOfWeek');
  15794. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15795. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').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 + '');
  15796. }
  15797. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15798. var template = null;
  15799. if (isString(formatter)) {
  15800. // Single formatter for all units at all levels
  15801. template = formatter;
  15802. } else if (isFunction(formatter)) {
  15803. // Callback formatter
  15804. template = formatter(tick.value, idx, {
  15805. level: tick.level
  15806. });
  15807. } else {
  15808. var defaults$1 = extend({}, defaultLeveledFormatter);
  15809. if (tick.level > 0) {
  15810. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15811. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15812. }
  15813. }
  15814. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15815. : defaults(formatter, defaults$1) : defaults$1;
  15816. var unit = getUnitFromValue(tick.value, isUTC);
  15817. if (mergedFormatter[unit]) {
  15818. template = mergedFormatter[unit];
  15819. } else if (mergedFormatter.inherit) {
  15820. // Unit formatter is not defined and should inherit from bigger units
  15821. var targetId = timeUnits.indexOf(unit);
  15822. for (var i = targetId - 1; i >= 0; --i) {
  15823. if (mergedFormatter[unit]) {
  15824. template = mergedFormatter[unit];
  15825. break;
  15826. }
  15827. }
  15828. template = template || defaults$1.none;
  15829. }
  15830. if (isArray(template)) {
  15831. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15832. levelId = Math.min(levelId, template.length - 1);
  15833. template = template[levelId];
  15834. }
  15835. }
  15836. return format(new Date(tick.value), template, isUTC, lang);
  15837. }
  15838. function getUnitFromValue(value, isUTC) {
  15839. var date = parseDate(value);
  15840. var M = date[monthGetterName(isUTC)]() + 1;
  15841. var d = date[dateGetterName(isUTC)]();
  15842. var h = date[hoursGetterName(isUTC)]();
  15843. var m = date[minutesGetterName(isUTC)]();
  15844. var s = date[secondsGetterName(isUTC)]();
  15845. var S = date[millisecondsGetterName(isUTC)]();
  15846. var isSecond = S === 0;
  15847. var isMinute = isSecond && s === 0;
  15848. var isHour = isMinute && m === 0;
  15849. var isDay = isHour && h === 0;
  15850. var isMonth = isDay && d === 1;
  15851. var isYear = isMonth && M === 1;
  15852. if (isYear) {
  15853. return 'year';
  15854. } else if (isMonth) {
  15855. return 'month';
  15856. } else if (isDay) {
  15857. return 'day';
  15858. } else if (isHour) {
  15859. return 'hour';
  15860. } else if (isMinute) {
  15861. return 'minute';
  15862. } else if (isSecond) {
  15863. return 'second';
  15864. } else {
  15865. return 'millisecond';
  15866. }
  15867. }
  15868. function getUnitValue(value, unit, isUTC) {
  15869. var date = isNumber(value) ? parseDate(value) : value;
  15870. unit = unit || getUnitFromValue(value, isUTC);
  15871. switch (unit) {
  15872. case 'year':
  15873. return date[fullYearGetterName(isUTC)]();
  15874. case 'half-year':
  15875. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15876. case 'quarter':
  15877. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15878. case 'month':
  15879. return date[monthGetterName(isUTC)]();
  15880. case 'day':
  15881. return date[dateGetterName(isUTC)]();
  15882. case 'half-day':
  15883. return date[hoursGetterName(isUTC)]() / 24;
  15884. case 'hour':
  15885. return date[hoursGetterName(isUTC)]();
  15886. case 'minute':
  15887. return date[minutesGetterName(isUTC)]();
  15888. case 'second':
  15889. return date[secondsGetterName(isUTC)]();
  15890. case 'millisecond':
  15891. return date[millisecondsGetterName(isUTC)]();
  15892. }
  15893. }
  15894. function fullYearGetterName(isUTC) {
  15895. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15896. }
  15897. function monthGetterName(isUTC) {
  15898. return isUTC ? 'getUTCMonth' : 'getMonth';
  15899. }
  15900. function dateGetterName(isUTC) {
  15901. return isUTC ? 'getUTCDate' : 'getDate';
  15902. }
  15903. function hoursGetterName(isUTC) {
  15904. return isUTC ? 'getUTCHours' : 'getHours';
  15905. }
  15906. function minutesGetterName(isUTC) {
  15907. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15908. }
  15909. function secondsGetterName(isUTC) {
  15910. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15911. }
  15912. function millisecondsGetterName(isUTC) {
  15913. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  15914. }
  15915. function fullYearSetterName(isUTC) {
  15916. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15917. }
  15918. function monthSetterName(isUTC) {
  15919. return isUTC ? 'setUTCMonth' : 'setMonth';
  15920. }
  15921. function dateSetterName(isUTC) {
  15922. return isUTC ? 'setUTCDate' : 'setDate';
  15923. }
  15924. function hoursSetterName(isUTC) {
  15925. return isUTC ? 'setUTCHours' : 'setHours';
  15926. }
  15927. function minutesSetterName(isUTC) {
  15928. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15929. }
  15930. function secondsSetterName(isUTC) {
  15931. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15932. }
  15933. function millisecondsSetterName(isUTC) {
  15934. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  15935. }
  15936. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15937. var textEl = new ZRText({
  15938. style: {
  15939. text: text,
  15940. font: font,
  15941. align: align,
  15942. verticalAlign: verticalAlign,
  15943. padding: padding,
  15944. rich: rich,
  15945. overflow: truncate ? 'truncate' : null,
  15946. lineHeight: lineHeight
  15947. }
  15948. });
  15949. return textEl.getBoundingRect();
  15950. }
  15951. /**
  15952. * Add a comma each three digit.
  15953. */
  15954. function addCommas(x) {
  15955. if (!isNumeric(x)) {
  15956. return isString(x) ? x : '-';
  15957. }
  15958. var parts = (x + '').split('.');
  15959. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15960. }
  15961. function toCamelCase(str, upperCaseFirst) {
  15962. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15963. return group1.toUpperCase();
  15964. });
  15965. if (upperCaseFirst && str) {
  15966. str = str.charAt(0).toUpperCase() + str.slice(1);
  15967. }
  15968. return str;
  15969. }
  15970. var normalizeCssArray$1 = normalizeCssArray;
  15971. /**
  15972. * Make value user readable for tooltip and label.
  15973. * "User readable":
  15974. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  15975. * Avoid to display an empty string, which users can not recognize there is
  15976. * a value and it might look like a bug.
  15977. */
  15978. function makeValueReadable(value, valueType, useUTC) {
  15979. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  15980. function stringToUserReadable(str) {
  15981. return str && trim(str) ? str : '-';
  15982. }
  15983. function isNumberUserReadable(num) {
  15984. return !!(num != null && !isNaN(num) && isFinite(num));
  15985. }
  15986. var isTypeTime = valueType === 'time';
  15987. var isValueDate = value instanceof Date;
  15988. if (isTypeTime || isValueDate) {
  15989. var date = isTypeTime ? parseDate(value) : value;
  15990. if (!isNaN(+date)) {
  15991. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  15992. } else if (isValueDate) {
  15993. return '-';
  15994. } // In other cases, continue to try to display the value in the following code.
  15995. }
  15996. if (valueType === 'ordinal') {
  15997. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  15998. } // By default.
  15999. var numericResult = numericToNumber(value);
  16000. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16001. }
  16002. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16003. var wrapVar = function (varName, seriesIdx) {
  16004. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16005. };
  16006. /**
  16007. * Template formatter
  16008. * @param {Array.<Object>|Object} paramsList
  16009. */
  16010. function formatTpl(tpl, paramsList, encode) {
  16011. if (!isArray(paramsList)) {
  16012. paramsList = [paramsList];
  16013. }
  16014. var seriesLen = paramsList.length;
  16015. if (!seriesLen) {
  16016. return '';
  16017. }
  16018. var $vars = paramsList[0].$vars || [];
  16019. for (var i = 0; i < $vars.length; i++) {
  16020. var alias = TPL_VAR_ALIAS[i];
  16021. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16022. }
  16023. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16024. for (var k = 0; k < $vars.length; k++) {
  16025. var val = paramsList[seriesIdx][$vars[k]];
  16026. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16027. }
  16028. }
  16029. return tpl;
  16030. }
  16031. function getTooltipMarker(inOpt, extraCssText) {
  16032. var opt = isString(inOpt) ? {
  16033. color: inOpt,
  16034. extraCssText: extraCssText
  16035. } : inOpt || {};
  16036. var color = opt.color;
  16037. var type = opt.type;
  16038. extraCssText = opt.extraCssText;
  16039. var renderMode = opt.renderMode || 'html';
  16040. if (!color) {
  16041. return '';
  16042. }
  16043. if (renderMode === 'html') {
  16044. 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:' // Only support string
  16045. + 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>';
  16046. } else {
  16047. // Should better not to auto generate style name by auto-increment number here.
  16048. // Because this util is usually called in tooltip formatter, which is probably
  16049. // called repeatedly when mouse move and the auto-increment number increases fast.
  16050. // Users can make their own style name by theirselves, make it unique and readable.
  16051. var markerId = opt.markerId || 'markerX';
  16052. return {
  16053. renderMode: renderMode,
  16054. content: '{' + markerId + '|} ',
  16055. style: type === 'subItem' ? {
  16056. width: 4,
  16057. height: 4,
  16058. borderRadius: 2,
  16059. backgroundColor: color
  16060. } : {
  16061. width: 10,
  16062. height: 10,
  16063. borderRadius: 5,
  16064. backgroundColor: color
  16065. }
  16066. };
  16067. }
  16068. }
  16069. /**
  16070. * @deprecated Use `time/format` instead.
  16071. * ISO Date format
  16072. * @param {string} tpl
  16073. * @param {number} value
  16074. * @param {boolean} [isUTC=false] Default in local time.
  16075. * see `module:echarts/scale/Time`
  16076. * and `module:echarts/util/number#parseDate`.
  16077. * @inner
  16078. */
  16079. function formatTime(tpl, value, isUTC) {
  16080. if ("development" !== 'production') {
  16081. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16082. }
  16083. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16084. tpl = 'MM-dd\nyyyy';
  16085. }
  16086. var date = parseDate(value);
  16087. var getUTC = isUTC ? 'getUTC' : 'get';
  16088. var y = date[getUTC + 'FullYear']();
  16089. var M = date[getUTC + 'Month']() + 1;
  16090. var d = date[getUTC + 'Date']();
  16091. var h = date[getUTC + 'Hours']();
  16092. var m = date[getUTC + 'Minutes']();
  16093. var s = date[getUTC + 'Seconds']();
  16094. var S = date[getUTC + 'Milliseconds']();
  16095. 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));
  16096. return tpl;
  16097. }
  16098. /**
  16099. * Capital first
  16100. * @param {string} str
  16101. * @return {string}
  16102. */
  16103. function capitalFirst(str) {
  16104. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16105. }
  16106. /**
  16107. * @return Never be null/undefined.
  16108. */
  16109. function convertToColorString(color, defaultColor) {
  16110. defaultColor = defaultColor || 'transparent';
  16111. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16112. }
  16113. /**
  16114. * open new tab
  16115. * @param link url
  16116. * @param target blank or self
  16117. */
  16118. function windowOpen(link, target) {
  16119. /* global window */
  16120. if (target === '_blank' || target === 'blank') {
  16121. var blank = window.open();
  16122. blank.opener = null;
  16123. blank.location.href = link;
  16124. } else {
  16125. window.open(link, target);
  16126. }
  16127. }
  16128. var each$1 = each;
  16129. /**
  16130. * @public
  16131. */
  16132. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16133. /**
  16134. * @public
  16135. */
  16136. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16137. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16138. var x = 0;
  16139. var y = 0;
  16140. if (maxWidth == null) {
  16141. maxWidth = Infinity;
  16142. }
  16143. if (maxHeight == null) {
  16144. maxHeight = Infinity;
  16145. }
  16146. var currentLineMaxSize = 0;
  16147. group.eachChild(function (child, idx) {
  16148. var rect = child.getBoundingRect();
  16149. var nextChild = group.childAt(idx + 1);
  16150. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16151. var nextX;
  16152. var nextY;
  16153. if (orient === 'horizontal') {
  16154. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16155. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16156. // FIXME compare before adding gap?
  16157. if (nextX > maxWidth || child.newline) {
  16158. x = 0;
  16159. nextX = moveX;
  16160. y += currentLineMaxSize + gap;
  16161. currentLineMaxSize = rect.height;
  16162. } else {
  16163. // FIXME: consider rect.y is not `0`?
  16164. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16165. }
  16166. } else {
  16167. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16168. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16169. if (nextY > maxHeight || child.newline) {
  16170. x += currentLineMaxSize + gap;
  16171. y = 0;
  16172. nextY = moveY;
  16173. currentLineMaxSize = rect.width;
  16174. } else {
  16175. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16176. }
  16177. }
  16178. if (child.newline) {
  16179. return;
  16180. }
  16181. child.x = x;
  16182. child.y = y;
  16183. child.markRedraw();
  16184. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16185. });
  16186. }
  16187. /**
  16188. * VBox or HBox layouting
  16189. * @param {string} orient
  16190. * @param {module:zrender/graphic/Group} group
  16191. * @param {number} gap
  16192. * @param {number} [width=Infinity]
  16193. * @param {number} [height=Infinity]
  16194. */
  16195. var box = boxLayout;
  16196. /**
  16197. * VBox layouting
  16198. * @param {module:zrender/graphic/Group} group
  16199. * @param {number} gap
  16200. * @param {number} [width=Infinity]
  16201. * @param {number} [height=Infinity]
  16202. */
  16203. var vbox = curry(boxLayout, 'vertical');
  16204. /**
  16205. * HBox layouting
  16206. * @param {module:zrender/graphic/Group} group
  16207. * @param {number} gap
  16208. * @param {number} [width=Infinity]
  16209. * @param {number} [height=Infinity]
  16210. */
  16211. var hbox = curry(boxLayout, 'horizontal');
  16212. /**
  16213. * Parse position info.
  16214. */
  16215. function getLayoutRect(positionInfo, containerRect, margin) {
  16216. margin = normalizeCssArray$1(margin || 0);
  16217. var containerWidth = containerRect.width;
  16218. var containerHeight = containerRect.height;
  16219. var left = parsePercent$1(positionInfo.left, containerWidth);
  16220. var top = parsePercent$1(positionInfo.top, containerHeight);
  16221. var right = parsePercent$1(positionInfo.right, containerWidth);
  16222. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16223. var width = parsePercent$1(positionInfo.width, containerWidth);
  16224. var height = parsePercent$1(positionInfo.height, containerHeight);
  16225. var verticalMargin = margin[2] + margin[0];
  16226. var horizontalMargin = margin[1] + margin[3];
  16227. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16228. if (isNaN(width)) {
  16229. width = containerWidth - right - horizontalMargin - left;
  16230. }
  16231. if (isNaN(height)) {
  16232. height = containerHeight - bottom - verticalMargin - top;
  16233. }
  16234. if (aspect != null) {
  16235. // If width and height are not given
  16236. // 1. Graph should not exceeds the container
  16237. // 2. Aspect must be keeped
  16238. // 3. Graph should take the space as more as possible
  16239. // FIXME
  16240. // Margin is not considered, because there is no case that both
  16241. // using margin and aspect so far.
  16242. if (isNaN(width) && isNaN(height)) {
  16243. if (aspect > containerWidth / containerHeight) {
  16244. width = containerWidth * 0.8;
  16245. } else {
  16246. height = containerHeight * 0.8;
  16247. }
  16248. } // Calculate width or height with given aspect
  16249. if (isNaN(width)) {
  16250. width = aspect * height;
  16251. }
  16252. if (isNaN(height)) {
  16253. height = width / aspect;
  16254. }
  16255. } // If left is not specified, calculate left from right and width
  16256. if (isNaN(left)) {
  16257. left = containerWidth - right - width - horizontalMargin;
  16258. }
  16259. if (isNaN(top)) {
  16260. top = containerHeight - bottom - height - verticalMargin;
  16261. } // Align left and top
  16262. switch (positionInfo.left || positionInfo.right) {
  16263. case 'center':
  16264. left = containerWidth / 2 - width / 2 - margin[3];
  16265. break;
  16266. case 'right':
  16267. left = containerWidth - width - horizontalMargin;
  16268. break;
  16269. }
  16270. switch (positionInfo.top || positionInfo.bottom) {
  16271. case 'middle':
  16272. case 'center':
  16273. top = containerHeight / 2 - height / 2 - margin[0];
  16274. break;
  16275. case 'bottom':
  16276. top = containerHeight - height - verticalMargin;
  16277. break;
  16278. } // If something is wrong and left, top, width, height are calculated as NaN
  16279. left = left || 0;
  16280. top = top || 0;
  16281. if (isNaN(width)) {
  16282. // Width may be NaN if only one value is given except width
  16283. width = containerWidth - horizontalMargin - left - (right || 0);
  16284. }
  16285. if (isNaN(height)) {
  16286. // Height may be NaN if only one value is given except height
  16287. height = containerHeight - verticalMargin - top - (bottom || 0);
  16288. }
  16289. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16290. rect.margin = margin;
  16291. return rect;
  16292. }
  16293. /**
  16294. * Position a zr element in viewport
  16295. * Group position is specified by either
  16296. * {left, top}, {right, bottom}
  16297. * If all properties exists, right and bottom will be igonred.
  16298. *
  16299. * Logic:
  16300. * 1. Scale (against origin point in parent coord)
  16301. * 2. Rotate (against origin point in parent coord)
  16302. * 3. Translate (with el.position by this method)
  16303. * So this method only fixes the last step 'Translate', which does not affect
  16304. * scaling and rotating.
  16305. *
  16306. * If be called repeatedly with the same input el, the same result will be gotten.
  16307. *
  16308. * Return true if the layout happened.
  16309. *
  16310. * @param el Should have `getBoundingRect` method.
  16311. * @param positionInfo
  16312. * @param positionInfo.left
  16313. * @param positionInfo.top
  16314. * @param positionInfo.right
  16315. * @param positionInfo.bottom
  16316. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16317. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16318. * @param containerRect
  16319. * @param margin
  16320. * @param opt
  16321. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16322. * @param opt.boundingMode
  16323. * Specify how to calculate boundingRect when locating.
  16324. * 'all': Position the boundingRect that is transformed and uioned
  16325. * both itself and its descendants.
  16326. * This mode simplies confine the elements in the bounding
  16327. * of their container (e.g., using 'right: 0').
  16328. * 'raw': Position the boundingRect that is not transformed and only itself.
  16329. * This mode is useful when you want a element can overflow its
  16330. * container. (Consider a rotated circle needs to be located in a corner.)
  16331. * In this mode positionInfo.width/height can only be number.
  16332. */
  16333. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16334. var h = !opt || !opt.hv || opt.hv[0];
  16335. var v = !opt || !opt.hv || opt.hv[1];
  16336. var boundingMode = opt && opt.boundingMode || 'all';
  16337. out = out || el;
  16338. out.x = el.x;
  16339. out.y = el.y;
  16340. if (!h && !v) {
  16341. return false;
  16342. }
  16343. var rect;
  16344. if (boundingMode === 'raw') {
  16345. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16346. } else {
  16347. rect = el.getBoundingRect();
  16348. if (el.needLocalTransform()) {
  16349. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16350. // which should not be modified.
  16351. rect = rect.clone();
  16352. rect.applyTransform(transform);
  16353. }
  16354. } // The real width and height can not be specified but calculated by the given el.
  16355. var layoutRect = getLayoutRect(defaults({
  16356. width: rect.width,
  16357. height: rect.height
  16358. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16359. // (see zrender/core/Transformable#getLocalTransform),
  16360. // we can just only modify el.position to get final result.
  16361. var dx = h ? layoutRect.x - rect.x : 0;
  16362. var dy = v ? layoutRect.y - rect.y : 0;
  16363. if (boundingMode === 'raw') {
  16364. out.x = dx;
  16365. out.y = dy;
  16366. } else {
  16367. out.x += dx;
  16368. out.y += dy;
  16369. }
  16370. if (out === el) {
  16371. el.markRedraw();
  16372. }
  16373. return true;
  16374. }
  16375. function fetchLayoutMode(ins) {
  16376. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16377. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16378. type: layoutMode
  16379. } : null;
  16380. }
  16381. /**
  16382. * Consider Case:
  16383. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16384. * through setOption or media query, using normal zrUtil.merge will cause
  16385. * {right: 0} does not take effect.
  16386. *
  16387. * @example
  16388. * ComponentModel.extend({
  16389. * init: function () {
  16390. * ...
  16391. * let inputPositionParams = layout.getLayoutParams(option);
  16392. * this.mergeOption(inputPositionParams);
  16393. * },
  16394. * mergeOption: function (newOption) {
  16395. * newOption && zrUtil.merge(thisOption, newOption, true);
  16396. * layout.mergeLayoutParam(thisOption, newOption);
  16397. * }
  16398. * });
  16399. *
  16400. * @param targetOption
  16401. * @param newOption
  16402. * @param opt
  16403. */
  16404. function mergeLayoutParam(targetOption, newOption, opt) {
  16405. var ignoreSize = opt && opt.ignoreSize;
  16406. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16407. var hResult = merge(HV_NAMES[0], 0);
  16408. var vResult = merge(HV_NAMES[1], 1);
  16409. copy(HV_NAMES[0], targetOption, hResult);
  16410. copy(HV_NAMES[1], targetOption, vResult);
  16411. function merge(names, hvIdx) {
  16412. var newParams = {};
  16413. var newValueCount = 0;
  16414. var merged = {};
  16415. var mergedValueCount = 0;
  16416. var enoughParamNumber = 2;
  16417. each$1(names, function (name) {
  16418. merged[name] = targetOption[name];
  16419. });
  16420. each$1(names, function (name) {
  16421. // Consider case: newOption.width is null, which is
  16422. // set by user for removing width setting.
  16423. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16424. hasValue(newParams, name) && newValueCount++;
  16425. hasValue(merged, name) && mergedValueCount++;
  16426. });
  16427. if (ignoreSize[hvIdx]) {
  16428. // Only one of left/right is premitted to exist.
  16429. if (hasValue(newOption, names[1])) {
  16430. merged[names[2]] = null;
  16431. } else if (hasValue(newOption, names[2])) {
  16432. merged[names[1]] = null;
  16433. }
  16434. return merged;
  16435. } // Case: newOption: {width: ..., right: ...},
  16436. // or targetOption: {right: ...} and newOption: {width: ...},
  16437. // There is no conflict when merged only has params count
  16438. // little than enoughParamNumber.
  16439. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16440. return merged;
  16441. } // Case: newOption: {width: ..., right: ...},
  16442. // Than we can make sure user only want those two, and ignore
  16443. // all origin params in targetOption.
  16444. else if (newValueCount >= enoughParamNumber) {
  16445. return newParams;
  16446. } else {
  16447. // Chose another param from targetOption by priority.
  16448. for (var i = 0; i < names.length; i++) {
  16449. var name_1 = names[i];
  16450. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16451. newParams[name_1] = targetOption[name_1];
  16452. break;
  16453. }
  16454. }
  16455. return newParams;
  16456. }
  16457. }
  16458. function hasProp(obj, name) {
  16459. return obj.hasOwnProperty(name);
  16460. }
  16461. function hasValue(obj, name) {
  16462. return obj[name] != null && obj[name] !== 'auto';
  16463. }
  16464. function copy(names, target, source) {
  16465. each$1(names, function (name) {
  16466. target[name] = source[name];
  16467. });
  16468. }
  16469. }
  16470. /**
  16471. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16472. */
  16473. function getLayoutParams(source) {
  16474. return copyLayoutParams({}, source);
  16475. }
  16476. /**
  16477. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16478. * @param {Object} source
  16479. * @return {Object} Result contains those props.
  16480. */
  16481. function copyLayoutParams(target, source) {
  16482. source && target && each$1(LOCATION_PARAMS, function (name) {
  16483. source.hasOwnProperty(name) && (target[name] = source[name]);
  16484. });
  16485. return target;
  16486. }
  16487. var inner = makeInner();
  16488. var ComponentModel =
  16489. /** @class */
  16490. function (_super) {
  16491. __extends(ComponentModel, _super);
  16492. function ComponentModel(option, parentModel, ecModel) {
  16493. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16494. _this.uid = getUID('ec_cpt_model');
  16495. return _this;
  16496. }
  16497. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16498. this.mergeDefaultAndTheme(option, ecModel);
  16499. };
  16500. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16501. var layoutMode = fetchLayoutMode(this);
  16502. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16503. var themeModel = ecModel.getTheme();
  16504. merge(option, themeModel.get(this.mainType));
  16505. merge(option, this.getDefaultOption());
  16506. if (layoutMode) {
  16507. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16508. }
  16509. };
  16510. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16511. merge(this.option, option, true);
  16512. var layoutMode = fetchLayoutMode(this);
  16513. if (layoutMode) {
  16514. mergeLayoutParam(this.option, option, layoutMode);
  16515. }
  16516. };
  16517. /**
  16518. * Called immediately after `init` or `mergeOption` of this instance called.
  16519. */
  16520. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16521. /**
  16522. * [How to declare defaultOption]:
  16523. *
  16524. * (A) If using class declaration in typescript (since echarts 5):
  16525. * ```ts
  16526. * import {ComponentOption} from '../model/option.js';
  16527. * export interface XxxOption extends ComponentOption {
  16528. * aaa: number
  16529. * }
  16530. * export class XxxModel extends Component {
  16531. * static type = 'xxx';
  16532. * static defaultOption: XxxOption = {
  16533. * aaa: 123
  16534. * }
  16535. * }
  16536. * Component.registerClass(XxxModel);
  16537. * ```
  16538. * ```ts
  16539. * import {inheritDefaultOption} from '../util/component.js';
  16540. * import {XxxModel, XxxOption} from './XxxModel.js';
  16541. * export interface XxxSubOption extends XxxOption {
  16542. * bbb: number
  16543. * }
  16544. * class XxxSubModel extends XxxModel {
  16545. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16546. * bbb: 456
  16547. * })
  16548. * fn() {
  16549. * let opt = this.getDefaultOption();
  16550. * // opt is {aaa: 123, bbb: 456}
  16551. * }
  16552. * }
  16553. * ```
  16554. *
  16555. * (B) If using class extend (previous approach in echarts 3 & 4):
  16556. * ```js
  16557. * let XxxComponent = Component.extend({
  16558. * defaultOption: {
  16559. * xx: 123
  16560. * }
  16561. * })
  16562. * ```
  16563. * ```js
  16564. * let XxxSubComponent = XxxComponent.extend({
  16565. * defaultOption: {
  16566. * yy: 456
  16567. * },
  16568. * fn: function () {
  16569. * let opt = this.getDefaultOption();
  16570. * // opt is {xx: 123, yy: 456}
  16571. * }
  16572. * })
  16573. * ```
  16574. */
  16575. ComponentModel.prototype.getDefaultOption = function () {
  16576. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16577. // in legacy env and auto merge defaultOption. So if using class
  16578. // declaration, defaultOption should be merged manually.
  16579. if (!isExtendedClass(ctor)) {
  16580. // When using ts class, defaultOption must be declared as static.
  16581. return ctor.defaultOption;
  16582. } // FIXME: remove this approach?
  16583. var fields = inner(this);
  16584. if (!fields.defaultOption) {
  16585. var optList = [];
  16586. var clz = ctor;
  16587. while (clz) {
  16588. var opt = clz.prototype.defaultOption;
  16589. opt && optList.push(opt);
  16590. clz = clz.superClass;
  16591. }
  16592. var defaultOption = {};
  16593. for (var i = optList.length - 1; i >= 0; i--) {
  16594. defaultOption = merge(defaultOption, optList[i], true);
  16595. }
  16596. fields.defaultOption = defaultOption;
  16597. }
  16598. return fields.defaultOption;
  16599. };
  16600. /**
  16601. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16602. * The same behavior as `modelUtil.parseFinder`.
  16603. *
  16604. * @param useDefault In many cases like series refer axis and axis refer grid,
  16605. * If axis index / axis id not specified, use the first target as default.
  16606. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16607. */
  16608. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16609. var indexKey = mainType + 'Index';
  16610. var idKey = mainType + 'Id';
  16611. return queryReferringComponents(this.ecModel, mainType, {
  16612. index: this.get(indexKey, true),
  16613. id: this.get(idKey, true)
  16614. }, opt);
  16615. };
  16616. ComponentModel.prototype.getBoxLayoutParams = function () {
  16617. // Consider itself having box layout configs.
  16618. var boxLayoutModel = this;
  16619. return {
  16620. left: boxLayoutModel.get('left'),
  16621. top: boxLayoutModel.get('top'),
  16622. right: boxLayoutModel.get('right'),
  16623. bottom: boxLayoutModel.get('bottom'),
  16624. width: boxLayoutModel.get('width'),
  16625. height: boxLayoutModel.get('height')
  16626. };
  16627. };
  16628. /**
  16629. * Get key for zlevel.
  16630. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16631. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16632. */
  16633. ComponentModel.prototype.getZLevelKey = function () {
  16634. return '';
  16635. };
  16636. ComponentModel.prototype.setZLevel = function (zlevel) {
  16637. this.option.zlevel = zlevel;
  16638. };
  16639. ComponentModel.protoInitialize = function () {
  16640. var proto = ComponentModel.prototype;
  16641. proto.type = 'component';
  16642. proto.id = '';
  16643. proto.name = '';
  16644. proto.mainType = '';
  16645. proto.subType = '';
  16646. proto.componentIndex = 0;
  16647. }();
  16648. return ComponentModel;
  16649. }(Model);
  16650. mountExtend(ComponentModel, Model);
  16651. enableClassManagement(ComponentModel);
  16652. enableSubTypeDefaulter(ComponentModel);
  16653. enableTopologicalTravel(ComponentModel, getDependencies);
  16654. function getDependencies(componentType) {
  16655. var deps = [];
  16656. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16657. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16658. }); // Ensure main type.
  16659. deps = map(deps, function (type) {
  16660. return parseClassType(type).main;
  16661. }); // Hack dataset for convenience.
  16662. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16663. deps.unshift('dataset');
  16664. }
  16665. return deps;
  16666. }
  16667. /*
  16668. * Licensed to the Apache Software Foundation (ASF) under one
  16669. * or more contributor license agreements. See the NOTICE file
  16670. * distributed with this work for additional information
  16671. * regarding copyright ownership. The ASF licenses this file
  16672. * to you under the Apache License, Version 2.0 (the
  16673. * "License"); you may not use this file except in compliance
  16674. * with the License. You may obtain a copy of the License at
  16675. *
  16676. * http://www.apache.org/licenses/LICENSE-2.0
  16677. *
  16678. * Unless required by applicable law or agreed to in writing,
  16679. * software distributed under the License is distributed on an
  16680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16681. * KIND, either express or implied. See the License for the
  16682. * specific language governing permissions and limitations
  16683. * under the License.
  16684. */
  16685. /**
  16686. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16687. */
  16688. /*
  16689. * Licensed to the Apache Software Foundation (ASF) under one
  16690. * or more contributor license agreements. See the NOTICE file
  16691. * distributed with this work for additional information
  16692. * regarding copyright ownership. The ASF licenses this file
  16693. * to you under the Apache License, Version 2.0 (the
  16694. * "License"); you may not use this file except in compliance
  16695. * with the License. You may obtain a copy of the License at
  16696. *
  16697. * http://www.apache.org/licenses/LICENSE-2.0
  16698. *
  16699. * Unless required by applicable law or agreed to in writing,
  16700. * software distributed under the License is distributed on an
  16701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16702. * KIND, either express or implied. See the License for the
  16703. * specific language governing permissions and limitations
  16704. * under the License.
  16705. */
  16706. var platform = ''; // Navigator not exists in node
  16707. if (typeof navigator !== 'undefined') {
  16708. /* global navigator */
  16709. platform = navigator.platform || '';
  16710. }
  16711. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16712. var globalDefault = {
  16713. darkMode: 'auto',
  16714. // backgroundColor: 'rgba(0,0,0,0)',
  16715. colorBy: 'series',
  16716. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16717. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16718. aria: {
  16719. decal: {
  16720. decals: [{
  16721. color: decalColor,
  16722. dashArrayX: [1, 0],
  16723. dashArrayY: [2, 5],
  16724. symbolSize: 1,
  16725. rotation: Math.PI / 6
  16726. }, {
  16727. color: decalColor,
  16728. symbol: 'circle',
  16729. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16730. dashArrayY: [6, 0],
  16731. symbolSize: 0.8
  16732. }, {
  16733. color: decalColor,
  16734. dashArrayX: [1, 0],
  16735. dashArrayY: [4, 3],
  16736. rotation: -Math.PI / 4
  16737. }, {
  16738. color: decalColor,
  16739. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16740. dashArrayY: [6, 0]
  16741. }, {
  16742. color: decalColor,
  16743. dashArrayX: [[1, 0], [1, 6]],
  16744. dashArrayY: [1, 0, 6, 0],
  16745. rotation: Math.PI / 4
  16746. }, {
  16747. color: decalColor,
  16748. symbol: 'triangle',
  16749. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16750. dashArrayY: [7, 2],
  16751. symbolSize: 0.75
  16752. }]
  16753. }
  16754. },
  16755. // If xAxis and yAxis declared, grid is created by default.
  16756. // grid: {},
  16757. textStyle: {
  16758. // color: '#000',
  16759. // decoration: 'none',
  16760. // PENDING
  16761. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16762. // fontFamily: 'Arial, Verdana, sans-serif',
  16763. fontSize: 12,
  16764. fontStyle: 'normal',
  16765. fontWeight: 'normal'
  16766. },
  16767. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16768. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16769. // Default is source-over
  16770. blendMode: null,
  16771. stateAnimation: {
  16772. duration: 300,
  16773. easing: 'cubicOut'
  16774. },
  16775. animation: 'auto',
  16776. animationDuration: 1000,
  16777. animationDurationUpdate: 500,
  16778. animationEasing: 'cubicInOut',
  16779. animationEasingUpdate: 'cubicInOut',
  16780. animationThreshold: 2000,
  16781. // Configuration for progressive/incremental rendering
  16782. progressiveThreshold: 3000,
  16783. progressive: 400,
  16784. // Threshold of if use single hover layer to optimize.
  16785. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16786. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16787. // which is unexpected.
  16788. // see example <echarts/test/heatmap-large.html>.
  16789. hoverLayerThreshold: 3000,
  16790. // See: module:echarts/scale/Time
  16791. useUTC: false
  16792. };
  16793. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16794. var SOURCE_FORMAT_ORIGINAL = 'original';
  16795. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16796. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16797. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16798. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16799. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16800. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16801. var SERIES_LAYOUT_BY_ROW = 'row';
  16802. var BE_ORDINAL = {
  16803. Must: 1,
  16804. Might: 2,
  16805. Not: 3 // Other cases
  16806. };
  16807. var innerGlobalModel = makeInner();
  16808. /**
  16809. * MUST be called before mergeOption of all series.
  16810. */
  16811. function resetSourceDefaulter(ecModel) {
  16812. // `datasetMap` is used to make default encode.
  16813. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16814. }
  16815. /**
  16816. * [The strategy of the arrengment of data dimensions for dataset]:
  16817. * "value way": all axes are non-category axes. So series one by one take
  16818. * several (the number is coordSysDims.length) dimensions from dataset.
  16819. * The result of data arrengment of data dimensions like:
  16820. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16821. * "category way": at least one axis is category axis. So the the first data
  16822. * dimension is always mapped to the first category axis and shared by
  16823. * all of the series. The other data dimensions are taken by series like
  16824. * "value way" does.
  16825. * The result of data arrengment of data dimensions like:
  16826. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16827. *
  16828. * @return encode Never be `null/undefined`.
  16829. */
  16830. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16831. var encode = {};
  16832. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16833. if (!datasetModel || !coordDimensions) {
  16834. return encode;
  16835. }
  16836. var encodeItemName = [];
  16837. var encodeSeriesName = [];
  16838. var ecModel = seriesModel.ecModel;
  16839. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16840. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16841. var baseCategoryDimIndex;
  16842. var categoryWayValueDimStart;
  16843. coordDimensions = coordDimensions.slice();
  16844. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16845. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16846. name: coordDimInfoLoose
  16847. };
  16848. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16849. baseCategoryDimIndex = coordDimIdx;
  16850. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16851. }
  16852. encode[coordDimInfo.name] = [];
  16853. });
  16854. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16855. categoryWayDim: categoryWayValueDimStart,
  16856. valueWayDim: 0
  16857. }); // TODO
  16858. // Auto detect first time axis and do arrangement.
  16859. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16860. var coordDimName = coordDimInfo.name;
  16861. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16862. if (baseCategoryDimIndex == null) {
  16863. var start = datasetRecord.valueWayDim;
  16864. pushDim(encode[coordDimName], start, count);
  16865. pushDim(encodeSeriesName, start, count);
  16866. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16867. // especially when encode x y specified.
  16868. // consider: when multiple series share one dimension
  16869. // category axis, series name should better use
  16870. // the other dimension name. On the other hand, use
  16871. // both dimensions name.
  16872. } // In category way, the first category axis.
  16873. else if (baseCategoryDimIndex === coordDimIdx) {
  16874. pushDim(encode[coordDimName], 0, count);
  16875. pushDim(encodeItemName, 0, count);
  16876. } // In category way, the other axis.
  16877. else {
  16878. var start = datasetRecord.categoryWayDim;
  16879. pushDim(encode[coordDimName], start, count);
  16880. pushDim(encodeSeriesName, start, count);
  16881. datasetRecord.categoryWayDim += count;
  16882. }
  16883. });
  16884. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16885. for (var i = 0; i < idxCount; i++) {
  16886. dimIdxArr.push(idxFrom + i);
  16887. }
  16888. }
  16889. function getDataDimCountOnCoordDim(coordDimInfo) {
  16890. var dimsDef = coordDimInfo.dimsDef;
  16891. return dimsDef ? dimsDef.length : 1;
  16892. }
  16893. encodeItemName.length && (encode.itemName = encodeItemName);
  16894. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16895. return encode;
  16896. }
  16897. /**
  16898. * Work for data like [{name: ..., value: ...}, ...].
  16899. *
  16900. * @return encode Never be `null/undefined`.
  16901. */
  16902. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16903. var encode = {};
  16904. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16905. if (!datasetModel) {
  16906. return encode;
  16907. }
  16908. var sourceFormat = source.sourceFormat;
  16909. var dimensionsDefine = source.dimensionsDefine;
  16910. var potentialNameDimIndex;
  16911. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16912. each(dimensionsDefine, function (dim, idx) {
  16913. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16914. potentialNameDimIndex = idx;
  16915. }
  16916. });
  16917. }
  16918. var idxResult = function () {
  16919. var idxRes0 = {};
  16920. var idxRes1 = {};
  16921. var guessRecords = []; // 5 is an experience value.
  16922. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16923. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16924. guessRecords.push(guessResult);
  16925. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16926. // and then find a name dim with the priority:
  16927. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16928. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16929. idxRes0.v = i;
  16930. }
  16931. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16932. idxRes0.n = i;
  16933. }
  16934. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16935. return idxRes0;
  16936. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16937. // find the first BE_ORDINAL.Might as the value dim,
  16938. // and then find a name dim with the priority:
  16939. // "other dim" > "the value dim itself".
  16940. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16941. // treated as number.
  16942. if (!isPureNumber) {
  16943. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16944. idxRes1.v = i;
  16945. }
  16946. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16947. idxRes1.n = i;
  16948. }
  16949. }
  16950. }
  16951. function fulfilled(idxResult) {
  16952. return idxResult.v != null && idxResult.n != null;
  16953. }
  16954. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16955. }();
  16956. if (idxResult) {
  16957. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16958. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label uses itemName in charts.
  16959. // So we don't set encodeLabel here.
  16960. encode.itemName = [nameDimIndex];
  16961. encode.seriesName = [nameDimIndex];
  16962. }
  16963. return encode;
  16964. }
  16965. /**
  16966. * @return If return null/undefined, indicate that should not use datasetModel.
  16967. */
  16968. function querySeriesUpstreamDatasetModel(seriesModel) {
  16969. // Caution: consider the scenario:
  16970. // A dataset is declared and a series is not expected to use the dataset,
  16971. // and at the beginning `setOption({series: { noData })` (just prepare other
  16972. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16973. // the user should set an empty array to avoid that dataset is used by default.
  16974. var thisData = seriesModel.get('data', true);
  16975. if (!thisData) {
  16976. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16977. index: seriesModel.get('datasetIndex', true),
  16978. id: seriesModel.get('datasetId', true)
  16979. }, SINGLE_REFERRING).models[0];
  16980. }
  16981. }
  16982. /**
  16983. * @return Always return an array event empty.
  16984. */
  16985. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16986. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16987. // Otherwise, no reference.
  16988. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16989. return [];
  16990. }
  16991. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16992. index: datasetModel.get('fromDatasetIndex', true),
  16993. id: datasetModel.get('fromDatasetId', true)
  16994. }, SINGLE_REFERRING).models;
  16995. }
  16996. /**
  16997. * The rule should not be complex, otherwise user might not
  16998. * be able to known where the data is wrong.
  16999. * The code is ugly, but how to make it neat?
  17000. */
  17001. function guessOrdinal(source, dimIndex) {
  17002. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17003. } // dimIndex may be overflow source data.
  17004. // return {BE_ORDINAL}
  17005. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17006. var result; // Experience value.
  17007. var maxLoop = 5;
  17008. if (isTypedArray(data)) {
  17009. return BE_ORDINAL.Not;
  17010. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17011. // always exists in source.
  17012. var dimName;
  17013. var dimType;
  17014. if (dimensionsDefine) {
  17015. var dimDefItem = dimensionsDefine[dimIndex];
  17016. if (isObject(dimDefItem)) {
  17017. dimName = dimDefItem.name;
  17018. dimType = dimDefItem.type;
  17019. } else if (isString(dimDefItem)) {
  17020. dimName = dimDefItem;
  17021. }
  17022. }
  17023. if (dimType != null) {
  17024. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17025. }
  17026. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17027. var dataArrayRows = data;
  17028. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17029. var sample = dataArrayRows[dimIndex];
  17030. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17031. if ((result = detectValue(sample[startIndex + i])) != null) {
  17032. return result;
  17033. }
  17034. }
  17035. } else {
  17036. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17037. var row = dataArrayRows[startIndex + i];
  17038. if (row && (result = detectValue(row[dimIndex])) != null) {
  17039. return result;
  17040. }
  17041. }
  17042. }
  17043. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17044. var dataObjectRows = data;
  17045. if (!dimName) {
  17046. return BE_ORDINAL.Not;
  17047. }
  17048. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17049. var item = dataObjectRows[i];
  17050. if (item && (result = detectValue(item[dimName])) != null) {
  17051. return result;
  17052. }
  17053. }
  17054. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17055. var dataKeyedColumns = data;
  17056. if (!dimName) {
  17057. return BE_ORDINAL.Not;
  17058. }
  17059. var sample = dataKeyedColumns[dimName];
  17060. if (!sample || isTypedArray(sample)) {
  17061. return BE_ORDINAL.Not;
  17062. }
  17063. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17064. if ((result = detectValue(sample[i])) != null) {
  17065. return result;
  17066. }
  17067. }
  17068. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17069. var dataOriginal = data;
  17070. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17071. var item = dataOriginal[i];
  17072. var val = getDataItemValue(item);
  17073. if (!isArray(val)) {
  17074. return BE_ORDINAL.Not;
  17075. }
  17076. if ((result = detectValue(val[dimIndex])) != null) {
  17077. return result;
  17078. }
  17079. }
  17080. }
  17081. function detectValue(val) {
  17082. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17083. // `isFinit('')` get `true`.
  17084. if (val != null && isFinite(val) && val !== '') {
  17085. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17086. } else if (beStr && val !== '-') {
  17087. return BE_ORDINAL.Must;
  17088. }
  17089. }
  17090. return BE_ORDINAL.Not;
  17091. }
  17092. var internalOptionCreatorMap = createHashMap();
  17093. function registerInternalOptionCreator(mainType, creator) {
  17094. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17095. internalOptionCreatorMap.set(mainType, creator);
  17096. }
  17097. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17098. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17099. if (!internalOptionCreator) {
  17100. return newCmptOptionList;
  17101. }
  17102. var internalOptions = internalOptionCreator(ecModel);
  17103. if (!internalOptions) {
  17104. return newCmptOptionList;
  17105. }
  17106. if ("development" !== 'production') {
  17107. for (var i = 0; i < internalOptions.length; i++) {
  17108. assert(isComponentIdInternal(internalOptions[i]));
  17109. }
  17110. }
  17111. return newCmptOptionList.concat(internalOptions);
  17112. }
  17113. var innerColor = makeInner();
  17114. var innerDecal = makeInner();
  17115. var PaletteMixin =
  17116. /** @class */
  17117. function () {
  17118. function PaletteMixin() {}
  17119. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17120. var defaultPalette = normalizeToArray(this.get('color', true));
  17121. var layeredPalette = this.get('colorLayer', true);
  17122. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17123. };
  17124. PaletteMixin.prototype.clearColorPalette = function () {
  17125. clearPalette(this, innerColor);
  17126. };
  17127. return PaletteMixin;
  17128. }();
  17129. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17130. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17131. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17132. }
  17133. function getNearestPalette(palettes, requestColorNum) {
  17134. var paletteNum = palettes.length; // TODO palettes must be in order
  17135. for (var i = 0; i < paletteNum; i++) {
  17136. if (palettes[i].length > requestColorNum) {
  17137. return palettes[i];
  17138. }
  17139. }
  17140. return palettes[paletteNum - 1];
  17141. }
  17142. /**
  17143. * @param name MUST NOT be null/undefined. Otherwise call this function
  17144. * twise with the same parameters will get different result.
  17145. * @param scope default this.
  17146. * @return Can be null/undefined
  17147. */
  17148. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17149. scope = scope || that;
  17150. var scopeFields = inner(scope);
  17151. var paletteIdx = scopeFields.paletteIdx || 0;
  17152. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17153. if (paletteNameMap.hasOwnProperty(name)) {
  17154. return paletteNameMap[name];
  17155. }
  17156. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17157. palette = palette || defaultPalette;
  17158. if (!palette || !palette.length) {
  17159. return;
  17160. }
  17161. var pickedPaletteItem = palette[paletteIdx];
  17162. if (name) {
  17163. paletteNameMap[name] = pickedPaletteItem;
  17164. }
  17165. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17166. return pickedPaletteItem;
  17167. }
  17168. function clearPalette(that, inner) {
  17169. inner(that).paletteIdx = 0;
  17170. inner(that).paletteNameMap = {};
  17171. }
  17172. // Internal method names:
  17173. // -----------------------
  17174. var reCreateSeriesIndices;
  17175. var assertSeriesInitialized;
  17176. var initBase;
  17177. var OPTION_INNER_KEY = '\0_ec_inner';
  17178. var OPTION_INNER_VALUE = 1;
  17179. var BUITIN_COMPONENTS_MAP = {
  17180. grid: 'GridComponent',
  17181. polar: 'PolarComponent',
  17182. geo: 'GeoComponent',
  17183. singleAxis: 'SingleAxisComponent',
  17184. parallel: 'ParallelComponent',
  17185. calendar: 'CalendarComponent',
  17186. graphic: 'GraphicComponent',
  17187. toolbox: 'ToolboxComponent',
  17188. tooltip: 'TooltipComponent',
  17189. axisPointer: 'AxisPointerComponent',
  17190. brush: 'BrushComponent',
  17191. title: 'TitleComponent',
  17192. timeline: 'TimelineComponent',
  17193. markPoint: 'MarkPointComponent',
  17194. markLine: 'MarkLineComponent',
  17195. markArea: 'MarkAreaComponent',
  17196. legend: 'LegendComponent',
  17197. dataZoom: 'DataZoomComponent',
  17198. visualMap: 'VisualMapComponent',
  17199. // aria: 'AriaComponent',
  17200. // dataset: 'DatasetComponent',
  17201. // Dependencies
  17202. xAxis: 'GridComponent',
  17203. yAxis: 'GridComponent',
  17204. angleAxis: 'PolarComponent',
  17205. radiusAxis: 'PolarComponent'
  17206. };
  17207. var BUILTIN_CHARTS_MAP = {
  17208. line: 'LineChart',
  17209. bar: 'BarChart',
  17210. pie: 'PieChart',
  17211. scatter: 'ScatterChart',
  17212. radar: 'RadarChart',
  17213. map: 'MapChart',
  17214. tree: 'TreeChart',
  17215. treemap: 'TreemapChart',
  17216. graph: 'GraphChart',
  17217. gauge: 'GaugeChart',
  17218. funnel: 'FunnelChart',
  17219. parallel: 'ParallelChart',
  17220. sankey: 'SankeyChart',
  17221. boxplot: 'BoxplotChart',
  17222. candlestick: 'CandlestickChart',
  17223. effectScatter: 'EffectScatterChart',
  17224. lines: 'LinesChart',
  17225. heatmap: 'HeatmapChart',
  17226. pictorialBar: 'PictorialBarChart',
  17227. themeRiver: 'ThemeRiverChart',
  17228. sunburst: 'SunburstChart',
  17229. custom: 'CustomChart'
  17230. };
  17231. var componetsMissingLogPrinted = {};
  17232. function checkMissingComponents(option) {
  17233. each(option, function (componentOption, mainType) {
  17234. if (!ComponentModel.hasClass(mainType)) {
  17235. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17236. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17237. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17238. componetsMissingLogPrinted[componentImportName] = true;
  17239. }
  17240. }
  17241. });
  17242. }
  17243. var GlobalModel =
  17244. /** @class */
  17245. function (_super) {
  17246. __extends(GlobalModel, _super);
  17247. function GlobalModel() {
  17248. return _super !== null && _super.apply(this, arguments) || this;
  17249. }
  17250. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17251. theme = theme || {};
  17252. this.option = null; // Mark as not initialized.
  17253. this._theme = new Model(theme);
  17254. this._locale = new Model(locale);
  17255. this._optionManager = optionManager;
  17256. };
  17257. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17258. if ("development" !== 'production') {
  17259. assert(option != null, 'option is null/undefined');
  17260. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17261. }
  17262. var innerOpt = normalizeSetOptionInput(opts);
  17263. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17264. this._resetOption(null, innerOpt);
  17265. };
  17266. /**
  17267. * @param type null/undefined: reset all.
  17268. * 'recreate': force recreate all.
  17269. * 'timeline': only reset timeline option
  17270. * 'media': only reset media query option
  17271. * @return Whether option changed.
  17272. */
  17273. GlobalModel.prototype.resetOption = function (type, opt) {
  17274. return this._resetOption(type, normalizeSetOptionInput(opt));
  17275. };
  17276. GlobalModel.prototype._resetOption = function (type, opt) {
  17277. var optionChanged = false;
  17278. var optionManager = this._optionManager;
  17279. if (!type || type === 'recreate') {
  17280. var baseOption = optionManager.mountOption(type === 'recreate');
  17281. if ("development" !== 'production') {
  17282. checkMissingComponents(baseOption);
  17283. }
  17284. if (!this.option || type === 'recreate') {
  17285. initBase(this, baseOption);
  17286. } else {
  17287. this.restoreData();
  17288. this._mergeOption(baseOption, opt);
  17289. }
  17290. optionChanged = true;
  17291. }
  17292. if (type === 'timeline' || type === 'media') {
  17293. this.restoreData();
  17294. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17295. // it should better not have the same props with `MediaUnit['option']`.
  17296. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17297. // rather than original "baseOption". If they both override a prop, the result might be
  17298. // unexpected when media state changed after `setOption` called.
  17299. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17300. // (`{baseOption, media}`) in `setOption`.
  17301. // For `timeline`, the case is the same.
  17302. if (!type || type === 'recreate' || type === 'timeline') {
  17303. var timelineOption = optionManager.getTimelineOption(this);
  17304. if (timelineOption) {
  17305. optionChanged = true;
  17306. this._mergeOption(timelineOption, opt);
  17307. }
  17308. }
  17309. if (!type || type === 'recreate' || type === 'media') {
  17310. var mediaOptions = optionManager.getMediaOption(this);
  17311. if (mediaOptions.length) {
  17312. each(mediaOptions, function (mediaOption) {
  17313. optionChanged = true;
  17314. this._mergeOption(mediaOption, opt);
  17315. }, this);
  17316. }
  17317. }
  17318. return optionChanged;
  17319. };
  17320. GlobalModel.prototype.mergeOption = function (option) {
  17321. this._mergeOption(option, null);
  17322. };
  17323. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17324. var option = this.option;
  17325. var componentsMap = this._componentsMap;
  17326. var componentsCount = this._componentsCount;
  17327. var newCmptTypes = [];
  17328. var newCmptTypeMap = createHashMap();
  17329. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17330. resetSourceDefaulter(this); // If no component class, merge directly.
  17331. // For example: color, animaiton options, etc.
  17332. each(newOption, function (componentOption, mainType) {
  17333. if (componentOption == null) {
  17334. return;
  17335. }
  17336. if (!ComponentModel.hasClass(mainType)) {
  17337. // globalSettingTask.dirty();
  17338. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17339. } else if (mainType) {
  17340. newCmptTypes.push(mainType);
  17341. newCmptTypeMap.set(mainType, true);
  17342. }
  17343. });
  17344. if (replaceMergeMainTypeMap) {
  17345. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17346. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17347. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17348. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17349. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17350. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17351. newCmptTypes.push(mainTypeInReplaceMerge);
  17352. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17353. }
  17354. });
  17355. }
  17356. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17357. function visitComponent(mainType) {
  17358. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17359. var oldCmptList = componentsMap.get(mainType);
  17360. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17361. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17362. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17363. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17364. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17365. // components, which is probably incorrect logic.
  17366. option[mainType] = null;
  17367. componentsMap.set(mainType, null);
  17368. componentsCount.set(mainType, 0);
  17369. var optionsByMainType = [];
  17370. var cmptsByMainType = [];
  17371. var cmptsCountByMainType = 0;
  17372. var tooltipExists;
  17373. var tooltipWarningLogged;
  17374. each(mappingResult, function (resultItem, index) {
  17375. var componentModel = resultItem.existing;
  17376. var newCmptOption = resultItem.newOption;
  17377. if (!newCmptOption) {
  17378. if (componentModel) {
  17379. // Consider where is no new option and should be merged using {},
  17380. // see removeEdgeAndAdd in topologicalTravel and
  17381. // ComponentModel.getAllClassMainTypes.
  17382. componentModel.mergeOption({}, this);
  17383. componentModel.optionUpdated({}, false);
  17384. } // If no both `resultItem.exist` and `resultItem.option`,
  17385. // either it is in `replaceMerge` and not matched by any id,
  17386. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17387. } else {
  17388. var isSeriesType = mainType === 'series';
  17389. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17390. );
  17391. if (!ComponentModelClass) {
  17392. if ("development" !== 'production') {
  17393. var subType = resultItem.keyInfo.subType;
  17394. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17395. if (!componetsMissingLogPrinted[subType]) {
  17396. componetsMissingLogPrinted[subType] = true;
  17397. if (seriesImportName) {
  17398. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17399. } else {
  17400. error("Unknown series " + subType);
  17401. }
  17402. }
  17403. }
  17404. return;
  17405. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17406. if (mainType === 'tooltip') {
  17407. if (tooltipExists) {
  17408. if ("development" !== 'production') {
  17409. if (!tooltipWarningLogged) {
  17410. warn('Currently only one tooltip component is allowed.');
  17411. tooltipWarningLogged = true;
  17412. }
  17413. }
  17414. return;
  17415. }
  17416. tooltipExists = true;
  17417. }
  17418. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17419. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17420. componentModel.mergeOption(newCmptOption, this);
  17421. componentModel.optionUpdated(newCmptOption, false);
  17422. } else {
  17423. // PENDING Global as parent ?
  17424. var extraOpt = extend({
  17425. componentIndex: index
  17426. }, resultItem.keyInfo);
  17427. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17428. extend(componentModel, extraOpt);
  17429. if (resultItem.brandNew) {
  17430. componentModel.__requireNewView = true;
  17431. }
  17432. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17433. // newCmptOption has been used as componentModel.option
  17434. // and may be merged with theme and default, so pass null
  17435. // to avoid confusion.
  17436. componentModel.optionUpdated(null, true);
  17437. }
  17438. }
  17439. if (componentModel) {
  17440. optionsByMainType.push(componentModel.option);
  17441. cmptsByMainType.push(componentModel);
  17442. cmptsCountByMainType++;
  17443. } else {
  17444. // Always do assign to avoid elided item in array.
  17445. optionsByMainType.push(void 0);
  17446. cmptsByMainType.push(void 0);
  17447. }
  17448. }, this);
  17449. option[mainType] = optionsByMainType;
  17450. componentsMap.set(mainType, cmptsByMainType);
  17451. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17452. if (mainType === 'series') {
  17453. reCreateSeriesIndices(this);
  17454. }
  17455. } // If no series declared, ensure `_seriesIndices` initialized.
  17456. if (!this._seriesIndices) {
  17457. reCreateSeriesIndices(this);
  17458. }
  17459. };
  17460. /**
  17461. * Get option for output (cloned option and inner info removed)
  17462. */
  17463. GlobalModel.prototype.getOption = function () {
  17464. var option = clone(this.option);
  17465. each(option, function (optInMainType, mainType) {
  17466. if (ComponentModel.hasClass(mainType)) {
  17467. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17468. // Inner cmpts might not be at last since ec5.0, but still
  17469. // compatible for users: if inner cmpt at last, splice the returned array.
  17470. var realLen = opts.length;
  17471. var metNonInner = false;
  17472. for (var i = realLen - 1; i >= 0; i--) {
  17473. // Remove options with inner id.
  17474. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17475. metNonInner = true;
  17476. } else {
  17477. opts[i] = null;
  17478. !metNonInner && realLen--;
  17479. }
  17480. }
  17481. opts.length = realLen;
  17482. option[mainType] = opts;
  17483. }
  17484. });
  17485. delete option[OPTION_INNER_KEY];
  17486. return option;
  17487. };
  17488. GlobalModel.prototype.getTheme = function () {
  17489. return this._theme;
  17490. };
  17491. GlobalModel.prototype.getLocaleModel = function () {
  17492. return this._locale;
  17493. };
  17494. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17495. this._payload = payload;
  17496. };
  17497. GlobalModel.prototype.getUpdatePayload = function () {
  17498. return this._payload;
  17499. };
  17500. /**
  17501. * @param idx If not specified, return the first one.
  17502. */
  17503. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17504. var list = this._componentsMap.get(mainType);
  17505. if (list) {
  17506. var cmpt = list[idx || 0];
  17507. if (cmpt) {
  17508. return cmpt;
  17509. } else if (idx == null) {
  17510. for (var i = 0; i < list.length; i++) {
  17511. if (list[i]) {
  17512. return list[i];
  17513. }
  17514. }
  17515. }
  17516. }
  17517. };
  17518. /**
  17519. * @return Never be null/undefined.
  17520. */
  17521. GlobalModel.prototype.queryComponents = function (condition) {
  17522. var mainType = condition.mainType;
  17523. if (!mainType) {
  17524. return [];
  17525. }
  17526. var index = condition.index;
  17527. var id = condition.id;
  17528. var name = condition.name;
  17529. var cmpts = this._componentsMap.get(mainType);
  17530. if (!cmpts || !cmpts.length) {
  17531. return [];
  17532. }
  17533. var result;
  17534. if (index != null) {
  17535. result = [];
  17536. each(normalizeToArray(index), function (idx) {
  17537. cmpts[idx] && result.push(cmpts[idx]);
  17538. });
  17539. } else if (id != null) {
  17540. result = queryByIdOrName('id', id, cmpts);
  17541. } else if (name != null) {
  17542. result = queryByIdOrName('name', name, cmpts);
  17543. } else {
  17544. // Return all non-empty components in that mainType
  17545. result = filter(cmpts, function (cmpt) {
  17546. return !!cmpt;
  17547. });
  17548. }
  17549. return filterBySubType(result, condition);
  17550. };
  17551. /**
  17552. * The interface is different from queryComponents,
  17553. * which is convenient for inner usage.
  17554. *
  17555. * @usage
  17556. * let result = findComponents(
  17557. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17558. * );
  17559. * let result = findComponents(
  17560. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17561. * );
  17562. * let result = findComponents(
  17563. * {mainType: 'series',
  17564. * filter: function (model, index) {...}}
  17565. * );
  17566. * // result like [component0, componnet1, ...]
  17567. */
  17568. GlobalModel.prototype.findComponents = function (condition) {
  17569. var query = condition.query;
  17570. var mainType = condition.mainType;
  17571. var queryCond = getQueryCond(query);
  17572. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17573. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17574. return !!cmpt;
  17575. });
  17576. return doFilter(filterBySubType(result, condition));
  17577. function getQueryCond(q) {
  17578. var indexAttr = mainType + 'Index';
  17579. var idAttr = mainType + 'Id';
  17580. var nameAttr = mainType + 'Name';
  17581. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17582. mainType: mainType,
  17583. // subType will be filtered finally.
  17584. index: q[indexAttr],
  17585. id: q[idAttr],
  17586. name: q[nameAttr]
  17587. } : null;
  17588. }
  17589. function doFilter(res) {
  17590. return condition.filter ? filter(res, condition.filter) : res;
  17591. }
  17592. };
  17593. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17594. var componentsMap = this._componentsMap;
  17595. if (isFunction(mainType)) {
  17596. var ctxForAll_1 = cb;
  17597. var cbForAll_1 = mainType;
  17598. componentsMap.each(function (cmpts, componentType) {
  17599. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17600. var cmpt = cmpts[i];
  17601. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17602. }
  17603. });
  17604. } else {
  17605. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17606. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17607. var cmpt = cmpts[i];
  17608. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17609. }
  17610. }
  17611. };
  17612. /**
  17613. * Get series list before filtered by name.
  17614. */
  17615. GlobalModel.prototype.getSeriesByName = function (name) {
  17616. var nameStr = convertOptionIdName(name, null);
  17617. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17618. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17619. });
  17620. };
  17621. /**
  17622. * Get series list before filtered by index.
  17623. */
  17624. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17625. return this._componentsMap.get('series')[seriesIndex];
  17626. };
  17627. /**
  17628. * Get series list before filtered by type.
  17629. * FIXME: rename to getRawSeriesByType?
  17630. */
  17631. GlobalModel.prototype.getSeriesByType = function (subType) {
  17632. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17633. return !!oneSeries && oneSeries.subType === subType;
  17634. });
  17635. };
  17636. /**
  17637. * Get all series before filtered.
  17638. */
  17639. GlobalModel.prototype.getSeries = function () {
  17640. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17641. return !!oneSeries;
  17642. });
  17643. };
  17644. /**
  17645. * Count series before filtered.
  17646. */
  17647. GlobalModel.prototype.getSeriesCount = function () {
  17648. return this._componentsCount.get('series');
  17649. };
  17650. /**
  17651. * After filtering, series may be different
  17652. * from raw series.
  17653. */
  17654. GlobalModel.prototype.eachSeries = function (cb, context) {
  17655. assertSeriesInitialized(this);
  17656. each(this._seriesIndices, function (rawSeriesIndex) {
  17657. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17658. cb.call(context, series, rawSeriesIndex);
  17659. }, this);
  17660. };
  17661. /**
  17662. * Iterate raw series before filtered.
  17663. *
  17664. * @param {Function} cb
  17665. * @param {*} context
  17666. */
  17667. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17668. each(this._componentsMap.get('series'), function (series) {
  17669. series && cb.call(context, series, series.componentIndex);
  17670. });
  17671. };
  17672. /**
  17673. * After filtering, series may be different.
  17674. * from raw series.
  17675. */
  17676. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17677. assertSeriesInitialized(this);
  17678. each(this._seriesIndices, function (rawSeriesIndex) {
  17679. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17680. if (series.subType === subType) {
  17681. cb.call(context, series, rawSeriesIndex);
  17682. }
  17683. }, this);
  17684. };
  17685. /**
  17686. * Iterate raw series before filtered of given type.
  17687. */
  17688. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17689. return each(this.getSeriesByType(subType), cb, context);
  17690. };
  17691. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17692. assertSeriesInitialized(this);
  17693. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17694. };
  17695. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17696. return (this._seriesIndices || []).slice();
  17697. };
  17698. GlobalModel.prototype.filterSeries = function (cb, context) {
  17699. assertSeriesInitialized(this);
  17700. var newSeriesIndices = [];
  17701. each(this._seriesIndices, function (seriesRawIdx) {
  17702. var series = this._componentsMap.get('series')[seriesRawIdx];
  17703. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17704. }, this);
  17705. this._seriesIndices = newSeriesIndices;
  17706. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17707. };
  17708. GlobalModel.prototype.restoreData = function (payload) {
  17709. reCreateSeriesIndices(this);
  17710. var componentsMap = this._componentsMap;
  17711. var componentTypes = [];
  17712. componentsMap.each(function (components, componentType) {
  17713. if (ComponentModel.hasClass(componentType)) {
  17714. componentTypes.push(componentType);
  17715. }
  17716. });
  17717. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17718. each(componentsMap.get(componentType), function (component) {
  17719. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17720. component.restoreData();
  17721. }
  17722. });
  17723. });
  17724. };
  17725. GlobalModel.internalField = function () {
  17726. reCreateSeriesIndices = function (ecModel) {
  17727. var seriesIndices = ecModel._seriesIndices = [];
  17728. each(ecModel._componentsMap.get('series'), function (series) {
  17729. // series may have been removed by `replaceMerge`.
  17730. series && seriesIndices.push(series.componentIndex);
  17731. });
  17732. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17733. };
  17734. assertSeriesInitialized = function (ecModel) {
  17735. // Components that use _seriesIndices should depends on series component,
  17736. // which make sure that their initialization is after series.
  17737. if ("development" !== 'production') {
  17738. if (!ecModel._seriesIndices) {
  17739. throw new Error('Option should contains series.');
  17740. }
  17741. }
  17742. };
  17743. initBase = function (ecModel, baseOption) {
  17744. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17745. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17746. ecModel.option = {};
  17747. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17748. // before series initialized.
  17749. ecModel._componentsMap = createHashMap({
  17750. series: []
  17751. });
  17752. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17753. // performed before theme and globalDefault merge.
  17754. var airaOption = baseOption.aria;
  17755. if (isObject(airaOption) && airaOption.enabled == null) {
  17756. airaOption.enabled = true;
  17757. }
  17758. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17759. merge(baseOption, globalDefault, false);
  17760. ecModel._mergeOption(baseOption, null);
  17761. };
  17762. }();
  17763. return GlobalModel;
  17764. }(Model);
  17765. function isNotTargetSeries(seriesModel, payload) {
  17766. if (payload) {
  17767. var index = payload.seriesIndex;
  17768. var id = payload.seriesId;
  17769. var name_1 = payload.seriesName;
  17770. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17771. }
  17772. }
  17773. function mergeTheme(option, theme) {
  17774. // PENDING
  17775. // NOT use `colorLayer` in theme if option has `color`
  17776. var notMergeColorLayer = option.color && !option.colorLayer;
  17777. each(theme, function (themeItem, name) {
  17778. if (name === 'colorLayer' && notMergeColorLayer) {
  17779. return;
  17780. } // If it is component model mainType, the model handles that merge later.
  17781. // otherwise, merge them here.
  17782. if (!ComponentModel.hasClass(name)) {
  17783. if (typeof themeItem === 'object') {
  17784. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17785. } else {
  17786. if (option[name] == null) {
  17787. option[name] = themeItem;
  17788. }
  17789. }
  17790. }
  17791. });
  17792. }
  17793. function queryByIdOrName(attr, idOrName, cmpts) {
  17794. // Here is a break from echarts4: string and number are
  17795. // treated as equal.
  17796. if (isArray(idOrName)) {
  17797. var keyMap_1 = createHashMap();
  17798. each(idOrName, function (idOrNameItem) {
  17799. if (idOrNameItem != null) {
  17800. var idName = convertOptionIdName(idOrNameItem, null);
  17801. idName != null && keyMap_1.set(idOrNameItem, true);
  17802. }
  17803. });
  17804. return filter(cmpts, function (cmpt) {
  17805. return cmpt && keyMap_1.get(cmpt[attr]);
  17806. });
  17807. } else {
  17808. var idName_1 = convertOptionIdName(idOrName, null);
  17809. return filter(cmpts, function (cmpt) {
  17810. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17811. });
  17812. }
  17813. }
  17814. function filterBySubType(components, condition) {
  17815. // Using hasOwnProperty for restrict. Consider
  17816. // subType is undefined in user payload.
  17817. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17818. return cmpt && cmpt.subType === condition.subType;
  17819. }) : components;
  17820. }
  17821. function normalizeSetOptionInput(opts) {
  17822. var replaceMergeMainTypeMap = createHashMap();
  17823. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17824. if ("development" !== 'production') {
  17825. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17826. }
  17827. replaceMergeMainTypeMap.set(mainType, true);
  17828. });
  17829. return {
  17830. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17831. };
  17832. }
  17833. mixin(GlobalModel, PaletteMixin);
  17834. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17835. 'getOption', // 'getViewOfComponentModel',
  17836. // 'getViewOfSeriesModel',
  17837. 'getId', 'updateLabelLayout'];
  17838. var ExtensionAPI =
  17839. /** @class */
  17840. function () {
  17841. function ExtensionAPI(ecInstance) {
  17842. each(availableMethods, function (methodName) {
  17843. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17844. }, this);
  17845. }
  17846. return ExtensionAPI;
  17847. }();
  17848. var coordinateSystemCreators = {};
  17849. var CoordinateSystemManager =
  17850. /** @class */
  17851. function () {
  17852. function CoordinateSystemManager() {
  17853. this._coordinateSystems = [];
  17854. }
  17855. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17856. var coordinateSystems = [];
  17857. each(coordinateSystemCreators, function (creator, type) {
  17858. var list = creator.create(ecModel, api);
  17859. coordinateSystems = coordinateSystems.concat(list || []);
  17860. });
  17861. this._coordinateSystems = coordinateSystems;
  17862. };
  17863. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17864. each(this._coordinateSystems, function (coordSys) {
  17865. coordSys.update && coordSys.update(ecModel, api);
  17866. });
  17867. };
  17868. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17869. return this._coordinateSystems.slice();
  17870. };
  17871. CoordinateSystemManager.register = function (type, creator) {
  17872. coordinateSystemCreators[type] = creator;
  17873. };
  17874. CoordinateSystemManager.get = function (type) {
  17875. return coordinateSystemCreators[type];
  17876. };
  17877. return CoordinateSystemManager;
  17878. }();
  17879. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17880. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17881. /**
  17882. * TERM EXPLANATIONS:
  17883. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17884. */
  17885. var OptionManager =
  17886. /** @class */
  17887. function () {
  17888. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17889. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17890. // rawOption cloned and backuped when timeline changed, which does no
  17891. // good to performance. What's more, that both timeline and setOption
  17892. // method supply 'notMerge' brings complex and some problems.
  17893. // Consider this case:
  17894. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17895. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17896. function OptionManager(api) {
  17897. this._timelineOptions = [];
  17898. this._mediaList = [];
  17899. /**
  17900. * -1, means default.
  17901. * empty means no media.
  17902. */
  17903. this._currentMediaIndices = [];
  17904. this._api = api;
  17905. }
  17906. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17907. if (rawOption) {
  17908. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17909. each(normalizeToArray(rawOption.series), function (series) {
  17910. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17911. });
  17912. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17913. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17914. });
  17915. } // Caution: some series modify option data, if do not clone,
  17916. // it should ensure that the repeat modify correctly
  17917. // (create a new object when modify itself).
  17918. rawOption = clone(rawOption); // FIXME
  17919. // If some property is set in timeline options or media option but
  17920. // not set in baseOption, a warning should be given.
  17921. var optionBackup = this._optionBackup;
  17922. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17923. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17924. if (optionBackup) {
  17925. // FIXME
  17926. // the restore merge solution is essentially incorrect.
  17927. // the mapping can not be 100% consistent with ecModel, which probably brings
  17928. // potential bug!
  17929. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  17930. // let fakeCmptsMap = this._fakeCmptsMap;
  17931. // if (!fakeCmptsMap) {
  17932. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17933. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17934. // }
  17935. // mergeToBackupOption(
  17936. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17937. // );
  17938. // For simplicity, timeline options and media options do not support merge,
  17939. // that is, if you `setOption` twice and both has timeline options, the latter
  17940. // timeline options will not be merged to the former, but just substitute them.
  17941. if (newParsedOption.timelineOptions.length) {
  17942. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17943. }
  17944. if (newParsedOption.mediaList.length) {
  17945. optionBackup.mediaList = newParsedOption.mediaList;
  17946. }
  17947. if (newParsedOption.mediaDefault) {
  17948. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17949. }
  17950. } else {
  17951. this._optionBackup = newParsedOption;
  17952. }
  17953. };
  17954. OptionManager.prototype.mountOption = function (isRecreate) {
  17955. var optionBackup = this._optionBackup;
  17956. this._timelineOptions = optionBackup.timelineOptions;
  17957. this._mediaList = optionBackup.mediaList;
  17958. this._mediaDefault = optionBackup.mediaDefault;
  17959. this._currentMediaIndices = [];
  17960. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17961. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17962. // each time `setOption` called, can be only used in `isRecreate`, because
  17963. // its reliability is under suspicion. In other cases option merge is
  17964. // performed by `model.mergeOption`.
  17965. ? optionBackup.baseOption : this._newBaseOption);
  17966. };
  17967. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17968. var option;
  17969. var timelineOptions = this._timelineOptions;
  17970. if (timelineOptions.length) {
  17971. // getTimelineOption can only be called after ecModel inited,
  17972. // so we can get currentIndex from timelineModel.
  17973. var timelineModel = ecModel.getComponent('timeline');
  17974. if (timelineModel) {
  17975. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17976. timelineOptions[timelineModel.getCurrentIndex()]);
  17977. }
  17978. }
  17979. return option;
  17980. };
  17981. OptionManager.prototype.getMediaOption = function (ecModel) {
  17982. var ecWidth = this._api.getWidth();
  17983. var ecHeight = this._api.getHeight();
  17984. var mediaList = this._mediaList;
  17985. var mediaDefault = this._mediaDefault;
  17986. var indices = [];
  17987. var result = []; // No media defined.
  17988. if (!mediaList.length && !mediaDefault) {
  17989. return result;
  17990. } // Multi media may be applied, the latter defined media has higher priority.
  17991. for (var i = 0, len = mediaList.length; i < len; i++) {
  17992. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17993. indices.push(i);
  17994. }
  17995. } // FIXME
  17996. // Whether mediaDefault should force users to provide? Otherwise
  17997. // the change by media query can not be recorvered.
  17998. if (!indices.length && mediaDefault) {
  17999. indices = [-1];
  18000. }
  18001. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18002. result = map(indices, function (index) {
  18003. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18004. });
  18005. } // Otherwise return nothing.
  18006. this._currentMediaIndices = indices;
  18007. return result;
  18008. };
  18009. return OptionManager;
  18010. }();
  18011. /**
  18012. * [RAW_OPTION_PATTERNS]
  18013. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18014. *
  18015. * (1) No prop "baseOption" declared:
  18016. * Root option is used as "baseOption" (except prop "options" and "media").
  18017. * ```js
  18018. * option = {
  18019. * series: [],
  18020. * timeline: {},
  18021. * options: [],
  18022. * };
  18023. * option = {
  18024. * series: [],
  18025. * media: {},
  18026. * };
  18027. * option = {
  18028. * series: [],
  18029. * timeline: {},
  18030. * options: [],
  18031. * media: {},
  18032. * }
  18033. * ```
  18034. *
  18035. * (2) Prop "baseOption" declared:
  18036. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18037. * inside "baseOption" except prop "timeline" (compat ec2).
  18038. * ```js
  18039. * option = {
  18040. * baseOption: {
  18041. * timeline: {},
  18042. * series: [],
  18043. * },
  18044. * options: []
  18045. * };
  18046. * option = {
  18047. * baseOption: {
  18048. * series: [],
  18049. * },
  18050. * media: []
  18051. * };
  18052. * option = {
  18053. * baseOption: {
  18054. * timeline: {},
  18055. * series: [],
  18056. * },
  18057. * options: []
  18058. * media: []
  18059. * };
  18060. * option = {
  18061. * // ec3 compat ec2: allow (only) `timeline` declared
  18062. * // outside baseOption. Keep this setting for compat.
  18063. * timeline: {},
  18064. * baseOption: {
  18065. * series: [],
  18066. * },
  18067. * options: [],
  18068. * media: []
  18069. * };
  18070. * ```
  18071. */
  18072. function parseRawOption( // `rawOption` May be modified
  18073. rawOption, optionPreprocessorFuncs, isNew) {
  18074. var mediaList = [];
  18075. var mediaDefault;
  18076. var baseOption;
  18077. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18078. var timelineOnRoot = rawOption.timeline;
  18079. var timelineOptionsOnRoot = rawOption.options;
  18080. var mediaOnRoot = rawOption.media;
  18081. var hasMedia = !!rawOption.media;
  18082. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18083. if (declaredBaseOption) {
  18084. baseOption = declaredBaseOption; // For merge option.
  18085. if (!baseOption.timeline) {
  18086. baseOption.timeline = timelineOnRoot;
  18087. }
  18088. } // For convenience, enable to use the root option as the `baseOption`:
  18089. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18090. else {
  18091. if (hasTimeline || hasMedia) {
  18092. rawOption.options = rawOption.media = null;
  18093. }
  18094. baseOption = rawOption;
  18095. }
  18096. if (hasMedia) {
  18097. if (isArray(mediaOnRoot)) {
  18098. each(mediaOnRoot, function (singleMedia) {
  18099. if ("development" !== 'production') {
  18100. // Real case of wrong config.
  18101. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18102. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18103. }
  18104. }
  18105. if (singleMedia && singleMedia.option) {
  18106. if (singleMedia.query) {
  18107. mediaList.push(singleMedia);
  18108. } else if (!mediaDefault) {
  18109. // Use the first media default.
  18110. mediaDefault = singleMedia;
  18111. }
  18112. }
  18113. });
  18114. } else {
  18115. if ("development" !== 'production') {
  18116. // Real case of wrong config.
  18117. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18118. }
  18119. }
  18120. }
  18121. doPreprocess(baseOption);
  18122. each(timelineOptionsOnRoot, function (option) {
  18123. return doPreprocess(option);
  18124. });
  18125. each(mediaList, function (media) {
  18126. return doPreprocess(media.option);
  18127. });
  18128. function doPreprocess(option) {
  18129. each(optionPreprocessorFuncs, function (preProcess) {
  18130. preProcess(option, isNew);
  18131. });
  18132. }
  18133. return {
  18134. baseOption: baseOption,
  18135. timelineOptions: timelineOptionsOnRoot || [],
  18136. mediaDefault: mediaDefault,
  18137. mediaList: mediaList
  18138. };
  18139. }
  18140. /**
  18141. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18142. * Support: width, height, aspectRatio
  18143. * Can use max or min as prefix.
  18144. */
  18145. function applyMediaQuery(query, ecWidth, ecHeight) {
  18146. var realMap = {
  18147. width: ecWidth,
  18148. height: ecHeight,
  18149. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18150. };
  18151. var applicable = true;
  18152. each(query, function (value, attr) {
  18153. var matched = attr.match(QUERY_REG);
  18154. if (!matched || !matched[1] || !matched[2]) {
  18155. return;
  18156. }
  18157. var operator = matched[1];
  18158. var realAttr = matched[2].toLowerCase();
  18159. if (!compare(realMap[realAttr], value, operator)) {
  18160. applicable = false;
  18161. }
  18162. });
  18163. return applicable;
  18164. }
  18165. function compare(real, expect, operator) {
  18166. if (operator === 'min') {
  18167. return real >= expect;
  18168. } else if (operator === 'max') {
  18169. return real <= expect;
  18170. } else {
  18171. // Equals
  18172. return real === expect;
  18173. }
  18174. }
  18175. function indicesEquals(indices1, indices2) {
  18176. // indices is always order by asc and has only finite number.
  18177. return indices1.join(',') === indices2.join(',');
  18178. }
  18179. var each$2 = each;
  18180. var isObject$1 = isObject;
  18181. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18182. function compatEC2ItemStyle(opt) {
  18183. var itemStyleOpt = opt && opt.itemStyle;
  18184. if (!itemStyleOpt) {
  18185. return;
  18186. }
  18187. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18188. var styleName = POSSIBLE_STYLES[i];
  18189. var normalItemStyleOpt = itemStyleOpt.normal;
  18190. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18191. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18192. if ("development" !== 'production') {
  18193. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18194. }
  18195. opt[styleName] = opt[styleName] || {};
  18196. if (!opt[styleName].normal) {
  18197. opt[styleName].normal = normalItemStyleOpt[styleName];
  18198. } else {
  18199. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18200. }
  18201. normalItemStyleOpt[styleName] = null;
  18202. }
  18203. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18204. if ("development" !== 'production') {
  18205. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18206. }
  18207. opt[styleName] = opt[styleName] || {};
  18208. if (!opt[styleName].emphasis) {
  18209. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18210. } else {
  18211. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18212. }
  18213. emphasisItemStyleOpt[styleName] = null;
  18214. }
  18215. }
  18216. }
  18217. function convertNormalEmphasis(opt, optType, useExtend) {
  18218. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18219. var normalOpt = opt[optType].normal;
  18220. var emphasisOpt = opt[optType].emphasis;
  18221. if (normalOpt) {
  18222. if ("development" !== 'production') {
  18223. // eslint-disable-next-line max-len
  18224. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18225. } // Timeline controlStyle has other properties besides normal and emphasis
  18226. if (useExtend) {
  18227. opt[optType].normal = opt[optType].emphasis = null;
  18228. defaults(opt[optType], normalOpt);
  18229. } else {
  18230. opt[optType] = normalOpt;
  18231. }
  18232. }
  18233. if (emphasisOpt) {
  18234. if ("development" !== 'production') {
  18235. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18236. }
  18237. opt.emphasis = opt.emphasis || {};
  18238. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18239. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18240. if (emphasisOpt.focus) {
  18241. opt.emphasis.focus = emphasisOpt.focus;
  18242. }
  18243. if (emphasisOpt.blurScope) {
  18244. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18245. }
  18246. }
  18247. }
  18248. }
  18249. function removeEC3NormalStatus(opt) {
  18250. convertNormalEmphasis(opt, 'itemStyle');
  18251. convertNormalEmphasis(opt, 'lineStyle');
  18252. convertNormalEmphasis(opt, 'areaStyle');
  18253. convertNormalEmphasis(opt, 'label');
  18254. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18255. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18256. convertNormalEmphasis(opt, 'edgeLabel');
  18257. }
  18258. function compatTextStyle(opt, propName) {
  18259. // Check whether is not object (string\null\undefined ...)
  18260. var labelOptSingle = isObject$1(opt) && opt[propName];
  18261. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18262. if (textStyle) {
  18263. if ("development" !== 'production') {
  18264. // eslint-disable-next-line max-len
  18265. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18266. }
  18267. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18268. var textPropName = TEXT_STYLE_OPTIONS[i];
  18269. if (textStyle.hasOwnProperty(textPropName)) {
  18270. labelOptSingle[textPropName] = textStyle[textPropName];
  18271. }
  18272. }
  18273. }
  18274. }
  18275. function compatEC3CommonStyles(opt) {
  18276. if (opt) {
  18277. removeEC3NormalStatus(opt);
  18278. compatTextStyle(opt, 'label');
  18279. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18280. }
  18281. }
  18282. function processSeries(seriesOpt) {
  18283. if (!isObject$1(seriesOpt)) {
  18284. return;
  18285. }
  18286. compatEC2ItemStyle(seriesOpt);
  18287. removeEC3NormalStatus(seriesOpt);
  18288. compatTextStyle(seriesOpt, 'label'); // treemap
  18289. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18290. compatTextStyle(seriesOpt, 'edgeLabel');
  18291. if (seriesOpt.emphasis) {
  18292. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18293. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18294. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18295. }
  18296. var markPoint = seriesOpt.markPoint;
  18297. if (markPoint) {
  18298. compatEC2ItemStyle(markPoint);
  18299. compatEC3CommonStyles(markPoint);
  18300. }
  18301. var markLine = seriesOpt.markLine;
  18302. if (markLine) {
  18303. compatEC2ItemStyle(markLine);
  18304. compatEC3CommonStyles(markLine);
  18305. }
  18306. var markArea = seriesOpt.markArea;
  18307. if (markArea) {
  18308. compatEC3CommonStyles(markArea);
  18309. }
  18310. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18311. // then the backward compat based on option type will not be performed.
  18312. if (seriesOpt.type === 'graph') {
  18313. data = data || seriesOpt.nodes;
  18314. var edgeData = seriesOpt.links || seriesOpt.edges;
  18315. if (edgeData && !isTypedArray(edgeData)) {
  18316. for (var i = 0; i < edgeData.length; i++) {
  18317. compatEC3CommonStyles(edgeData[i]);
  18318. }
  18319. }
  18320. each(seriesOpt.categories, function (opt) {
  18321. removeEC3NormalStatus(opt);
  18322. });
  18323. }
  18324. if (data && !isTypedArray(data)) {
  18325. for (var i = 0; i < data.length; i++) {
  18326. compatEC3CommonStyles(data[i]);
  18327. }
  18328. } // mark point data
  18329. markPoint = seriesOpt.markPoint;
  18330. if (markPoint && markPoint.data) {
  18331. var mpData = markPoint.data;
  18332. for (var i = 0; i < mpData.length; i++) {
  18333. compatEC3CommonStyles(mpData[i]);
  18334. }
  18335. } // mark line data
  18336. markLine = seriesOpt.markLine;
  18337. if (markLine && markLine.data) {
  18338. var mlData = markLine.data;
  18339. for (var i = 0; i < mlData.length; i++) {
  18340. if (isArray(mlData[i])) {
  18341. compatEC3CommonStyles(mlData[i][0]);
  18342. compatEC3CommonStyles(mlData[i][1]);
  18343. } else {
  18344. compatEC3CommonStyles(mlData[i]);
  18345. }
  18346. }
  18347. } // Series
  18348. if (seriesOpt.type === 'gauge') {
  18349. compatTextStyle(seriesOpt, 'axisLabel');
  18350. compatTextStyle(seriesOpt, 'title');
  18351. compatTextStyle(seriesOpt, 'detail');
  18352. } else if (seriesOpt.type === 'treemap') {
  18353. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18354. each(seriesOpt.levels, function (opt) {
  18355. removeEC3NormalStatus(opt);
  18356. });
  18357. } else if (seriesOpt.type === 'tree') {
  18358. removeEC3NormalStatus(seriesOpt.leaves);
  18359. } // sunburst starts from ec4, so it does not need to compat levels.
  18360. }
  18361. function toArr(o) {
  18362. return isArray(o) ? o : o ? [o] : [];
  18363. }
  18364. function toObj(o) {
  18365. return (isArray(o) ? o[0] : o) || {};
  18366. }
  18367. function globalCompatStyle(option, isTheme) {
  18368. each$2(toArr(option.series), function (seriesOpt) {
  18369. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18370. });
  18371. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18372. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18373. each$2(axes, function (axisName) {
  18374. each$2(toArr(option[axisName]), function (axisOpt) {
  18375. if (axisOpt) {
  18376. compatTextStyle(axisOpt, 'axisLabel');
  18377. compatTextStyle(axisOpt.axisPointer, 'label');
  18378. }
  18379. });
  18380. });
  18381. each$2(toArr(option.parallel), function (parallelOpt) {
  18382. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18383. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18384. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18385. });
  18386. each$2(toArr(option.calendar), function (calendarOpt) {
  18387. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18388. compatTextStyle(calendarOpt, 'dayLabel');
  18389. compatTextStyle(calendarOpt, 'monthLabel');
  18390. compatTextStyle(calendarOpt, 'yearLabel');
  18391. }); // radar.name.textStyle
  18392. each$2(toArr(option.radar), function (radarOpt) {
  18393. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18394. if (radarOpt.name && radarOpt.axisName == null) {
  18395. radarOpt.axisName = radarOpt.name;
  18396. delete radarOpt.name;
  18397. if ("development" !== 'production') {
  18398. deprecateLog('name property in radar component has been changed to axisName');
  18399. }
  18400. }
  18401. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18402. radarOpt.axisNameGap = radarOpt.nameGap;
  18403. delete radarOpt.nameGap;
  18404. if ("development" !== 'production') {
  18405. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18406. }
  18407. }
  18408. if ("development" !== 'production') {
  18409. each$2(radarOpt.indicator, function (indicatorOpt) {
  18410. if (indicatorOpt.text) {
  18411. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18412. }
  18413. });
  18414. }
  18415. });
  18416. each$2(toArr(option.geo), function (geoOpt) {
  18417. if (isObject$1(geoOpt)) {
  18418. compatEC3CommonStyles(geoOpt);
  18419. each$2(toArr(geoOpt.regions), function (regionObj) {
  18420. compatEC3CommonStyles(regionObj);
  18421. });
  18422. }
  18423. });
  18424. each$2(toArr(option.timeline), function (timelineOpt) {
  18425. compatEC3CommonStyles(timelineOpt);
  18426. convertNormalEmphasis(timelineOpt, 'label');
  18427. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18428. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18429. var data = timelineOpt.data;
  18430. isArray(data) && each(data, function (item) {
  18431. if (isObject(item)) {
  18432. convertNormalEmphasis(item, 'label');
  18433. convertNormalEmphasis(item, 'itemStyle');
  18434. }
  18435. });
  18436. });
  18437. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18438. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18439. each$2(toolboxOpt.feature, function (featureOpt) {
  18440. convertNormalEmphasis(featureOpt, 'iconStyle');
  18441. });
  18442. });
  18443. compatTextStyle(toObj(option.axisPointer), 'label');
  18444. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18445. // storedLogs = {};
  18446. }
  18447. function get(opt, path) {
  18448. var pathArr = path.split(',');
  18449. var obj = opt;
  18450. for (var i = 0; i < pathArr.length; i++) {
  18451. obj = obj && obj[pathArr[i]];
  18452. if (obj == null) {
  18453. break;
  18454. }
  18455. }
  18456. return obj;
  18457. }
  18458. function set$1(opt, path, val, overwrite) {
  18459. var pathArr = path.split(',');
  18460. var obj = opt;
  18461. var key;
  18462. var i = 0;
  18463. for (; i < pathArr.length - 1; i++) {
  18464. key = pathArr[i];
  18465. if (obj[key] == null) {
  18466. obj[key] = {};
  18467. }
  18468. obj = obj[key];
  18469. }
  18470. if (overwrite || obj[pathArr[i]] == null) {
  18471. obj[pathArr[i]] = val;
  18472. }
  18473. }
  18474. function compatLayoutProperties(option) {
  18475. option && each(LAYOUT_PROPERTIES, function (prop) {
  18476. if (prop[0] in option && !(prop[1] in option)) {
  18477. option[prop[1]] = option[prop[0]];
  18478. }
  18479. });
  18480. }
  18481. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18482. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18483. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18484. function compatBarItemStyle(option) {
  18485. var itemStyle = option && option.itemStyle;
  18486. if (itemStyle) {
  18487. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18488. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18489. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18490. if (itemStyle[oldName] != null) {
  18491. itemStyle[newName] = itemStyle[oldName];
  18492. if ("development" !== 'production') {
  18493. deprecateReplaceLog(oldName, newName);
  18494. }
  18495. }
  18496. }
  18497. }
  18498. }
  18499. function compatPieLabel(option) {
  18500. if (!option) {
  18501. return;
  18502. }
  18503. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18504. if ("development" !== 'production') {
  18505. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18506. }
  18507. option.edgeDistance = option.margin;
  18508. }
  18509. }
  18510. function compatSunburstState(option) {
  18511. if (!option) {
  18512. return;
  18513. }
  18514. if (option.downplay && !option.blur) {
  18515. option.blur = option.downplay;
  18516. if ("development" !== 'production') {
  18517. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18518. }
  18519. }
  18520. }
  18521. function compatGraphFocus(option) {
  18522. if (!option) {
  18523. return;
  18524. }
  18525. if (option.focusNodeAdjacency != null) {
  18526. option.emphasis = option.emphasis || {};
  18527. if (option.emphasis.focus == null) {
  18528. if ("development" !== 'production') {
  18529. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18530. }
  18531. option.emphasis.focus = 'adjacency';
  18532. }
  18533. }
  18534. }
  18535. function traverseTree(data, cb) {
  18536. if (data) {
  18537. for (var i = 0; i < data.length; i++) {
  18538. cb(data[i]);
  18539. data[i] && traverseTree(data[i].children, cb);
  18540. }
  18541. }
  18542. }
  18543. function globalBackwardCompat(option, isTheme) {
  18544. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18545. option.series = normalizeToArray(option.series);
  18546. each(option.series, function (seriesOpt) {
  18547. if (!isObject(seriesOpt)) {
  18548. return;
  18549. }
  18550. var seriesType = seriesOpt.type;
  18551. if (seriesType === 'line') {
  18552. if (seriesOpt.clipOverflow != null) {
  18553. seriesOpt.clip = seriesOpt.clipOverflow;
  18554. if ("development" !== 'production') {
  18555. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18556. }
  18557. }
  18558. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18559. if (seriesOpt.clockWise != null) {
  18560. seriesOpt.clockwise = seriesOpt.clockWise;
  18561. if ("development" !== 'production') {
  18562. deprecateReplaceLog('clockWise', 'clockwise');
  18563. }
  18564. }
  18565. compatPieLabel(seriesOpt.label);
  18566. var data = seriesOpt.data;
  18567. if (data && !isTypedArray(data)) {
  18568. for (var i = 0; i < data.length; i++) {
  18569. compatPieLabel(data[i]);
  18570. }
  18571. }
  18572. if (seriesOpt.hoverOffset != null) {
  18573. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18574. if (seriesOpt.emphasis.scaleSize = null) {
  18575. if ("development" !== 'production') {
  18576. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18577. }
  18578. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18579. }
  18580. }
  18581. } else if (seriesType === 'gauge') {
  18582. var pointerColor = get(seriesOpt, 'pointer.color');
  18583. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18584. } else if (seriesType === 'bar') {
  18585. compatBarItemStyle(seriesOpt);
  18586. compatBarItemStyle(seriesOpt.backgroundStyle);
  18587. compatBarItemStyle(seriesOpt.emphasis);
  18588. var data = seriesOpt.data;
  18589. if (data && !isTypedArray(data)) {
  18590. for (var i = 0; i < data.length; i++) {
  18591. if (typeof data[i] === 'object') {
  18592. compatBarItemStyle(data[i]);
  18593. compatBarItemStyle(data[i] && data[i].emphasis);
  18594. }
  18595. }
  18596. }
  18597. } else if (seriesType === 'sunburst') {
  18598. var highlightPolicy = seriesOpt.highlightPolicy;
  18599. if (highlightPolicy) {
  18600. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18601. if (!seriesOpt.emphasis.focus) {
  18602. seriesOpt.emphasis.focus = highlightPolicy;
  18603. if ("development" !== 'production') {
  18604. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18605. }
  18606. }
  18607. }
  18608. compatSunburstState(seriesOpt);
  18609. traverseTree(seriesOpt.data, compatSunburstState);
  18610. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18611. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18612. } else if (seriesType === 'map') {
  18613. if (seriesOpt.mapType && !seriesOpt.map) {
  18614. if ("development" !== 'production') {
  18615. deprecateReplaceLog('mapType', 'map', 'map');
  18616. }
  18617. seriesOpt.map = seriesOpt.mapType;
  18618. }
  18619. if (seriesOpt.mapLocation) {
  18620. if ("development" !== 'production') {
  18621. deprecateLog('`mapLocation` is not used anymore.');
  18622. }
  18623. defaults(seriesOpt, seriesOpt.mapLocation);
  18624. }
  18625. }
  18626. if (seriesOpt.hoverAnimation != null) {
  18627. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18628. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18629. if ("development" !== 'production') {
  18630. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18631. }
  18632. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18633. }
  18634. }
  18635. compatLayoutProperties(seriesOpt);
  18636. }); // dataRange has changed to visualMap
  18637. if (option.dataRange) {
  18638. option.visualMap = option.dataRange;
  18639. }
  18640. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18641. var options = option[componentName];
  18642. if (options) {
  18643. if (!isArray(options)) {
  18644. options = [options];
  18645. }
  18646. each(options, function (option) {
  18647. compatLayoutProperties(option);
  18648. });
  18649. }
  18650. });
  18651. }
  18652. // data processing stage is blocked in stream.
  18653. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18654. // (2) Only register once when import repeatedly.
  18655. // Should be executed after series is filtered and before stack calculation.
  18656. function dataStack(ecModel) {
  18657. var stackInfoMap = createHashMap();
  18658. ecModel.eachSeries(function (seriesModel) {
  18659. var stack = seriesModel.get('stack'); // Compatible: when `stack` is set as '', do not stack.
  18660. if (stack) {
  18661. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18662. var data = seriesModel.getData();
  18663. var stackInfo = {
  18664. // Used for calculate axis extent automatically.
  18665. // TODO: Type getCalculationInfo return more specific type?
  18666. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18667. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18668. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18669. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18670. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18671. data: data,
  18672. seriesModel: seriesModel
  18673. }; // If stacked on axis that do not support data stack.
  18674. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18675. return;
  18676. }
  18677. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18678. stackInfoList.push(stackInfo);
  18679. }
  18680. });
  18681. stackInfoMap.each(calculateStack);
  18682. }
  18683. function calculateStack(stackInfoList) {
  18684. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18685. var resultVal = [];
  18686. var resultNaN = [NaN, NaN];
  18687. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18688. var targetData = targetStackInfo.data;
  18689. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18690. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign'; // Should not write on raw data, because stack series model list changes
  18691. // depending on legend selection.
  18692. targetData.modify(dims, function (v0, v1, dataIndex) {
  18693. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18694. // should also be NaN, to draw a appropriate belt area.
  18695. if (isNaN(sum)) {
  18696. return resultNaN;
  18697. }
  18698. var byValue;
  18699. var stackedDataRawIndex;
  18700. if (isStackedByIndex) {
  18701. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18702. } else {
  18703. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18704. } // If stackOver is NaN, chart view will render point on value start.
  18705. var stackedOver = NaN;
  18706. for (var j = idxInStack - 1; j >= 0; j--) {
  18707. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18708. if (!isStackedByIndex) {
  18709. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18710. }
  18711. if (stackedDataRawIndex >= 0) {
  18712. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18713. if (stackStrategy === 'all' // single stack group
  18714. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18715. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18716. ) {
  18717. // The sum has to be very small to be affected by the
  18718. // floating arithmetic problem. An incorrect result will probably
  18719. // cause axis min/max to be filtered incorrectly.
  18720. sum = addSafe(sum, val);
  18721. stackedOver = val;
  18722. break;
  18723. }
  18724. }
  18725. }
  18726. resultVal[0] = sum;
  18727. resultVal[1] = stackedOver;
  18728. return resultVal;
  18729. });
  18730. });
  18731. }
  18732. var SourceImpl =
  18733. /** @class */
  18734. function () {
  18735. function SourceImpl(fields) {
  18736. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18737. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18738. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18739. this.startIndex = fields.startIndex || 0;
  18740. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18741. this.metaRawOption = fields.metaRawOption;
  18742. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18743. if (dimensionsDefine) {
  18744. for (var i = 0; i < dimensionsDefine.length; i++) {
  18745. var dim = dimensionsDefine[i];
  18746. if (dim.type == null) {
  18747. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18748. dim.type = 'ordinal';
  18749. }
  18750. }
  18751. }
  18752. }
  18753. }
  18754. return SourceImpl;
  18755. }();
  18756. function isSourceInstance(val) {
  18757. return val instanceof SourceImpl;
  18758. }
  18759. /**
  18760. * Create a source from option.
  18761. * NOTE: Created source is immutable. Don't change any properties in it.
  18762. */
  18763. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18764. sourceFormat) {
  18765. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18766. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18767. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18768. var source = new SourceImpl({
  18769. data: sourceData,
  18770. sourceFormat: sourceFormat,
  18771. seriesLayoutBy: seriesLayoutBy,
  18772. dimensionsDefine: determined.dimensionsDefine,
  18773. startIndex: determined.startIndex,
  18774. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18775. metaRawOption: clone(thisMetaRawOption)
  18776. });
  18777. return source;
  18778. }
  18779. /**
  18780. * Wrap original series data for some compatibility cases.
  18781. */
  18782. function createSourceFromSeriesDataOption(data) {
  18783. return new SourceImpl({
  18784. data: data,
  18785. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18786. });
  18787. }
  18788. /**
  18789. * Clone source but excludes source data.
  18790. */
  18791. function cloneSourceShallow(source) {
  18792. return new SourceImpl({
  18793. data: source.data,
  18794. sourceFormat: source.sourceFormat,
  18795. seriesLayoutBy: source.seriesLayoutBy,
  18796. dimensionsDefine: clone(source.dimensionsDefine),
  18797. startIndex: source.startIndex,
  18798. dimensionsDetectedCount: source.dimensionsDetectedCount
  18799. });
  18800. }
  18801. /**
  18802. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18803. */
  18804. function detectSourceFormat(data) {
  18805. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18806. if (isTypedArray(data)) {
  18807. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18808. } else if (isArray(data)) {
  18809. // FIXME Whether tolerate null in top level array?
  18810. if (data.length === 0) {
  18811. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18812. }
  18813. for (var i = 0, len = data.length; i < len; i++) {
  18814. var item = data[i];
  18815. if (item == null) {
  18816. continue;
  18817. } else if (isArray(item)) {
  18818. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18819. break;
  18820. } else if (isObject(item)) {
  18821. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18822. break;
  18823. }
  18824. }
  18825. } else if (isObject(data)) {
  18826. for (var key in data) {
  18827. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18828. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18829. break;
  18830. }
  18831. }
  18832. }
  18833. return sourceFormat;
  18834. }
  18835. /**
  18836. * Determine the source definitions from data standalone dimensions definitions
  18837. * are not specified.
  18838. */
  18839. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18840. // {
  18841. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18842. // }
  18843. // in `dataset` or `series`
  18844. dimensionsDefine) {
  18845. var dimensionsDetectedCount;
  18846. var startIndex; // PENDING: Could data be null/undefined here?
  18847. // currently, if `dataset.source` not specified, error thrown.
  18848. // if `series.data` not specified, nothing rendered without error thrown.
  18849. // Should test these cases.
  18850. if (!data) {
  18851. return {
  18852. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18853. startIndex: startIndex,
  18854. dimensionsDetectedCount: dimensionsDetectedCount
  18855. };
  18856. }
  18857. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18858. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18859. // Caution: consider a line with 5 string and 1 number,
  18860. // it still can not be sure it is a head, because the
  18861. // 5 string may be 5 values of category columns.
  18862. if (sourceHeader === 'auto' || sourceHeader == null) {
  18863. arrayRowsTravelFirst(function (val) {
  18864. // '-' is regarded as null/undefined.
  18865. if (val != null && val !== '-') {
  18866. if (isString(val)) {
  18867. startIndex == null && (startIndex = 1);
  18868. } else {
  18869. startIndex = 0;
  18870. }
  18871. } // 10 is an experience number, avoid long loop.
  18872. }, seriesLayoutBy, dataArrayRows, 10);
  18873. } else {
  18874. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18875. }
  18876. if (!dimensionsDefine && startIndex === 1) {
  18877. dimensionsDefine = [];
  18878. arrayRowsTravelFirst(function (val, index) {
  18879. dimensionsDefine[index] = val != null ? val + '' : '';
  18880. }, seriesLayoutBy, dataArrayRows, Infinity);
  18881. }
  18882. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18883. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18884. if (!dimensionsDefine) {
  18885. dimensionsDefine = objectRowsCollectDimensions(data);
  18886. }
  18887. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18888. if (!dimensionsDefine) {
  18889. dimensionsDefine = [];
  18890. each(data, function (colArr, key) {
  18891. dimensionsDefine.push(key);
  18892. });
  18893. }
  18894. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18895. var value0 = getDataItemValue(data[0]);
  18896. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18897. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18898. if ("development" !== 'production') {
  18899. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18900. }
  18901. }
  18902. return {
  18903. startIndex: startIndex,
  18904. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18905. dimensionsDetectedCount: dimensionsDetectedCount
  18906. };
  18907. }
  18908. function objectRowsCollectDimensions(data) {
  18909. var firstIndex = 0;
  18910. var obj;
  18911. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18912. if (obj) {
  18913. return keys(obj);
  18914. }
  18915. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18916. // which is reasonable. But dimension name is duplicated.
  18917. // Returns undefined or an array contains only object without null/undefined or string.
  18918. function normalizeDimensionsOption(dimensionsDefine) {
  18919. if (!dimensionsDefine) {
  18920. // The meaning of null/undefined is different from empty array.
  18921. return;
  18922. }
  18923. var nameMap = createHashMap();
  18924. return map(dimensionsDefine, function (rawItem, index) {
  18925. rawItem = isObject(rawItem) ? rawItem : {
  18926. name: rawItem
  18927. }; // Other fields will be discarded.
  18928. var item = {
  18929. name: rawItem.name,
  18930. displayName: rawItem.displayName,
  18931. type: rawItem.type
  18932. }; // User can set null in dimensions.
  18933. // We don't auto specify name, otherwise a given name may
  18934. // cause it to be referred unexpectedly.
  18935. if (item.name == null) {
  18936. return item;
  18937. } // Also consider number form like 2012.
  18938. item.name += ''; // User may also specify displayName.
  18939. // displayName will always exists except user not
  18940. // specified or dim name is not specified or detected.
  18941. // (A auto generated dim name will not be used as
  18942. // displayName).
  18943. if (item.displayName == null) {
  18944. item.displayName = item.name;
  18945. }
  18946. var exist = nameMap.get(item.name);
  18947. if (!exist) {
  18948. nameMap.set(item.name, {
  18949. count: 1
  18950. });
  18951. } else {
  18952. item.name += '-' + exist.count++;
  18953. }
  18954. return item;
  18955. });
  18956. }
  18957. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18958. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18959. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18960. cb(data[i] ? data[i][0] : null, i);
  18961. }
  18962. } else {
  18963. var value0 = data[0] || [];
  18964. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18965. cb(value0[i], i);
  18966. }
  18967. }
  18968. }
  18969. function shouldRetrieveDataByName(source) {
  18970. var sourceFormat = source.sourceFormat;
  18971. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  18972. }
  18973. /*
  18974. * Licensed to the Apache Software Foundation (ASF) under one
  18975. * or more contributor license agreements. See the NOTICE file
  18976. * distributed with this work for additional information
  18977. * regarding copyright ownership. The ASF licenses this file
  18978. * to you under the Apache License, Version 2.0 (the
  18979. * "License"); you may not use this file except in compliance
  18980. * with the License. You may obtain a copy of the License at
  18981. *
  18982. * http://www.apache.org/licenses/LICENSE-2.0
  18983. *
  18984. * Unless required by applicable law or agreed to in writing,
  18985. * software distributed under the License is distributed on an
  18986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18987. * KIND, either express or implied. See the License for the
  18988. * specific language governing permissions and limitations
  18989. * under the License.
  18990. */
  18991. /**
  18992. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18993. */
  18994. /*
  18995. * Licensed to the Apache Software Foundation (ASF) under one
  18996. * or more contributor license agreements. See the NOTICE file
  18997. * distributed with this work for additional information
  18998. * regarding copyright ownership. The ASF licenses this file
  18999. * to you under the Apache License, Version 2.0 (the
  19000. * "License"); you may not use this file except in compliance
  19001. * with the License. You may obtain a copy of the License at
  19002. *
  19003. * http://www.apache.org/licenses/LICENSE-2.0
  19004. *
  19005. * Unless required by applicable law or agreed to in writing,
  19006. * software distributed under the License is distributed on an
  19007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19008. * KIND, either express or implied. See the License for the
  19009. * specific language governing permissions and limitations
  19010. * under the License.
  19011. */
  19012. var _a, _b, _c; // TODO
  19013. var providerMethods;
  19014. var mountMethods;
  19015. /**
  19016. * If normal array used, mutable chunk size is supported.
  19017. * If typed array used, chunk size must be fixed.
  19018. */
  19019. var DefaultDataProvider =
  19020. /** @class */
  19021. function () {
  19022. function DefaultDataProvider(sourceParam, dimSize) {
  19023. // let source: Source;
  19024. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  19025. this._source = source;
  19026. var data = this._data = source.data; // Typed array. TODO IE10+?
  19027. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19028. if ("development" !== 'production') {
  19029. if (dimSize == null) {
  19030. throw new Error('Typed array data must specify dimension size');
  19031. }
  19032. }
  19033. this._offset = 0;
  19034. this._dimSize = dimSize;
  19035. this._data = data;
  19036. }
  19037. mountMethods(this, data, source);
  19038. }
  19039. DefaultDataProvider.prototype.getSource = function () {
  19040. return this._source;
  19041. };
  19042. DefaultDataProvider.prototype.count = function () {
  19043. return 0;
  19044. };
  19045. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19046. return;
  19047. };
  19048. DefaultDataProvider.prototype.appendData = function (newData) {};
  19049. DefaultDataProvider.prototype.clean = function () {};
  19050. DefaultDataProvider.protoInitialize = function () {
  19051. // PENDING: To avoid potential incompat (e.g., prototype
  19052. // is visited somewhere), still init them on prototype.
  19053. var proto = DefaultDataProvider.prototype;
  19054. proto.pure = false;
  19055. proto.persistent = true;
  19056. }();
  19057. DefaultDataProvider.internalField = function () {
  19058. var _a;
  19059. mountMethods = function (provider, data, source) {
  19060. var sourceFormat = source.sourceFormat;
  19061. var seriesLayoutBy = source.seriesLayoutBy;
  19062. var startIndex = source.startIndex;
  19063. var dimsDef = source.dimensionsDefine;
  19064. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19065. if ("development" !== 'production') {
  19066. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19067. }
  19068. extend(provider, methods);
  19069. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19070. provider.getItem = getItemForTypedArray;
  19071. provider.count = countForTypedArray;
  19072. provider.fillStorage = fillStorageForTypedArray;
  19073. } else {
  19074. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19075. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19076. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19077. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19078. }
  19079. };
  19080. var getItemForTypedArray = function (idx, out) {
  19081. idx = idx - this._offset;
  19082. out = out || [];
  19083. var data = this._data;
  19084. var dimSize = this._dimSize;
  19085. var offset = dimSize * idx;
  19086. for (var i = 0; i < dimSize; i++) {
  19087. out[i] = data[offset + i];
  19088. }
  19089. return out;
  19090. };
  19091. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19092. var data = this._data;
  19093. var dimSize = this._dimSize;
  19094. for (var dim = 0; dim < dimSize; dim++) {
  19095. var dimExtent = extent[dim];
  19096. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19097. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19098. var count = end - start;
  19099. var arr = storage[dim];
  19100. for (var i = 0; i < count; i++) {
  19101. // appendData with TypedArray will always do replace in provider.
  19102. var val = data[i * dimSize + dim];
  19103. arr[start + i] = val;
  19104. val < min && (min = val);
  19105. val > max && (max = val);
  19106. }
  19107. dimExtent[0] = min;
  19108. dimExtent[1] = max;
  19109. }
  19110. };
  19111. var countForTypedArray = function () {
  19112. return this._data ? this._data.length / this._dimSize : 0;
  19113. };
  19114. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19115. pure: true,
  19116. appendData: appendDataSimply
  19117. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19118. pure: true,
  19119. appendData: function () {
  19120. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19121. }
  19122. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19123. pure: true,
  19124. appendData: appendDataSimply
  19125. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19126. pure: true,
  19127. appendData: function (newData) {
  19128. var data = this._data;
  19129. each(newData, function (newCol, key) {
  19130. var oldCol = data[key] || (data[key] = []);
  19131. for (var i = 0; i < (newCol || []).length; i++) {
  19132. oldCol.push(newCol[i]);
  19133. }
  19134. });
  19135. }
  19136. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19137. appendData: appendDataSimply
  19138. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19139. persistent: false,
  19140. pure: true,
  19141. appendData: function (newData) {
  19142. if ("development" !== 'production') {
  19143. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19144. }
  19145. this._data = newData;
  19146. },
  19147. // Clean self if data is already used.
  19148. clean: function () {
  19149. // PENDING
  19150. this._offset += this.count();
  19151. this._data = null;
  19152. }
  19153. }, _a);
  19154. function appendDataSimply(newData) {
  19155. for (var i = 0; i < newData.length; i++) {
  19156. this._data.push(newData[i]);
  19157. }
  19158. }
  19159. }();
  19160. return DefaultDataProvider;
  19161. }();
  19162. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19163. return rawData[idx];
  19164. };
  19165. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19166. return rawData[idx + startIndex];
  19167. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19168. idx += startIndex;
  19169. var item = out || [];
  19170. var data = rawData;
  19171. for (var i = 0; i < data.length; i++) {
  19172. var row = data[i];
  19173. item[i] = row ? row[idx] : null;
  19174. }
  19175. return item;
  19176. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19177. var item = out || [];
  19178. for (var i = 0; i < dimsDef.length; i++) {
  19179. var dimName = dimsDef[i].name;
  19180. if ("development" !== 'production') {
  19181. if (dimName == null) {
  19182. throw new Error();
  19183. }
  19184. }
  19185. var col = rawData[dimName];
  19186. item[i] = col ? col[idx] : null;
  19187. }
  19188. return item;
  19189. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19190. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19191. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19192. if ("development" !== 'production') {
  19193. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19194. }
  19195. return method;
  19196. }
  19197. var countSimply = function (rawData, startIndex, dimsDef) {
  19198. return rawData.length;
  19199. };
  19200. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19201. return Math.max(0, rawData.length - startIndex);
  19202. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19203. var row = rawData[0];
  19204. return row ? Math.max(0, row.length - startIndex) : 0;
  19205. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19206. var dimName = dimsDef[0].name;
  19207. if ("development" !== 'production') {
  19208. if (dimName == null) {
  19209. throw new Error();
  19210. }
  19211. }
  19212. var col = rawData[dimName];
  19213. return col ? col.length : 0;
  19214. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19215. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19216. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19217. if ("development" !== 'production') {
  19218. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19219. }
  19220. return method;
  19221. }
  19222. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19223. return dataItem[dimIndex];
  19224. };
  19225. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19226. return dataItem[property];
  19227. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19228. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19229. // dataItem is {coord: [...]}
  19230. var value = getDataItemValue(dataItem);
  19231. return !(value instanceof Array) ? value : value[dimIndex];
  19232. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19233. function getRawSourceValueGetter(sourceFormat) {
  19234. var method = rawSourceValueGetterMap[sourceFormat];
  19235. if ("development" !== 'production') {
  19236. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19237. }
  19238. return method;
  19239. }
  19240. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19241. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19242. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19243. // Consider persistent.
  19244. // Caution: why use raw value to display on label or tooltip?
  19245. // A reason is to avoid format. For example time value we do not know
  19246. // how to format is expected. More over, if stack is used, calculated
  19247. // value may be 0.91000000001, which have brings trouble to display.
  19248. // TODO: consider how to treat null/undefined/NaN when display?
  19249. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19250. // Otherwise, return OptionDataValue.
  19251. dim) {
  19252. if (!data) {
  19253. return;
  19254. } // Consider data may be not persistent.
  19255. var dataItem = data.getRawDataItem(dataIndex);
  19256. if (dataItem == null) {
  19257. return;
  19258. }
  19259. var store = data.getStore();
  19260. var sourceFormat = store.getSource().sourceFormat;
  19261. if (dim != null) {
  19262. var dimIndex = data.getDimensionIndex(dim);
  19263. var property = store.getDimensionProperty(dimIndex);
  19264. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19265. } else {
  19266. var result = dataItem;
  19267. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19268. result = getDataItemValue(dataItem);
  19269. }
  19270. return result;
  19271. }
  19272. }
  19273. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19274. var DataFormatMixin =
  19275. /** @class */
  19276. function () {
  19277. function DataFormatMixin() {}
  19278. /**
  19279. * Get params for formatter
  19280. */
  19281. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19282. var data = this.getData(dataType);
  19283. var rawValue = this.getRawValue(dataIndex, dataType);
  19284. var rawDataIndex = data.getRawIndex(dataIndex);
  19285. var name = data.getName(dataIndex);
  19286. var itemOpt = data.getRawDataItem(dataIndex);
  19287. var style = data.getItemVisual(dataIndex, 'style');
  19288. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19289. var borderColor = style && style.stroke;
  19290. var mainType = this.mainType;
  19291. var isSeries = mainType === 'series';
  19292. var userOutput = data.userOutput && data.userOutput.get();
  19293. return {
  19294. componentType: mainType,
  19295. componentSubType: this.subType,
  19296. componentIndex: this.componentIndex,
  19297. seriesType: isSeries ? this.subType : null,
  19298. seriesIndex: this.seriesIndex,
  19299. seriesId: isSeries ? this.id : null,
  19300. seriesName: isSeries ? this.name : null,
  19301. name: name,
  19302. dataIndex: rawDataIndex,
  19303. data: itemOpt,
  19304. dataType: dataType,
  19305. value: rawValue,
  19306. color: color,
  19307. borderColor: borderColor,
  19308. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19309. encode: userOutput ? userOutput.encode : null,
  19310. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19311. $vars: ['seriesName', 'name', 'value']
  19312. };
  19313. };
  19314. /**
  19315. * Format label
  19316. * @param dataIndex
  19317. * @param status 'normal' by default
  19318. * @param dataType
  19319. * @param labelDimIndex Only used in some chart that
  19320. * use formatter in different dimensions, like radar.
  19321. * @param formatter Formatter given outside.
  19322. * @return return null/undefined if no formatter
  19323. */
  19324. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19325. status = status || 'normal';
  19326. var data = this.getData(dataType);
  19327. var params = this.getDataParams(dataIndex, dataType);
  19328. if (extendParams) {
  19329. params.value = extendParams.interpolatedValue;
  19330. }
  19331. if (labelDimIndex != null && isArray(params.value)) {
  19332. params.value = params.value[labelDimIndex];
  19333. }
  19334. if (!formatter) {
  19335. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19336. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19337. }
  19338. if (isFunction(formatter)) {
  19339. params.status = status;
  19340. params.dimensionIndex = labelDimIndex;
  19341. return formatter(params);
  19342. } else if (isString(formatter)) {
  19343. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19344. // Do not support '}' in dim name util have to.
  19345. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19346. var len = dimStr.length;
  19347. var dimLoose = dimStr;
  19348. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19349. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19350. if ("development" !== 'production') {
  19351. if (isNaN(dimLoose)) {
  19352. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19353. }
  19354. }
  19355. }
  19356. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19357. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19358. var dimIndex = data.getDimensionIndex(dimLoose);
  19359. if (dimIndex >= 0) {
  19360. val = extendParams.interpolatedValue[dimIndex];
  19361. }
  19362. }
  19363. return val != null ? val + '' : '';
  19364. });
  19365. }
  19366. };
  19367. /**
  19368. * Get raw value in option
  19369. */
  19370. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19371. return retrieveRawValue(this.getData(dataType), idx);
  19372. };
  19373. /**
  19374. * Should be implemented.
  19375. * @param {number} dataIndex
  19376. * @param {boolean} [multipleSeries=false]
  19377. * @param {string} [dataType]
  19378. */
  19379. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19380. // Empty function
  19381. return;
  19382. };
  19383. return DataFormatMixin;
  19384. }();
  19385. // but guess little chance has been used outside. Do we need to backward
  19386. // compat it?
  19387. // type TooltipFormatResultLegacyObject = {
  19388. // // `html` means the markup language text, either in 'html' or 'richText'.
  19389. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19390. // // string. But still support it for backward compatibility.
  19391. // html: string;
  19392. // markers: Dictionary<ColorString>;
  19393. // };
  19394. /**
  19395. * For backward compat, normalize the return from `formatTooltip`.
  19396. */
  19397. function normalizeTooltipFormatResult(result) {
  19398. var markupText; // let markers: Dictionary<ColorString>;
  19399. var markupFragment;
  19400. if (isObject(result)) {
  19401. if (result.type) {
  19402. markupFragment = result;
  19403. } else {
  19404. if ("development" !== 'production') {
  19405. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19406. }
  19407. } // else {
  19408. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19409. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19410. // if (markersExisting) {
  19411. // markers = zrUtil.merge(markersExisting, markers);
  19412. // }
  19413. // }
  19414. } else {
  19415. markupText = result;
  19416. }
  19417. return {
  19418. text: markupText,
  19419. // markers: markers || markersExisting,
  19420. frag: markupFragment
  19421. };
  19422. }
  19423. /**
  19424. * @param {Object} define
  19425. * @return See the return of `createTask`.
  19426. */
  19427. function createTask(define) {
  19428. return new Task(define);
  19429. }
  19430. var Task =
  19431. /** @class */
  19432. function () {
  19433. function Task(define) {
  19434. define = define || {};
  19435. this._reset = define.reset;
  19436. this._plan = define.plan;
  19437. this._count = define.count;
  19438. this._onDirty = define.onDirty;
  19439. this._dirty = true;
  19440. }
  19441. /**
  19442. * @param step Specified step.
  19443. * @param skip Skip customer perform call.
  19444. * @param modBy Sampling window size.
  19445. * @param modDataCount Sampling count.
  19446. * @return whether unfinished.
  19447. */
  19448. Task.prototype.perform = function (performArgs) {
  19449. var upTask = this._upstream;
  19450. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19451. // Pull data. Must pull data each time, because context.data
  19452. // may be updated by Series.setData.
  19453. if (this._dirty && upTask) {
  19454. var context = this.context;
  19455. context.data = context.outputData = upTask.context.outputData;
  19456. }
  19457. if (this.__pipeline) {
  19458. this.__pipeline.currentTask = this;
  19459. }
  19460. var planResult;
  19461. if (this._plan && !skip) {
  19462. planResult = this._plan(this.context);
  19463. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19464. // elements uniformed distributed when progress, especially when moving or zooming.
  19465. var lastModBy = normalizeModBy(this._modBy);
  19466. var lastModDataCount = this._modDataCount || 0;
  19467. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19468. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19469. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19470. planResult = 'reset';
  19471. }
  19472. function normalizeModBy(val) {
  19473. !(val >= 1) && (val = 1); // jshint ignore:line
  19474. return val;
  19475. }
  19476. var forceFirstProgress;
  19477. if (this._dirty || planResult === 'reset') {
  19478. this._dirty = false;
  19479. forceFirstProgress = this._doReset(skip);
  19480. }
  19481. this._modBy = modBy;
  19482. this._modDataCount = modDataCount;
  19483. var step = performArgs && performArgs.step;
  19484. if (upTask) {
  19485. if ("development" !== 'production') {
  19486. assert(upTask._outputDueEnd != null);
  19487. }
  19488. this._dueEnd = upTask._outputDueEnd;
  19489. } // DataTask or overallTask
  19490. else {
  19491. if ("development" !== 'production') {
  19492. assert(!this._progress || this._count);
  19493. }
  19494. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19495. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19496. // If no progress, pass index from upstream to downstream each time plan called.
  19497. if (this._progress) {
  19498. var start = this._dueIndex;
  19499. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19500. if (!skip && (forceFirstProgress || start < end)) {
  19501. var progress = this._progress;
  19502. if (isArray(progress)) {
  19503. for (var i = 0; i < progress.length; i++) {
  19504. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19505. }
  19506. } else {
  19507. this._doProgress(progress, start, end, modBy, modDataCount);
  19508. }
  19509. }
  19510. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19511. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19512. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19513. if ("development" !== 'production') {
  19514. // ??? Can not rollback.
  19515. assert(outputDueEnd >= this._outputDueEnd);
  19516. }
  19517. this._outputDueEnd = outputDueEnd;
  19518. } else {
  19519. // (1) Some overall task has no progress.
  19520. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19521. // This should always be performed so it can be passed to downstream.
  19522. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19523. }
  19524. return this.unfinished();
  19525. };
  19526. Task.prototype.dirty = function () {
  19527. this._dirty = true;
  19528. this._onDirty && this._onDirty(this.context);
  19529. };
  19530. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19531. iterator.reset(start, end, modBy, modDataCount);
  19532. this._callingProgress = progress;
  19533. this._callingProgress({
  19534. start: start,
  19535. end: end,
  19536. count: end - start,
  19537. next: iterator.next
  19538. }, this.context);
  19539. };
  19540. Task.prototype._doReset = function (skip) {
  19541. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19542. this._settedOutputEnd = null;
  19543. var progress;
  19544. var forceFirstProgress;
  19545. if (!skip && this._reset) {
  19546. progress = this._reset(this.context);
  19547. if (progress && progress.progress) {
  19548. forceFirstProgress = progress.forceFirstProgress;
  19549. progress = progress.progress;
  19550. } // To simplify no progress checking, array must has item.
  19551. if (isArray(progress) && !progress.length) {
  19552. progress = null;
  19553. }
  19554. }
  19555. this._progress = progress;
  19556. this._modBy = this._modDataCount = null;
  19557. var downstream = this._downstream;
  19558. downstream && downstream.dirty();
  19559. return forceFirstProgress;
  19560. };
  19561. Task.prototype.unfinished = function () {
  19562. return this._progress && this._dueIndex < this._dueEnd;
  19563. };
  19564. /**
  19565. * @param downTask The downstream task.
  19566. * @return The downstream task.
  19567. */
  19568. Task.prototype.pipe = function (downTask) {
  19569. if ("development" !== 'production') {
  19570. assert(downTask && !downTask._disposed && downTask !== this);
  19571. } // If already downstream, do not dirty downTask.
  19572. if (this._downstream !== downTask || this._dirty) {
  19573. this._downstream = downTask;
  19574. downTask._upstream = this;
  19575. downTask.dirty();
  19576. }
  19577. };
  19578. Task.prototype.dispose = function () {
  19579. if (this._disposed) {
  19580. return;
  19581. }
  19582. this._upstream && (this._upstream._downstream = null);
  19583. this._downstream && (this._downstream._upstream = null);
  19584. this._dirty = false;
  19585. this._disposed = true;
  19586. };
  19587. Task.prototype.getUpstream = function () {
  19588. return this._upstream;
  19589. };
  19590. Task.prototype.getDownstream = function () {
  19591. return this._downstream;
  19592. };
  19593. Task.prototype.setOutputEnd = function (end) {
  19594. // This only happens in dataTask, dataZoom, map, currently.
  19595. // where dataZoom do not set end each time, but only set
  19596. // when reset. So we should record the set end, in case
  19597. // that the stub of dataZoom perform again and earse the
  19598. // set end by upstream.
  19599. this._outputDueEnd = this._settedOutputEnd = end;
  19600. };
  19601. return Task;
  19602. }();
  19603. var iterator = function () {
  19604. var end;
  19605. var current;
  19606. var modBy;
  19607. var modDataCount;
  19608. var winCount;
  19609. var it = {
  19610. reset: function (s, e, sStep, sCount) {
  19611. current = s;
  19612. end = e;
  19613. modBy = sStep;
  19614. modDataCount = sCount;
  19615. winCount = Math.ceil(modDataCount / modBy);
  19616. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19617. }
  19618. };
  19619. return it;
  19620. function sequentialNext() {
  19621. return current < end ? current++ : null;
  19622. }
  19623. function modNext() {
  19624. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19625. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19626. // Use normal linear rendering mode.
  19627. : current;
  19628. current++;
  19629. return result;
  19630. }
  19631. }(); // -----------------------------------------------------------------------------
  19632. // For stream debug (Should be commented out after used!)
  19633. // @usage: printTask(this, 'begin');
  19634. // @usage: printTask(this, null, {someExtraProp});
  19635. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19636. //
  19637. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19638. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19639. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19640. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19641. // let props = [];
  19642. // if (task.__pipeline) {
  19643. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19644. // props.push({text: '__idxInPipeline/total', value: val});
  19645. // } else {
  19646. // let stubCount = 0;
  19647. // task.agentStubMap.each(() => stubCount++);
  19648. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19649. // }
  19650. // props.push({text: 'uid', value: task.uidDebug});
  19651. // if (task.__pipeline) {
  19652. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19653. // task.agent && props.push(
  19654. // {text: 'stubFor', value: task.agent.uidDebug}
  19655. // );
  19656. // }
  19657. // props.push(
  19658. // {text: 'dirty', value: task._dirty},
  19659. // {text: 'dueIndex', value: task._dueIndex},
  19660. // {text: 'dueEnd', value: task._dueEnd},
  19661. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19662. // );
  19663. // if (extra) {
  19664. // Object.keys(extra).forEach(key => {
  19665. // props.push({text: key, value: extra[key]});
  19666. // });
  19667. // }
  19668. // let args = ['color: blue'];
  19669. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19670. // args.push('color: green', 'color: red'),
  19671. // `${item.text}: %c${item.value}`
  19672. // )).join('%c, ');
  19673. // console.log.apply(console, [msg].concat(args));
  19674. // // console.log(this);
  19675. // };
  19676. // window.printPipeline = function (task: any, prefix: string) {
  19677. // const pipeline = task.__pipeline;
  19678. // let currTask = pipeline.head;
  19679. // while (currTask) {
  19680. // window.printTask(currTask, prefix);
  19681. // currTask = currTask._downstream;
  19682. // }
  19683. // };
  19684. // window.showChain = function (chainHeadTask) {
  19685. // var chain = [];
  19686. // var task = chainHeadTask;
  19687. // while (task) {
  19688. // chain.push({
  19689. // task: task,
  19690. // up: task._upstream,
  19691. // down: task._downstream,
  19692. // idxInPipeline: task.__idxInPipeline
  19693. // });
  19694. // task = task._downstream;
  19695. // }
  19696. // return chain;
  19697. // };
  19698. // window.findTaskInChain = function (task, chainHeadTask) {
  19699. // let chain = window.showChain(chainHeadTask);
  19700. // let result = [];
  19701. // for (let i = 0; i < chain.length; i++) {
  19702. // let chainItem = chain[i];
  19703. // if (chainItem.task === task) {
  19704. // result.push(i);
  19705. // }
  19706. // }
  19707. // return result;
  19708. // };
  19709. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19710. // let chainA = window.showChain(chainHeadTaskA);
  19711. // for (let i = 0; i < chainA.length; i++) {
  19712. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19713. // }
  19714. // };
  19715. /**
  19716. * Convert raw the value in to inner value in List.
  19717. *
  19718. * [Performance sensitive]
  19719. *
  19720. * [Caution]: this is the key logic of user value parser.
  19721. * For backward compatibility, do not modify it until you have to!
  19722. */
  19723. function parseDataValue(value, // For high performance, do not omit the second param.
  19724. opt) {
  19725. // Performance sensitive.
  19726. var dimType = opt && opt.type;
  19727. if (dimType === 'ordinal') {
  19728. // If given value is a category string
  19729. return value;
  19730. }
  19731. if (dimType === 'time' // spead up when using timestamp
  19732. && !isNumber(value) && value != null && value !== '-') {
  19733. value = +parseDate(value);
  19734. } // dimType defaults 'number'.
  19735. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19736. // parse to NaN.
  19737. // number-like string (like ' 123 ') can be converted to a number.
  19738. // where null/undefined or other string will be converted to NaN.
  19739. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19740. // If object, also parse to NaN
  19741. : +value;
  19742. }
  19743. var valueParserMap = createHashMap({
  19744. 'number': function (val) {
  19745. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  19746. // Here the number parser can have loose rule:
  19747. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19748. return parseFloat(val);
  19749. },
  19750. 'time': function (val) {
  19751. // return timestamp.
  19752. return +parseDate(val);
  19753. },
  19754. 'trim': function (val) {
  19755. return isString(val) ? trim(val) : val;
  19756. }
  19757. });
  19758. var SortOrderComparator =
  19759. /** @class */
  19760. function () {
  19761. /**
  19762. * @param order by default: 'asc'
  19763. * @param incomparable by default: Always on the tail.
  19764. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19765. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  19766. */
  19767. function SortOrderComparator(order, incomparable) {
  19768. var isDesc = order === 'desc';
  19769. this._resultLT = isDesc ? 1 : -1;
  19770. if (incomparable == null) {
  19771. incomparable = isDesc ? 'min' : 'max';
  19772. }
  19773. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19774. } // See [SORT_COMPARISON_RULE].
  19775. // Performance sensitive.
  19776. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  19777. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19778. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  19779. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  19780. var lvalNotNumeric = isNaN(lvalFloat);
  19781. var rvalNotNumeric = isNaN(rvalFloat);
  19782. if (lvalNotNumeric) {
  19783. lvalFloat = this._incomparable;
  19784. }
  19785. if (rvalNotNumeric) {
  19786. rvalFloat = this._incomparable;
  19787. }
  19788. if (lvalNotNumeric && rvalNotNumeric) {
  19789. var lvalIsStr = isString(lval);
  19790. var rvalIsStr = isString(rval);
  19791. if (lvalIsStr) {
  19792. lvalFloat = rvalIsStr ? lval : 0;
  19793. }
  19794. if (rvalIsStr) {
  19795. rvalFloat = lvalIsStr ? rval : 0;
  19796. }
  19797. }
  19798. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  19799. };
  19800. return SortOrderComparator;
  19801. }();
  19802. /**
  19803. * TODO: disable writable.
  19804. * This structure will be exposed to users.
  19805. */
  19806. var ExternalSource =
  19807. /** @class */
  19808. function () {
  19809. function ExternalSource() {}
  19810. ExternalSource.prototype.getRawData = function () {
  19811. // Only built-in transform available.
  19812. throw new Error('not supported');
  19813. };
  19814. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19815. // Only built-in transform available.
  19816. throw new Error('not supported');
  19817. };
  19818. ExternalSource.prototype.cloneRawData = function () {
  19819. return;
  19820. };
  19821. /**
  19822. * @return If dimension not found, return null/undefined.
  19823. */
  19824. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19825. return;
  19826. };
  19827. /**
  19828. * dimensions defined if and only if either:
  19829. * (a) dataset.dimensions are declared.
  19830. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19831. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19832. * the defined dimensions.
  19833. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19834. * @return Always return an array (even empty array).
  19835. */
  19836. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19837. return;
  19838. };
  19839. ExternalSource.prototype.count = function () {
  19840. return;
  19841. };
  19842. /**
  19843. * Only support by dimension index.
  19844. * No need to support by dimension name in transform function,
  19845. * because transform function is not case-specific, no need to use name literally.
  19846. */
  19847. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19848. return;
  19849. };
  19850. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19851. return;
  19852. };
  19853. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19854. return parseDataValue(rawVal, dimInfo);
  19855. };
  19856. return ExternalSource;
  19857. }();
  19858. function createExternalSource(internalSource, externalTransform) {
  19859. var extSource = new ExternalSource();
  19860. var data = internalSource.data;
  19861. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19862. var sourceHeaderCount = internalSource.startIndex;
  19863. var errMsg = '';
  19864. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19865. // For the logic simplicity in transformer, only 'culumn' is
  19866. // supported in data transform. Otherwise, the `dimensionsDefine`
  19867. // might be detected by 'row', which probably confuses users.
  19868. if ("development" !== 'production') {
  19869. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19870. }
  19871. throwError(errMsg);
  19872. } // [MEMO]
  19873. // Create a new dimensions structure for exposing.
  19874. // Do not expose all dimension info to users directly.
  19875. // Because the dimension is probably auto detected from data and not might reliable.
  19876. // Should not lead the transformers to think that is reliable and return it.
  19877. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19878. var dimensions = [];
  19879. var dimsByName = {};
  19880. var dimsDef = internalSource.dimensionsDefine;
  19881. if (dimsDef) {
  19882. each(dimsDef, function (dimDef, idx) {
  19883. var name = dimDef.name;
  19884. var dimDefExt = {
  19885. index: idx,
  19886. name: name,
  19887. displayName: dimDef.displayName
  19888. };
  19889. dimensions.push(dimDefExt); // Users probably do not specify dimension name. For simplicity, data transform
  19890. // does not generate dimension name.
  19891. if (name != null) {
  19892. // Dimension name should not be duplicated.
  19893. // For simplicity, data transform forbids name duplication, do not generate
  19894. // new name like module `completeDimensions.ts` did, but just tell users.
  19895. var errMsg_1 = '';
  19896. if (hasOwn(dimsByName, name)) {
  19897. if ("development" !== 'production') {
  19898. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19899. }
  19900. throwError(errMsg_1);
  19901. }
  19902. dimsByName[name] = dimDefExt;
  19903. }
  19904. });
  19905. } // If dimension definitions are not defined and can not be detected.
  19906. // e.g., pure data `[[11, 22], ...]`.
  19907. else {
  19908. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19909. // Do not generete name or anything others. The consequence process in
  19910. // `transform` or `series` probably have there own name generation strategry.
  19911. dimensions.push({
  19912. index: i
  19913. });
  19914. }
  19915. } // Implement public methods:
  19916. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19917. if (externalTransform.__isBuiltIn) {
  19918. extSource.getRawDataItem = function (dataIndex) {
  19919. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19920. };
  19921. extSource.getRawData = bind(getRawData, null, internalSource);
  19922. }
  19923. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19924. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19925. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19926. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19927. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19928. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19929. return retrieveValueFromItem(rawItem, dimIndex);
  19930. };
  19931. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19932. if (dataItem == null) {
  19933. return;
  19934. }
  19935. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19936. if (dimDef) {
  19937. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19938. }
  19939. };
  19940. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19941. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19942. return extSource;
  19943. }
  19944. function getRawData(upstream) {
  19945. var sourceFormat = upstream.sourceFormat;
  19946. if (!isSupportedSourceFormat(sourceFormat)) {
  19947. var errMsg = '';
  19948. if ("development" !== 'production') {
  19949. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19950. }
  19951. throwError(errMsg);
  19952. }
  19953. return upstream.data;
  19954. }
  19955. function cloneRawData(upstream) {
  19956. var sourceFormat = upstream.sourceFormat;
  19957. var data = upstream.data;
  19958. if (!isSupportedSourceFormat(sourceFormat)) {
  19959. var errMsg = '';
  19960. if ("development" !== 'production') {
  19961. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19962. }
  19963. throwError(errMsg);
  19964. }
  19965. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19966. var result = [];
  19967. for (var i = 0, len = data.length; i < len; i++) {
  19968. // Not strictly clone for performance
  19969. result.push(data[i].slice());
  19970. }
  19971. return result;
  19972. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19973. var result = [];
  19974. for (var i = 0, len = data.length; i < len; i++) {
  19975. // Not strictly clone for performance
  19976. result.push(extend({}, data[i]));
  19977. }
  19978. return result;
  19979. }
  19980. }
  19981. function getDimensionInfo(dimensions, dimsByName, dim) {
  19982. if (dim == null) {
  19983. return;
  19984. } // Keep the same logic as `List::getDimension` did.
  19985. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  19986. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19987. return dimensions[dim];
  19988. } else if (hasOwn(dimsByName, dim)) {
  19989. return dimsByName[dim];
  19990. }
  19991. }
  19992. function cloneAllDimensionInfo(dimensions) {
  19993. return clone(dimensions);
  19994. }
  19995. var externalTransformMap = createHashMap();
  19996. function registerExternalTransform(externalTransform) {
  19997. externalTransform = clone(externalTransform);
  19998. var type = externalTransform.type;
  19999. var errMsg = '';
  20000. if (!type) {
  20001. if ("development" !== 'production') {
  20002. errMsg = 'Must have a `type` when `registerTransform`.';
  20003. }
  20004. throwError(errMsg);
  20005. }
  20006. var typeParsed = type.split(':');
  20007. if (typeParsed.length !== 2) {
  20008. if ("development" !== 'production') {
  20009. errMsg = 'Name must include namespace like "ns:regression".';
  20010. }
  20011. throwError(errMsg);
  20012. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20013. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20014. var isBuiltIn = false;
  20015. if (typeParsed[0] === 'echarts') {
  20016. type = typeParsed[1];
  20017. isBuiltIn = true;
  20018. }
  20019. externalTransform.__isBuiltIn = isBuiltIn;
  20020. externalTransformMap.set(type, externalTransform);
  20021. }
  20022. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20023. var pipedTransOption = normalizeToArray(rawTransOption);
  20024. var pipeLen = pipedTransOption.length;
  20025. var errMsg = '';
  20026. if (!pipeLen) {
  20027. if ("development" !== 'production') {
  20028. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20029. }
  20030. throwError(errMsg);
  20031. }
  20032. for (var i = 0, len = pipeLen; i < len; i++) {
  20033. var transOption = pipedTransOption[i];
  20034. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  20035. // piped transform only support single output, except the last one.
  20036. if (i !== len - 1) {
  20037. sourceList.length = Math.max(sourceList.length, 1);
  20038. }
  20039. }
  20040. return sourceList;
  20041. }
  20042. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  20043. pipeIndex) {
  20044. var errMsg = '';
  20045. if (!upSourceList.length) {
  20046. if ("development" !== 'production') {
  20047. errMsg = 'Must have at least one upstream dataset.';
  20048. }
  20049. throwError(errMsg);
  20050. }
  20051. if (!isObject(transOption)) {
  20052. if ("development" !== 'production') {
  20053. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20054. }
  20055. throwError(errMsg);
  20056. }
  20057. var transType = transOption.type;
  20058. var externalTransform = externalTransformMap.get(transType);
  20059. if (!externalTransform) {
  20060. if ("development" !== 'production') {
  20061. errMsg = 'Can not find transform on type "' + transType + '".';
  20062. }
  20063. throwError(errMsg);
  20064. } // Prepare source
  20065. var extUpSourceList = map(upSourceList, function (upSource) {
  20066. return createExternalSource(upSource, externalTransform);
  20067. });
  20068. var resultList = normalizeToArray(externalTransform.transform({
  20069. upstream: extUpSourceList[0],
  20070. upstreamList: extUpSourceList,
  20071. config: clone(transOption.config)
  20072. }));
  20073. if ("development" !== 'production') {
  20074. if (transOption.print) {
  20075. var printStrArr = map(resultList, function (extSource) {
  20076. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20077. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20078. }).join('\n');
  20079. log(printStrArr);
  20080. }
  20081. }
  20082. return map(resultList, function (result, resultIndex) {
  20083. var errMsg = '';
  20084. if (!isObject(result)) {
  20085. if ("development" !== 'production') {
  20086. errMsg = 'A transform should not return some empty results.';
  20087. }
  20088. throwError(errMsg);
  20089. }
  20090. if (!result.data) {
  20091. if ("development" !== 'production') {
  20092. errMsg = 'Transform result data should be not be null or undefined';
  20093. }
  20094. throwError(errMsg);
  20095. }
  20096. var sourceFormat = detectSourceFormat(result.data);
  20097. if (!isSupportedSourceFormat(sourceFormat)) {
  20098. if ("development" !== 'production') {
  20099. errMsg = 'Transform result data should be array rows or object rows.';
  20100. }
  20101. throwError(errMsg);
  20102. }
  20103. var resultMetaRawOption;
  20104. var firstUpSource = upSourceList[0];
  20105. /**
  20106. * Intuitively, the end users known the content of the original `dataset.source`,
  20107. * calucating the transform result in mind.
  20108. * Suppose the original `dataset.source` is:
  20109. * ```js
  20110. * [
  20111. * ['product', '2012', '2013', '2014', '2015'],
  20112. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20113. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20114. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20115. * ]
  20116. * ```
  20117. * The dimension info have to be detected from the source data.
  20118. * Some of the transformers (like filter, sort) will follow the dimension info
  20119. * of upstream, while others use new dimensions (like aggregate).
  20120. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20121. * We also allow transformers to ignore the output `dimensions` field, and
  20122. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20123. * dimensions in transformers.
  20124. *
  20125. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20126. */
  20127. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20128. // dimensions definitions. We do not inherit anything from upstream.
  20129. && !result.dimensions) {
  20130. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result, because:
  20131. // (1) The returned data always does not contain header line and can not be used
  20132. // as dimension-detection. In this case we can not use "detected dimensions" of
  20133. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20134. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20135. // So the original detected header should be add to the result, otherwise they can not be read.
  20136. if (startIndex) {
  20137. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20138. }
  20139. resultMetaRawOption = {
  20140. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20141. sourceHeader: startIndex,
  20142. dimensions: firstUpSource.metaRawOption.dimensions
  20143. };
  20144. } else {
  20145. resultMetaRawOption = {
  20146. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20147. sourceHeader: 0,
  20148. dimensions: result.dimensions
  20149. };
  20150. }
  20151. return createSource(result.data, resultMetaRawOption, null);
  20152. });
  20153. }
  20154. function isSupportedSourceFormat(sourceFormat) {
  20155. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20156. }
  20157. var UNDEFINED = 'undefined';
  20158. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20159. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20160. // different from the Ctor of typed array.
  20161. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20162. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20163. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20164. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20165. /**
  20166. * Multi dimensional data store
  20167. */
  20168. var dataCtors = {
  20169. 'float': CtorFloat64Array,
  20170. 'int': CtorInt32Array,
  20171. // Ordinal data type can be string or int
  20172. 'ordinal': Array,
  20173. 'number': Array,
  20174. 'time': CtorFloat64Array
  20175. };
  20176. var defaultDimValueGetters;
  20177. function getIndicesCtor(rawCount) {
  20178. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20179. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20180. }
  20181. function getInitialExtent() {
  20182. return [Infinity, -Infinity];
  20183. }
  20184. function cloneChunk(originalChunk) {
  20185. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20186. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20187. }
  20188. function prepareStore(store, dimIdx, dimType, end, append) {
  20189. var DataCtor = dataCtors[dimType || 'float'];
  20190. if (append) {
  20191. var oldStore = store[dimIdx];
  20192. var oldLen = oldStore && oldStore.length;
  20193. if (!(oldLen === end)) {
  20194. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20195. // within the initial chunkSize.
  20196. for (var j = 0; j < oldLen; j++) {
  20197. newStore[j] = oldStore[j];
  20198. }
  20199. store[dimIdx] = newStore;
  20200. }
  20201. } else {
  20202. store[dimIdx] = new DataCtor(end);
  20203. }
  20204. }
  20205. /**
  20206. * Basically, DataStore API keep immutable.
  20207. */
  20208. var DataStore =
  20209. /** @class */
  20210. function () {
  20211. function DataStore() {
  20212. this._chunks = []; // It will not be calculated until needed.
  20213. this._rawExtent = [];
  20214. this._extent = [];
  20215. this._count = 0;
  20216. this._rawCount = 0;
  20217. this._calcDimNameToIdx = createHashMap();
  20218. }
  20219. /**
  20220. * Initialize from data
  20221. */
  20222. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20223. if ("development" !== 'production') {
  20224. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20225. }
  20226. this._provider = provider; // Clear
  20227. this._chunks = [];
  20228. this._indices = null;
  20229. this.getRawIndex = this._getRawIdxIdentity;
  20230. var source = provider.getSource();
  20231. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20232. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20233. this._rawExtent = [];
  20234. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20235. this._dimensions = map(inputDimensions, function (dim) {
  20236. if ("development" !== 'production') {
  20237. if (willRetrieveDataByName) {
  20238. assert(dim.property != null);
  20239. }
  20240. }
  20241. return {
  20242. // Only pick these two props. Not leak other properties like orderMeta.
  20243. type: dim.type,
  20244. property: dim.property
  20245. };
  20246. });
  20247. this._initDataFromProvider(0, provider.count());
  20248. };
  20249. DataStore.prototype.getProvider = function () {
  20250. return this._provider;
  20251. };
  20252. /**
  20253. * Caution: even when a `source` instance owned by a series, the created data store
  20254. * may still be shared by different sereis (the source hash does not use all `source`
  20255. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20256. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20257. * thus should not be fetch here.
  20258. */
  20259. DataStore.prototype.getSource = function () {
  20260. return this._provider.getSource();
  20261. };
  20262. /**
  20263. * @caution Only used in dataStack.
  20264. */
  20265. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20266. var calcDimNameToIdx = this._calcDimNameToIdx;
  20267. var dimensions = this._dimensions;
  20268. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20269. if (calcDimIdx != null) {
  20270. if (dimensions[calcDimIdx].type === type) {
  20271. return calcDimIdx;
  20272. }
  20273. } else {
  20274. calcDimIdx = dimensions.length;
  20275. }
  20276. dimensions[calcDimIdx] = {
  20277. type: type
  20278. };
  20279. calcDimNameToIdx.set(dimName, calcDimIdx);
  20280. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20281. this._rawExtent[calcDimIdx] = getInitialExtent();
  20282. return calcDimIdx;
  20283. };
  20284. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20285. var chunk = this._chunks[dimIdx];
  20286. var dim = this._dimensions[dimIdx];
  20287. var rawExtents = this._rawExtent;
  20288. var offset = dim.ordinalOffset || 0;
  20289. var len = chunk.length;
  20290. if (offset === 0) {
  20291. // We need to reset the rawExtent if collect is from start.
  20292. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20293. rawExtents[dimIdx] = getInitialExtent();
  20294. }
  20295. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20296. for (var i = offset; i < len; i++) {
  20297. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20298. if (!isNaN(val)) {
  20299. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20300. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20301. }
  20302. }
  20303. dim.ordinalMeta = ordinalMeta;
  20304. dim.ordinalOffset = len;
  20305. dim.type = 'ordinal'; // Force to be ordinal
  20306. };
  20307. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20308. var dimInfo = this._dimensions[dimIdx];
  20309. var ordinalMeta = dimInfo.ordinalMeta;
  20310. return ordinalMeta;
  20311. };
  20312. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20313. var item = this._dimensions[dimIndex];
  20314. return item && item.property;
  20315. };
  20316. /**
  20317. * Caution: Can be only called on raw data (before `this._indices` created).
  20318. */
  20319. DataStore.prototype.appendData = function (data) {
  20320. if ("development" !== 'production') {
  20321. assert(!this._indices, 'appendData can only be called on raw data.');
  20322. }
  20323. var provider = this._provider;
  20324. var start = this.count();
  20325. provider.appendData(data);
  20326. var end = provider.count();
  20327. if (!provider.persistent) {
  20328. end += start;
  20329. }
  20330. if (start < end) {
  20331. this._initDataFromProvider(start, end, true);
  20332. }
  20333. return [start, end];
  20334. };
  20335. DataStore.prototype.appendValues = function (values, minFillLen) {
  20336. var chunks = this._chunks;
  20337. var dimensions = this._dimensions;
  20338. var dimLen = dimensions.length;
  20339. var rawExtent = this._rawExtent;
  20340. var start = this.count();
  20341. var end = start + Math.max(values.length, minFillLen || 0);
  20342. for (var i = 0; i < dimLen; i++) {
  20343. var dim = dimensions[i];
  20344. prepareStore(chunks, i, dim.type, end, true);
  20345. }
  20346. var emptyDataItem = [];
  20347. for (var idx = start; idx < end; idx++) {
  20348. var sourceIdx = idx - start; // Store the data by dimensions
  20349. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20350. var dim = dimensions[dimIdx];
  20351. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20352. chunks[dimIdx][idx] = val;
  20353. var dimRawExtent = rawExtent[dimIdx];
  20354. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20355. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20356. }
  20357. }
  20358. this._rawCount = this._count = end;
  20359. return {
  20360. start: start,
  20361. end: end
  20362. };
  20363. };
  20364. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20365. var provider = this._provider;
  20366. var chunks = this._chunks;
  20367. var dimensions = this._dimensions;
  20368. var dimLen = dimensions.length;
  20369. var rawExtent = this._rawExtent;
  20370. var dimNames = map(dimensions, function (dim) {
  20371. return dim.property;
  20372. });
  20373. for (var i = 0; i < dimLen; i++) {
  20374. var dim = dimensions[i];
  20375. if (!rawExtent[i]) {
  20376. rawExtent[i] = getInitialExtent();
  20377. }
  20378. prepareStore(chunks, i, dim.type, end, append);
  20379. }
  20380. if (provider.fillStorage) {
  20381. provider.fillStorage(start, end, chunks, rawExtent);
  20382. } else {
  20383. var dataItem = [];
  20384. for (var idx = start; idx < end; idx++) {
  20385. // NOTICE: Try not to write things into dataItem
  20386. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20387. // [1, 2]
  20388. // 2
  20389. // Bar chart, line chart which uses category axis
  20390. // only gives the 'y' value. 'x' value is the indices of category
  20391. // Use a tempValue to normalize the value to be a (x, y) value
  20392. // Store the data by dimensions
  20393. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20394. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20395. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20396. dimStorage[idx] = val;
  20397. var dimRawExtent = rawExtent[dimIdx];
  20398. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20399. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20400. }
  20401. }
  20402. }
  20403. if (!provider.persistent && provider.clean) {
  20404. // Clean unused data if data source is typed array.
  20405. provider.clean();
  20406. }
  20407. this._rawCount = this._count = end; // Reset data extent
  20408. this._extent = [];
  20409. };
  20410. DataStore.prototype.count = function () {
  20411. return this._count;
  20412. };
  20413. /**
  20414. * Get value. Return NaN if idx is out of range.
  20415. */
  20416. DataStore.prototype.get = function (dim, idx) {
  20417. if (!(idx >= 0 && idx < this._count)) {
  20418. return NaN;
  20419. }
  20420. var dimStore = this._chunks[dim];
  20421. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20422. };
  20423. DataStore.prototype.getValues = function (dimensions, idx) {
  20424. var values = [];
  20425. var dimArr = [];
  20426. if (idx == null) {
  20427. idx = dimensions; // TODO get all from store?
  20428. dimensions = []; // All dimensions
  20429. for (var i = 0; i < this._dimensions.length; i++) {
  20430. dimArr.push(i);
  20431. }
  20432. } else {
  20433. dimArr = dimensions;
  20434. }
  20435. for (var i = 0, len = dimArr.length; i < len; i++) {
  20436. values.push(this.get(dimArr[i], idx));
  20437. }
  20438. return values;
  20439. };
  20440. /**
  20441. * @param dim concrete dim
  20442. */
  20443. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20444. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20445. return NaN;
  20446. }
  20447. var dimStore = this._chunks[dim];
  20448. return dimStore ? dimStore[rawIdx] : NaN;
  20449. };
  20450. /**
  20451. * Get sum of data in one dimension
  20452. */
  20453. DataStore.prototype.getSum = function (dim) {
  20454. var dimData = this._chunks[dim];
  20455. var sum = 0;
  20456. if (dimData) {
  20457. for (var i = 0, len = this.count(); i < len; i++) {
  20458. var value = this.get(dim, i);
  20459. if (!isNaN(value)) {
  20460. sum += value;
  20461. }
  20462. }
  20463. }
  20464. return sum;
  20465. };
  20466. /**
  20467. * Get median of data in one dimension
  20468. */
  20469. DataStore.prototype.getMedian = function (dim) {
  20470. var dimDataArray = []; // map all data of one dimension
  20471. this.each([dim], function (val) {
  20472. if (!isNaN(val)) {
  20473. dimDataArray.push(val);
  20474. }
  20475. }); // TODO
  20476. // Use quick select?
  20477. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20478. return a - b;
  20479. });
  20480. var len = this.count(); // calculate median
  20481. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20482. };
  20483. /**
  20484. * Retrieve the index with given raw data index.
  20485. */
  20486. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20487. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20488. return -1;
  20489. }
  20490. if (!this._indices) {
  20491. return rawIndex;
  20492. } // Indices are ascending
  20493. var indices = this._indices; // If rawIndex === dataIndex
  20494. var rawDataIndex = indices[rawIndex];
  20495. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20496. return rawIndex;
  20497. }
  20498. var left = 0;
  20499. var right = this._count - 1;
  20500. while (left <= right) {
  20501. var mid = (left + right) / 2 | 0;
  20502. if (indices[mid] < rawIndex) {
  20503. left = mid + 1;
  20504. } else if (indices[mid] > rawIndex) {
  20505. right = mid - 1;
  20506. } else {
  20507. return mid;
  20508. }
  20509. }
  20510. return -1;
  20511. };
  20512. /**
  20513. * Retrieve the index of nearest value.
  20514. * @param dim
  20515. * @param value
  20516. * @param [maxDistance=Infinity]
  20517. * @return If and only if multiple indices have
  20518. * the same value, they are put to the result.
  20519. */
  20520. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20521. var chunks = this._chunks;
  20522. var dimData = chunks[dim];
  20523. var nearestIndices = [];
  20524. if (!dimData) {
  20525. return nearestIndices;
  20526. }
  20527. if (maxDistance == null) {
  20528. maxDistance = Infinity;
  20529. }
  20530. var minDist = Infinity;
  20531. var minDiff = -1;
  20532. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20533. for (var i = 0, len = this.count(); i < len; i++) {
  20534. var dataIndex = this.getRawIndex(i);
  20535. var diff = value - dimData[dataIndex];
  20536. var dist = Math.abs(diff);
  20537. if (dist <= maxDistance) {
  20538. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20539. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20540. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20541. // So we choose the one that `diff >= 0` in this case.
  20542. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20543. // should be push to `nearestIndices`.
  20544. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20545. minDist = dist;
  20546. minDiff = diff;
  20547. nearestIndicesLen = 0;
  20548. }
  20549. if (diff === minDiff) {
  20550. nearestIndices[nearestIndicesLen++] = i;
  20551. }
  20552. }
  20553. }
  20554. nearestIndices.length = nearestIndicesLen;
  20555. return nearestIndices;
  20556. };
  20557. DataStore.prototype.getIndices = function () {
  20558. var newIndices;
  20559. var indices = this._indices;
  20560. if (indices) {
  20561. var Ctor = indices.constructor;
  20562. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20563. if (Ctor === Array) {
  20564. newIndices = new Ctor(thisCount);
  20565. for (var i = 0; i < thisCount; i++) {
  20566. newIndices[i] = indices[i];
  20567. }
  20568. } else {
  20569. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20570. }
  20571. } else {
  20572. var Ctor = getIndicesCtor(this._rawCount);
  20573. newIndices = new Ctor(this.count());
  20574. for (var i = 0; i < newIndices.length; i++) {
  20575. newIndices[i] = i;
  20576. }
  20577. }
  20578. return newIndices;
  20579. };
  20580. /**
  20581. * Data filter.
  20582. */
  20583. DataStore.prototype.filter = function (dims, cb) {
  20584. if (!this._count) {
  20585. return this;
  20586. }
  20587. var newStore = this.clone();
  20588. var count = newStore.count();
  20589. var Ctor = getIndicesCtor(newStore._rawCount);
  20590. var newIndices = new Ctor(count);
  20591. var value = [];
  20592. var dimSize = dims.length;
  20593. var offset = 0;
  20594. var dim0 = dims[0];
  20595. var chunks = newStore._chunks;
  20596. for (var i = 0; i < count; i++) {
  20597. var keep = void 0;
  20598. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20599. if (dimSize === 0) {
  20600. keep = cb(i);
  20601. } else if (dimSize === 1) {
  20602. var val = chunks[dim0][rawIdx];
  20603. keep = cb(val, i);
  20604. } else {
  20605. var k = 0;
  20606. for (; k < dimSize; k++) {
  20607. value[k] = chunks[dims[k]][rawIdx];
  20608. }
  20609. value[k] = i;
  20610. keep = cb.apply(null, value);
  20611. }
  20612. if (keep) {
  20613. newIndices[offset++] = rawIdx;
  20614. }
  20615. } // Set indices after filtered.
  20616. if (offset < count) {
  20617. newStore._indices = newIndices;
  20618. }
  20619. newStore._count = offset; // Reset data extent
  20620. newStore._extent = [];
  20621. newStore._updateGetRawIdx();
  20622. return newStore;
  20623. };
  20624. /**
  20625. * Select data in range. (For optimization of filter)
  20626. * (Manually inline code, support 5 million data filtering in data zoom.)
  20627. */
  20628. DataStore.prototype.selectRange = function (range) {
  20629. var newStore = this.clone();
  20630. var len = newStore._count;
  20631. if (!len) {
  20632. return this;
  20633. }
  20634. var dims = keys(range);
  20635. var dimSize = dims.length;
  20636. if (!dimSize) {
  20637. return this;
  20638. }
  20639. var originalCount = newStore.count();
  20640. var Ctor = getIndicesCtor(newStore._rawCount);
  20641. var newIndices = new Ctor(originalCount);
  20642. var offset = 0;
  20643. var dim0 = dims[0];
  20644. var min = range[dim0][0];
  20645. var max = range[dim0][1];
  20646. var storeArr = newStore._chunks;
  20647. var quickFinished = false;
  20648. if (!newStore._indices) {
  20649. // Extreme optimization for common case. About 2x faster in chrome.
  20650. var idx = 0;
  20651. if (dimSize === 1) {
  20652. var dimStorage = storeArr[dims[0]];
  20653. for (var i = 0; i < len; i++) {
  20654. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20655. // value indicates the line should be broken. But for the case like
  20656. // scatter plot, a data item with empty value will not be rendered,
  20657. // but the axis extent may be effected if some other dim of the data
  20658. // item has value. Fortunately it is not a significant negative effect.
  20659. if (val >= min && val <= max || isNaN(val)) {
  20660. newIndices[offset++] = idx;
  20661. }
  20662. idx++;
  20663. }
  20664. quickFinished = true;
  20665. } else if (dimSize === 2) {
  20666. var dimStorage = storeArr[dims[0]];
  20667. var dimStorage2 = storeArr[dims[1]];
  20668. var min2 = range[dims[1]][0];
  20669. var max2 = range[dims[1]][1];
  20670. for (var i = 0; i < len; i++) {
  20671. var val = dimStorage[i];
  20672. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20673. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20674. newIndices[offset++] = idx;
  20675. }
  20676. idx++;
  20677. }
  20678. quickFinished = true;
  20679. }
  20680. }
  20681. if (!quickFinished) {
  20682. if (dimSize === 1) {
  20683. for (var i = 0; i < originalCount; i++) {
  20684. var rawIndex = newStore.getRawIndex(i);
  20685. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20686. if (val >= min && val <= max || isNaN(val)) {
  20687. newIndices[offset++] = rawIndex;
  20688. }
  20689. }
  20690. } else {
  20691. for (var i = 0; i < originalCount; i++) {
  20692. var keep = true;
  20693. var rawIndex = newStore.getRawIndex(i);
  20694. for (var k = 0; k < dimSize; k++) {
  20695. var dimk = dims[k];
  20696. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20697. if (val < range[dimk][0] || val > range[dimk][1]) {
  20698. keep = false;
  20699. }
  20700. }
  20701. if (keep) {
  20702. newIndices[offset++] = newStore.getRawIndex(i);
  20703. }
  20704. }
  20705. }
  20706. } // Set indices after filtered.
  20707. if (offset < originalCount) {
  20708. newStore._indices = newIndices;
  20709. }
  20710. newStore._count = offset; // Reset data extent
  20711. newStore._extent = [];
  20712. newStore._updateGetRawIdx();
  20713. return newStore;
  20714. }; // /**
  20715. // * Data mapping to a plain array
  20716. // */
  20717. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  20718. // const result: any[] = [];
  20719. // this.each(dims, function () {
  20720. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  20721. // });
  20722. // return result;
  20723. // }
  20724. /**
  20725. * Data mapping to a new List with given dimensions
  20726. */
  20727. DataStore.prototype.map = function (dims, cb) {
  20728. // TODO only clone picked chunks.
  20729. var target = this.clone(dims);
  20730. this._updateDims(target, dims, cb);
  20731. return target;
  20732. };
  20733. /**
  20734. * @caution Danger!! Only used in dataStack.
  20735. */
  20736. DataStore.prototype.modify = function (dims, cb) {
  20737. this._updateDims(this, dims, cb);
  20738. };
  20739. DataStore.prototype._updateDims = function (target, dims, cb) {
  20740. var targetChunks = target._chunks;
  20741. var tmpRetValue = [];
  20742. var dimSize = dims.length;
  20743. var dataCount = target.count();
  20744. var values = [];
  20745. var rawExtent = target._rawExtent;
  20746. for (var i = 0; i < dims.length; i++) {
  20747. rawExtent[dims[i]] = getInitialExtent();
  20748. }
  20749. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  20750. var rawIndex = target.getRawIndex(dataIndex);
  20751. for (var k = 0; k < dimSize; k++) {
  20752. values[k] = targetChunks[dims[k]][rawIndex];
  20753. }
  20754. values[dimSize] = dataIndex;
  20755. var retValue = cb && cb.apply(null, values);
  20756. if (retValue != null) {
  20757. // a number or string (in oridinal dimension)?
  20758. if (typeof retValue !== 'object') {
  20759. tmpRetValue[0] = retValue;
  20760. retValue = tmpRetValue;
  20761. }
  20762. for (var i = 0; i < retValue.length; i++) {
  20763. var dim = dims[i];
  20764. var val = retValue[i];
  20765. var rawExtentOnDim = rawExtent[dim];
  20766. var dimStore = targetChunks[dim];
  20767. if (dimStore) {
  20768. dimStore[rawIndex] = val;
  20769. }
  20770. if (val < rawExtentOnDim[0]) {
  20771. rawExtentOnDim[0] = val;
  20772. }
  20773. if (val > rawExtentOnDim[1]) {
  20774. rawExtentOnDim[1] = val;
  20775. }
  20776. }
  20777. }
  20778. }
  20779. };
  20780. /**
  20781. * Large data down sampling using largest-triangle-three-buckets
  20782. * @param {string} valueDimension
  20783. * @param {number} targetCount
  20784. */
  20785. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  20786. var target = this.clone([valueDimension], true);
  20787. var targetStorage = target._chunks;
  20788. var dimStore = targetStorage[valueDimension];
  20789. var len = this.count();
  20790. var sampledIndex = 0;
  20791. var frameSize = Math.floor(1 / rate);
  20792. var currentRawIndex = this.getRawIndex(0);
  20793. var maxArea;
  20794. var area;
  20795. var nextRawIndex;
  20796. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  20797. newIndices[sampledIndex++] = currentRawIndex;
  20798. for (var i = 1; i < len - 1; i += frameSize) {
  20799. var nextFrameStart = Math.min(i + frameSize, len - 1);
  20800. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  20801. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  20802. var avgY = 0;
  20803. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  20804. var rawIndex = this.getRawIndex(idx);
  20805. var y = dimStore[rawIndex];
  20806. if (isNaN(y)) {
  20807. continue;
  20808. }
  20809. avgY += y;
  20810. }
  20811. avgY /= nextFrameEnd - nextFrameStart;
  20812. var frameStart = i;
  20813. var frameEnd = Math.min(i + frameSize, len);
  20814. var pointAX = i - 1;
  20815. var pointAY = dimStore[currentRawIndex];
  20816. maxArea = -1;
  20817. nextRawIndex = frameStart;
  20818. var firstNaNIndex = -1;
  20819. var countNaN = 0; // Find a point from current frame that construct a triangle with largest area with previous selected point
  20820. // And the average of next frame.
  20821. for (var idx = frameStart; idx < frameEnd; idx++) {
  20822. var rawIndex = this.getRawIndex(idx);
  20823. var y = dimStore[rawIndex];
  20824. if (isNaN(y)) {
  20825. countNaN++;
  20826. if (firstNaNIndex < 0) {
  20827. firstNaNIndex = rawIndex;
  20828. }
  20829. continue;
  20830. } // Calculate triangle area over three buckets
  20831. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  20832. if (area > maxArea) {
  20833. maxArea = area;
  20834. nextRawIndex = rawIndex; // Next a is this b
  20835. }
  20836. }
  20837. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  20838. // Append first NaN point in every bucket.
  20839. // It is necessary to ensure the correct order of indices.
  20840. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  20841. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  20842. }
  20843. newIndices[sampledIndex++] = nextRawIndex;
  20844. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  20845. } // First frame use the last data.
  20846. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  20847. target._count = sampledIndex;
  20848. target._indices = newIndices;
  20849. target.getRawIndex = this._getRawIdx;
  20850. return target;
  20851. };
  20852. /**
  20853. * Large data down sampling on given dimension
  20854. * @param sampleIndex Sample index for name and id
  20855. */
  20856. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20857. var target = this.clone([dimension], true);
  20858. var targetStorage = target._chunks;
  20859. var frameValues = [];
  20860. var frameSize = Math.floor(1 / rate);
  20861. var dimStore = targetStorage[dimension];
  20862. var len = this.count();
  20863. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  20864. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  20865. var offset = 0;
  20866. for (var i = 0; i < len; i += frameSize) {
  20867. // Last frame
  20868. if (frameSize > len - i) {
  20869. frameSize = len - i;
  20870. frameValues.length = frameSize;
  20871. }
  20872. for (var k = 0; k < frameSize; k++) {
  20873. var dataIdx = this.getRawIndex(i + k);
  20874. frameValues[k] = dimStore[dataIdx];
  20875. }
  20876. var value = sampleValue(frameValues);
  20877. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  20878. dimStore[sampleFrameIdx] = value;
  20879. if (value < rawExtentOnDim[0]) {
  20880. rawExtentOnDim[0] = value;
  20881. }
  20882. if (value > rawExtentOnDim[1]) {
  20883. rawExtentOnDim[1] = value;
  20884. }
  20885. newIndices[offset++] = sampleFrameIdx;
  20886. }
  20887. target._count = offset;
  20888. target._indices = newIndices;
  20889. target._updateGetRawIdx();
  20890. return target;
  20891. };
  20892. /**
  20893. * Data iteration
  20894. * @param ctx default this
  20895. * @example
  20896. * list.each('x', function (x, idx) {});
  20897. * list.each(['x', 'y'], function (x, y, idx) {});
  20898. * list.each(function (idx) {})
  20899. */
  20900. DataStore.prototype.each = function (dims, cb) {
  20901. if (!this._count) {
  20902. return;
  20903. }
  20904. var dimSize = dims.length;
  20905. var chunks = this._chunks;
  20906. for (var i = 0, len = this.count(); i < len; i++) {
  20907. var rawIdx = this.getRawIndex(i); // Simple optimization
  20908. switch (dimSize) {
  20909. case 0:
  20910. cb(i);
  20911. break;
  20912. case 1:
  20913. cb(chunks[dims[0]][rawIdx], i);
  20914. break;
  20915. case 2:
  20916. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  20917. break;
  20918. default:
  20919. var k = 0;
  20920. var value = [];
  20921. for (; k < dimSize; k++) {
  20922. value[k] = chunks[dims[k]][rawIdx];
  20923. } // Index
  20924. value[k] = i;
  20925. cb.apply(null, value);
  20926. }
  20927. }
  20928. };
  20929. /**
  20930. * Get extent of data in one dimension
  20931. */
  20932. DataStore.prototype.getDataExtent = function (dim) {
  20933. // Make sure use concrete dim as cache name.
  20934. var dimData = this._chunks[dim];
  20935. var initialExtent = getInitialExtent();
  20936. if (!dimData) {
  20937. return initialExtent;
  20938. } // Make more strict checkings to ensure hitting cache.
  20939. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  20940. // happened before filtering. We cache raw extent, which is not
  20941. // necessary to be cleared and recalculated when restore data.
  20942. var useRaw = !this._indices;
  20943. var dimExtent;
  20944. if (useRaw) {
  20945. return this._rawExtent[dim].slice();
  20946. }
  20947. dimExtent = this._extent[dim];
  20948. if (dimExtent) {
  20949. return dimExtent.slice();
  20950. }
  20951. dimExtent = initialExtent;
  20952. var min = dimExtent[0];
  20953. var max = dimExtent[1];
  20954. for (var i = 0; i < currEnd; i++) {
  20955. var rawIdx = this.getRawIndex(i);
  20956. var value = dimData[rawIdx];
  20957. value < min && (min = value);
  20958. value > max && (max = value);
  20959. }
  20960. dimExtent = [min, max];
  20961. this._extent[dim] = dimExtent;
  20962. return dimExtent;
  20963. };
  20964. /**
  20965. * Get raw data item
  20966. */
  20967. DataStore.prototype.getRawDataItem = function (idx) {
  20968. var rawIdx = this.getRawIndex(idx);
  20969. if (!this._provider.persistent) {
  20970. var val = [];
  20971. var chunks = this._chunks;
  20972. for (var i = 0; i < chunks.length; i++) {
  20973. val.push(chunks[i][rawIdx]);
  20974. }
  20975. return val;
  20976. } else {
  20977. return this._provider.getItem(rawIdx);
  20978. }
  20979. };
  20980. /**
  20981. * Clone shallow.
  20982. *
  20983. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  20984. */
  20985. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  20986. var target = new DataStore();
  20987. var chunks = this._chunks;
  20988. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  20989. obj[dimIdx] = true;
  20990. return obj;
  20991. }, {});
  20992. if (clonedDimsMap) {
  20993. for (var i = 0; i < chunks.length; i++) {
  20994. // Not clone if dim is not picked.
  20995. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  20996. }
  20997. } else {
  20998. target._chunks = chunks;
  20999. }
  21000. this._copyCommonProps(target);
  21001. if (!ignoreIndices) {
  21002. target._indices = this._cloneIndices();
  21003. }
  21004. target._updateGetRawIdx();
  21005. return target;
  21006. };
  21007. DataStore.prototype._copyCommonProps = function (target) {
  21008. target._count = this._count;
  21009. target._rawCount = this._rawCount;
  21010. target._provider = this._provider;
  21011. target._dimensions = this._dimensions;
  21012. target._extent = clone(this._extent);
  21013. target._rawExtent = clone(this._rawExtent);
  21014. };
  21015. DataStore.prototype._cloneIndices = function () {
  21016. if (this._indices) {
  21017. var Ctor = this._indices.constructor;
  21018. var indices = void 0;
  21019. if (Ctor === Array) {
  21020. var thisCount = this._indices.length;
  21021. indices = new Ctor(thisCount);
  21022. for (var i = 0; i < thisCount; i++) {
  21023. indices[i] = this._indices[i];
  21024. }
  21025. } else {
  21026. indices = new Ctor(this._indices);
  21027. }
  21028. return indices;
  21029. }
  21030. return null;
  21031. };
  21032. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21033. return idx;
  21034. };
  21035. DataStore.prototype._getRawIdx = function (idx) {
  21036. if (idx < this._count && idx >= 0) {
  21037. return this._indices[idx];
  21038. }
  21039. return -1;
  21040. };
  21041. DataStore.prototype._updateGetRawIdx = function () {
  21042. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21043. };
  21044. DataStore.internalField = function () {
  21045. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21046. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21047. }
  21048. defaultDimValueGetters = {
  21049. arrayRows: getDimValueSimply,
  21050. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21051. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21052. },
  21053. keyedColumns: getDimValueSimply,
  21054. original: function (dataItem, property, dataIndex, dimIndex) {
  21055. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21056. // If dataItem is an plain object with no value field, the let `value`
  21057. // will be assigned with the object, but it will be tread correctly
  21058. // in the `convertValue`.
  21059. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21060. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  21061. : value, this._dimensions[dimIndex]);
  21062. },
  21063. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21064. return dataItem[dimIndex];
  21065. }
  21066. };
  21067. }();
  21068. return DataStore;
  21069. }();
  21070. /**
  21071. * [REQUIREMENT_MEMO]:
  21072. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21073. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21074. * `root-dataset`. Them on `series` has higher priority.
  21075. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21076. * confuse users: whether those props indicate how to visit the upstream source or visit
  21077. * the transform result source, and some transforms has nothing to do with these props,
  21078. * and some transforms might have multiple upstream.
  21079. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21080. * declared in `root-dataset`.
  21081. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21082. * That is for reducing complexity in transforms.
  21083. * PENDING: Whether to provide transposition transform?
  21084. *
  21085. * [IMPLEMENTAION_MEMO]:
  21086. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21087. * They will not be calculated until `source` is about to be visited (to prevent from
  21088. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21089. *
  21090. * [DIMENSION_INHERIT_RULE]:
  21091. * By default the dimensions are inherited from ancestors, unless a transform return
  21092. * a new dimensions definition.
  21093. * Consider the case:
  21094. * ```js
  21095. * dataset: [{
  21096. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21097. * }, {
  21098. * transform: { type: 'filter', ... }
  21099. * }]
  21100. * dataset: [{
  21101. * dimension: ['Product', 'Sales', 'Prise'],
  21102. * source: [ ['Cookies', 321, 44.21], ...]
  21103. * }, {
  21104. * transform: { type: 'filter', ... }
  21105. * }]
  21106. * ```
  21107. * The two types of option should have the same behavior after transform.
  21108. *
  21109. *
  21110. * [SCENARIO]:
  21111. * (1) Provide source data directly:
  21112. * ```js
  21113. * series: {
  21114. * encode: {...},
  21115. * dimensions: [...]
  21116. * seriesLayoutBy: 'row',
  21117. * data: [[...]]
  21118. * }
  21119. * ```
  21120. * (2) Series refer to dataset.
  21121. * ```js
  21122. * series: [{
  21123. * encode: {...}
  21124. * // Ignore datasetIndex means `datasetIndex: 0`
  21125. * // and the dimensions defination in dataset is used
  21126. * }, {
  21127. * encode: {...},
  21128. * seriesLayoutBy: 'column',
  21129. * datasetIndex: 1
  21130. * }]
  21131. * ```
  21132. * (3) dataset transform
  21133. * ```js
  21134. * dataset: [{
  21135. * source: [...]
  21136. * }, {
  21137. * source: [...]
  21138. * }, {
  21139. * // By default from 0.
  21140. * transform: { type: 'filter', config: {...} }
  21141. * }, {
  21142. * // Piped.
  21143. * transform: [
  21144. * { type: 'filter', config: {...} },
  21145. * { type: 'sort', config: {...} }
  21146. * ]
  21147. * }, {
  21148. * id: 'regressionData',
  21149. * fromDatasetIndex: 1,
  21150. * // Third-party transform
  21151. * transform: { type: 'ecStat:regression', config: {...} }
  21152. * }, {
  21153. * // retrieve the extra result.
  21154. * id: 'regressionFormula',
  21155. * fromDatasetId: 'regressionData',
  21156. * fromTransformResult: 1
  21157. * }]
  21158. * ```
  21159. */
  21160. var SourceManager =
  21161. /** @class */
  21162. function () {
  21163. function SourceManager(sourceHost) {
  21164. // Cached source. Do not repeat calculating if not dirty.
  21165. this._sourceList = [];
  21166. this._storeList = []; // version sign of each upstream source manager.
  21167. this._upstreamSignList = [];
  21168. this._versionSignBase = 0;
  21169. this._dirty = true;
  21170. this._sourceHost = sourceHost;
  21171. }
  21172. /**
  21173. * Mark dirty.
  21174. */
  21175. SourceManager.prototype.dirty = function () {
  21176. this._setLocalSource([], []);
  21177. this._storeList = [];
  21178. this._dirty = true;
  21179. };
  21180. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21181. this._sourceList = sourceList;
  21182. this._upstreamSignList = upstreamSignList;
  21183. this._versionSignBase++;
  21184. if (this._versionSignBase > 9e10) {
  21185. this._versionSignBase = 0;
  21186. }
  21187. };
  21188. /**
  21189. * For detecting whether the upstream source is dirty, so that
  21190. * the local cached source (in `_sourceList`) should be discarded.
  21191. */
  21192. SourceManager.prototype._getVersionSign = function () {
  21193. return this._sourceHost.uid + '_' + this._versionSignBase;
  21194. };
  21195. /**
  21196. * Always return a source instance. Otherwise throw error.
  21197. */
  21198. SourceManager.prototype.prepareSource = function () {
  21199. // For the case that call `setOption` multiple time but no data changed,
  21200. // cache the result source to prevent from repeating transform.
  21201. if (this._isDirty()) {
  21202. this._createSource();
  21203. this._dirty = false;
  21204. }
  21205. };
  21206. SourceManager.prototype._createSource = function () {
  21207. this._setLocalSource([], []);
  21208. var sourceHost = this._sourceHost;
  21209. var upSourceMgrList = this._getUpstreamSourceManagers();
  21210. var hasUpstream = !!upSourceMgrList.length;
  21211. var resultSourceList;
  21212. var upstreamSignList;
  21213. if (isSeries(sourceHost)) {
  21214. var seriesModel = sourceHost;
  21215. var data = void 0;
  21216. var sourceFormat = void 0;
  21217. var upSource = void 0; // Has upstream dataset
  21218. if (hasUpstream) {
  21219. var upSourceMgr = upSourceMgrList[0];
  21220. upSourceMgr.prepareSource();
  21221. upSource = upSourceMgr.getSource();
  21222. data = upSource.data;
  21223. sourceFormat = upSource.sourceFormat;
  21224. upstreamSignList = [upSourceMgr._getVersionSign()];
  21225. } // Series data is from own.
  21226. else {
  21227. data = seriesModel.get('data', true);
  21228. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21229. upstreamSignList = [];
  21230. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21231. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21232. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21233. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21234. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21235. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21236. // but series need `seriesLayoutBy: 'row'`.
  21237. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21238. // to avoid extra memory cost of high dimensional data.
  21239. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21240. resultSourceList = needsCreateSource ? [createSource(data, {
  21241. seriesLayoutBy: seriesLayoutBy,
  21242. sourceHeader: sourceHeader,
  21243. dimensions: dimensions
  21244. }, sourceFormat)] : [];
  21245. } else {
  21246. var datasetModel = sourceHost; // Has upstream dataset.
  21247. if (hasUpstream) {
  21248. var result = this._applyTransform(upSourceMgrList);
  21249. resultSourceList = result.sourceList;
  21250. upstreamSignList = result.upstreamSignList;
  21251. } // Is root dataset.
  21252. else {
  21253. var sourceData = datasetModel.get('source', true);
  21254. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21255. upstreamSignList = [];
  21256. }
  21257. }
  21258. if ("development" !== 'production') {
  21259. assert(resultSourceList && upstreamSignList);
  21260. }
  21261. this._setLocalSource(resultSourceList, upstreamSignList);
  21262. };
  21263. SourceManager.prototype._applyTransform = function (upMgrList) {
  21264. var datasetModel = this._sourceHost;
  21265. var transformOption = datasetModel.get('transform', true);
  21266. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21267. if ("development" !== 'production') {
  21268. assert(fromTransformResult != null || transformOption != null);
  21269. }
  21270. if (fromTransformResult != null) {
  21271. var errMsg = '';
  21272. if (upMgrList.length !== 1) {
  21273. if ("development" !== 'production') {
  21274. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21275. }
  21276. doThrow(errMsg);
  21277. }
  21278. }
  21279. var sourceList;
  21280. var upSourceList = [];
  21281. var upstreamSignList = [];
  21282. each(upMgrList, function (upMgr) {
  21283. upMgr.prepareSource();
  21284. var upSource = upMgr.getSource(fromTransformResult || 0);
  21285. var errMsg = '';
  21286. if (fromTransformResult != null && !upSource) {
  21287. if ("development" !== 'production') {
  21288. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21289. }
  21290. doThrow(errMsg);
  21291. }
  21292. upSourceList.push(upSource);
  21293. upstreamSignList.push(upMgr._getVersionSign());
  21294. });
  21295. if (transformOption) {
  21296. sourceList = applyDataTransform(transformOption, upSourceList, {
  21297. datasetIndex: datasetModel.componentIndex
  21298. });
  21299. } else if (fromTransformResult != null) {
  21300. sourceList = [cloneSourceShallow(upSourceList[0])];
  21301. }
  21302. return {
  21303. sourceList: sourceList,
  21304. upstreamSignList: upstreamSignList
  21305. };
  21306. };
  21307. SourceManager.prototype._isDirty = function () {
  21308. if (this._dirty) {
  21309. return true;
  21310. } // All sourceList is from the some upstream.
  21311. var upSourceMgrList = this._getUpstreamSourceManagers();
  21312. for (var i = 0; i < upSourceMgrList.length; i++) {
  21313. var upSrcMgr = upSourceMgrList[i];
  21314. if ( // Consider the case that there is ancestor diry, call it recursively.
  21315. // The performance is probably not an issue because usually the chain is not long.
  21316. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21317. return true;
  21318. }
  21319. }
  21320. };
  21321. /**
  21322. * @param sourceIndex By default 0, means "main source".
  21323. * In most cases there is only one source.
  21324. */
  21325. SourceManager.prototype.getSource = function (sourceIndex) {
  21326. sourceIndex = sourceIndex || 0;
  21327. var source = this._sourceList[sourceIndex];
  21328. if (!source) {
  21329. // Series may share source instance with dataset.
  21330. var upSourceMgrList = this._getUpstreamSourceManagers();
  21331. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21332. }
  21333. return source;
  21334. };
  21335. /**
  21336. *
  21337. * Get a data store which can be shared across series.
  21338. * Only available for series.
  21339. *
  21340. * @param seriesDimRequest Dimensions that are generated in series.
  21341. * Should have been sorted by `storeDimIndex` asc.
  21342. */
  21343. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21344. if ("development" !== 'production') {
  21345. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21346. }
  21347. var schema = seriesDimRequest.makeStoreSchema();
  21348. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21349. };
  21350. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21351. // TODO Can use other sourceIndex?
  21352. var sourceIndex = 0;
  21353. var storeList = this._storeList;
  21354. var cachedStoreMap = storeList[sourceIndex];
  21355. if (!cachedStoreMap) {
  21356. cachedStoreMap = storeList[sourceIndex] = {};
  21357. }
  21358. var cachedStore = cachedStoreMap[sourceReadKey];
  21359. if (!cachedStore) {
  21360. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21361. if (isSeries(this._sourceHost) && upSourceMgr) {
  21362. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21363. } else {
  21364. cachedStore = new DataStore(); // Always create store from source of series.
  21365. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21366. }
  21367. cachedStoreMap[sourceReadKey] = cachedStore;
  21368. }
  21369. return cachedStore;
  21370. };
  21371. /**
  21372. * PENDING: Is it fast enough?
  21373. * If no upstream, return empty array.
  21374. */
  21375. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21376. // Always get the relationship from the raw option.
  21377. // Do not cache the link of the dependency graph, so that
  21378. // there is no need to update them when change happens.
  21379. var sourceHost = this._sourceHost;
  21380. if (isSeries(sourceHost)) {
  21381. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21382. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21383. } else {
  21384. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21385. return datasetModel.getSourceManager();
  21386. });
  21387. }
  21388. };
  21389. SourceManager.prototype._getSourceMetaRawOption = function () {
  21390. var sourceHost = this._sourceHost;
  21391. var seriesLayoutBy;
  21392. var sourceHeader;
  21393. var dimensions;
  21394. if (isSeries(sourceHost)) {
  21395. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21396. sourceHeader = sourceHost.get('sourceHeader', true);
  21397. dimensions = sourceHost.get('dimensions', true);
  21398. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21399. else if (!this._getUpstreamSourceManagers().length) {
  21400. var model = sourceHost;
  21401. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21402. sourceHeader = model.get('sourceHeader', true);
  21403. dimensions = model.get('dimensions', true);
  21404. }
  21405. return {
  21406. seriesLayoutBy: seriesLayoutBy,
  21407. sourceHeader: sourceHeader,
  21408. dimensions: dimensions
  21409. };
  21410. };
  21411. return SourceManager;
  21412. }();
  21413. // disable the transform merge, but do not disable transform clone from rawOption.
  21414. function disableTransformOptionMerge(datasetModel) {
  21415. var transformOption = datasetModel.option.transform;
  21416. transformOption && setAsPrimitive(datasetModel.option.transform);
  21417. }
  21418. function isSeries(sourceHost) {
  21419. // Avoid circular dependency with Series.ts
  21420. return sourceHost.mainType === 'series';
  21421. }
  21422. function doThrow(errMsg) {
  21423. throw new Error(errMsg);
  21424. }
  21425. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21426. function getTooltipTextStyle(textStyle, renderMode) {
  21427. var nameFontColor = textStyle.color || '#6e7079';
  21428. var nameFontSize = textStyle.fontSize || 12;
  21429. var nameFontWeight = textStyle.fontWeight || '400';
  21430. var valueFontColor = textStyle.color || '#464646';
  21431. var valueFontSize = textStyle.fontSize || 14;
  21432. var valueFontWeight = textStyle.fontWeight || '900';
  21433. if (renderMode === 'html') {
  21434. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21435. return {
  21436. // eslint-disable-next-line max-len
  21437. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21438. // eslint-disable-next-line max-len
  21439. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21440. };
  21441. } else {
  21442. return {
  21443. nameStyle: {
  21444. fontSize: nameFontSize,
  21445. fill: nameFontColor,
  21446. fontWeight: nameFontWeight
  21447. },
  21448. valueStyle: {
  21449. fontSize: valueFontSize,
  21450. fill: valueFontColor,
  21451. fontWeight: valueFontWeight
  21452. }
  21453. };
  21454. }
  21455. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21456. // (value from UI design)
  21457. var HTML_GAPS = [0, 10, 20, 30];
  21458. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21459. function createTooltipMarkup(type, option) {
  21460. option.type = type;
  21461. return option;
  21462. }
  21463. function isSectionFragment(frag) {
  21464. return frag.type === 'section';
  21465. }
  21466. function getBuilder(frag) {
  21467. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21468. }
  21469. function getBlockGapLevel(frag) {
  21470. if (isSectionFragment(frag)) {
  21471. var gapLevel_1 = 0;
  21472. var subBlockLen = frag.blocks.length;
  21473. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21474. each(frag.blocks, function (subBlock) {
  21475. var subGapLevel = getBlockGapLevel(subBlock); // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21476. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21477. if (subGapLevel >= gapLevel_1) {
  21478. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && ( // 0 always can not be readable gap level.
  21479. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21480. // look weird in case `multipleSeries`.
  21481. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21482. }
  21483. });
  21484. return gapLevel_1;
  21485. }
  21486. return 0;
  21487. }
  21488. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21489. var noHeader = fragment.noHeader;
  21490. var gaps = getGap(getBlockGapLevel(fragment));
  21491. var subMarkupTextList = [];
  21492. var subBlocks = fragment.blocks || [];
  21493. assert(!subBlocks || isArray(subBlocks));
  21494. subBlocks = subBlocks || [];
  21495. var orderMode = ctx.orderMode;
  21496. if (fragment.sortBlocks && orderMode) {
  21497. subBlocks = subBlocks.slice();
  21498. var orderMap = {
  21499. valueAsc: 'asc',
  21500. valueDesc: 'desc'
  21501. };
  21502. if (hasOwn(orderMap, orderMode)) {
  21503. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21504. subBlocks.sort(function (a, b) {
  21505. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21506. });
  21507. } // FIXME 'seriesDesc' necessary?
  21508. else if (orderMode === 'seriesDesc') {
  21509. subBlocks.reverse();
  21510. }
  21511. }
  21512. each(subBlocks, function (subBlock, idx) {
  21513. var valueFormatter = fragment.valueFormatter;
  21514. var subMarkupText = getBuilder(subBlock)( // Inherit valueFormatter
  21515. valueFormatter ? extend(extend({}, ctx), {
  21516. valueFormatter: valueFormatter
  21517. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21518. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21519. });
  21520. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21521. if (noHeader) {
  21522. return subMarkupText;
  21523. }
  21524. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21525. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21526. if (ctx.renderMode === 'richText') {
  21527. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21528. } else {
  21529. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21530. }
  21531. }
  21532. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21533. var renderMode = ctx.renderMode;
  21534. var noName = fragment.noName;
  21535. var noValue = fragment.noValue;
  21536. var noMarker = !fragment.markerType;
  21537. var name = fragment.name;
  21538. var useUTC = ctx.useUTC;
  21539. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21540. value = isArray(value) ? value : [value];
  21541. return map(value, function (val, idx) {
  21542. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21543. });
  21544. };
  21545. if (noName && noValue) {
  21546. return;
  21547. }
  21548. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21549. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21550. var valueTypeOption = fragment.valueType;
  21551. var readableValueList = noValue ? [] : valueFormatter(fragment.value);
  21552. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21553. var valueCloseToMarker = !noMarker && noName;
  21554. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21555. nameStyle = _a.nameStyle,
  21556. valueStyle = _a.valueStyle;
  21557. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21558. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21559. }
  21560. /**
  21561. * @return markupText. null/undefined means no content.
  21562. */
  21563. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21564. if (!fragment) {
  21565. return;
  21566. }
  21567. var builder = getBuilder(fragment);
  21568. var ctx = {
  21569. useUTC: useUTC,
  21570. renderMode: renderMode,
  21571. orderMode: orderMode,
  21572. markupStyleCreator: markupStyleCreator,
  21573. valueFormatter: fragment.valueFormatter
  21574. };
  21575. return builder(ctx, fragment, 0, toolTipTextStyle);
  21576. }
  21577. function getGap(gapLevel) {
  21578. return {
  21579. html: HTML_GAPS[gapLevel],
  21580. richText: RICH_TEXT_GAPS[gapLevel]
  21581. };
  21582. }
  21583. function wrapBlockHTML(encodedContent, topGap) {
  21584. var clearfix = '<div style="clear:both"></div>';
  21585. var marginCSS = "margin: " + topGap + "px 0 0";
  21586. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21587. }
  21588. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21589. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21590. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21591. }
  21592. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21593. // Do not too close to marker, considering there are multiple values separated by spaces.
  21594. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21595. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21596. valueList = isArray(valueList) ? valueList : [valueList];
  21597. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21598. + map(valueList, function (value) {
  21599. return encodeHTML(value);
  21600. }).join('&nbsp;&nbsp;') + '</span>';
  21601. }
  21602. function wrapInlineNameRichText(ctx, name, style) {
  21603. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21604. }
  21605. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21606. var styles = [style];
  21607. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21608. alignRight && styles.push({
  21609. padding: [0, 0, 0, paddingLeft],
  21610. align: 'right'
  21611. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21612. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  21613. }
  21614. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21615. var style = series.getData().getItemVisual(dataIndex, 'style');
  21616. var color = style[series.visualDrawType];
  21617. return convertToColorString(color);
  21618. }
  21619. function getPaddingFromTooltipModel(model, renderMode) {
  21620. var padding = model.get('padding');
  21621. return padding != null ? padding // We give slightly different to look pretty.
  21622. : renderMode === 'richText' ? [8, 10] : 10;
  21623. }
  21624. /**
  21625. * The major feature is generate styles for `renderMode: 'richText'`.
  21626. * But it also serves `renderMode: 'html'` to provide
  21627. * "renderMode-independent" API.
  21628. */
  21629. var TooltipMarkupStyleCreator =
  21630. /** @class */
  21631. function () {
  21632. function TooltipMarkupStyleCreator() {
  21633. this.richTextStyles = {}; // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  21634. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  21635. // rather than static shared by all creators (which will cause it increase to fast).
  21636. this._nextStyleNameId = getRandomIdBase();
  21637. }
  21638. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21639. return '__EC_aUTo_' + this._nextStyleNameId++;
  21640. };
  21641. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21642. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21643. var marker = getTooltipMarker({
  21644. color: colorStr,
  21645. type: markerType,
  21646. renderMode: renderMode,
  21647. markerId: markerId
  21648. });
  21649. if (isString(marker)) {
  21650. return marker;
  21651. } else {
  21652. if ("development" !== 'production') {
  21653. assert(markerId);
  21654. }
  21655. this.richTextStyles[markerId] = marker.style;
  21656. return marker.content;
  21657. }
  21658. };
  21659. /**
  21660. * @usage
  21661. * ```ts
  21662. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21663. * // The styles will be auto merged.
  21664. * {
  21665. * fontSize: 12,
  21666. * color: 'blue'
  21667. * },
  21668. * {
  21669. * padding: 20
  21670. * }
  21671. * ]);
  21672. * ```
  21673. */
  21674. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21675. var finalStl = {};
  21676. if (isArray(styles)) {
  21677. each(styles, function (stl) {
  21678. return extend(finalStl, stl);
  21679. });
  21680. } else {
  21681. extend(finalStl, styles);
  21682. }
  21683. var styleName = this._generateStyleName();
  21684. this.richTextStyles[styleName] = finalStl;
  21685. return "{" + styleName + "|" + text + "}";
  21686. };
  21687. return TooltipMarkupStyleCreator;
  21688. }();
  21689. function defaultSeriesFormatTooltip(opt) {
  21690. var series = opt.series;
  21691. var dataIndex = opt.dataIndex;
  21692. var multipleSeries = opt.multipleSeries;
  21693. var data = series.getData();
  21694. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21695. var tooltipDimLen = tooltipDims.length;
  21696. var value = series.getRawValue(dataIndex);
  21697. var isValueArr = isArray(value);
  21698. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21699. var inlineValue;
  21700. var inlineValueType;
  21701. var subBlocks;
  21702. var sortParam;
  21703. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21704. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21705. inlineValue = formatArrResult.inlineValues;
  21706. inlineValueType = formatArrResult.inlineValueTypes;
  21707. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  21708. sortParam = formatArrResult.inlineValues[0];
  21709. } else if (tooltipDimLen) {
  21710. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  21711. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  21712. inlineValueType = dimInfo.type;
  21713. } else {
  21714. sortParam = inlineValue = isValueArr ? value[0] : value;
  21715. } // Do not show generated series name. It might not be readable.
  21716. var seriesNameSpecified = isNameSpecified(series);
  21717. var seriesName = seriesNameSpecified && series.name || '';
  21718. var itemName = data.getName(dataIndex);
  21719. var inlineName = multipleSeries ? seriesName : itemName;
  21720. return createTooltipMarkup('section', {
  21721. header: seriesName,
  21722. // When series name is not specified, do not show a header line with only '-'.
  21723. // This case always happens in tooltip.trigger: 'item'.
  21724. noHeader: multipleSeries || !seriesNameSpecified,
  21725. sortParam: sortParam,
  21726. blocks: [createTooltipMarkup('nameValue', {
  21727. markerType: 'item',
  21728. markerColor: markerColor,
  21729. // Do not mix display seriesName and itemName in one tooltip,
  21730. // which might confuses users.
  21731. name: inlineName,
  21732. // name dimension might be auto assigned, where the name might
  21733. // be not readable. So we check trim here.
  21734. noName: !trim(inlineName),
  21735. value: inlineValue,
  21736. valueType: inlineValueType
  21737. })].concat(subBlocks || [])
  21738. });
  21739. }
  21740. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  21741. // check: category-no-encode-has-axis-data in dataset.html
  21742. var data = series.getData();
  21743. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  21744. var dimItem = data.getDimensionInfo(idx);
  21745. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21746. }, false);
  21747. var inlineValues = [];
  21748. var inlineValueTypes = [];
  21749. var blocks = [];
  21750. tooltipDims.length ? each(tooltipDims, function (dim) {
  21751. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21752. }) // By default, all dims is used on tooltip.
  21753. : each(value, setEachItem);
  21754. function setEachItem(val, dim) {
  21755. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  21756. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21757. return;
  21758. }
  21759. if (isValueMultipleLine) {
  21760. blocks.push(createTooltipMarkup('nameValue', {
  21761. markerType: 'subItem',
  21762. markerColor: colorStr,
  21763. name: dimInfo.displayName,
  21764. value: val,
  21765. valueType: dimInfo.type
  21766. }));
  21767. } else {
  21768. inlineValues.push(val);
  21769. inlineValueTypes.push(dimInfo.type);
  21770. }
  21771. }
  21772. return {
  21773. inlineValues: inlineValues,
  21774. inlineValueTypes: inlineValueTypes,
  21775. blocks: blocks
  21776. };
  21777. }
  21778. var inner$1 = makeInner();
  21779. function getSelectionKey(data, dataIndex) {
  21780. return data.getName(dataIndex) || data.getId(dataIndex);
  21781. }
  21782. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  21783. var SeriesModel =
  21784. /** @class */
  21785. function (_super) {
  21786. __extends(SeriesModel, _super);
  21787. function SeriesModel() {
  21788. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  21789. // the class members must not be initialized in constructor or declaration place.
  21790. // Otherwise there is bad case:
  21791. // class A {xxx = 1;}
  21792. // enableClassExtend(A);
  21793. // class B extends A {}
  21794. // var C = B.extend({xxx: 5});
  21795. // var c = new C();
  21796. // console.log(c.xxx); // expect 5 but always 1.
  21797. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  21798. // Props about data selection
  21799. // ---------------------------------------
  21800. _this._selectedDataIndicesMap = {};
  21801. return _this;
  21802. }
  21803. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  21804. this.seriesIndex = this.componentIndex;
  21805. this.dataTask = createTask({
  21806. count: dataTaskCount,
  21807. reset: dataTaskReset
  21808. });
  21809. this.dataTask.context = {
  21810. model: this
  21811. };
  21812. this.mergeDefaultAndTheme(option, ecModel);
  21813. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  21814. sourceManager.prepareSource();
  21815. var data = this.getInitialData(option, ecModel);
  21816. wrapData(data, this);
  21817. this.dataTask.context.data = data;
  21818. if ("development" !== 'production') {
  21819. assert(data, 'getInitialData returned invalid data.');
  21820. }
  21821. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  21822. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21823. // cause data.graph.data !== data when using
  21824. // module:echarts/data/Graph or module:echarts/data/Tree.
  21825. // See module:echarts/data/helper/linkSeriesData
  21826. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21827. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21828. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21829. // Call `seriesModel.getRawData()` instead.
  21830. // this.restoreData();
  21831. autoSeriesName(this);
  21832. this._initSelectedMapFromData(data);
  21833. };
  21834. /**
  21835. * Util for merge default and theme to option
  21836. */
  21837. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  21838. var layoutMode = fetchLayoutMode(this);
  21839. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  21840. // But if name duplicate between series subType
  21841. // (for example: parallel) add component mainType,
  21842. // add suffix 'Series'.
  21843. var themeSubType = this.subType;
  21844. if (ComponentModel.hasClass(themeSubType)) {
  21845. themeSubType += 'Series';
  21846. }
  21847. merge(option, ecModel.getTheme().get(this.subType));
  21848. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  21849. defaultEmphasis(option, 'label', ['show']);
  21850. this.fillDataTextStyle(option.data);
  21851. if (layoutMode) {
  21852. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21853. }
  21854. };
  21855. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  21856. // this.settingTask.dirty();
  21857. newSeriesOption = merge(this.option, newSeriesOption, true);
  21858. this.fillDataTextStyle(newSeriesOption.data);
  21859. var layoutMode = fetchLayoutMode(this);
  21860. if (layoutMode) {
  21861. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21862. }
  21863. var sourceManager = inner$1(this).sourceManager;
  21864. sourceManager.dirty();
  21865. sourceManager.prepareSource();
  21866. var data = this.getInitialData(newSeriesOption, ecModel);
  21867. wrapData(data, this);
  21868. this.dataTask.dirty();
  21869. this.dataTask.context.data = data;
  21870. inner$1(this).dataBeforeProcessed = data;
  21871. autoSeriesName(this);
  21872. this._initSelectedMapFromData(data);
  21873. };
  21874. SeriesModel.prototype.fillDataTextStyle = function (data) {
  21875. // Default data label emphasis `show`
  21876. // FIXME Tree structure data ?
  21877. // FIXME Performance ?
  21878. if (data && !isTypedArray(data)) {
  21879. var props = ['show'];
  21880. for (var i = 0; i < data.length; i++) {
  21881. if (data[i] && data[i].label) {
  21882. defaultEmphasis(data[i], 'label', props);
  21883. }
  21884. }
  21885. }
  21886. };
  21887. /**
  21888. * Init a data structure from data related option in series
  21889. * Must be overridden.
  21890. */
  21891. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  21892. return;
  21893. };
  21894. /**
  21895. * Append data to list
  21896. */
  21897. SeriesModel.prototype.appendData = function (params) {
  21898. // FIXME ???
  21899. // (1) If data from dataset, forbidden append.
  21900. // (2) support append data of dataset.
  21901. var data = this.getRawData();
  21902. data.appendData(params.data);
  21903. };
  21904. /**
  21905. * Consider some method like `filter`, `map` need make new data,
  21906. * We should make sure that `seriesModel.getData()` get correct
  21907. * data in the stream procedure. So we fetch data from upstream
  21908. * each time `task.perform` called.
  21909. */
  21910. SeriesModel.prototype.getData = function (dataType) {
  21911. var task = getCurrentTask(this);
  21912. if (task) {
  21913. var data = task.context.data;
  21914. return dataType == null ? data : data.getLinkedData(dataType);
  21915. } else {
  21916. // When series is not alive (that may happen when click toolbox
  21917. // restore or setOption with not merge mode), series data may
  21918. // be still need to judge animation or something when graphic
  21919. // elements want to know whether fade out.
  21920. return inner$1(this).data;
  21921. }
  21922. };
  21923. SeriesModel.prototype.getAllData = function () {
  21924. var mainData = this.getData();
  21925. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  21926. data: mainData
  21927. }];
  21928. };
  21929. SeriesModel.prototype.setData = function (data) {
  21930. var task = getCurrentTask(this);
  21931. if (task) {
  21932. var context = task.context; // Consider case: filter, data sample.
  21933. // FIXME:TS never used, so comment it
  21934. // if (context.data !== data && task.modifyOutputEnd) {
  21935. // task.setOutputEnd(data.count());
  21936. // }
  21937. context.outputData = data; // Caution: setData should update context.data,
  21938. // Because getData may be called multiply in a
  21939. // single stage and expect to get the data just
  21940. // set. (For example, AxisProxy, x y both call
  21941. // getData and setDate sequentially).
  21942. // So the context.data should be fetched from
  21943. // upstream each time when a stage starts to be
  21944. // performed.
  21945. if (task !== this.dataTask) {
  21946. context.data = data;
  21947. }
  21948. }
  21949. inner$1(this).data = data;
  21950. };
  21951. SeriesModel.prototype.getEncode = function () {
  21952. var encode = this.get('encode', true);
  21953. if (encode) {
  21954. return createHashMap(encode);
  21955. }
  21956. };
  21957. SeriesModel.prototype.getSourceManager = function () {
  21958. return inner$1(this).sourceManager;
  21959. };
  21960. SeriesModel.prototype.getSource = function () {
  21961. return this.getSourceManager().getSource();
  21962. };
  21963. /**
  21964. * Get data before processed
  21965. */
  21966. SeriesModel.prototype.getRawData = function () {
  21967. return inner$1(this).dataBeforeProcessed;
  21968. };
  21969. SeriesModel.prototype.getColorBy = function () {
  21970. var colorBy = this.get('colorBy');
  21971. return colorBy || 'series';
  21972. };
  21973. SeriesModel.prototype.isColorBySeries = function () {
  21974. return this.getColorBy() === 'series';
  21975. };
  21976. /**
  21977. * Get base axis if has coordinate system and has axis.
  21978. * By default use coordSys.getBaseAxis();
  21979. * Can be overridden for some chart.
  21980. * @return {type} description
  21981. */
  21982. SeriesModel.prototype.getBaseAxis = function () {
  21983. var coordSys = this.coordinateSystem; // @ts-ignore
  21984. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21985. };
  21986. /**
  21987. * Default tooltip formatter
  21988. *
  21989. * @param dataIndex
  21990. * @param multipleSeries
  21991. * @param dataType
  21992. * @param renderMode valid values: 'html'(by default) and 'richText'.
  21993. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21994. * string is used as DOM HTML content.
  21995. * 'richText' is used for rendering tooltip in rich text form, for those where
  21996. * DOM operation is not supported.
  21997. * @return formatted tooltip with `html` and `markers`
  21998. * Notice: The override method can also return string
  21999. */
  22000. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22001. return defaultSeriesFormatTooltip({
  22002. series: this,
  22003. dataIndex: dataIndex,
  22004. multipleSeries: multipleSeries
  22005. });
  22006. };
  22007. SeriesModel.prototype.isAnimationEnabled = function () {
  22008. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  22009. // In ssr mode, renderToString will generate svg with css animation.
  22010. if (env.node && !(ecModel && ecModel.ssr)) {
  22011. return false;
  22012. }
  22013. var animationEnabled = this.getShallow('animation');
  22014. if (animationEnabled) {
  22015. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22016. animationEnabled = false;
  22017. }
  22018. }
  22019. return !!animationEnabled;
  22020. };
  22021. SeriesModel.prototype.restoreData = function () {
  22022. this.dataTask.dirty();
  22023. };
  22024. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22025. var ecModel = this.ecModel; // PENDING
  22026. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22027. if (!color) {
  22028. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22029. }
  22030. return color;
  22031. };
  22032. /**
  22033. * Use `data.mapDimensionsAll(coordDim)` instead.
  22034. * @deprecated
  22035. */
  22036. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22037. return this.getRawData().mapDimensionsAll(coordDim);
  22038. };
  22039. /**
  22040. * Get progressive rendering count each step
  22041. */
  22042. SeriesModel.prototype.getProgressive = function () {
  22043. return this.get('progressive');
  22044. };
  22045. /**
  22046. * Get progressive rendering count each step
  22047. */
  22048. SeriesModel.prototype.getProgressiveThreshold = function () {
  22049. return this.get('progressiveThreshold');
  22050. }; // PENGING If selectedMode is null ?
  22051. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22052. this._innerSelect(this.getData(dataType), innerDataIndices);
  22053. };
  22054. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22055. var selectedMap = this.option.selectedMap;
  22056. if (!selectedMap) {
  22057. return;
  22058. }
  22059. var selectedMode = this.option.selectedMode;
  22060. var data = this.getData(dataType);
  22061. if (selectedMode === 'series' || selectedMap === 'all') {
  22062. this.option.selectedMap = {};
  22063. this._selectedDataIndicesMap = {};
  22064. return;
  22065. }
  22066. for (var i = 0; i < innerDataIndices.length; i++) {
  22067. var dataIndex = innerDataIndices[i];
  22068. var nameOrId = getSelectionKey(data, dataIndex);
  22069. selectedMap[nameOrId] = false;
  22070. this._selectedDataIndicesMap[nameOrId] = -1;
  22071. }
  22072. };
  22073. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22074. var tmpArr = [];
  22075. for (var i = 0; i < innerDataIndices.length; i++) {
  22076. tmpArr[0] = innerDataIndices[i];
  22077. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22078. }
  22079. };
  22080. SeriesModel.prototype.getSelectedDataIndices = function () {
  22081. if (this.option.selectedMap === 'all') {
  22082. return [].slice.call(this.getData().getIndices());
  22083. }
  22084. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22085. var nameOrIds = keys(selectedDataIndicesMap);
  22086. var dataIndices = [];
  22087. for (var i = 0; i < nameOrIds.length; i++) {
  22088. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22089. if (dataIndex >= 0) {
  22090. dataIndices.push(dataIndex);
  22091. }
  22092. }
  22093. return dataIndices;
  22094. };
  22095. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22096. var selectedMap = this.option.selectedMap;
  22097. if (!selectedMap) {
  22098. return false;
  22099. }
  22100. var data = this.getData(dataType);
  22101. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22102. };
  22103. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22104. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22105. return true;
  22106. }
  22107. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  22108. if (!universalTransitionOpt) {
  22109. return false;
  22110. }
  22111. if (universalTransitionOpt === true) {
  22112. return true;
  22113. } // Can be simply 'universalTransition: true'
  22114. return universalTransitionOpt && universalTransitionOpt.enabled;
  22115. };
  22116. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22117. var _a, _b;
  22118. var option = this.option;
  22119. var selectedMode = option.selectedMode;
  22120. var len = innerDataIndices.length;
  22121. if (!selectedMode || !len) {
  22122. return;
  22123. }
  22124. if (selectedMode === 'series') {
  22125. option.selectedMap = 'all';
  22126. } else if (selectedMode === 'multiple') {
  22127. if (!isObject(option.selectedMap)) {
  22128. option.selectedMap = {};
  22129. }
  22130. var selectedMap = option.selectedMap;
  22131. for (var i = 0; i < len; i++) {
  22132. var dataIndex = innerDataIndices[i]; // TODO different types of data share same object.
  22133. var nameOrId = getSelectionKey(data, dataIndex);
  22134. selectedMap[nameOrId] = true;
  22135. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22136. }
  22137. } else if (selectedMode === 'single' || selectedMode === true) {
  22138. var lastDataIndex = innerDataIndices[len - 1];
  22139. var nameOrId = getSelectionKey(data, lastDataIndex);
  22140. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22141. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22142. }
  22143. };
  22144. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22145. // Ignore select info in data if selectedMap exists.
  22146. // NOTE It's only for legacy usage. edge data is not supported.
  22147. if (this.option.selectedMap) {
  22148. return;
  22149. }
  22150. var dataIndices = [];
  22151. if (data.hasItemOption) {
  22152. data.each(function (idx) {
  22153. var rawItem = data.getRawDataItem(idx);
  22154. if (rawItem && rawItem.selected) {
  22155. dataIndices.push(idx);
  22156. }
  22157. });
  22158. }
  22159. if (dataIndices.length > 0) {
  22160. this._innerSelect(data, dataIndices);
  22161. }
  22162. }; // /**
  22163. // * @see {module:echarts/stream/Scheduler}
  22164. // */
  22165. // abstract pipeTask: null
  22166. SeriesModel.registerClass = function (clz) {
  22167. return ComponentModel.registerClass(clz);
  22168. };
  22169. SeriesModel.protoInitialize = function () {
  22170. var proto = SeriesModel.prototype;
  22171. proto.type = 'series.__base__';
  22172. proto.seriesIndex = 0;
  22173. proto.ignoreStyleOnData = false;
  22174. proto.hasSymbolVisual = false;
  22175. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22176. proto.visualStyleAccessPath = 'itemStyle';
  22177. proto.visualDrawType = 'fill';
  22178. }();
  22179. return SeriesModel;
  22180. }(ComponentModel);
  22181. mixin(SeriesModel, DataFormatMixin);
  22182. mixin(SeriesModel, PaletteMixin);
  22183. mountExtend(SeriesModel, ComponentModel);
  22184. /**
  22185. * MUST be called after `prepareSource` called
  22186. * Here we need to make auto series, especially for auto legend. But we
  22187. * do not modify series.name in option to avoid side effects.
  22188. */
  22189. function autoSeriesName(seriesModel) {
  22190. // User specified name has higher priority, otherwise it may cause
  22191. // series can not be queried unexpectedly.
  22192. var name = seriesModel.name;
  22193. if (!isNameSpecified(seriesModel)) {
  22194. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22195. }
  22196. }
  22197. function getSeriesAutoName(seriesModel) {
  22198. var data = seriesModel.getRawData();
  22199. var dataDims = data.mapDimensionsAll('seriesName');
  22200. var nameArr = [];
  22201. each(dataDims, function (dataDim) {
  22202. var dimInfo = data.getDimensionInfo(dataDim);
  22203. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22204. });
  22205. return nameArr.join(' ');
  22206. }
  22207. function dataTaskCount(context) {
  22208. return context.model.getRawData().count();
  22209. }
  22210. function dataTaskReset(context) {
  22211. var seriesModel = context.model;
  22212. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22213. return dataTaskProgress;
  22214. }
  22215. function dataTaskProgress(param, context) {
  22216. // Avoid repeat cloneShallow when data just created in reset.
  22217. if (context.outputData && param.end > context.outputData.count()) {
  22218. context.model.getRawData().cloneShallow(context.outputData);
  22219. }
  22220. } // TODO refactor
  22221. function wrapData(data, seriesModel) {
  22222. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22223. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22224. });
  22225. }
  22226. function onDataChange(seriesModel, newList) {
  22227. var task = getCurrentTask(seriesModel);
  22228. if (task) {
  22229. // Consider case: filter, selectRange
  22230. task.setOutputEnd((newList || this).count());
  22231. }
  22232. return newList;
  22233. }
  22234. function getCurrentTask(seriesModel) {
  22235. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22236. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22237. if (pipeline) {
  22238. // When pipline finished, the currrentTask keep the last
  22239. // task (renderTask).
  22240. var task = pipeline.currentTask;
  22241. if (task) {
  22242. var agentStubMap = task.agentStubMap;
  22243. if (agentStubMap) {
  22244. task = agentStubMap.get(seriesModel.uid);
  22245. }
  22246. }
  22247. return task;
  22248. }
  22249. }
  22250. var ComponentView =
  22251. /** @class */
  22252. function () {
  22253. function ComponentView() {
  22254. this.group = new Group();
  22255. this.uid = getUID('viewComponent');
  22256. }
  22257. ComponentView.prototype.init = function (ecModel, api) {};
  22258. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22259. ComponentView.prototype.dispose = function (ecModel, api) {};
  22260. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22261. };
  22262. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22263. };
  22264. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22265. };
  22266. /**
  22267. * Hook for toggle blur target series.
  22268. * Can be used in marker for blur or leave blur the markers
  22269. */
  22270. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  22271. };
  22272. /**
  22273. * Traverse the new rendered elements.
  22274. *
  22275. * It will traverse the new added element in progressive rendering.
  22276. * And traverse all in normal rendering.
  22277. */
  22278. ComponentView.prototype.eachRendered = function (cb) {
  22279. var group = this.group;
  22280. if (group) {
  22281. group.traverse(cb);
  22282. }
  22283. };
  22284. return ComponentView;
  22285. }();
  22286. enableClassExtend(ComponentView);
  22287. enableClassManagement(ComponentView);
  22288. /**
  22289. * @return {string} If large mode changed, return string 'reset';
  22290. */
  22291. function createRenderPlanner() {
  22292. var inner = makeInner();
  22293. return function (seriesModel) {
  22294. var fields = inner(seriesModel);
  22295. var pipelineContext = seriesModel.pipelineContext;
  22296. var originalLarge = !!fields.large;
  22297. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22298. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22299. // on `performRawSeries` in `Schedular.js`.
  22300. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22301. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22302. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22303. };
  22304. }
  22305. var inner$2 = makeInner();
  22306. var renderPlanner = createRenderPlanner();
  22307. var ChartView =
  22308. /** @class */
  22309. function () {
  22310. function ChartView() {
  22311. this.group = new Group();
  22312. this.uid = getUID('viewChart');
  22313. this.renderTask = createTask({
  22314. plan: renderTaskPlan,
  22315. reset: renderTaskReset
  22316. });
  22317. this.renderTask.context = {
  22318. view: this
  22319. };
  22320. }
  22321. ChartView.prototype.init = function (ecModel, api) {};
  22322. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22323. if ("development" !== 'production') {
  22324. throw new Error('render method must been implemented');
  22325. }
  22326. };
  22327. /**
  22328. * Highlight series or specified data item.
  22329. */
  22330. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22331. var data = seriesModel.getData(payload && payload.dataType);
  22332. if (!data) {
  22333. if ("development" !== 'production') {
  22334. error("Unknown dataType " + payload.dataType);
  22335. }
  22336. return;
  22337. }
  22338. toggleHighlight(data, payload, 'emphasis');
  22339. };
  22340. /**
  22341. * Downplay series or specified data item.
  22342. */
  22343. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22344. var data = seriesModel.getData(payload && payload.dataType);
  22345. if (!data) {
  22346. if ("development" !== 'production') {
  22347. error("Unknown dataType " + payload.dataType);
  22348. }
  22349. return;
  22350. }
  22351. toggleHighlight(data, payload, 'normal');
  22352. };
  22353. /**
  22354. * Remove self.
  22355. */
  22356. ChartView.prototype.remove = function (ecModel, api) {
  22357. this.group.removeAll();
  22358. };
  22359. /**
  22360. * Dispose self.
  22361. */
  22362. ChartView.prototype.dispose = function (ecModel, api) {};
  22363. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22364. this.render(seriesModel, ecModel, api, payload);
  22365. }; // FIXME never used?
  22366. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22367. this.render(seriesModel, ecModel, api, payload);
  22368. }; // FIXME never used?
  22369. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22370. this.render(seriesModel, ecModel, api, payload);
  22371. };
  22372. /**
  22373. * Traverse the new rendered elements.
  22374. *
  22375. * It will traverse the new added element in progressive rendering.
  22376. * And traverse all in normal rendering.
  22377. */
  22378. ChartView.prototype.eachRendered = function (cb) {
  22379. traverseElements(this.group, cb);
  22380. };
  22381. ChartView.markUpdateMethod = function (payload, methodName) {
  22382. inner$2(payload).updateMethod = methodName;
  22383. };
  22384. ChartView.protoInitialize = function () {
  22385. var proto = ChartView.prototype;
  22386. proto.type = 'chart';
  22387. }();
  22388. return ChartView;
  22389. }();
  22390. /**
  22391. * Set state of single element
  22392. */
  22393. function elSetState(el, state, highlightDigit) {
  22394. if (el && isHighDownDispatcher(el)) {
  22395. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22396. }
  22397. }
  22398. function toggleHighlight(data, payload, state) {
  22399. var dataIndex = queryDataIndex(data, payload);
  22400. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22401. if (dataIndex != null) {
  22402. each(normalizeToArray(dataIndex), function (dataIdx) {
  22403. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22404. });
  22405. } else {
  22406. data.eachItemGraphicEl(function (el) {
  22407. elSetState(el, state, highlightDigit);
  22408. });
  22409. }
  22410. }
  22411. enableClassExtend(ChartView, ['dispose']);
  22412. enableClassManagement(ChartView);
  22413. function renderTaskPlan(context) {
  22414. return renderPlanner(context.model);
  22415. }
  22416. function renderTaskReset(context) {
  22417. var seriesModel = context.model;
  22418. var ecModel = context.ecModel;
  22419. var api = context.api;
  22420. var payload = context.payload; // FIXME: remove updateView updateVisual
  22421. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22422. var view = context.view;
  22423. var updateMethod = payload && inner$2(payload).updateMethod;
  22424. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22425. // is less than progressive threshold.
  22426. : 'render';
  22427. if (methodName !== 'render') {
  22428. view[methodName](seriesModel, ecModel, api, payload);
  22429. }
  22430. return progressMethodMap[methodName];
  22431. }
  22432. var progressMethodMap = {
  22433. incrementalPrepareRender: {
  22434. progress: function (params, context) {
  22435. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22436. }
  22437. },
  22438. render: {
  22439. // Put view.render in `progress` to support appendData. But in this case
  22440. // view.render should not be called in reset, otherwise it will be called
  22441. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22442. // in any cases.
  22443. forceFirstProgress: true,
  22444. progress: function (params, context) {
  22445. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22446. }
  22447. }
  22448. };
  22449. /*
  22450. * Licensed to the Apache Software Foundation (ASF) under one
  22451. * or more contributor license agreements. See the NOTICE file
  22452. * distributed with this work for additional information
  22453. * regarding copyright ownership. The ASF licenses this file
  22454. * to you under the Apache License, Version 2.0 (the
  22455. * "License"); you may not use this file except in compliance
  22456. * with the License. You may obtain a copy of the License at
  22457. *
  22458. * http://www.apache.org/licenses/LICENSE-2.0
  22459. *
  22460. * Unless required by applicable law or agreed to in writing,
  22461. * software distributed under the License is distributed on an
  22462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22463. * KIND, either express or implied. See the License for the
  22464. * specific language governing permissions and limitations
  22465. * under the License.
  22466. */
  22467. /**
  22468. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22469. */
  22470. /*
  22471. * Licensed to the Apache Software Foundation (ASF) under one
  22472. * or more contributor license agreements. See the NOTICE file
  22473. * distributed with this work for additional information
  22474. * regarding copyright ownership. The ASF licenses this file
  22475. * to you under the Apache License, Version 2.0 (the
  22476. * "License"); you may not use this file except in compliance
  22477. * with the License. You may obtain a copy of the License at
  22478. *
  22479. * http://www.apache.org/licenses/LICENSE-2.0
  22480. *
  22481. * Unless required by applicable law or agreed to in writing,
  22482. * software distributed under the License is distributed on an
  22483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22484. * KIND, either express or implied. See the License for the
  22485. * specific language governing permissions and limitations
  22486. * under the License.
  22487. */
  22488. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22489. var RATE = '\0__throttleRate';
  22490. var THROTTLE_TYPE = '\0__throttleType';
  22491. /**
  22492. * @public
  22493. * @param {(Function)} fn
  22494. * @param {number} [delay=0] Unit: ms.
  22495. * @param {boolean} [debounce=false]
  22496. * true: If call interval less than `delay`, only the last call works.
  22497. * false: If call interval less than `delay, call works on fixed rate.
  22498. * @return {(Function)} throttled fn.
  22499. */
  22500. function throttle(fn, delay, debounce) {
  22501. var currCall;
  22502. var lastCall = 0;
  22503. var lastExec = 0;
  22504. var timer = null;
  22505. var diff;
  22506. var scope;
  22507. var args;
  22508. var debounceNextCall;
  22509. delay = delay || 0;
  22510. function exec() {
  22511. lastExec = new Date().getTime();
  22512. timer = null;
  22513. fn.apply(scope, args || []);
  22514. }
  22515. var cb = function () {
  22516. var cbArgs = [];
  22517. for (var _i = 0; _i < arguments.length; _i++) {
  22518. cbArgs[_i] = arguments[_i];
  22519. }
  22520. currCall = new Date().getTime();
  22521. scope = this;
  22522. args = cbArgs;
  22523. var thisDelay = debounceNextCall || delay;
  22524. var thisDebounce = debounceNextCall || debounce;
  22525. debounceNextCall = null;
  22526. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22527. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22528. // than a new call of `cb`, that is, preserving the command order. Consider
  22529. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22530. // happens, either the `exec` is called dierectly, or the call is delayed.
  22531. // But the delayed call should never be later than next call of `cb`. Under
  22532. // this assurance, we can simply update view state each time `dispatchAction`
  22533. // triggered by user roaming, but not need to add extra code to avoid the
  22534. // state being "rolled-back".
  22535. if (thisDebounce) {
  22536. timer = setTimeout(exec, thisDelay);
  22537. } else {
  22538. if (diff >= 0) {
  22539. exec();
  22540. } else {
  22541. timer = setTimeout(exec, -diff);
  22542. }
  22543. }
  22544. lastCall = currCall;
  22545. };
  22546. /**
  22547. * Clear throttle.
  22548. * @public
  22549. */
  22550. cb.clear = function () {
  22551. if (timer) {
  22552. clearTimeout(timer);
  22553. timer = null;
  22554. }
  22555. };
  22556. /**
  22557. * Enable debounce once.
  22558. */
  22559. cb.debounceNextCall = function (debounceDelay) {
  22560. debounceNextCall = debounceDelay;
  22561. };
  22562. return cb;
  22563. }
  22564. /**
  22565. * Create throttle method or update throttle rate.
  22566. *
  22567. * @example
  22568. * ComponentView.prototype.render = function () {
  22569. * ...
  22570. * throttle.createOrUpdate(
  22571. * this,
  22572. * '_dispatchAction',
  22573. * this.model.get('throttle'),
  22574. * 'fixRate'
  22575. * );
  22576. * };
  22577. * ComponentView.prototype.remove = function () {
  22578. * throttle.clear(this, '_dispatchAction');
  22579. * };
  22580. * ComponentView.prototype.dispose = function () {
  22581. * throttle.clear(this, '_dispatchAction');
  22582. * };
  22583. *
  22584. */
  22585. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22586. var fn = obj[fnAttr];
  22587. if (!fn) {
  22588. return;
  22589. }
  22590. var originFn = fn[ORIGIN_METHOD] || fn;
  22591. var lastThrottleType = fn[THROTTLE_TYPE];
  22592. var lastRate = fn[RATE];
  22593. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22594. if (rate == null || !throttleType) {
  22595. return obj[fnAttr] = originFn;
  22596. }
  22597. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22598. fn[ORIGIN_METHOD] = originFn;
  22599. fn[THROTTLE_TYPE] = throttleType;
  22600. fn[RATE] = rate;
  22601. }
  22602. return fn;
  22603. }
  22604. /**
  22605. * Clear throttle. Example see throttle.createOrUpdate.
  22606. */
  22607. function clear(obj, fnAttr) {
  22608. var fn = obj[fnAttr];
  22609. if (fn && fn[ORIGIN_METHOD]) {
  22610. // Clear throttle
  22611. fn.clear && fn.clear();
  22612. obj[fnAttr] = fn[ORIGIN_METHOD];
  22613. }
  22614. }
  22615. var inner$3 = makeInner();
  22616. var defaultStyleMappers = {
  22617. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22618. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22619. };
  22620. var defaultColorKey = {
  22621. lineStyle: 'stroke',
  22622. itemStyle: 'fill'
  22623. };
  22624. function getStyleMapper(seriesModel, stylePath) {
  22625. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22626. if (!styleMapper) {
  22627. console.warn("Unknown style type '" + stylePath + "'.");
  22628. return defaultStyleMappers.itemStyle;
  22629. }
  22630. return styleMapper;
  22631. }
  22632. function getDefaultColorKey(seriesModel, stylePath) {
  22633. // return defaultColorKey[stylePath] ||
  22634. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22635. if (!colorKey) {
  22636. console.warn("Unknown style type '" + stylePath + "'.");
  22637. return 'fill';
  22638. }
  22639. return colorKey;
  22640. }
  22641. var seriesStyleTask = {
  22642. createOnAllSeries: true,
  22643. performRawSeries: true,
  22644. reset: function (seriesModel, ecModel) {
  22645. var data = seriesModel.getData();
  22646. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22647. var styleModel = seriesModel.getModel(stylePath);
  22648. var getStyle = getStyleMapper(seriesModel, stylePath);
  22649. var globalStyle = getStyle(styleModel);
  22650. var decalOption = styleModel.getShallow('decal');
  22651. if (decalOption) {
  22652. data.setVisual('decal', decalOption);
  22653. decalOption.dirty = true;
  22654. } // TODO
  22655. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22656. var color = globalStyle[colorKey]; // TODO style callback
  22657. var colorCallback = isFunction(color) ? color : null;
  22658. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22659. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22660. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  22661. // make it effect palette. Because some scenarios users need to make some series
  22662. // transparent or as background, which should better not effect the palette.
  22663. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22664. seriesModel.name, null, ecModel.getSeriesCount());
  22665. if (!globalStyle[colorKey]) {
  22666. globalStyle[colorKey] = colorPalette;
  22667. data.setVisual('colorFromPalette', true);
  22668. }
  22669. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22670. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22671. }
  22672. data.setVisual('style', globalStyle);
  22673. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22674. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22675. data.setVisual('colorFromPalette', false);
  22676. return {
  22677. dataEach: function (data, idx) {
  22678. var dataParams = seriesModel.getDataParams(idx);
  22679. var itemStyle = extend({}, globalStyle);
  22680. itemStyle[colorKey] = colorCallback(dataParams);
  22681. data.setItemVisual(idx, 'style', itemStyle);
  22682. }
  22683. };
  22684. }
  22685. }
  22686. };
  22687. var sharedModel = new Model();
  22688. var dataStyleTask = {
  22689. createOnAllSeries: true,
  22690. performRawSeries: true,
  22691. reset: function (seriesModel, ecModel) {
  22692. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22693. return;
  22694. }
  22695. var data = seriesModel.getData();
  22696. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22697. var getStyle = getStyleMapper(seriesModel, stylePath);
  22698. var colorKey = data.getVisual('drawType');
  22699. return {
  22700. dataEach: data.hasItemOption ? function (data, idx) {
  22701. // Not use getItemModel for performance considuration
  22702. var rawItem = data.getRawDataItem(idx);
  22703. if (rawItem && rawItem[stylePath]) {
  22704. sharedModel.option = rawItem[stylePath];
  22705. var style = getStyle(sharedModel);
  22706. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  22707. extend(existsStyle, style);
  22708. if (sharedModel.option.decal) {
  22709. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  22710. sharedModel.option.decal.dirty = true;
  22711. }
  22712. if (colorKey in style) {
  22713. data.setItemVisual(idx, 'colorFromPalette', false);
  22714. }
  22715. }
  22716. } : null
  22717. };
  22718. }
  22719. }; // Pick color from palette for the data which has not been set with color yet.
  22720. // Note: do not support stream rendering. No such cases yet.
  22721. var dataColorPaletteTask = {
  22722. performRawSeries: true,
  22723. overallReset: function (ecModel) {
  22724. // Each type of series uses one scope.
  22725. // Pie and funnel are using different scopes.
  22726. var paletteScopeGroupByType = createHashMap();
  22727. ecModel.eachSeries(function (seriesModel) {
  22728. var colorBy = seriesModel.getColorBy();
  22729. if (seriesModel.isColorBySeries()) {
  22730. return;
  22731. }
  22732. var key = seriesModel.type + '-' + colorBy;
  22733. var colorScope = paletteScopeGroupByType.get(key);
  22734. if (!colorScope) {
  22735. colorScope = {};
  22736. paletteScopeGroupByType.set(key, colorScope);
  22737. }
  22738. inner$3(seriesModel).scope = colorScope;
  22739. });
  22740. ecModel.eachSeries(function (seriesModel) {
  22741. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  22742. return;
  22743. }
  22744. var dataAll = seriesModel.getRawData();
  22745. var idxMap = {};
  22746. var data = seriesModel.getData();
  22747. var colorScope = inner$3(seriesModel).scope;
  22748. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22749. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22750. data.each(function (idx) {
  22751. var rawIdx = data.getRawIndex(idx);
  22752. idxMap[rawIdx] = idx;
  22753. }); // Iterate on data before filtered. To make sure color from palette can be
  22754. // Consistent when toggling legend.
  22755. dataAll.each(function (rawIdx) {
  22756. var idx = idxMap[rawIdx];
  22757. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  22758. // also picked from color palette. So following situation is not in the case:
  22759. // 1. series.itemStyle.color is set
  22760. // 2. color is encoded by visualMap
  22761. if (fromPalette) {
  22762. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  22763. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  22764. var dataCount = dataAll.count();
  22765. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  22766. }
  22767. });
  22768. });
  22769. }
  22770. };
  22771. var PI$3 = Math.PI;
  22772. /**
  22773. * @param {module:echarts/ExtensionAPI} api
  22774. * @param {Object} [opts]
  22775. * @param {string} [opts.text]
  22776. * @param {string} [opts.color]
  22777. * @param {string} [opts.textColor]
  22778. * @return {module:zrender/Element}
  22779. */
  22780. function defaultLoading(api, opts) {
  22781. opts = opts || {};
  22782. defaults(opts, {
  22783. text: 'loading',
  22784. textColor: '#000',
  22785. fontSize: 12,
  22786. fontWeight: 'normal',
  22787. fontStyle: 'normal',
  22788. fontFamily: 'sans-serif',
  22789. maskColor: 'rgba(255, 255, 255, 0.8)',
  22790. showSpinner: true,
  22791. color: '#5470c6',
  22792. spinnerRadius: 10,
  22793. lineWidth: 5,
  22794. zlevel: 0
  22795. });
  22796. var group = new Group();
  22797. var mask = new Rect({
  22798. style: {
  22799. fill: opts.maskColor
  22800. },
  22801. zlevel: opts.zlevel,
  22802. z: 10000
  22803. });
  22804. group.add(mask);
  22805. var textContent = new ZRText({
  22806. style: {
  22807. text: opts.text,
  22808. fill: opts.textColor,
  22809. fontSize: opts.fontSize,
  22810. fontWeight: opts.fontWeight,
  22811. fontStyle: opts.fontStyle,
  22812. fontFamily: opts.fontFamily
  22813. },
  22814. zlevel: opts.zlevel,
  22815. z: 10001
  22816. });
  22817. var labelRect = new Rect({
  22818. style: {
  22819. fill: 'none'
  22820. },
  22821. textContent: textContent,
  22822. textConfig: {
  22823. position: 'right',
  22824. distance: 10
  22825. },
  22826. zlevel: opts.zlevel,
  22827. z: 10001
  22828. });
  22829. group.add(labelRect);
  22830. var arc;
  22831. if (opts.showSpinner) {
  22832. arc = new Arc({
  22833. shape: {
  22834. startAngle: -PI$3 / 2,
  22835. endAngle: -PI$3 / 2 + 0.1,
  22836. r: opts.spinnerRadius
  22837. },
  22838. style: {
  22839. stroke: opts.color,
  22840. lineCap: 'round',
  22841. lineWidth: opts.lineWidth
  22842. },
  22843. zlevel: opts.zlevel,
  22844. z: 10001
  22845. });
  22846. arc.animateShape(true).when(1000, {
  22847. endAngle: PI$3 * 3 / 2
  22848. }).start('circularInOut');
  22849. arc.animateShape(true).when(1000, {
  22850. startAngle: PI$3 * 3 / 2
  22851. }).delay(300).start('circularInOut');
  22852. group.add(arc);
  22853. } // Inject resize
  22854. group.resize = function () {
  22855. var textWidth = textContent.getBoundingRect().width;
  22856. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22857. // textDistance needs to be calculated when both animation and text exist
  22858. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  22859. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  22860. + (textWidth ? 0 : r);
  22861. var cy = api.getHeight() / 2;
  22862. opts.showSpinner && arc.setShape({
  22863. cx: cx,
  22864. cy: cy
  22865. });
  22866. labelRect.setShape({
  22867. x: cx - r,
  22868. y: cy - r,
  22869. width: r * 2,
  22870. height: r * 2
  22871. });
  22872. mask.setShape({
  22873. x: 0,
  22874. y: 0,
  22875. width: api.getWidth(),
  22876. height: api.getHeight()
  22877. });
  22878. };
  22879. group.resize();
  22880. return group;
  22881. }
  22882. var Scheduler =
  22883. /** @class */
  22884. function () {
  22885. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22886. // key: handlerUID
  22887. this._stageTaskMap = createHashMap();
  22888. this.ecInstance = ecInstance;
  22889. this.api = api; // Fix current processors in case that in some rear cases that
  22890. // processors might be registered after echarts instance created.
  22891. // Register processors incrementally for a echarts instance is
  22892. // not supported by this stream architecture.
  22893. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22894. visualHandlers = this._visualHandlers = visualHandlers.slice();
  22895. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22896. }
  22897. Scheduler.prototype.restoreData = function (ecModel, payload) {
  22898. // TODO: Only restore needed series and components, but not all components.
  22899. // Currently `restoreData` of all of the series and component will be called.
  22900. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22901. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22902. // and some components like coordinate system, axes, dataZoom, visualMap only
  22903. // need their target series refresh.
  22904. // (1) If we are implementing this feature some day, we should consider these cases:
  22905. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22906. // on the settings of `dataZoom`), it should be re-performed if the component
  22907. // is modified by `setOption`.
  22908. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22909. // it should be re-performed when the result array of `getTargetSeries` changed.
  22910. // We use `dependencies` to cover these issues.
  22911. // (3) How to update target series when coordinate system related components modified.
  22912. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22913. // and this case all of the tasks will be set as dirty.
  22914. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  22915. // depends on all of the series.
  22916. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22917. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22918. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22919. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22920. // probably cause state chaos (consider `dataZoomProcessor`).
  22921. this._stageTaskMap.each(function (taskRecord) {
  22922. var overallTask = taskRecord.overallTask;
  22923. overallTask && overallTask.dirty();
  22924. });
  22925. }; // If seriesModel provided, incremental threshold is check by series data.
  22926. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  22927. // For overall task
  22928. if (!task.__pipeline) {
  22929. return;
  22930. }
  22931. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22932. var pCtx = pipeline.context;
  22933. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  22934. var step = incremental ? pipeline.step : null;
  22935. var modDataCount = pCtx && pCtx.modDataCount;
  22936. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22937. return {
  22938. step: step,
  22939. modBy: modBy,
  22940. modDataCount: modDataCount
  22941. };
  22942. };
  22943. Scheduler.prototype.getPipeline = function (pipelineId) {
  22944. return this._pipelineMap.get(pipelineId);
  22945. };
  22946. /**
  22947. * Current, progressive rendering starts from visual and layout.
  22948. * Always detect render mode in the same stage, avoiding that incorrect
  22949. * detection caused by data filtering.
  22950. * Caution:
  22951. * `updateStreamModes` use `seriesModel.getData()`.
  22952. */
  22953. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  22954. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22955. var data = seriesModel.getData();
  22956. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  22957. // animation frame. Note that some types of series do not provide
  22958. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22959. // use the term `incremental` but not `progressive` to describe the
  22960. // case that `chart.appendData`.
  22961. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  22962. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22963. // see `test/candlestick-large3.html`
  22964. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22965. seriesModel.pipelineContext = pipeline.context = {
  22966. progressiveRender: progressiveRender,
  22967. modDataCount: modDataCount,
  22968. large: large
  22969. };
  22970. };
  22971. Scheduler.prototype.restorePipelines = function (ecModel) {
  22972. var scheduler = this;
  22973. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22974. ecModel.eachSeries(function (seriesModel) {
  22975. var progressive = seriesModel.getProgressive();
  22976. var pipelineId = seriesModel.uid;
  22977. pipelineMap.set(pipelineId, {
  22978. id: pipelineId,
  22979. head: null,
  22980. tail: null,
  22981. threshold: seriesModel.getProgressiveThreshold(),
  22982. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22983. blockIndex: -1,
  22984. step: Math.round(progressive || 700),
  22985. count: 0
  22986. });
  22987. scheduler._pipe(seriesModel, seriesModel.dataTask);
  22988. });
  22989. };
  22990. Scheduler.prototype.prepareStageTasks = function () {
  22991. var stageTaskMap = this._stageTaskMap;
  22992. var ecModel = this.api.getModel();
  22993. var api = this.api;
  22994. each(this._allHandlers, function (handler) {
  22995. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  22996. var errMsg = '';
  22997. if ("development" !== 'production') {
  22998. // Currently do not need to support to sepecify them both.
  22999. errMsg = '"reset" and "overallReset" must not be both specified.';
  23000. }
  23001. assert(!(handler.reset && handler.overallReset), errMsg);
  23002. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23003. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23004. }, this);
  23005. };
  23006. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23007. var renderTask = view.renderTask;
  23008. var context = renderTask.context;
  23009. context.model = model;
  23010. context.ecModel = ecModel;
  23011. context.api = api;
  23012. renderTask.__block = !view.incrementalPrepareRender;
  23013. this._pipe(model, renderTask);
  23014. };
  23015. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23016. // If we do not use `block` here, it should be considered when to update modes.
  23017. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23018. block: true
  23019. });
  23020. };
  23021. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23022. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23023. };
  23024. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23025. opt = opt || {};
  23026. var unfinished = false;
  23027. var scheduler = this;
  23028. each(stageHandlers, function (stageHandler, idx) {
  23029. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23030. return;
  23031. }
  23032. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23033. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23034. var overallTask = stageHandlerRecord.overallTask;
  23035. if (overallTask) {
  23036. var overallNeedDirty_1;
  23037. var agentStubMap = overallTask.agentStubMap;
  23038. agentStubMap.each(function (stub) {
  23039. if (needSetDirty(opt, stub)) {
  23040. stub.dirty();
  23041. overallNeedDirty_1 = true;
  23042. }
  23043. });
  23044. overallNeedDirty_1 && overallTask.dirty();
  23045. scheduler.updatePayload(overallTask, payload);
  23046. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  23047. // then execute the overall task. And stub will call seriesModel.setData,
  23048. // which ensures that in the overallTask seriesModel.getData() will not
  23049. // return incorrect data.
  23050. agentStubMap.each(function (stub) {
  23051. stub.perform(performArgs_1);
  23052. });
  23053. if (overallTask.perform(performArgs_1)) {
  23054. unfinished = true;
  23055. }
  23056. } else if (seriesTaskMap) {
  23057. seriesTaskMap.each(function (task, pipelineId) {
  23058. if (needSetDirty(opt, task)) {
  23059. task.dirty();
  23060. }
  23061. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  23062. // if intending to declare `performRawSeries` in handlers, only
  23063. // stream-independent (specifically, data item independent) operations can be
  23064. // performed. Because if a series is filtered, most of the tasks will not
  23065. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23066. // Perhaps we should not provide a separate callback for this case instead
  23067. // of providing the config `performRawSeries`. The stream-dependent operations
  23068. // and stream-independent operations should better not be mixed.
  23069. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23070. scheduler.updatePayload(task, payload);
  23071. if (task.perform(performArgs)) {
  23072. unfinished = true;
  23073. }
  23074. });
  23075. }
  23076. });
  23077. function needSetDirty(opt, task) {
  23078. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23079. }
  23080. this.unfinished = unfinished || this.unfinished;
  23081. };
  23082. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23083. var unfinished;
  23084. ecModel.eachSeries(function (seriesModel) {
  23085. // Progress to the end for dataInit and dataRestore.
  23086. unfinished = seriesModel.dataTask.perform() || unfinished;
  23087. });
  23088. this.unfinished = unfinished || this.unfinished;
  23089. };
  23090. Scheduler.prototype.plan = function () {
  23091. // Travel pipelines, check block.
  23092. this._pipelineMap.each(function (pipeline) {
  23093. var task = pipeline.tail;
  23094. do {
  23095. if (task.__block) {
  23096. pipeline.blockIndex = task.__idxInPipeline;
  23097. break;
  23098. }
  23099. task = task.getUpstream();
  23100. } while (task);
  23101. });
  23102. };
  23103. Scheduler.prototype.updatePayload = function (task, payload) {
  23104. payload !== 'remain' && (task.context.payload = payload);
  23105. };
  23106. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23107. var scheduler = this;
  23108. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  23109. // do not need to reuse the map.
  23110. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23111. var seriesType = stageHandler.seriesType;
  23112. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23113. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23114. // it works but it may cause other irrelevant charts blocked.
  23115. if (stageHandler.createOnAllSeries) {
  23116. ecModel.eachRawSeries(create);
  23117. } else if (seriesType) {
  23118. ecModel.eachRawSeriesByType(seriesType, create);
  23119. } else if (getTargetSeries) {
  23120. getTargetSeries(ecModel, api).each(create);
  23121. }
  23122. function create(seriesModel) {
  23123. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23124. // Reuse original task instance.
  23125. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23126. plan: seriesTaskPlan,
  23127. reset: seriesTaskReset,
  23128. count: seriesTaskCount
  23129. }));
  23130. task.context = {
  23131. model: seriesModel,
  23132. ecModel: ecModel,
  23133. api: api,
  23134. // PENDING: `useClearVisual` not used?
  23135. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23136. plan: stageHandler.plan,
  23137. reset: stageHandler.reset,
  23138. scheduler: scheduler
  23139. };
  23140. scheduler._pipe(seriesModel, task);
  23141. }
  23142. };
  23143. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23144. var scheduler = this;
  23145. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23146. || createTask({
  23147. reset: overallTaskReset
  23148. });
  23149. overallTask.context = {
  23150. ecModel: ecModel,
  23151. api: api,
  23152. overallReset: stageHandler.overallReset,
  23153. scheduler: scheduler
  23154. };
  23155. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23156. // do not need to reuse the map.
  23157. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23158. var seriesType = stageHandler.seriesType;
  23159. var getTargetSeries = stageHandler.getTargetSeries;
  23160. var overallProgress = true;
  23161. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23162. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23163. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23164. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23165. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23166. // we set the pipeline block.
  23167. var errMsg = '';
  23168. if ("development" !== 'production') {
  23169. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23170. }
  23171. assert(!stageHandler.createOnAllSeries, errMsg);
  23172. if (seriesType) {
  23173. ecModel.eachRawSeriesByType(seriesType, createStub);
  23174. } else if (getTargetSeries) {
  23175. getTargetSeries(ecModel, api).each(createStub);
  23176. } // Otherwise, (usually it is legacy case), the overall task will only be
  23177. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23178. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23179. // dirty info from upstream.
  23180. else {
  23181. overallProgress = false;
  23182. each(ecModel.getSeries(), createStub);
  23183. }
  23184. function createStub(seriesModel) {
  23185. var pipelineId = seriesModel.uid;
  23186. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23187. // should be set as dirty and re-performed.
  23188. shouldOverallTaskDirty = true, createTask({
  23189. reset: stubReset,
  23190. onDirty: stubOnDirty
  23191. })));
  23192. stub.context = {
  23193. model: seriesModel,
  23194. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23195. // modifyOutputEnd: modifyOutputEnd
  23196. };
  23197. stub.agent = overallTask;
  23198. stub.__block = overallProgress;
  23199. scheduler._pipe(seriesModel, stub);
  23200. }
  23201. if (shouldOverallTaskDirty) {
  23202. overallTask.dirty();
  23203. }
  23204. };
  23205. Scheduler.prototype._pipe = function (seriesModel, task) {
  23206. var pipelineId = seriesModel.uid;
  23207. var pipeline = this._pipelineMap.get(pipelineId);
  23208. !pipeline.head && (pipeline.head = task);
  23209. pipeline.tail && pipeline.tail.pipe(task);
  23210. pipeline.tail = task;
  23211. task.__idxInPipeline = pipeline.count++;
  23212. task.__pipeline = pipeline;
  23213. };
  23214. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23215. if (isFunction(stageHandler)) {
  23216. stageHandler = {
  23217. overallReset: stageHandler,
  23218. seriesType: detectSeriseType(stageHandler)
  23219. };
  23220. }
  23221. stageHandler.uid = getUID('stageHandler');
  23222. visualType && (stageHandler.visualType = visualType);
  23223. return stageHandler;
  23224. };
  23225. return Scheduler;
  23226. }();
  23227. function overallTaskReset(context) {
  23228. context.overallReset(context.ecModel, context.api, context.payload);
  23229. }
  23230. function stubReset(context) {
  23231. return context.overallProgress && stubProgress;
  23232. }
  23233. function stubProgress() {
  23234. this.agent.dirty();
  23235. this.getDownstream().dirty();
  23236. }
  23237. function stubOnDirty() {
  23238. this.agent && this.agent.dirty();
  23239. }
  23240. function seriesTaskPlan(context) {
  23241. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23242. }
  23243. function seriesTaskReset(context) {
  23244. if (context.useClearVisual) {
  23245. context.data.clearAllVisual();
  23246. }
  23247. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23248. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23249. return makeSeriesTaskProgress(idx);
  23250. }) : singleSeriesTaskProgress;
  23251. }
  23252. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23253. function makeSeriesTaskProgress(resetDefineIdx) {
  23254. return function (params, context) {
  23255. var data = context.data;
  23256. var resetDefine = context.resetDefines[resetDefineIdx];
  23257. if (resetDefine && resetDefine.dataEach) {
  23258. for (var i = params.start; i < params.end; i++) {
  23259. resetDefine.dataEach(data, i);
  23260. }
  23261. } else if (resetDefine && resetDefine.progress) {
  23262. resetDefine.progress(params, data);
  23263. }
  23264. };
  23265. }
  23266. function seriesTaskCount(context) {
  23267. return context.data.count();
  23268. }
  23269. /**
  23270. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23271. * To ensure that they can work normally, they should work in block mode, that is,
  23272. * they should not be started util the previous tasks finished. So they cause the
  23273. * progressive rendering disabled. We try to detect the series type, to narrow down
  23274. * the block range to only the series type they concern, but not all series.
  23275. */
  23276. function detectSeriseType(legacyFunc) {
  23277. seriesType = null;
  23278. try {
  23279. // Assume there is no async when calling `eachSeriesByType`.
  23280. legacyFunc(ecModelMock, apiMock);
  23281. } catch (e) {}
  23282. return seriesType;
  23283. }
  23284. var ecModelMock = {};
  23285. var apiMock = {};
  23286. var seriesType;
  23287. mockMethods(ecModelMock, GlobalModel);
  23288. mockMethods(apiMock, ExtensionAPI);
  23289. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23290. seriesType = type;
  23291. };
  23292. ecModelMock.eachComponent = function (cond) {
  23293. if (cond.mainType === 'series' && cond.subType) {
  23294. seriesType = cond.subType;
  23295. }
  23296. };
  23297. function mockMethods(target, Clz) {
  23298. /* eslint-disable */
  23299. for (var name_1 in Clz.prototype) {
  23300. // Do not use hasOwnProperty
  23301. target[name_1] = noop;
  23302. }
  23303. /* eslint-enable */
  23304. }
  23305. /*
  23306. * Licensed to the Apache Software Foundation (ASF) under one
  23307. * or more contributor license agreements. See the NOTICE file
  23308. * distributed with this work for additional information
  23309. * regarding copyright ownership. The ASF licenses this file
  23310. * to you under the Apache License, Version 2.0 (the
  23311. * "License"); you may not use this file except in compliance
  23312. * with the License. You may obtain a copy of the License at
  23313. *
  23314. * http://www.apache.org/licenses/LICENSE-2.0
  23315. *
  23316. * Unless required by applicable law or agreed to in writing,
  23317. * software distributed under the License is distributed on an
  23318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23319. * KIND, either express or implied. See the License for the
  23320. * specific language governing permissions and limitations
  23321. * under the License.
  23322. */
  23323. /**
  23324. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23325. */
  23326. /*
  23327. * Licensed to the Apache Software Foundation (ASF) under one
  23328. * or more contributor license agreements. See the NOTICE file
  23329. * distributed with this work for additional information
  23330. * regarding copyright ownership. The ASF licenses this file
  23331. * to you under the Apache License, Version 2.0 (the
  23332. * "License"); you may not use this file except in compliance
  23333. * with the License. You may obtain a copy of the License at
  23334. *
  23335. * http://www.apache.org/licenses/LICENSE-2.0
  23336. *
  23337. * Unless required by applicable law or agreed to in writing,
  23338. * software distributed under the License is distributed on an
  23339. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23340. * KIND, either express or implied. See the License for the
  23341. * specific language governing permissions and limitations
  23342. * under the License.
  23343. */
  23344. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23345. var lightTheme = {
  23346. color: colorAll,
  23347. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23348. };
  23349. /*
  23350. * Licensed to the Apache Software Foundation (ASF) under one
  23351. * or more contributor license agreements. See the NOTICE file
  23352. * distributed with this work for additional information
  23353. * regarding copyright ownership. The ASF licenses this file
  23354. * to you under the Apache License, Version 2.0 (the
  23355. * "License"); you may not use this file except in compliance
  23356. * with the License. You may obtain a copy of the License at
  23357. *
  23358. * http://www.apache.org/licenses/LICENSE-2.0
  23359. *
  23360. * Unless required by applicable law or agreed to in writing,
  23361. * software distributed under the License is distributed on an
  23362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23363. * KIND, either express or implied. See the License for the
  23364. * specific language governing permissions and limitations
  23365. * under the License.
  23366. */
  23367. /**
  23368. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23369. */
  23370. /*
  23371. * Licensed to the Apache Software Foundation (ASF) under one
  23372. * or more contributor license agreements. See the NOTICE file
  23373. * distributed with this work for additional information
  23374. * regarding copyright ownership. The ASF licenses this file
  23375. * to you under the Apache License, Version 2.0 (the
  23376. * "License"); you may not use this file except in compliance
  23377. * with the License. You may obtain a copy of the License at
  23378. *
  23379. * http://www.apache.org/licenses/LICENSE-2.0
  23380. *
  23381. * Unless required by applicable law or agreed to in writing,
  23382. * software distributed under the License is distributed on an
  23383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23384. * KIND, either express or implied. See the License for the
  23385. * specific language governing permissions and limitations
  23386. * under the License.
  23387. */
  23388. var contrastColor = '#B9B8CE';
  23389. var backgroundColor = '#100C2A';
  23390. var axisCommon = function () {
  23391. return {
  23392. axisLine: {
  23393. lineStyle: {
  23394. color: contrastColor
  23395. }
  23396. },
  23397. splitLine: {
  23398. lineStyle: {
  23399. color: '#484753'
  23400. }
  23401. },
  23402. splitArea: {
  23403. areaStyle: {
  23404. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23405. }
  23406. },
  23407. minorSplitLine: {
  23408. lineStyle: {
  23409. color: '#20203B'
  23410. }
  23411. }
  23412. };
  23413. };
  23414. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23415. var theme = {
  23416. darkMode: true,
  23417. color: colorPalette,
  23418. backgroundColor: backgroundColor,
  23419. axisPointer: {
  23420. lineStyle: {
  23421. color: '#817f91'
  23422. },
  23423. crossStyle: {
  23424. color: '#817f91'
  23425. },
  23426. label: {
  23427. // TODO Contrast of label backgorundColor
  23428. color: '#fff'
  23429. }
  23430. },
  23431. legend: {
  23432. textStyle: {
  23433. color: contrastColor
  23434. }
  23435. },
  23436. textStyle: {
  23437. color: contrastColor
  23438. },
  23439. title: {
  23440. textStyle: {
  23441. color: '#EEF1FA'
  23442. },
  23443. subtextStyle: {
  23444. color: '#B9B8CE'
  23445. }
  23446. },
  23447. toolbox: {
  23448. iconStyle: {
  23449. borderColor: contrastColor
  23450. }
  23451. },
  23452. dataZoom: {
  23453. borderColor: '#71708A',
  23454. textStyle: {
  23455. color: contrastColor
  23456. },
  23457. brushStyle: {
  23458. color: 'rgba(135,163,206,0.3)'
  23459. },
  23460. handleStyle: {
  23461. color: '#353450',
  23462. borderColor: '#C5CBE3'
  23463. },
  23464. moveHandleStyle: {
  23465. color: '#B0B6C3',
  23466. opacity: 0.3
  23467. },
  23468. fillerColor: 'rgba(135,163,206,0.2)',
  23469. emphasis: {
  23470. handleStyle: {
  23471. borderColor: '#91B7F2',
  23472. color: '#4D587D'
  23473. },
  23474. moveHandleStyle: {
  23475. color: '#636D9A',
  23476. opacity: 0.7
  23477. }
  23478. },
  23479. dataBackground: {
  23480. lineStyle: {
  23481. color: '#71708A',
  23482. width: 1
  23483. },
  23484. areaStyle: {
  23485. color: '#71708A'
  23486. }
  23487. },
  23488. selectedDataBackground: {
  23489. lineStyle: {
  23490. color: '#87A3CE'
  23491. },
  23492. areaStyle: {
  23493. color: '#87A3CE'
  23494. }
  23495. }
  23496. },
  23497. visualMap: {
  23498. textStyle: {
  23499. color: contrastColor
  23500. }
  23501. },
  23502. timeline: {
  23503. lineStyle: {
  23504. color: contrastColor
  23505. },
  23506. label: {
  23507. color: contrastColor
  23508. },
  23509. controlStyle: {
  23510. color: contrastColor,
  23511. borderColor: contrastColor
  23512. }
  23513. },
  23514. calendar: {
  23515. itemStyle: {
  23516. color: backgroundColor
  23517. },
  23518. dayLabel: {
  23519. color: contrastColor
  23520. },
  23521. monthLabel: {
  23522. color: contrastColor
  23523. },
  23524. yearLabel: {
  23525. color: contrastColor
  23526. }
  23527. },
  23528. timeAxis: axisCommon(),
  23529. logAxis: axisCommon(),
  23530. valueAxis: axisCommon(),
  23531. categoryAxis: axisCommon(),
  23532. line: {
  23533. symbol: 'circle'
  23534. },
  23535. graph: {
  23536. color: colorPalette
  23537. },
  23538. gauge: {
  23539. title: {
  23540. color: contrastColor
  23541. },
  23542. axisLine: {
  23543. lineStyle: {
  23544. color: [[1, 'rgba(207,212,219,0.2)']]
  23545. }
  23546. },
  23547. axisLabel: {
  23548. color: contrastColor
  23549. },
  23550. detail: {
  23551. color: '#EEF1FA'
  23552. }
  23553. },
  23554. candlestick: {
  23555. itemStyle: {
  23556. color: '#f64e56',
  23557. color0: '#54ea92',
  23558. borderColor: '#f64e56',
  23559. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23560. // borderColor0: '#09a443'
  23561. }
  23562. }
  23563. };
  23564. theme.categoryAxis.splitLine.show = false;
  23565. /**
  23566. * Usage of query:
  23567. * `chart.on('click', query, handler);`
  23568. * The `query` can be:
  23569. * + The component type query string, only `mainType` or `mainType.subType`,
  23570. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23571. * + The component query object, like:
  23572. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23573. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23574. * + The data query object, like:
  23575. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23576. * + The other query object (cmponent customized query), like:
  23577. * `{element: 'some'}` (only available in custom series).
  23578. *
  23579. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23580. * same as there is no such prop in the `query` object.
  23581. */
  23582. var ECEventProcessor =
  23583. /** @class */
  23584. function () {
  23585. function ECEventProcessor() {}
  23586. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23587. var cptQuery = {};
  23588. var dataQuery = {};
  23589. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23590. if (isString(query)) {
  23591. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23592. cptQuery.mainType = condCptType.main || null;
  23593. cptQuery.subType = condCptType.sub || null;
  23594. } // `query` is an object, convert to {mainType, index, name, id}.
  23595. else {
  23596. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23597. // can not be used in `compomentModel.filterForExposedEvent`.
  23598. var suffixes_1 = ['Index', 'Name', 'Id'];
  23599. var dataKeys_1 = {
  23600. name: 1,
  23601. dataIndex: 1,
  23602. dataType: 1
  23603. };
  23604. each(query, function (val, key) {
  23605. var reserved = false;
  23606. for (var i = 0; i < suffixes_1.length; i++) {
  23607. var propSuffix = suffixes_1[i];
  23608. var suffixPos = key.lastIndexOf(propSuffix);
  23609. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23610. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23611. if (mainType !== 'data') {
  23612. cptQuery.mainType = mainType;
  23613. cptQuery[propSuffix.toLowerCase()] = val;
  23614. reserved = true;
  23615. }
  23616. }
  23617. }
  23618. if (dataKeys_1.hasOwnProperty(key)) {
  23619. dataQuery[key] = val;
  23620. reserved = true;
  23621. }
  23622. if (!reserved) {
  23623. otherQuery[key] = val;
  23624. }
  23625. });
  23626. }
  23627. return {
  23628. cptQuery: cptQuery,
  23629. dataQuery: dataQuery,
  23630. otherQuery: otherQuery
  23631. };
  23632. };
  23633. ECEventProcessor.prototype.filter = function (eventType, query) {
  23634. // They should be assigned before each trigger call.
  23635. var eventInfo = this.eventInfo;
  23636. if (!eventInfo) {
  23637. return true;
  23638. }
  23639. var targetEl = eventInfo.targetEl;
  23640. var packedEvent = eventInfo.packedEvent;
  23641. var model = eventInfo.model;
  23642. var view = eventInfo.view; // For event like 'globalout'.
  23643. if (!model || !view) {
  23644. return true;
  23645. }
  23646. var cptQuery = query.cptQuery;
  23647. var dataQuery = query.dataQuery;
  23648. 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));
  23649. function check(query, host, prop, propOnHost) {
  23650. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23651. }
  23652. };
  23653. ECEventProcessor.prototype.afterTrigger = function () {
  23654. // Make sure the eventInfo won't be used in next trigger.
  23655. this.eventInfo = null;
  23656. };
  23657. return ECEventProcessor;
  23658. }();
  23659. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23660. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  23661. var seriesSymbolTask = {
  23662. createOnAllSeries: true,
  23663. // For legend.
  23664. performRawSeries: true,
  23665. reset: function (seriesModel, ecModel) {
  23666. var data = seriesModel.getData();
  23667. if (seriesModel.legendIcon) {
  23668. data.setVisual('legendIcon', seriesModel.legendIcon);
  23669. }
  23670. if (!seriesModel.hasSymbolVisual) {
  23671. return;
  23672. }
  23673. var symbolOptions = {};
  23674. var symbolOptionsCb = {};
  23675. var hasCallback = false;
  23676. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23677. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23678. var val = seriesModel.get(symbolPropName);
  23679. if (isFunction(val)) {
  23680. hasCallback = true;
  23681. symbolOptionsCb[symbolPropName] = val;
  23682. } else {
  23683. symbolOptions[symbolPropName] = val;
  23684. }
  23685. }
  23686. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23687. data.setVisual(extend({
  23688. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23689. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23690. }, symbolOptions)); // Only visible series has each data be visual encoded
  23691. if (ecModel.isSeriesFiltered(seriesModel)) {
  23692. return;
  23693. }
  23694. var symbolPropsCb = keys(symbolOptionsCb);
  23695. function dataEach(data, idx) {
  23696. var rawValue = seriesModel.getRawValue(idx);
  23697. var params = seriesModel.getDataParams(idx);
  23698. for (var i = 0; i < symbolPropsCb.length; i++) {
  23699. var symbolPropName = symbolPropsCb[i];
  23700. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23701. }
  23702. }
  23703. return {
  23704. dataEach: hasCallback ? dataEach : null
  23705. };
  23706. }
  23707. };
  23708. var dataSymbolTask = {
  23709. createOnAllSeries: true,
  23710. // For legend.
  23711. performRawSeries: true,
  23712. reset: function (seriesModel, ecModel) {
  23713. if (!seriesModel.hasSymbolVisual) {
  23714. return;
  23715. } // Only visible series has each data be visual encoded
  23716. if (ecModel.isSeriesFiltered(seriesModel)) {
  23717. return;
  23718. }
  23719. var data = seriesModel.getData();
  23720. function dataEach(data, idx) {
  23721. var itemModel = data.getItemModel(idx);
  23722. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  23723. var symbolPropName = SYMBOL_PROPS[i];
  23724. var val = itemModel.getShallow(symbolPropName, true);
  23725. if (val != null) {
  23726. data.setItemVisual(idx, symbolPropName, val);
  23727. }
  23728. }
  23729. }
  23730. return {
  23731. dataEach: data.hasItemOption ? dataEach : null
  23732. };
  23733. }
  23734. };
  23735. /*
  23736. * Licensed to the Apache Software Foundation (ASF) under one
  23737. * or more contributor license agreements. See the NOTICE file
  23738. * distributed with this work for additional information
  23739. * regarding copyright ownership. The ASF licenses this file
  23740. * to you under the Apache License, Version 2.0 (the
  23741. * "License"); you may not use this file except in compliance
  23742. * with the License. You may obtain a copy of the License at
  23743. *
  23744. * http://www.apache.org/licenses/LICENSE-2.0
  23745. *
  23746. * Unless required by applicable law or agreed to in writing,
  23747. * software distributed under the License is distributed on an
  23748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23749. * KIND, either express or implied. See the License for the
  23750. * specific language governing permissions and limitations
  23751. * under the License.
  23752. */
  23753. /**
  23754. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23755. */
  23756. /*
  23757. * Licensed to the Apache Software Foundation (ASF) under one
  23758. * or more contributor license agreements. See the NOTICE file
  23759. * distributed with this work for additional information
  23760. * regarding copyright ownership. The ASF licenses this file
  23761. * to you under the Apache License, Version 2.0 (the
  23762. * "License"); you may not use this file except in compliance
  23763. * with the License. You may obtain a copy of the License at
  23764. *
  23765. * http://www.apache.org/licenses/LICENSE-2.0
  23766. *
  23767. * Unless required by applicable law or agreed to in writing,
  23768. * software distributed under the License is distributed on an
  23769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23770. * KIND, either express or implied. See the License for the
  23771. * specific language governing permissions and limitations
  23772. * under the License.
  23773. */
  23774. function getItemVisualFromData(data, dataIndex, key) {
  23775. switch (key) {
  23776. case 'color':
  23777. var style = data.getItemVisual(dataIndex, 'style');
  23778. return style[data.getVisual('drawType')];
  23779. case 'opacity':
  23780. return data.getItemVisual(dataIndex, 'style').opacity;
  23781. case 'symbol':
  23782. case 'symbolSize':
  23783. case 'liftZ':
  23784. return data.getItemVisual(dataIndex, key);
  23785. default:
  23786. if ("development" !== 'production') {
  23787. console.warn("Unknown visual type " + key);
  23788. }
  23789. }
  23790. }
  23791. function getVisualFromData(data, key) {
  23792. switch (key) {
  23793. case 'color':
  23794. var style = data.getVisual('style');
  23795. return style[data.getVisual('drawType')];
  23796. case 'opacity':
  23797. return data.getVisual('style').opacity;
  23798. case 'symbol':
  23799. case 'symbolSize':
  23800. case 'liftZ':
  23801. return data.getVisual(key);
  23802. default:
  23803. if ("development" !== 'production') {
  23804. console.warn("Unknown visual type " + key);
  23805. }
  23806. }
  23807. }
  23808. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23809. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23810. function getSeriesIndices(ecModel, payload) {
  23811. var seriesIndices = [];
  23812. ecModel.eachComponent({
  23813. mainType: 'series',
  23814. subType: seriesType,
  23815. query: payload
  23816. }, function (seriesModel) {
  23817. seriesIndices.push(seriesModel.seriesIndex);
  23818. });
  23819. return seriesIndices;
  23820. }
  23821. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23822. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23823. payload = extend({}, payload);
  23824. if ("development" !== 'production') {
  23825. deprecateReplaceLog(payload.type, eventsMap[1]);
  23826. }
  23827. api.dispatchAction(extend(payload, {
  23828. type: eventsMap[1],
  23829. seriesIndex: getSeriesIndices(ecModel, payload)
  23830. }));
  23831. });
  23832. });
  23833. }
  23834. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23835. var legacyEventName = type + eventPostfix;
  23836. if (!ecIns.isSilent(legacyEventName)) {
  23837. if ("development" !== 'production') {
  23838. deprecateLog("event " + legacyEventName + " is deprecated.");
  23839. }
  23840. ecModel.eachComponent({
  23841. mainType: 'series',
  23842. subType: 'pie'
  23843. }, function (seriesModel) {
  23844. var seriesIndex = seriesModel.seriesIndex;
  23845. var selectedMap = seriesModel.option.selectedMap;
  23846. var selected = payload.selected;
  23847. for (var i = 0; i < selected.length; i++) {
  23848. if (selected[i].seriesIndex === seriesIndex) {
  23849. var data = seriesModel.getData();
  23850. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23851. ecIns.trigger(legacyEventName, {
  23852. type: legacyEventName,
  23853. seriesId: seriesModel.id,
  23854. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23855. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  23856. });
  23857. }
  23858. }
  23859. });
  23860. }
  23861. }
  23862. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23863. messageCenter.on('selectchanged', function (params) {
  23864. var ecModel = api.getModel();
  23865. if (params.isFromClick) {
  23866. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23867. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23868. } else if (params.fromAction === 'select') {
  23869. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23870. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23871. } else if (params.fromAction === 'unselect') {
  23872. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23873. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23874. }
  23875. });
  23876. }
  23877. /*
  23878. * Licensed to the Apache Software Foundation (ASF) under one
  23879. * or more contributor license agreements. See the NOTICE file
  23880. * distributed with this work for additional information
  23881. * regarding copyright ownership. The ASF licenses this file
  23882. * to you under the Apache License, Version 2.0 (the
  23883. * "License"); you may not use this file except in compliance
  23884. * with the License. You may obtain a copy of the License at
  23885. *
  23886. * http://www.apache.org/licenses/LICENSE-2.0
  23887. *
  23888. * Unless required by applicable law or agreed to in writing,
  23889. * software distributed under the License is distributed on an
  23890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23891. * KIND, either express or implied. See the License for the
  23892. * specific language governing permissions and limitations
  23893. * under the License.
  23894. */
  23895. /**
  23896. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23897. */
  23898. /*
  23899. * Licensed to the Apache Software Foundation (ASF) under one
  23900. * or more contributor license agreements. See the NOTICE file
  23901. * distributed with this work for additional information
  23902. * regarding copyright ownership. The ASF licenses this file
  23903. * to you under the Apache License, Version 2.0 (the
  23904. * "License"); you may not use this file except in compliance
  23905. * with the License. You may obtain a copy of the License at
  23906. *
  23907. * http://www.apache.org/licenses/LICENSE-2.0
  23908. *
  23909. * Unless required by applicable law or agreed to in writing,
  23910. * software distributed under the License is distributed on an
  23911. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23912. * KIND, either express or implied. See the License for the
  23913. * specific language governing permissions and limitations
  23914. * under the License.
  23915. */
  23916. function findEventDispatcher(target, det, returnFirstMatch) {
  23917. var found;
  23918. while (target) {
  23919. if (det(target)) {
  23920. found = target;
  23921. if (returnFirstMatch) {
  23922. break;
  23923. }
  23924. }
  23925. target = target.__hostTarget || target.parent;
  23926. }
  23927. return found;
  23928. }
  23929. var wmUniqueIndex = Math.round(Math.random() * 9);
  23930. var supportDefineProperty = typeof Object.defineProperty === 'function';
  23931. var WeakMap = (function () {
  23932. function WeakMap() {
  23933. this._id = '__ec_inner_' + wmUniqueIndex++;
  23934. }
  23935. WeakMap.prototype.get = function (key) {
  23936. return this._guard(key)[this._id];
  23937. };
  23938. WeakMap.prototype.set = function (key, value) {
  23939. var target = this._guard(key);
  23940. if (supportDefineProperty) {
  23941. Object.defineProperty(target, this._id, {
  23942. value: value,
  23943. enumerable: false,
  23944. configurable: true
  23945. });
  23946. }
  23947. else {
  23948. target[this._id] = value;
  23949. }
  23950. return this;
  23951. };
  23952. WeakMap.prototype["delete"] = function (key) {
  23953. if (this.has(key)) {
  23954. delete this._guard(key)[this._id];
  23955. return true;
  23956. }
  23957. return false;
  23958. };
  23959. WeakMap.prototype.has = function (key) {
  23960. return !!this._guard(key)[this._id];
  23961. };
  23962. WeakMap.prototype._guard = function (key) {
  23963. if (key !== Object(key)) {
  23964. throw TypeError('Value of WeakMap is not a non-null object.');
  23965. }
  23966. return key;
  23967. };
  23968. return WeakMap;
  23969. }());
  23970. /**
  23971. * Triangle shape
  23972. * @inner
  23973. */
  23974. var Triangle = Path.extend({
  23975. type: 'triangle',
  23976. shape: {
  23977. cx: 0,
  23978. cy: 0,
  23979. width: 0,
  23980. height: 0
  23981. },
  23982. buildPath: function (path, shape) {
  23983. var cx = shape.cx;
  23984. var cy = shape.cy;
  23985. var width = shape.width / 2;
  23986. var height = shape.height / 2;
  23987. path.moveTo(cx, cy - height);
  23988. path.lineTo(cx + width, cy + height);
  23989. path.lineTo(cx - width, cy + height);
  23990. path.closePath();
  23991. }
  23992. });
  23993. /**
  23994. * Diamond shape
  23995. * @inner
  23996. */
  23997. var Diamond = Path.extend({
  23998. type: 'diamond',
  23999. shape: {
  24000. cx: 0,
  24001. cy: 0,
  24002. width: 0,
  24003. height: 0
  24004. },
  24005. buildPath: function (path, shape) {
  24006. var cx = shape.cx;
  24007. var cy = shape.cy;
  24008. var width = shape.width / 2;
  24009. var height = shape.height / 2;
  24010. path.moveTo(cx, cy - height);
  24011. path.lineTo(cx + width, cy);
  24012. path.lineTo(cx, cy + height);
  24013. path.lineTo(cx - width, cy);
  24014. path.closePath();
  24015. }
  24016. });
  24017. /**
  24018. * Pin shape
  24019. * @inner
  24020. */
  24021. var Pin = Path.extend({
  24022. type: 'pin',
  24023. shape: {
  24024. // x, y on the cusp
  24025. x: 0,
  24026. y: 0,
  24027. width: 0,
  24028. height: 0
  24029. },
  24030. buildPath: function (path, shape) {
  24031. var x = shape.x;
  24032. var y = shape.y;
  24033. var w = shape.width / 5 * 3; // Height must be larger than width
  24034. var h = Math.max(w, shape.height);
  24035. var r = w / 2; // Dist on y with tangent point and circle center
  24036. var dy = r * r / (h - r);
  24037. var cy = y - h + r + dy;
  24038. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  24039. var dx = Math.cos(angle) * r;
  24040. var tanX = Math.sin(angle);
  24041. var tanY = Math.cos(angle);
  24042. var cpLen = r * 0.6;
  24043. var cpLen2 = r * 0.7;
  24044. path.moveTo(x - dx, cy + dy);
  24045. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24046. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24047. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24048. path.closePath();
  24049. }
  24050. });
  24051. /**
  24052. * Arrow shape
  24053. * @inner
  24054. */
  24055. var Arrow = Path.extend({
  24056. type: 'arrow',
  24057. shape: {
  24058. x: 0,
  24059. y: 0,
  24060. width: 0,
  24061. height: 0
  24062. },
  24063. buildPath: function (ctx, shape) {
  24064. var height = shape.height;
  24065. var width = shape.width;
  24066. var x = shape.x;
  24067. var y = shape.y;
  24068. var dx = width / 3 * 2;
  24069. ctx.moveTo(x, y);
  24070. ctx.lineTo(x + dx, y + height);
  24071. ctx.lineTo(x, y + height / 4 * 3);
  24072. ctx.lineTo(x - dx, y + height);
  24073. ctx.lineTo(x, y);
  24074. ctx.closePath();
  24075. }
  24076. });
  24077. /**
  24078. * Map of path constructors
  24079. */
  24080. // TODO Use function to build symbol path.
  24081. var symbolCtors = {
  24082. line: Line,
  24083. rect: Rect,
  24084. roundRect: Rect,
  24085. square: Rect,
  24086. circle: Circle,
  24087. diamond: Diamond,
  24088. pin: Pin,
  24089. arrow: Arrow,
  24090. triangle: Triangle
  24091. };
  24092. var symbolShapeMakers = {
  24093. line: function (x, y, w, h, shape) {
  24094. shape.x1 = x;
  24095. shape.y1 = y + h / 2;
  24096. shape.x2 = x + w;
  24097. shape.y2 = y + h / 2;
  24098. },
  24099. rect: function (x, y, w, h, shape) {
  24100. shape.x = x;
  24101. shape.y = y;
  24102. shape.width = w;
  24103. shape.height = h;
  24104. },
  24105. roundRect: function (x, y, w, h, shape) {
  24106. shape.x = x;
  24107. shape.y = y;
  24108. shape.width = w;
  24109. shape.height = h;
  24110. shape.r = Math.min(w, h) / 4;
  24111. },
  24112. square: function (x, y, w, h, shape) {
  24113. var size = Math.min(w, h);
  24114. shape.x = x;
  24115. shape.y = y;
  24116. shape.width = size;
  24117. shape.height = size;
  24118. },
  24119. circle: function (x, y, w, h, shape) {
  24120. // Put circle in the center of square
  24121. shape.cx = x + w / 2;
  24122. shape.cy = y + h / 2;
  24123. shape.r = Math.min(w, h) / 2;
  24124. },
  24125. diamond: function (x, y, w, h, shape) {
  24126. shape.cx = x + w / 2;
  24127. shape.cy = y + h / 2;
  24128. shape.width = w;
  24129. shape.height = h;
  24130. },
  24131. pin: function (x, y, w, h, shape) {
  24132. shape.x = x + w / 2;
  24133. shape.y = y + h / 2;
  24134. shape.width = w;
  24135. shape.height = h;
  24136. },
  24137. arrow: function (x, y, w, h, shape) {
  24138. shape.x = x + w / 2;
  24139. shape.y = y + h / 2;
  24140. shape.width = w;
  24141. shape.height = h;
  24142. },
  24143. triangle: function (x, y, w, h, shape) {
  24144. shape.cx = x + w / 2;
  24145. shape.cy = y + h / 2;
  24146. shape.width = w;
  24147. shape.height = h;
  24148. }
  24149. };
  24150. var symbolBuildProxies = {};
  24151. each(symbolCtors, function (Ctor, name) {
  24152. symbolBuildProxies[name] = new Ctor();
  24153. });
  24154. var SymbolClz = Path.extend({
  24155. type: 'symbol',
  24156. shape: {
  24157. symbolType: '',
  24158. x: 0,
  24159. y: 0,
  24160. width: 0,
  24161. height: 0
  24162. },
  24163. calculateTextPosition: function (out, config, rect) {
  24164. var res = calculateTextPosition(out, config, rect);
  24165. var shape = this.shape;
  24166. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24167. res.y = rect.y + rect.height * 0.4;
  24168. }
  24169. return res;
  24170. },
  24171. buildPath: function (ctx, shape, inBundle) {
  24172. var symbolType = shape.symbolType;
  24173. if (symbolType !== 'none') {
  24174. var proxySymbol = symbolBuildProxies[symbolType];
  24175. if (!proxySymbol) {
  24176. // Default rect
  24177. symbolType = 'rect';
  24178. proxySymbol = symbolBuildProxies[symbolType];
  24179. }
  24180. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24181. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24182. }
  24183. }
  24184. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24185. function symbolPathSetColor(color, innerColor) {
  24186. if (this.type !== 'image') {
  24187. var symbolStyle = this.style;
  24188. if (this.__isEmptyBrush) {
  24189. symbolStyle.stroke = color;
  24190. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24191. symbolStyle.lineWidth = 2;
  24192. } else if (this.shape.symbolType === 'line') {
  24193. symbolStyle.stroke = color;
  24194. } else {
  24195. symbolStyle.fill = color;
  24196. }
  24197. this.markRedraw();
  24198. }
  24199. }
  24200. /**
  24201. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24202. */
  24203. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24204. keepAspect) {
  24205. // TODO Support image object, DynamicImage.
  24206. var isEmpty = symbolType.indexOf('empty') === 0;
  24207. if (isEmpty) {
  24208. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24209. }
  24210. var symbolPath;
  24211. if (symbolType.indexOf('image://') === 0) {
  24212. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24213. } else if (symbolType.indexOf('path://') === 0) {
  24214. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24215. } else {
  24216. symbolPath = new SymbolClz({
  24217. shape: {
  24218. symbolType: symbolType,
  24219. x: x,
  24220. y: y,
  24221. width: w,
  24222. height: h
  24223. }
  24224. });
  24225. }
  24226. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24227. symbolPath.setColor = symbolPathSetColor;
  24228. if (color) {
  24229. symbolPath.setColor(color);
  24230. }
  24231. return symbolPath;
  24232. }
  24233. function normalizeSymbolSize(symbolSize) {
  24234. if (!isArray(symbolSize)) {
  24235. symbolSize = [+symbolSize, +symbolSize];
  24236. }
  24237. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24238. }
  24239. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24240. if (symbolOffset == null) {
  24241. return;
  24242. }
  24243. if (!isArray(symbolOffset)) {
  24244. symbolOffset = [symbolOffset, symbolOffset];
  24245. }
  24246. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24247. }
  24248. function isSafeNum(num) {
  24249. return isFinite(num);
  24250. }
  24251. function createLinearGradient(ctx, obj, rect) {
  24252. var x = obj.x == null ? 0 : obj.x;
  24253. var x2 = obj.x2 == null ? 1 : obj.x2;
  24254. var y = obj.y == null ? 0 : obj.y;
  24255. var y2 = obj.y2 == null ? 0 : obj.y2;
  24256. if (!obj.global) {
  24257. x = x * rect.width + rect.x;
  24258. x2 = x2 * rect.width + rect.x;
  24259. y = y * rect.height + rect.y;
  24260. y2 = y2 * rect.height + rect.y;
  24261. }
  24262. x = isSafeNum(x) ? x : 0;
  24263. x2 = isSafeNum(x2) ? x2 : 1;
  24264. y = isSafeNum(y) ? y : 0;
  24265. y2 = isSafeNum(y2) ? y2 : 0;
  24266. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24267. return canvasGradient;
  24268. }
  24269. function createRadialGradient(ctx, obj, rect) {
  24270. var width = rect.width;
  24271. var height = rect.height;
  24272. var min = Math.min(width, height);
  24273. var x = obj.x == null ? 0.5 : obj.x;
  24274. var y = obj.y == null ? 0.5 : obj.y;
  24275. var r = obj.r == null ? 0.5 : obj.r;
  24276. if (!obj.global) {
  24277. x = x * width + rect.x;
  24278. y = y * height + rect.y;
  24279. r = r * min;
  24280. }
  24281. x = isSafeNum(x) ? x : 0.5;
  24282. y = isSafeNum(y) ? y : 0.5;
  24283. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24284. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24285. return canvasGradient;
  24286. }
  24287. function getCanvasGradient(ctx, obj, rect) {
  24288. var canvasGradient = obj.type === 'radial'
  24289. ? createRadialGradient(ctx, obj, rect)
  24290. : createLinearGradient(ctx, obj, rect);
  24291. var colorStops = obj.colorStops;
  24292. for (var i = 0; i < colorStops.length; i++) {
  24293. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24294. }
  24295. return canvasGradient;
  24296. }
  24297. function isClipPathChanged(clipPaths, prevClipPaths) {
  24298. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24299. return false;
  24300. }
  24301. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24302. return true;
  24303. }
  24304. for (var i = 0; i < clipPaths.length; i++) {
  24305. if (clipPaths[i] !== prevClipPaths[i]) {
  24306. return true;
  24307. }
  24308. }
  24309. return false;
  24310. }
  24311. function parseInt10(val) {
  24312. return parseInt(val, 10);
  24313. }
  24314. function getSize(root, whIdx, opts) {
  24315. var wh = ['width', 'height'][whIdx];
  24316. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24317. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24318. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24319. if (opts[wh] != null && opts[wh] !== 'auto') {
  24320. return parseFloat(opts[wh]);
  24321. }
  24322. var stl = document.defaultView.getComputedStyle(root);
  24323. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24324. - (parseInt10(stl[plt]) || 0)
  24325. - (parseInt10(stl[prb]) || 0)) | 0;
  24326. }
  24327. function normalizeLineDash(lineType, lineWidth) {
  24328. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24329. return null;
  24330. }
  24331. return lineType === 'dashed'
  24332. ? [4 * lineWidth, 2 * lineWidth]
  24333. : lineType === 'dotted'
  24334. ? [lineWidth]
  24335. : isNumber(lineType)
  24336. ? [lineType] : isArray(lineType) ? lineType : null;
  24337. }
  24338. function getLineDash(el) {
  24339. var style = el.style;
  24340. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24341. var lineDashOffset = style.lineDashOffset;
  24342. if (lineDash) {
  24343. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24344. if (lineScale_1 && lineScale_1 !== 1) {
  24345. lineDash = map(lineDash, function (rawVal) {
  24346. return rawVal / lineScale_1;
  24347. });
  24348. lineDashOffset /= lineScale_1;
  24349. }
  24350. }
  24351. return [lineDash, lineDashOffset];
  24352. }
  24353. var pathProxyForDraw = new PathProxy(true);
  24354. function styleHasStroke(style) {
  24355. var stroke = style.stroke;
  24356. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24357. }
  24358. function isValidStrokeFillStyle(strokeOrFill) {
  24359. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24360. }
  24361. function styleHasFill(style) {
  24362. var fill = style.fill;
  24363. return fill != null && fill !== 'none';
  24364. }
  24365. function doFillPath(ctx, style) {
  24366. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24367. var originalGlobalAlpha = ctx.globalAlpha;
  24368. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24369. ctx.fill();
  24370. ctx.globalAlpha = originalGlobalAlpha;
  24371. }
  24372. else {
  24373. ctx.fill();
  24374. }
  24375. }
  24376. function doStrokePath(ctx, style) {
  24377. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24378. var originalGlobalAlpha = ctx.globalAlpha;
  24379. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24380. ctx.stroke();
  24381. ctx.globalAlpha = originalGlobalAlpha;
  24382. }
  24383. else {
  24384. ctx.stroke();
  24385. }
  24386. }
  24387. function createCanvasPattern(ctx, pattern, el) {
  24388. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24389. if (isImageReady(image)) {
  24390. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24391. if (typeof DOMMatrix === 'function'
  24392. && canvasPattern
  24393. && canvasPattern.setTransform) {
  24394. var matrix = new DOMMatrix();
  24395. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24396. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24397. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24398. canvasPattern.setTransform(matrix);
  24399. }
  24400. return canvasPattern;
  24401. }
  24402. }
  24403. function brushPath(ctx, el, style, inBatch) {
  24404. var _a;
  24405. var hasStroke = styleHasStroke(style);
  24406. var hasFill = styleHasFill(style);
  24407. var strokePercent = style.strokePercent;
  24408. var strokePart = strokePercent < 1;
  24409. var firstDraw = !el.path;
  24410. if ((!el.silent || strokePart) && firstDraw) {
  24411. el.createPathProxy();
  24412. }
  24413. var path = el.path || pathProxyForDraw;
  24414. var dirtyFlag = el.__dirty;
  24415. if (!inBatch) {
  24416. var fill = style.fill;
  24417. var stroke = style.stroke;
  24418. var hasFillGradient = hasFill && !!fill.colorStops;
  24419. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24420. var hasFillPattern = hasFill && !!fill.image;
  24421. var hasStrokePattern = hasStroke && !!stroke.image;
  24422. var fillGradient = void 0;
  24423. var strokeGradient = void 0;
  24424. var fillPattern = void 0;
  24425. var strokePattern = void 0;
  24426. var rect = void 0;
  24427. if (hasFillGradient || hasStrokeGradient) {
  24428. rect = el.getBoundingRect();
  24429. }
  24430. if (hasFillGradient) {
  24431. fillGradient = dirtyFlag
  24432. ? getCanvasGradient(ctx, fill, rect)
  24433. : el.__canvasFillGradient;
  24434. el.__canvasFillGradient = fillGradient;
  24435. }
  24436. if (hasStrokeGradient) {
  24437. strokeGradient = dirtyFlag
  24438. ? getCanvasGradient(ctx, stroke, rect)
  24439. : el.__canvasStrokeGradient;
  24440. el.__canvasStrokeGradient = strokeGradient;
  24441. }
  24442. if (hasFillPattern) {
  24443. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24444. ? createCanvasPattern(ctx, fill, el)
  24445. : el.__canvasFillPattern;
  24446. el.__canvasFillPattern = fillPattern;
  24447. }
  24448. if (hasStrokePattern) {
  24449. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24450. ? createCanvasPattern(ctx, stroke, el)
  24451. : el.__canvasStrokePattern;
  24452. el.__canvasStrokePattern = fillPattern;
  24453. }
  24454. if (hasFillGradient) {
  24455. ctx.fillStyle = fillGradient;
  24456. }
  24457. else if (hasFillPattern) {
  24458. if (fillPattern) {
  24459. ctx.fillStyle = fillPattern;
  24460. }
  24461. else {
  24462. hasFill = false;
  24463. }
  24464. }
  24465. if (hasStrokeGradient) {
  24466. ctx.strokeStyle = strokeGradient;
  24467. }
  24468. else if (hasStrokePattern) {
  24469. if (strokePattern) {
  24470. ctx.strokeStyle = strokePattern;
  24471. }
  24472. else {
  24473. hasStroke = false;
  24474. }
  24475. }
  24476. }
  24477. var scale = el.getGlobalScale();
  24478. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24479. var lineDash;
  24480. var lineDashOffset;
  24481. if (ctx.setLineDash && style.lineDash) {
  24482. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24483. }
  24484. var needsRebuild = true;
  24485. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24486. path.setDPR(ctx.dpr);
  24487. if (strokePart) {
  24488. path.setContext(null);
  24489. }
  24490. else {
  24491. path.setContext(ctx);
  24492. needsRebuild = false;
  24493. }
  24494. path.reset();
  24495. el.buildPath(path, el.shape, inBatch);
  24496. path.toStatic();
  24497. el.pathUpdated();
  24498. }
  24499. if (needsRebuild) {
  24500. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24501. }
  24502. if (lineDash) {
  24503. ctx.setLineDash(lineDash);
  24504. ctx.lineDashOffset = lineDashOffset;
  24505. }
  24506. if (!inBatch) {
  24507. if (style.strokeFirst) {
  24508. if (hasStroke) {
  24509. doStrokePath(ctx, style);
  24510. }
  24511. if (hasFill) {
  24512. doFillPath(ctx, style);
  24513. }
  24514. }
  24515. else {
  24516. if (hasFill) {
  24517. doFillPath(ctx, style);
  24518. }
  24519. if (hasStroke) {
  24520. doStrokePath(ctx, style);
  24521. }
  24522. }
  24523. }
  24524. if (lineDash) {
  24525. ctx.setLineDash([]);
  24526. }
  24527. }
  24528. function brushImage(ctx, el, style) {
  24529. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24530. if (!image || !isImageReady(image)) {
  24531. return;
  24532. }
  24533. var x = style.x || 0;
  24534. var y = style.y || 0;
  24535. var width = el.getWidth();
  24536. var height = el.getHeight();
  24537. var aspect = image.width / image.height;
  24538. if (width == null && height != null) {
  24539. width = height * aspect;
  24540. }
  24541. else if (height == null && width != null) {
  24542. height = width / aspect;
  24543. }
  24544. else if (width == null && height == null) {
  24545. width = image.width;
  24546. height = image.height;
  24547. }
  24548. if (style.sWidth && style.sHeight) {
  24549. var sx = style.sx || 0;
  24550. var sy = style.sy || 0;
  24551. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24552. }
  24553. else if (style.sx && style.sy) {
  24554. var sx = style.sx;
  24555. var sy = style.sy;
  24556. var sWidth = width - sx;
  24557. var sHeight = height - sy;
  24558. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24559. }
  24560. else {
  24561. ctx.drawImage(image, x, y, width, height);
  24562. }
  24563. }
  24564. function brushText(ctx, el, style) {
  24565. var _a;
  24566. var text = style.text;
  24567. text != null && (text += '');
  24568. if (text) {
  24569. ctx.font = style.font || DEFAULT_FONT;
  24570. ctx.textAlign = style.textAlign;
  24571. ctx.textBaseline = style.textBaseline;
  24572. var lineDash = void 0;
  24573. var lineDashOffset = void 0;
  24574. if (ctx.setLineDash && style.lineDash) {
  24575. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24576. }
  24577. if (lineDash) {
  24578. ctx.setLineDash(lineDash);
  24579. ctx.lineDashOffset = lineDashOffset;
  24580. }
  24581. if (style.strokeFirst) {
  24582. if (styleHasStroke(style)) {
  24583. ctx.strokeText(text, style.x, style.y);
  24584. }
  24585. if (styleHasFill(style)) {
  24586. ctx.fillText(text, style.x, style.y);
  24587. }
  24588. }
  24589. else {
  24590. if (styleHasFill(style)) {
  24591. ctx.fillText(text, style.x, style.y);
  24592. }
  24593. if (styleHasStroke(style)) {
  24594. ctx.strokeText(text, style.x, style.y);
  24595. }
  24596. }
  24597. if (lineDash) {
  24598. ctx.setLineDash([]);
  24599. }
  24600. }
  24601. }
  24602. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24603. var STROKE_PROPS = [
  24604. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24605. ];
  24606. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24607. var styleChanged = false;
  24608. if (!forceSetAll) {
  24609. prevStyle = prevStyle || {};
  24610. if (style === prevStyle) {
  24611. return false;
  24612. }
  24613. }
  24614. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24615. flushPathDrawn(ctx, scope);
  24616. styleChanged = true;
  24617. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24618. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24619. }
  24620. if (forceSetAll || style.blend !== prevStyle.blend) {
  24621. if (!styleChanged) {
  24622. flushPathDrawn(ctx, scope);
  24623. styleChanged = true;
  24624. }
  24625. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24626. }
  24627. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24628. var propName = SHADOW_NUMBER_PROPS[i];
  24629. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24630. if (!styleChanged) {
  24631. flushPathDrawn(ctx, scope);
  24632. styleChanged = true;
  24633. }
  24634. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24635. }
  24636. }
  24637. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24638. if (!styleChanged) {
  24639. flushPathDrawn(ctx, scope);
  24640. styleChanged = true;
  24641. }
  24642. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24643. }
  24644. return styleChanged;
  24645. }
  24646. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24647. var style = getStyle(el, scope.inHover);
  24648. var prevStyle = forceSetAll
  24649. ? null
  24650. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24651. if (style === prevStyle) {
  24652. return false;
  24653. }
  24654. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24655. if (forceSetAll || style.fill !== prevStyle.fill) {
  24656. if (!styleChanged) {
  24657. flushPathDrawn(ctx, scope);
  24658. styleChanged = true;
  24659. }
  24660. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24661. }
  24662. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24663. if (!styleChanged) {
  24664. flushPathDrawn(ctx, scope);
  24665. styleChanged = true;
  24666. }
  24667. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24668. }
  24669. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24670. if (!styleChanged) {
  24671. flushPathDrawn(ctx, scope);
  24672. styleChanged = true;
  24673. }
  24674. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24675. }
  24676. if (el.hasStroke()) {
  24677. var lineWidth = style.lineWidth;
  24678. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24679. if (ctx.lineWidth !== newLineWidth) {
  24680. if (!styleChanged) {
  24681. flushPathDrawn(ctx, scope);
  24682. styleChanged = true;
  24683. }
  24684. ctx.lineWidth = newLineWidth;
  24685. }
  24686. }
  24687. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24688. var prop = STROKE_PROPS[i];
  24689. var propName = prop[0];
  24690. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24691. if (!styleChanged) {
  24692. flushPathDrawn(ctx, scope);
  24693. styleChanged = true;
  24694. }
  24695. ctx[propName] = style[propName] || prop[1];
  24696. }
  24697. }
  24698. return styleChanged;
  24699. }
  24700. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24701. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24702. }
  24703. function setContextTransform(ctx, el) {
  24704. var m = el.transform;
  24705. var dpr = ctx.dpr || 1;
  24706. if (m) {
  24707. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24708. }
  24709. else {
  24710. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24711. }
  24712. }
  24713. function updateClipStatus(clipPaths, ctx, scope) {
  24714. var allClipped = false;
  24715. for (var i = 0; i < clipPaths.length; i++) {
  24716. var clipPath = clipPaths[i];
  24717. allClipped = allClipped || clipPath.isZeroArea();
  24718. setContextTransform(ctx, clipPath);
  24719. ctx.beginPath();
  24720. clipPath.buildPath(ctx, clipPath.shape);
  24721. ctx.clip();
  24722. }
  24723. scope.allClipped = allClipped;
  24724. }
  24725. function isTransformChanged(m0, m1) {
  24726. if (m0 && m1) {
  24727. return m0[0] !== m1[0]
  24728. || m0[1] !== m1[1]
  24729. || m0[2] !== m1[2]
  24730. || m0[3] !== m1[3]
  24731. || m0[4] !== m1[4]
  24732. || m0[5] !== m1[5];
  24733. }
  24734. else if (!m0 && !m1) {
  24735. return false;
  24736. }
  24737. return true;
  24738. }
  24739. var DRAW_TYPE_PATH = 1;
  24740. var DRAW_TYPE_IMAGE = 2;
  24741. var DRAW_TYPE_TEXT = 3;
  24742. var DRAW_TYPE_INCREMENTAL = 4;
  24743. function canPathBatch(style) {
  24744. var hasFill = styleHasFill(style);
  24745. var hasStroke = styleHasStroke(style);
  24746. return !(style.lineDash
  24747. || !(+hasFill ^ +hasStroke)
  24748. || (hasFill && typeof style.fill !== 'string')
  24749. || (hasStroke && typeof style.stroke !== 'string')
  24750. || style.strokePercent < 1
  24751. || style.strokeOpacity < 1
  24752. || style.fillOpacity < 1);
  24753. }
  24754. function flushPathDrawn(ctx, scope) {
  24755. scope.batchFill && ctx.fill();
  24756. scope.batchStroke && ctx.stroke();
  24757. scope.batchFill = '';
  24758. scope.batchStroke = '';
  24759. }
  24760. function getStyle(el, inHover) {
  24761. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24762. }
  24763. function brushSingle(ctx, el) {
  24764. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24765. }
  24766. function brush(ctx, el, scope, isLast) {
  24767. var m = el.transform;
  24768. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24769. el.__dirty &= ~REDRAW_BIT;
  24770. el.__isRendered = false;
  24771. return;
  24772. }
  24773. var clipPaths = el.__clipPaths;
  24774. var prevElClipPaths = scope.prevElClipPaths;
  24775. var forceSetTransform = false;
  24776. var forceSetStyle = false;
  24777. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24778. if (prevElClipPaths && prevElClipPaths.length) {
  24779. flushPathDrawn(ctx, scope);
  24780. ctx.restore();
  24781. forceSetStyle = forceSetTransform = true;
  24782. scope.prevElClipPaths = null;
  24783. scope.allClipped = false;
  24784. scope.prevEl = null;
  24785. }
  24786. if (clipPaths && clipPaths.length) {
  24787. flushPathDrawn(ctx, scope);
  24788. ctx.save();
  24789. updateClipStatus(clipPaths, ctx, scope);
  24790. forceSetTransform = true;
  24791. }
  24792. scope.prevElClipPaths = clipPaths;
  24793. }
  24794. if (scope.allClipped) {
  24795. el.__isRendered = false;
  24796. return;
  24797. }
  24798. el.beforeBrush && el.beforeBrush();
  24799. el.innerBeforeBrush();
  24800. var prevEl = scope.prevEl;
  24801. if (!prevEl) {
  24802. forceSetStyle = forceSetTransform = true;
  24803. }
  24804. var canBatchPath = el instanceof Path
  24805. && el.autoBatch
  24806. && canPathBatch(el.style);
  24807. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24808. flushPathDrawn(ctx, scope);
  24809. setContextTransform(ctx, el);
  24810. }
  24811. else if (!canBatchPath) {
  24812. flushPathDrawn(ctx, scope);
  24813. }
  24814. var style = getStyle(el, scope.inHover);
  24815. if (el instanceof Path) {
  24816. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24817. forceSetStyle = true;
  24818. scope.lastDrawType = DRAW_TYPE_PATH;
  24819. }
  24820. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24821. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24822. ctx.beginPath();
  24823. }
  24824. brushPath(ctx, el, style, canBatchPath);
  24825. if (canBatchPath) {
  24826. scope.batchFill = style.fill || '';
  24827. scope.batchStroke = style.stroke || '';
  24828. }
  24829. }
  24830. else {
  24831. if (el instanceof TSpan) {
  24832. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24833. forceSetStyle = true;
  24834. scope.lastDrawType = DRAW_TYPE_TEXT;
  24835. }
  24836. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24837. brushText(ctx, el, style);
  24838. }
  24839. else if (el instanceof ZRImage) {
  24840. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24841. forceSetStyle = true;
  24842. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24843. }
  24844. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24845. brushImage(ctx, el, style);
  24846. }
  24847. else if (el.getTemporalDisplayables) {
  24848. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24849. forceSetStyle = true;
  24850. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24851. }
  24852. brushIncremental(ctx, el, scope);
  24853. }
  24854. }
  24855. if (canBatchPath && isLast) {
  24856. flushPathDrawn(ctx, scope);
  24857. }
  24858. el.innerAfterBrush();
  24859. el.afterBrush && el.afterBrush();
  24860. scope.prevEl = el;
  24861. el.__dirty = 0;
  24862. el.__isRendered = true;
  24863. }
  24864. function brushIncremental(ctx, el, scope) {
  24865. var displayables = el.getDisplayables();
  24866. var temporalDisplayables = el.getTemporalDisplayables();
  24867. ctx.save();
  24868. var innerScope = {
  24869. prevElClipPaths: null,
  24870. prevEl: null,
  24871. allClipped: false,
  24872. viewWidth: scope.viewWidth,
  24873. viewHeight: scope.viewHeight,
  24874. inHover: scope.inHover
  24875. };
  24876. var i;
  24877. var len;
  24878. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24879. var displayable = displayables[i];
  24880. displayable.beforeBrush && displayable.beforeBrush();
  24881. displayable.innerBeforeBrush();
  24882. brush(ctx, displayable, innerScope, i === len - 1);
  24883. displayable.innerAfterBrush();
  24884. displayable.afterBrush && displayable.afterBrush();
  24885. innerScope.prevEl = displayable;
  24886. }
  24887. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24888. var displayable = temporalDisplayables[i_1];
  24889. displayable.beforeBrush && displayable.beforeBrush();
  24890. displayable.innerBeforeBrush();
  24891. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24892. displayable.innerAfterBrush();
  24893. displayable.afterBrush && displayable.afterBrush();
  24894. innerScope.prevEl = displayable;
  24895. }
  24896. el.clearTemporalDisplayables();
  24897. el.notClear = true;
  24898. ctx.restore();
  24899. }
  24900. var decalMap = new WeakMap();
  24901. var decalCache = new LRU(100);
  24902. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24903. /**
  24904. * Create or update pattern image from decal options
  24905. *
  24906. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24907. * @return {Pattern} pattern with generated image, null if no decal
  24908. */
  24909. function createOrUpdatePatternFromDecal(decalObject, api) {
  24910. if (decalObject === 'none') {
  24911. return null;
  24912. }
  24913. var dpr = api.getDevicePixelRatio();
  24914. var zr = api.getZr();
  24915. var isSVG = zr.painter.type === 'svg';
  24916. if (decalObject.dirty) {
  24917. decalMap["delete"](decalObject);
  24918. }
  24919. var oldPattern = decalMap.get(decalObject);
  24920. if (oldPattern) {
  24921. return oldPattern;
  24922. }
  24923. var decalOpt = defaults(decalObject, {
  24924. symbol: 'rect',
  24925. symbolSize: 1,
  24926. symbolKeepAspect: true,
  24927. color: 'rgba(0, 0, 0, 0.2)',
  24928. backgroundColor: null,
  24929. dashArrayX: 5,
  24930. dashArrayY: 5,
  24931. rotation: 0,
  24932. maxTileWidth: 512,
  24933. maxTileHeight: 512
  24934. });
  24935. if (decalOpt.backgroundColor === 'none') {
  24936. decalOpt.backgroundColor = null;
  24937. }
  24938. var pattern = {
  24939. repeat: 'repeat'
  24940. };
  24941. setPatternnSource(pattern);
  24942. pattern.rotation = decalOpt.rotation;
  24943. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24944. decalMap.set(decalObject, pattern);
  24945. decalObject.dirty = false;
  24946. return pattern;
  24947. function setPatternnSource(pattern) {
  24948. var keys = [dpr];
  24949. var isValidKey = true;
  24950. for (var i = 0; i < decalKeys.length; ++i) {
  24951. var value = decalOpt[decalKeys[i]];
  24952. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  24953. isValidKey = false;
  24954. break;
  24955. }
  24956. keys.push(value);
  24957. }
  24958. var cacheKey;
  24959. if (isValidKey) {
  24960. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24961. var cache = decalCache.get(cacheKey);
  24962. if (cache) {
  24963. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24964. }
  24965. }
  24966. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24967. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24968. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24969. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24970. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24971. var canvas = !isSVG && platformApi.createCanvas();
  24972. var svgRoot = isSVG && {
  24973. tag: 'g',
  24974. attrs: {},
  24975. key: 'dcl',
  24976. children: []
  24977. };
  24978. var pSize = getPatternSize();
  24979. var ctx;
  24980. if (canvas) {
  24981. canvas.width = pSize.width * dpr;
  24982. canvas.height = pSize.height * dpr;
  24983. ctx = canvas.getContext('2d');
  24984. }
  24985. brushDecal();
  24986. if (isValidKey) {
  24987. decalCache.put(cacheKey, canvas || svgRoot);
  24988. }
  24989. pattern.image = canvas;
  24990. pattern.svgElement = svgRoot;
  24991. pattern.svgWidth = pSize.width;
  24992. pattern.svgHeight = pSize.height;
  24993. /**
  24994. * Get minimum length that can make a repeatable pattern.
  24995. *
  24996. * @return {Object} pattern width and height
  24997. */
  24998. function getPatternSize() {
  24999. /**
  25000. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25001. * |--- --- --- --- --- ...
  25002. * |-- -- -- -- -- -- -- -- ...
  25003. * |--- --- --- --- --- ...
  25004. * |-- -- -- -- -- -- -- -- ...
  25005. * So the minimum length of X is 15,
  25006. * which is the least common multiple of `3 + 2` and `2 + 1`
  25007. * |--- --- --- |--- --- ...
  25008. * |-- -- -- -- -- |-- -- -- ...
  25009. */
  25010. var width = 1;
  25011. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25012. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25013. }
  25014. var symbolRepeats = 1;
  25015. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25016. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25017. }
  25018. width *= symbolRepeats;
  25019. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25020. if ("development" !== 'production') {
  25021. var warn = function (attrName) {
  25022. /* eslint-disable-next-line */
  25023. 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.");
  25024. };
  25025. if (width > decalOpt.maxTileWidth) {
  25026. warn('maxTileWidth');
  25027. }
  25028. if (height > decalOpt.maxTileHeight) {
  25029. warn('maxTileHeight');
  25030. }
  25031. }
  25032. return {
  25033. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25034. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25035. };
  25036. }
  25037. function brushDecal() {
  25038. if (ctx) {
  25039. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25040. if (decalOpt.backgroundColor) {
  25041. ctx.fillStyle = decalOpt.backgroundColor;
  25042. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25043. }
  25044. }
  25045. var ySum = 0;
  25046. for (var i = 0; i < dashArrayY.length; ++i) {
  25047. ySum += dashArrayY[i];
  25048. }
  25049. if (ySum <= 0) {
  25050. // dashArrayY is 0, draw nothing
  25051. return;
  25052. }
  25053. var y = -lineBlockLengthY;
  25054. var yId = 0;
  25055. var yIdTotal = 0;
  25056. var xId0 = 0;
  25057. while (y < pSize.height) {
  25058. if (yId % 2 === 0) {
  25059. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25060. var x = 0;
  25061. var xId1 = 0;
  25062. var xId1Total = 0;
  25063. while (x < pSize.width * 2) {
  25064. var xSum = 0;
  25065. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25066. xSum += dashArrayX[xId0][i];
  25067. }
  25068. if (xSum <= 0) {
  25069. // Skip empty line
  25070. break;
  25071. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25072. if (xId1 % 2 === 0) {
  25073. var size = (1 - decalOpt.symbolSize) * 0.5;
  25074. var left = x + dashArrayX[xId0][xId1] * size;
  25075. var top_1 = y + dashArrayY[yId] * size;
  25076. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25077. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25078. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25079. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25080. }
  25081. x += dashArrayX[xId0][xId1];
  25082. ++xId1Total;
  25083. ++xId1;
  25084. if (xId1 === dashArrayX[xId0].length) {
  25085. xId1 = 0;
  25086. }
  25087. }
  25088. ++xId0;
  25089. if (xId0 === dashArrayX.length) {
  25090. xId0 = 0;
  25091. }
  25092. }
  25093. y += dashArrayY[yId];
  25094. ++yIdTotal;
  25095. ++yId;
  25096. if (yId === dashArrayY.length) {
  25097. yId = 0;
  25098. }
  25099. }
  25100. function brushSymbol(x, y, width, height, symbolType) {
  25101. var scale = isSVG ? 1 : dpr;
  25102. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25103. if (isSVG) {
  25104. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25105. if (symbolVNode) {
  25106. svgRoot.children.push(symbolVNode);
  25107. }
  25108. } else {
  25109. // Paint to canvas for all other renderers.
  25110. brushSingle(ctx, symbol);
  25111. }
  25112. }
  25113. }
  25114. }
  25115. }
  25116. /**
  25117. * Convert symbol array into normalized array
  25118. *
  25119. * @param {string | (string | string[])[]} symbol symbol input
  25120. * @return {string[][]} normolized symbol array
  25121. */
  25122. function normalizeSymbolArray(symbol) {
  25123. if (!symbol || symbol.length === 0) {
  25124. return [['rect']];
  25125. }
  25126. if (isString(symbol)) {
  25127. return [[symbol]];
  25128. }
  25129. var isAllString = true;
  25130. for (var i = 0; i < symbol.length; ++i) {
  25131. if (!isString(symbol[i])) {
  25132. isAllString = false;
  25133. break;
  25134. }
  25135. }
  25136. if (isAllString) {
  25137. return normalizeSymbolArray([symbol]);
  25138. }
  25139. var result = [];
  25140. for (var i = 0; i < symbol.length; ++i) {
  25141. if (isString(symbol[i])) {
  25142. result.push([symbol[i]]);
  25143. } else {
  25144. result.push(symbol[i]);
  25145. }
  25146. }
  25147. return result;
  25148. }
  25149. /**
  25150. * Convert dash input into dashArray
  25151. *
  25152. * @param {DecalDashArrayX} dash dash input
  25153. * @return {number[][]} normolized dash array
  25154. */
  25155. function normalizeDashArrayX(dash) {
  25156. if (!dash || dash.length === 0) {
  25157. return [[0, 0]];
  25158. }
  25159. if (isNumber(dash)) {
  25160. var dashValue = Math.ceil(dash);
  25161. return [[dashValue, dashValue]];
  25162. }
  25163. /**
  25164. * [20, 5] should be normalized into [[20, 5]],
  25165. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25166. */
  25167. var isAllNumber = true;
  25168. for (var i = 0; i < dash.length; ++i) {
  25169. if (!isNumber(dash[i])) {
  25170. isAllNumber = false;
  25171. break;
  25172. }
  25173. }
  25174. if (isAllNumber) {
  25175. return normalizeDashArrayX([dash]);
  25176. }
  25177. var result = [];
  25178. for (var i = 0; i < dash.length; ++i) {
  25179. if (isNumber(dash[i])) {
  25180. var dashValue = Math.ceil(dash[i]);
  25181. result.push([dashValue, dashValue]);
  25182. } else {
  25183. var dashValue = map(dash[i], function (n) {
  25184. return Math.ceil(n);
  25185. });
  25186. if (dashValue.length % 2 === 1) {
  25187. // [4, 2, 1] means |---- - -- |---- - -- |
  25188. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25189. result.push(dashValue.concat(dashValue));
  25190. } else {
  25191. result.push(dashValue);
  25192. }
  25193. }
  25194. }
  25195. return result;
  25196. }
  25197. /**
  25198. * Convert dash input into dashArray
  25199. *
  25200. * @param {DecalDashArrayY} dash dash input
  25201. * @return {number[]} normolized dash array
  25202. */
  25203. function normalizeDashArrayY(dash) {
  25204. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25205. return [0, 0];
  25206. }
  25207. if (isNumber(dash)) {
  25208. var dashValue_1 = Math.ceil(dash);
  25209. return [dashValue_1, dashValue_1];
  25210. }
  25211. var dashValue = map(dash, function (n) {
  25212. return Math.ceil(n);
  25213. });
  25214. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25215. }
  25216. /**
  25217. * Get block length of each line. A block is the length of dash line and space.
  25218. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25219. * that, so the block length of this line is 5.
  25220. *
  25221. * @param {number[][]} dash dash array of X or Y
  25222. * @return {number[]} block length of each line
  25223. */
  25224. function getLineBlockLengthX(dash) {
  25225. return map(dash, function (line) {
  25226. return getLineBlockLengthY(line);
  25227. });
  25228. }
  25229. function getLineBlockLengthY(dash) {
  25230. var blockLength = 0;
  25231. for (var i = 0; i < dash.length; ++i) {
  25232. blockLength += dash[i];
  25233. }
  25234. if (dash.length % 2 === 1) {
  25235. // [4, 2, 1] means |---- - -- |---- - -- |
  25236. // So total length is (4 + 2 + 1) * 2
  25237. return blockLength * 2;
  25238. }
  25239. return blockLength;
  25240. }
  25241. function decalVisual(ecModel, api) {
  25242. ecModel.eachRawSeries(function (seriesModel) {
  25243. if (ecModel.isSeriesFiltered(seriesModel)) {
  25244. return;
  25245. }
  25246. var data = seriesModel.getData();
  25247. if (data.hasItemVisual()) {
  25248. data.each(function (idx) {
  25249. var decal = data.getItemVisual(idx, 'decal');
  25250. if (decal) {
  25251. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25252. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25253. }
  25254. });
  25255. }
  25256. var decal = data.getVisual('decal');
  25257. if (decal) {
  25258. var style = data.getVisual('style');
  25259. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25260. }
  25261. });
  25262. }
  25263. var lifecycle = new Eventful();
  25264. // The implementations will be registered when installing the component.
  25265. // Avoid these code being bundled to the core module.
  25266. var implsStore = {}; // TODO Type
  25267. function registerImpl(name, impl) {
  25268. if ("development" !== 'production') {
  25269. if (implsStore[name]) {
  25270. error("Already has an implementation of " + name + ".");
  25271. }
  25272. }
  25273. implsStore[name] = impl;
  25274. }
  25275. function getImpl(name) {
  25276. if ("development" !== 'production') {
  25277. if (!implsStore[name]) {
  25278. error("Implementation of " + name + " doesn't exists.");
  25279. }
  25280. }
  25281. return implsStore[name];
  25282. }
  25283. var version$1 = '5.4.2';
  25284. var dependencies = {
  25285. zrender: '5.4.3'
  25286. };
  25287. var TEST_FRAME_REMAIN_TIME = 1;
  25288. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  25289. // So data stack stage should be in front of data processing stage.
  25290. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  25291. // put at the beginning of data processing.
  25292. var PRIORITY_PROCESSOR_FILTER = 1000;
  25293. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25294. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25295. var PRIORITY_VISUAL_LAYOUT = 1000;
  25296. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25297. var PRIORITY_VISUAL_GLOBAL = 2000;
  25298. var PRIORITY_VISUAL_CHART = 3000;
  25299. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25300. // overwrite the viusal result of component (like `visualMap`)
  25301. // using data item specific setting (like itemStyle.xxx on data item)
  25302. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25303. // visual result like `symbolSize`.
  25304. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25305. var PRIORITY_VISUAL_BRUSH = 5000;
  25306. var PRIORITY_VISUAL_ARIA = 6000;
  25307. var PRIORITY_VISUAL_DECAL = 7000;
  25308. var PRIORITY = {
  25309. PROCESSOR: {
  25310. FILTER: PRIORITY_PROCESSOR_FILTER,
  25311. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25312. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25313. },
  25314. VISUAL: {
  25315. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25316. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25317. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25318. CHART: PRIORITY_VISUAL_CHART,
  25319. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25320. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25321. BRUSH: PRIORITY_VISUAL_BRUSH,
  25322. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25323. ARIA: PRIORITY_VISUAL_ARIA,
  25324. DECAL: PRIORITY_VISUAL_DECAL
  25325. }
  25326. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25327. // where they must not be invoked nestedly, except the only case: invoke
  25328. // dispatchAction with updateMethod "none" in main process.
  25329. // This flag is used to carry out this rule.
  25330. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25331. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25332. var PENDING_UPDATE = '__pendingUpdate';
  25333. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25334. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25335. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25336. var CONNECT_STATUS_PENDING = 0;
  25337. var CONNECT_STATUS_UPDATING = 1;
  25338. var CONNECT_STATUS_UPDATED = 2;
  25339. function createRegisterEventWithLowercaseECharts(method) {
  25340. return function () {
  25341. var args = [];
  25342. for (var _i = 0; _i < arguments.length; _i++) {
  25343. args[_i] = arguments[_i];
  25344. }
  25345. if (this.isDisposed()) {
  25346. disposedWarning(this.id);
  25347. return;
  25348. }
  25349. return toLowercaseNameAndCallEventful(this, method, args);
  25350. };
  25351. }
  25352. function createRegisterEventWithLowercaseMessageCenter(method) {
  25353. return function () {
  25354. var args = [];
  25355. for (var _i = 0; _i < arguments.length; _i++) {
  25356. args[_i] = arguments[_i];
  25357. }
  25358. return toLowercaseNameAndCallEventful(this, method, args);
  25359. };
  25360. }
  25361. function toLowercaseNameAndCallEventful(host, method, args) {
  25362. // `args[0]` is event name. Event name is all lowercase.
  25363. args[0] = args[0] && args[0].toLowerCase();
  25364. return Eventful.prototype[method].apply(host, args);
  25365. }
  25366. var MessageCenter =
  25367. /** @class */
  25368. function (_super) {
  25369. __extends(MessageCenter, _super);
  25370. function MessageCenter() {
  25371. return _super !== null && _super.apply(this, arguments) || this;
  25372. }
  25373. return MessageCenter;
  25374. }(Eventful);
  25375. var messageCenterProto = MessageCenter.prototype;
  25376. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25377. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25378. // Internal method names for class ECharts
  25379. // ---------------------------------------
  25380. var prepare;
  25381. var prepareView;
  25382. var updateDirectly;
  25383. var updateMethods;
  25384. var doConvertPixel;
  25385. var updateStreamModes;
  25386. var doDispatchAction;
  25387. var flushPendingActions;
  25388. var triggerUpdatedEvent;
  25389. var bindRenderedEvent;
  25390. var bindMouseEvent;
  25391. var render;
  25392. var renderComponents;
  25393. var renderSeries;
  25394. var createExtensionAPI;
  25395. var enableConnect;
  25396. var markStatusToUpdate;
  25397. var applyChangedStates;
  25398. var ECharts =
  25399. /** @class */
  25400. function (_super) {
  25401. __extends(ECharts, _super);
  25402. function ECharts(dom, // Theme name or themeOption.
  25403. theme, opts) {
  25404. var _this = _super.call(this, new ECEventProcessor()) || this;
  25405. _this._chartsViews = [];
  25406. _this._chartsMap = {};
  25407. _this._componentsViews = [];
  25408. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25409. _this._pendingActions = [];
  25410. opts = opts || {}; // Get theme by name
  25411. if (isString(theme)) {
  25412. theme = themeStorage[theme];
  25413. }
  25414. _this._dom = dom;
  25415. var defaultRenderer = 'canvas';
  25416. var defaultCoarsePointer = 'auto';
  25417. var defaultUseDirtyRect = false;
  25418. if ("development" !== 'production') {
  25419. var root =
  25420. /* eslint-disable-next-line */
  25421. env.hasGlobalWindow ? window : global;
  25422. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25423. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25424. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25425. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25426. }
  25427. var zr = _this._zr = init(dom, {
  25428. renderer: opts.renderer || defaultRenderer,
  25429. devicePixelRatio: opts.devicePixelRatio,
  25430. width: opts.width,
  25431. height: opts.height,
  25432. ssr: opts.ssr,
  25433. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25434. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25435. pointerSize: opts.pointerSize
  25436. });
  25437. _this._ssr = opts.ssr; // Expect 60 fps.
  25438. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25439. theme = clone(theme);
  25440. theme && globalBackwardCompat(theme, true);
  25441. _this._theme = theme;
  25442. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25443. _this._coordSysMgr = new CoordinateSystemManager();
  25444. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25445. function prioritySortFunc(a, b) {
  25446. return a.__prio - b.__prio;
  25447. }
  25448. sort(visualFuncs, prioritySortFunc);
  25449. sort(dataProcessorFuncs, prioritySortFunc);
  25450. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25451. _this._messageCenter = new MessageCenter(); // Init mouse events
  25452. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25453. _this.resize = bind(_this.resize, _this);
  25454. zr.animation.on('frame', _this._onframe, _this);
  25455. bindRenderedEvent(zr, _this);
  25456. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25457. setAsPrimitive(_this);
  25458. return _this;
  25459. }
  25460. ECharts.prototype._onframe = function () {
  25461. if (this._disposed) {
  25462. return;
  25463. }
  25464. applyChangedStates(this);
  25465. var scheduler = this._scheduler; // Lazy update
  25466. if (this[PENDING_UPDATE]) {
  25467. var silent = this[PENDING_UPDATE].silent;
  25468. this[IN_MAIN_PROCESS_KEY] = true;
  25469. try {
  25470. prepare(this);
  25471. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25472. } catch (e) {
  25473. this[IN_MAIN_PROCESS_KEY] = false;
  25474. this[PENDING_UPDATE] = null;
  25475. throw e;
  25476. } // At present, in each frame, zrender performs:
  25477. // (1) animation step forward.
  25478. // (2) trigger('frame') (where this `_onframe` is called)
  25479. // (3) zrender flush (render).
  25480. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25481. // will render the final state of the elements before the real animation started.
  25482. this._zr.flush();
  25483. this[IN_MAIN_PROCESS_KEY] = false;
  25484. this[PENDING_UPDATE] = null;
  25485. flushPendingActions.call(this, silent);
  25486. triggerUpdatedEvent.call(this, silent);
  25487. } // Avoid do both lazy update and progress in one frame.
  25488. else if (scheduler.unfinished) {
  25489. // Stream progress.
  25490. var remainTime = TEST_FRAME_REMAIN_TIME;
  25491. var ecModel = this._model;
  25492. var api = this._api;
  25493. scheduler.unfinished = false;
  25494. do {
  25495. var startTime = +new Date();
  25496. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25497. scheduler.performDataProcessorTasks(ecModel);
  25498. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25499. // each frame is not a good user experience. So we follow the rule that
  25500. // the extent of the coordinate system is determined in the first frame (the
  25501. // frame is executed immediately after task reset.
  25502. // this._coordSysMgr.update(ecModel, api);
  25503. // console.log('--- ec frame visual ---', remainTime);
  25504. scheduler.performVisualTasks(ecModel);
  25505. renderSeries(this, this._model, api, 'remain', {});
  25506. remainTime -= +new Date() - startTime;
  25507. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25508. if (!scheduler.unfinished) {
  25509. this._zr.flush();
  25510. } // Else, zr flushing be ensue within the same frame,
  25511. // because zr flushing is after onframe event.
  25512. }
  25513. };
  25514. ECharts.prototype.getDom = function () {
  25515. return this._dom;
  25516. };
  25517. ECharts.prototype.getId = function () {
  25518. return this.id;
  25519. };
  25520. ECharts.prototype.getZr = function () {
  25521. return this._zr;
  25522. };
  25523. ECharts.prototype.isSSR = function () {
  25524. return this._ssr;
  25525. };
  25526. /* eslint-disable-next-line */
  25527. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25528. if (this[IN_MAIN_PROCESS_KEY]) {
  25529. if ("development" !== 'production') {
  25530. error('`setOption` should not be called during main process.');
  25531. }
  25532. return;
  25533. }
  25534. if (this._disposed) {
  25535. disposedWarning(this.id);
  25536. return;
  25537. }
  25538. var silent;
  25539. var replaceMerge;
  25540. var transitionOpt;
  25541. if (isObject(notMerge)) {
  25542. lazyUpdate = notMerge.lazyUpdate;
  25543. silent = notMerge.silent;
  25544. replaceMerge = notMerge.replaceMerge;
  25545. transitionOpt = notMerge.transition;
  25546. notMerge = notMerge.notMerge;
  25547. }
  25548. this[IN_MAIN_PROCESS_KEY] = true;
  25549. if (!this._model || notMerge) {
  25550. var optionManager = new OptionManager(this._api);
  25551. var theme = this._theme;
  25552. var ecModel = this._model = new GlobalModel();
  25553. ecModel.scheduler = this._scheduler;
  25554. ecModel.ssr = this._ssr;
  25555. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25556. }
  25557. this._model.setOption(option, {
  25558. replaceMerge: replaceMerge
  25559. }, optionPreprocessorFuncs);
  25560. var updateParams = {
  25561. seriesTransition: transitionOpt,
  25562. optionChanged: true
  25563. };
  25564. if (lazyUpdate) {
  25565. this[PENDING_UPDATE] = {
  25566. silent: silent,
  25567. updateParams: updateParams
  25568. };
  25569. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25570. // It should wake it up to make sure zrender start to render at the next frame.
  25571. this.getZr().wakeUp();
  25572. } else {
  25573. try {
  25574. prepare(this);
  25575. updateMethods.update.call(this, null, updateParams);
  25576. } catch (e) {
  25577. this[PENDING_UPDATE] = null;
  25578. this[IN_MAIN_PROCESS_KEY] = false;
  25579. throw e;
  25580. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  25581. // fetched after `setOption`.
  25582. if (!this._ssr) {
  25583. // not use flush when using ssr mode.
  25584. this._zr.flush();
  25585. }
  25586. this[PENDING_UPDATE] = null;
  25587. this[IN_MAIN_PROCESS_KEY] = false;
  25588. flushPendingActions.call(this, silent);
  25589. triggerUpdatedEvent.call(this, silent);
  25590. }
  25591. };
  25592. /**
  25593. * @deprecated
  25594. */
  25595. ECharts.prototype.setTheme = function () {
  25596. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25597. }; // We don't want developers to use getModel directly.
  25598. ECharts.prototype.getModel = function () {
  25599. return this._model;
  25600. };
  25601. ECharts.prototype.getOption = function () {
  25602. return this._model && this._model.getOption();
  25603. };
  25604. ECharts.prototype.getWidth = function () {
  25605. return this._zr.getWidth();
  25606. };
  25607. ECharts.prototype.getHeight = function () {
  25608. return this._zr.getHeight();
  25609. };
  25610. ECharts.prototype.getDevicePixelRatio = function () {
  25611. return this._zr.painter.dpr
  25612. /* eslint-disable-next-line */
  25613. || env.hasGlobalWindow && window.devicePixelRatio || 1;
  25614. };
  25615. /**
  25616. * Get canvas which has all thing rendered
  25617. * @deprecated Use renderToCanvas instead.
  25618. */
  25619. ECharts.prototype.getRenderedCanvas = function (opts) {
  25620. if ("development" !== 'production') {
  25621. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25622. }
  25623. return this.renderToCanvas(opts);
  25624. };
  25625. ECharts.prototype.renderToCanvas = function (opts) {
  25626. opts = opts || {};
  25627. var painter = this._zr.painter;
  25628. if ("development" !== 'production') {
  25629. if (painter.type !== 'canvas') {
  25630. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25631. }
  25632. }
  25633. return painter.getRenderedCanvas({
  25634. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25635. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25636. });
  25637. };
  25638. ECharts.prototype.renderToSVGString = function (opts) {
  25639. opts = opts || {};
  25640. var painter = this._zr.painter;
  25641. if ("development" !== 'production') {
  25642. if (painter.type !== 'svg') {
  25643. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25644. }
  25645. }
  25646. return painter.renderToString({
  25647. useViewBox: opts.useViewBox
  25648. });
  25649. };
  25650. /**
  25651. * Get svg data url
  25652. */
  25653. ECharts.prototype.getSvgDataURL = function () {
  25654. if (!env.svgSupported) {
  25655. return;
  25656. }
  25657. var zr = this._zr;
  25658. var list = zr.storage.getDisplayList(); // Stop animations
  25659. each(list, function (el) {
  25660. el.stopAnimation(null, true);
  25661. });
  25662. return zr.painter.toDataURL();
  25663. };
  25664. ECharts.prototype.getDataURL = function (opts) {
  25665. if (this._disposed) {
  25666. disposedWarning(this.id);
  25667. return;
  25668. }
  25669. opts = opts || {};
  25670. var excludeComponents = opts.excludeComponents;
  25671. var ecModel = this._model;
  25672. var excludesComponentViews = [];
  25673. var self = this;
  25674. each(excludeComponents, function (componentType) {
  25675. ecModel.eachComponent({
  25676. mainType: componentType
  25677. }, function (component) {
  25678. var view = self._componentsMap[component.__viewId];
  25679. if (!view.group.ignore) {
  25680. excludesComponentViews.push(view);
  25681. view.group.ignore = true;
  25682. }
  25683. });
  25684. });
  25685. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25686. each(excludesComponentViews, function (view) {
  25687. view.group.ignore = false;
  25688. });
  25689. return url;
  25690. };
  25691. ECharts.prototype.getConnectedDataURL = function (opts) {
  25692. if (this._disposed) {
  25693. disposedWarning(this.id);
  25694. return;
  25695. }
  25696. var isSvg = opts.type === 'svg';
  25697. var groupId = this.group;
  25698. var mathMin = Math.min;
  25699. var mathMax = Math.max;
  25700. var MAX_NUMBER = Infinity;
  25701. if (connectedGroups[groupId]) {
  25702. var left_1 = MAX_NUMBER;
  25703. var top_1 = MAX_NUMBER;
  25704. var right_1 = -MAX_NUMBER;
  25705. var bottom_1 = -MAX_NUMBER;
  25706. var canvasList_1 = [];
  25707. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  25708. each(instances$1, function (chart, id) {
  25709. if (chart.group === groupId) {
  25710. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  25711. var boundingRect = chart.getDom().getBoundingClientRect();
  25712. left_1 = mathMin(boundingRect.left, left_1);
  25713. top_1 = mathMin(boundingRect.top, top_1);
  25714. right_1 = mathMax(boundingRect.right, right_1);
  25715. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  25716. canvasList_1.push({
  25717. dom: canvas,
  25718. left: boundingRect.left,
  25719. top: boundingRect.top
  25720. });
  25721. }
  25722. });
  25723. left_1 *= dpr_1;
  25724. top_1 *= dpr_1;
  25725. right_1 *= dpr_1;
  25726. bottom_1 *= dpr_1;
  25727. var width = right_1 - left_1;
  25728. var height = bottom_1 - top_1;
  25729. var targetCanvas = platformApi.createCanvas();
  25730. var zr_1 = init(targetCanvas, {
  25731. renderer: isSvg ? 'svg' : 'canvas'
  25732. });
  25733. zr_1.resize({
  25734. width: width,
  25735. height: height
  25736. });
  25737. if (isSvg) {
  25738. var content_1 = '';
  25739. each(canvasList_1, function (item) {
  25740. var x = item.left - left_1;
  25741. var y = item.top - top_1;
  25742. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  25743. });
  25744. zr_1.painter.getSvgRoot().innerHTML = content_1;
  25745. if (opts.connectedBackgroundColor) {
  25746. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  25747. }
  25748. zr_1.refreshImmediately();
  25749. return zr_1.painter.toDataURL();
  25750. } else {
  25751. // Background between the charts
  25752. if (opts.connectedBackgroundColor) {
  25753. zr_1.add(new Rect({
  25754. shape: {
  25755. x: 0,
  25756. y: 0,
  25757. width: width,
  25758. height: height
  25759. },
  25760. style: {
  25761. fill: opts.connectedBackgroundColor
  25762. }
  25763. }));
  25764. }
  25765. each(canvasList_1, function (item) {
  25766. var img = new ZRImage({
  25767. style: {
  25768. x: item.left * dpr_1 - left_1,
  25769. y: item.top * dpr_1 - top_1,
  25770. image: item.dom
  25771. }
  25772. });
  25773. zr_1.add(img);
  25774. });
  25775. zr_1.refreshImmediately();
  25776. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  25777. }
  25778. } else {
  25779. return this.getDataURL(opts);
  25780. }
  25781. };
  25782. ECharts.prototype.convertToPixel = function (finder, value) {
  25783. return doConvertPixel(this, 'convertToPixel', finder, value);
  25784. };
  25785. ECharts.prototype.convertFromPixel = function (finder, value) {
  25786. return doConvertPixel(this, 'convertFromPixel', finder, value);
  25787. };
  25788. /**
  25789. * Is the specified coordinate systems or components contain the given pixel point.
  25790. * @param {Array|number} value
  25791. * @return {boolean} result
  25792. */
  25793. ECharts.prototype.containPixel = function (finder, value) {
  25794. if (this._disposed) {
  25795. disposedWarning(this.id);
  25796. return;
  25797. }
  25798. var ecModel = this._model;
  25799. var result;
  25800. var findResult = parseFinder(ecModel, finder);
  25801. each(findResult, function (models, key) {
  25802. key.indexOf('Models') >= 0 && each(models, function (model) {
  25803. var coordSys = model.coordinateSystem;
  25804. if (coordSys && coordSys.containPoint) {
  25805. result = result || !!coordSys.containPoint(value);
  25806. } else if (key === 'seriesModels') {
  25807. var view = this._chartsMap[model.__viewId];
  25808. if (view && view.containPoint) {
  25809. result = result || view.containPoint(value, model);
  25810. } else {
  25811. if ("development" !== 'production') {
  25812. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  25813. }
  25814. }
  25815. } else {
  25816. if ("development" !== 'production') {
  25817. warn(key + ': containPoint is not supported');
  25818. }
  25819. }
  25820. }, this);
  25821. }, this);
  25822. return !!result;
  25823. };
  25824. /**
  25825. * Get visual from series or data.
  25826. * @param finder
  25827. * If string, e.g., 'series', means {seriesIndex: 0}.
  25828. * If Object, could contain some of these properties below:
  25829. * {
  25830. * seriesIndex / seriesId / seriesName,
  25831. * dataIndex / dataIndexInside
  25832. * }
  25833. * If dataIndex is not specified, series visual will be fetched,
  25834. * but not data item visual.
  25835. * If all of seriesIndex, seriesId, seriesName are not specified,
  25836. * visual will be fetched from first series.
  25837. * @param visualType 'color', 'symbol', 'symbolSize'
  25838. */
  25839. ECharts.prototype.getVisual = function (finder, visualType) {
  25840. var ecModel = this._model;
  25841. var parsedFinder = parseFinder(ecModel, finder, {
  25842. defaultMainType: 'series'
  25843. });
  25844. var seriesModel = parsedFinder.seriesModel;
  25845. if ("development" !== 'production') {
  25846. if (!seriesModel) {
  25847. warn('There is no specified series model');
  25848. }
  25849. }
  25850. var data = seriesModel.getData();
  25851. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  25852. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  25853. };
  25854. /**
  25855. * Get view of corresponding component model
  25856. */
  25857. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  25858. return this._componentsMap[componentModel.__viewId];
  25859. };
  25860. /**
  25861. * Get view of corresponding series model
  25862. */
  25863. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  25864. return this._chartsMap[seriesModel.__viewId];
  25865. };
  25866. ECharts.prototype._initEvents = function () {
  25867. var _this = this;
  25868. each(MOUSE_EVENT_NAMES, function (eveName) {
  25869. var handler = function (e) {
  25870. var ecModel = _this.getModel();
  25871. var el = e.target;
  25872. var params;
  25873. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  25874. if (isGlobalOut) {
  25875. params = {};
  25876. } else {
  25877. el && findEventDispatcher(el, function (parent) {
  25878. var ecData = getECData(parent);
  25879. if (ecData && ecData.dataIndex != null) {
  25880. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  25881. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  25882. return true;
  25883. } // If element has custom eventData of components
  25884. else if (ecData.eventData) {
  25885. params = extend({}, ecData.eventData);
  25886. return true;
  25887. }
  25888. }, true);
  25889. } // Contract: if params prepared in mouse event,
  25890. // these properties must be specified:
  25891. // {
  25892. // componentType: string (component main type)
  25893. // componentIndex: number
  25894. // }
  25895. // Otherwise event query can not work.
  25896. if (params) {
  25897. var componentType = params.componentType;
  25898. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  25899. // markLine/markPoint/markArea, the componentType is
  25900. // 'markLine'/'markPoint'/'markArea', but we should better
  25901. // enable them to be queried by seriesIndex, since their
  25902. // option is set in each series.
  25903. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  25904. componentType = 'series';
  25905. componentIndex = params.seriesIndex;
  25906. }
  25907. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  25908. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  25909. if ("development" !== 'production') {
  25910. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25911. // be missed, otherwise there is no way to distinguish source component.
  25912. // See `dataFormat.getDataParams`.
  25913. if (!isGlobalOut && !(model && view)) {
  25914. warn('model or view can not be found by params');
  25915. }
  25916. }
  25917. params.event = e;
  25918. params.type = eveName;
  25919. _this._$eventProcessor.eventInfo = {
  25920. targetEl: el,
  25921. packedEvent: params,
  25922. model: model,
  25923. view: view
  25924. };
  25925. _this.trigger(eveName, params);
  25926. }
  25927. }; // Consider that some component (like tooltip, brush, ...)
  25928. // register zr event handler, but user event handler might
  25929. // do anything, such as call `setOption` or `dispatchAction`,
  25930. // which probably update any of the content and probably
  25931. // cause problem if it is called previous other inner handlers.
  25932. handler.zrEventfulCallAtLast = true;
  25933. _this._zr.on(eveName, handler, _this);
  25934. });
  25935. each(eventActionMap, function (actionType, eventType) {
  25936. _this._messageCenter.on(eventType, function (event) {
  25937. this.trigger(eventType, event);
  25938. }, _this);
  25939. }); // Extra events
  25940. // TODO register?
  25941. each(['selectchanged'], function (eventType) {
  25942. _this._messageCenter.on(eventType, function (event) {
  25943. this.trigger(eventType, event);
  25944. }, _this);
  25945. });
  25946. handleLegacySelectEvents(this._messageCenter, this, this._api);
  25947. };
  25948. ECharts.prototype.isDisposed = function () {
  25949. return this._disposed;
  25950. };
  25951. ECharts.prototype.clear = function () {
  25952. if (this._disposed) {
  25953. disposedWarning(this.id);
  25954. return;
  25955. }
  25956. this.setOption({
  25957. series: []
  25958. }, true);
  25959. };
  25960. ECharts.prototype.dispose = function () {
  25961. if (this._disposed) {
  25962. disposedWarning(this.id);
  25963. return;
  25964. }
  25965. this._disposed = true;
  25966. var dom = this.getDom();
  25967. if (dom) {
  25968. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25969. }
  25970. var chart = this;
  25971. var api = chart._api;
  25972. var ecModel = chart._model;
  25973. each(chart._componentsViews, function (component) {
  25974. component.dispose(ecModel, api);
  25975. });
  25976. each(chart._chartsViews, function (chart) {
  25977. chart.dispose(ecModel, api);
  25978. }); // Dispose after all views disposed
  25979. chart._zr.dispose(); // Set properties to null.
  25980. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  25981. 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;
  25982. delete instances$1[chart.id];
  25983. };
  25984. /**
  25985. * Resize the chart
  25986. */
  25987. ECharts.prototype.resize = function (opts) {
  25988. if (this[IN_MAIN_PROCESS_KEY]) {
  25989. if ("development" !== 'production') {
  25990. error('`resize` should not be called during main process.');
  25991. }
  25992. return;
  25993. }
  25994. if (this._disposed) {
  25995. disposedWarning(this.id);
  25996. return;
  25997. }
  25998. this._zr.resize(opts);
  25999. var ecModel = this._model; // Resize loading effect
  26000. this._loadingFX && this._loadingFX.resize();
  26001. if (!ecModel) {
  26002. return;
  26003. }
  26004. var needPrepare = ecModel.resetOption('media');
  26005. var silent = opts && opts.silent; // There is some real cases that:
  26006. // chart.setOption(option, { lazyUpdate: true });
  26007. // chart.resize();
  26008. if (this[PENDING_UPDATE]) {
  26009. if (silent == null) {
  26010. silent = this[PENDING_UPDATE].silent;
  26011. }
  26012. needPrepare = true;
  26013. this[PENDING_UPDATE] = null;
  26014. }
  26015. this[IN_MAIN_PROCESS_KEY] = true;
  26016. try {
  26017. needPrepare && prepare(this);
  26018. updateMethods.update.call(this, {
  26019. type: 'resize',
  26020. animation: extend({
  26021. // Disable animation
  26022. duration: 0
  26023. }, opts && opts.animation)
  26024. });
  26025. } catch (e) {
  26026. this[IN_MAIN_PROCESS_KEY] = false;
  26027. throw e;
  26028. }
  26029. this[IN_MAIN_PROCESS_KEY] = false;
  26030. flushPendingActions.call(this, silent);
  26031. triggerUpdatedEvent.call(this, silent);
  26032. };
  26033. ECharts.prototype.showLoading = function (name, cfg) {
  26034. if (this._disposed) {
  26035. disposedWarning(this.id);
  26036. return;
  26037. }
  26038. if (isObject(name)) {
  26039. cfg = name;
  26040. name = '';
  26041. }
  26042. name = name || 'default';
  26043. this.hideLoading();
  26044. if (!loadingEffects[name]) {
  26045. if ("development" !== 'production') {
  26046. warn('Loading effects ' + name + ' not exists.');
  26047. }
  26048. return;
  26049. }
  26050. var el = loadingEffects[name](this._api, cfg);
  26051. var zr = this._zr;
  26052. this._loadingFX = el;
  26053. zr.add(el);
  26054. };
  26055. /**
  26056. * Hide loading effect
  26057. */
  26058. ECharts.prototype.hideLoading = function () {
  26059. if (this._disposed) {
  26060. disposedWarning(this.id);
  26061. return;
  26062. }
  26063. this._loadingFX && this._zr.remove(this._loadingFX);
  26064. this._loadingFX = null;
  26065. };
  26066. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26067. var payload = extend({}, eventObj);
  26068. payload.type = eventActionMap[eventObj.type];
  26069. return payload;
  26070. };
  26071. /**
  26072. * @param opt If pass boolean, means opt.silent
  26073. * @param opt.silent Default `false`. Whether trigger events.
  26074. * @param opt.flush Default `undefined`.
  26075. * true: Flush immediately, and then pixel in canvas can be fetched
  26076. * immediately. Caution: it might affect performance.
  26077. * false: Not flush.
  26078. * undefined: Auto decide whether perform flush.
  26079. */
  26080. ECharts.prototype.dispatchAction = function (payload, opt) {
  26081. if (this._disposed) {
  26082. disposedWarning(this.id);
  26083. return;
  26084. }
  26085. if (!isObject(opt)) {
  26086. opt = {
  26087. silent: !!opt
  26088. };
  26089. }
  26090. if (!actions[payload.type]) {
  26091. return;
  26092. } // Avoid dispatch action before setOption. Especially in `connect`.
  26093. if (!this._model) {
  26094. return;
  26095. } // May dispatchAction in rendering procedure
  26096. if (this[IN_MAIN_PROCESS_KEY]) {
  26097. this._pendingActions.push(payload);
  26098. return;
  26099. }
  26100. var silent = opt.silent;
  26101. doDispatchAction.call(this, payload, silent);
  26102. var flush = opt.flush;
  26103. if (flush) {
  26104. this._zr.flush();
  26105. } else if (flush !== false && env.browser.weChat) {
  26106. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26107. // hang when sliding page (on touch event), which cause that zr does not
  26108. // refresh until user interaction finished, which is not expected.
  26109. // But `dispatchAction` may be called too frequently when pan on touch
  26110. // screen, which impacts performance if do not throttle them.
  26111. this._throttledZrFlush();
  26112. }
  26113. flushPendingActions.call(this, silent);
  26114. triggerUpdatedEvent.call(this, silent);
  26115. };
  26116. ECharts.prototype.updateLabelLayout = function () {
  26117. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26118. // Not adding series labels.
  26119. // TODO
  26120. updatedSeries: []
  26121. });
  26122. };
  26123. ECharts.prototype.appendData = function (params) {
  26124. if (this._disposed) {
  26125. disposedWarning(this.id);
  26126. return;
  26127. }
  26128. var seriesIndex = params.seriesIndex;
  26129. var ecModel = this.getModel();
  26130. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26131. if ("development" !== 'production') {
  26132. assert(params.data && seriesModel);
  26133. }
  26134. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  26135. // system, util some scenario require that. In the expected usage of
  26136. // `appendData`, the initial extent of coordinate system should better
  26137. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26138. // the extent changed while `appendData`, the location of the painted
  26139. // graphic elements have to be changed, which make the usage of
  26140. // `appendData` meaningless.
  26141. this._scheduler.unfinished = true;
  26142. this.getZr().wakeUp();
  26143. }; // A work around for no `internal` modifier in ts yet but
  26144. // need to strictly hide private methods to JS users.
  26145. ECharts.internalField = function () {
  26146. prepare = function (ecIns) {
  26147. var scheduler = ecIns._scheduler;
  26148. scheduler.restorePipelines(ecIns._model);
  26149. scheduler.prepareStageTasks();
  26150. prepareView(ecIns, true);
  26151. prepareView(ecIns, false);
  26152. scheduler.plan();
  26153. };
  26154. /**
  26155. * Prepare view instances of charts and components
  26156. */
  26157. prepareView = function (ecIns, isComponent) {
  26158. var ecModel = ecIns._model;
  26159. var scheduler = ecIns._scheduler;
  26160. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26161. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26162. var zr = ecIns._zr;
  26163. var api = ecIns._api;
  26164. for (var i = 0; i < viewList.length; i++) {
  26165. viewList[i].__alive = false;
  26166. }
  26167. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26168. componentType !== 'series' && doPrepare(model);
  26169. }) : ecModel.eachSeries(doPrepare);
  26170. function doPrepare(model) {
  26171. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26172. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26173. // especially no id but have the same type & name & index. See the `model.id` generation
  26174. // rule in `makeIdAndName` and `viewId` generation rule here).
  26175. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26176. // the new model has nothing to do with the old model.
  26177. var requireNewView = model.__requireNewView; // This command should not work twice.
  26178. model.__requireNewView = false; // Consider: id same and type changed.
  26179. var viewId = '_ec_' + model.id + '_' + model.type;
  26180. var view = !requireNewView && viewMap[viewId];
  26181. if (!view) {
  26182. var classType = parseClassType(model.type);
  26183. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  26184. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26185. // For backward compat, still support a chart type declared as only subType
  26186. // like "liquidfill", but recommend "series.liquidfill"
  26187. // But need a base class to make a type series.
  26188. ChartView.getClass(classType.sub);
  26189. if ("development" !== 'production') {
  26190. assert(Clazz, classType.sub + ' does not exist.');
  26191. }
  26192. view = new Clazz();
  26193. view.init(ecModel, api);
  26194. viewMap[viewId] = view;
  26195. viewList.push(view);
  26196. zr.add(view.group);
  26197. }
  26198. model.__viewId = view.__id = viewId;
  26199. view.__alive = true;
  26200. view.__model = model;
  26201. view.group.__ecComponentInfo = {
  26202. mainType: model.mainType,
  26203. index: model.componentIndex
  26204. };
  26205. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26206. }
  26207. for (var i = 0; i < viewList.length;) {
  26208. var view = viewList[i];
  26209. if (!view.__alive) {
  26210. !isComponent && view.renderTask.dispose();
  26211. zr.remove(view.group);
  26212. view.dispose(ecModel, api);
  26213. viewList.splice(i, 1);
  26214. if (viewMap[view.__id] === view) {
  26215. delete viewMap[view.__id];
  26216. }
  26217. view.__id = view.group.__ecComponentInfo = null;
  26218. } else {
  26219. i++;
  26220. }
  26221. }
  26222. };
  26223. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26224. var ecModel = ecIns._model;
  26225. ecModel.setUpdatePayload(payload); // broadcast
  26226. if (!mainType) {
  26227. // FIXME
  26228. // Chart will not be update directly here, except set dirty.
  26229. // But there is no such scenario now.
  26230. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26231. return;
  26232. }
  26233. var query = {};
  26234. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26235. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26236. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26237. var condition = {
  26238. mainType: mainType,
  26239. query: query
  26240. };
  26241. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26242. var excludeSeriesId = payload.excludeSeriesId;
  26243. var excludeSeriesIdMap;
  26244. if (excludeSeriesId != null) {
  26245. excludeSeriesIdMap = createHashMap();
  26246. each(normalizeToArray(excludeSeriesId), function (id) {
  26247. var modelId = convertOptionIdName(id, null);
  26248. if (modelId != null) {
  26249. excludeSeriesIdMap.set(modelId, true);
  26250. }
  26251. });
  26252. } // If dispatchAction before setOption, do nothing.
  26253. ecModel && ecModel.eachComponent(condition, function (model) {
  26254. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26255. if (isExcluded) {
  26256. return;
  26257. }
  26258. if (isHighDownPayload(payload)) {
  26259. if (model instanceof SeriesModel) {
  26260. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26261. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26262. }
  26263. } else {
  26264. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26265. focusSelf = _a.focusSelf,
  26266. dispatchers = _a.dispatchers;
  26267. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26268. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26269. } // PENDING:
  26270. // Whether to put this "enter emphasis" code in `ComponentView`,
  26271. // which will be the same as `ChartView` but might be not necessary
  26272. // and will be far from this logic.
  26273. if (dispatchers) {
  26274. each(dispatchers, function (dispatcher) {
  26275. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26276. });
  26277. }
  26278. }
  26279. } else if (isSelectChangePayload(payload)) {
  26280. // TODO geo
  26281. if (model instanceof SeriesModel) {
  26282. toggleSelectionFromPayload(model, payload, ecIns._api);
  26283. updateSeriesElementSelection(model);
  26284. markStatusToUpdate(ecIns);
  26285. }
  26286. }
  26287. }, ecIns);
  26288. ecModel && ecModel.eachComponent(condition, function (model) {
  26289. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26290. if (isExcluded) {
  26291. return;
  26292. }
  26293. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26294. }, ecIns);
  26295. function callView(view) {
  26296. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26297. }
  26298. };
  26299. updateMethods = {
  26300. prepareAndUpdate: function (payload) {
  26301. prepare(this);
  26302. updateMethods.update.call(this, payload, {
  26303. // Needs to mark option changed if newOption is given.
  26304. // It's from MagicType.
  26305. // TODO If use a separate flag optionChanged in payload?
  26306. optionChanged: payload.newOption != null
  26307. });
  26308. },
  26309. update: function (payload, updateParams) {
  26310. var ecModel = this._model;
  26311. var api = this._api;
  26312. var zr = this._zr;
  26313. var coordSysMgr = this._coordSysMgr;
  26314. var scheduler = this._scheduler; // update before setOption
  26315. if (!ecModel) {
  26316. return;
  26317. }
  26318. ecModel.setUpdatePayload(payload);
  26319. scheduler.restoreData(ecModel, payload);
  26320. scheduler.performSeriesTasks(ecModel); // TODO
  26321. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26322. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26323. // Create new coordinate system each update
  26324. // In LineView may save the old coordinate system and use it to get the original point.
  26325. coordSysMgr.create(ecModel, api);
  26326. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  26327. // stream modes after data processing, where the filtered data is used to
  26328. // determine whether to use progressive rendering.
  26329. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  26330. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26331. // the drawback is the full coord info can not be fetched. Fortunately this full
  26332. // coord is not required in stream mode updater currently.
  26333. coordSysMgr.update(ecModel, api);
  26334. clearColorPalette(ecModel);
  26335. scheduler.performVisualTasks(ecModel, payload);
  26336. render(this, ecModel, api, payload, updateParams); // Set background
  26337. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26338. var darkMode = ecModel.get('darkMode');
  26339. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  26340. if (darkMode != null && darkMode !== 'auto') {
  26341. zr.setDarkMode(darkMode);
  26342. }
  26343. lifecycle.trigger('afterupdate', ecModel, api);
  26344. },
  26345. updateTransform: function (payload) {
  26346. var _this = this;
  26347. var ecModel = this._model;
  26348. var api = this._api; // update before setOption
  26349. if (!ecModel) {
  26350. return;
  26351. }
  26352. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  26353. var componentDirtyList = [];
  26354. ecModel.eachComponent(function (componentType, componentModel) {
  26355. if (componentType === 'series') {
  26356. return;
  26357. }
  26358. var componentView = _this.getViewOfComponentModel(componentModel);
  26359. if (componentView && componentView.__alive) {
  26360. if (componentView.updateTransform) {
  26361. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26362. result && result.update && componentDirtyList.push(componentView);
  26363. } else {
  26364. componentDirtyList.push(componentView);
  26365. }
  26366. }
  26367. });
  26368. var seriesDirtyMap = createHashMap();
  26369. ecModel.eachSeries(function (seriesModel) {
  26370. var chartView = _this._chartsMap[seriesModel.__viewId];
  26371. if (chartView.updateTransform) {
  26372. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26373. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26374. } else {
  26375. seriesDirtyMap.set(seriesModel.uid, 1);
  26376. }
  26377. });
  26378. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26379. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26380. this._scheduler.performVisualTasks(ecModel, payload, {
  26381. setDirty: true,
  26382. dirtyMap: seriesDirtyMap
  26383. }); // Currently, not call render of components. Geo render cost a lot.
  26384. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26385. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26386. lifecycle.trigger('afterupdate', ecModel, api);
  26387. },
  26388. updateView: function (payload) {
  26389. var ecModel = this._model; // update before setOption
  26390. if (!ecModel) {
  26391. return;
  26392. }
  26393. ecModel.setUpdatePayload(payload);
  26394. ChartView.markUpdateMethod(payload, 'updateView');
  26395. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26396. this._scheduler.performVisualTasks(ecModel, payload, {
  26397. setDirty: true
  26398. });
  26399. render(this, ecModel, this._api, payload, {});
  26400. lifecycle.trigger('afterupdate', ecModel, this._api);
  26401. },
  26402. updateVisual: function (payload) {
  26403. // updateMethods.update.call(this, payload);
  26404. var _this = this;
  26405. var ecModel = this._model; // update before setOption
  26406. if (!ecModel) {
  26407. return;
  26408. }
  26409. ecModel.setUpdatePayload(payload); // clear all visual
  26410. ecModel.eachSeries(function (seriesModel) {
  26411. seriesModel.getData().clearAllVisual();
  26412. }); // Perform visual
  26413. ChartView.markUpdateMethod(payload, 'updateVisual');
  26414. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26415. this._scheduler.performVisualTasks(ecModel, payload, {
  26416. visualType: 'visual',
  26417. setDirty: true
  26418. });
  26419. ecModel.eachComponent(function (componentType, componentModel) {
  26420. if (componentType !== 'series') {
  26421. var componentView = _this.getViewOfComponentModel(componentModel);
  26422. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26423. }
  26424. });
  26425. ecModel.eachSeries(function (seriesModel) {
  26426. var chartView = _this._chartsMap[seriesModel.__viewId];
  26427. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26428. });
  26429. lifecycle.trigger('afterupdate', ecModel, this._api);
  26430. },
  26431. updateLayout: function (payload) {
  26432. updateMethods.update.call(this, payload);
  26433. }
  26434. };
  26435. doConvertPixel = function (ecIns, methodName, finder, value) {
  26436. if (ecIns._disposed) {
  26437. disposedWarning(ecIns.id);
  26438. return;
  26439. }
  26440. var ecModel = ecIns._model;
  26441. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26442. var result;
  26443. var parsedFinder = parseFinder(ecModel, finder);
  26444. for (var i = 0; i < coordSysList.length; i++) {
  26445. var coordSys = coordSysList[i];
  26446. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26447. return result;
  26448. }
  26449. }
  26450. if ("development" !== 'production') {
  26451. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26452. }
  26453. };
  26454. updateStreamModes = function (ecIns, ecModel) {
  26455. var chartsMap = ecIns._chartsMap;
  26456. var scheduler = ecIns._scheduler;
  26457. ecModel.eachSeries(function (seriesModel) {
  26458. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26459. });
  26460. };
  26461. doDispatchAction = function (payload, silent) {
  26462. var _this = this;
  26463. var ecModel = this.getModel();
  26464. var payloadType = payload.type;
  26465. var escapeConnect = payload.escapeConnect;
  26466. var actionWrap = actions[payloadType];
  26467. var actionInfo = actionWrap.actionInfo;
  26468. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26469. var updateMethod = cptTypeTmp.pop();
  26470. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26471. this[IN_MAIN_PROCESS_KEY] = true;
  26472. var payloads = [payload];
  26473. var batched = false; // Batch action
  26474. if (payload.batch) {
  26475. batched = true;
  26476. payloads = map(payload.batch, function (item) {
  26477. item = defaults(extend({}, item), payload);
  26478. item.batch = null;
  26479. return item;
  26480. });
  26481. }
  26482. var eventObjBatch = [];
  26483. var eventObj;
  26484. var isSelectChange = isSelectChangePayload(payload);
  26485. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  26486. if (isHighDown) {
  26487. allLeaveBlur(this._api);
  26488. }
  26489. each(payloads, function (batchItem) {
  26490. // Action can specify the event by return it.
  26491. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26492. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26493. eventObj.type = actionInfo.event || eventObj.type;
  26494. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26495. if (isHighDown) {
  26496. var _a = preParseFinder(payload),
  26497. queryOptionMap = _a.queryOptionMap,
  26498. mainTypeSpecified = _a.mainTypeSpecified;
  26499. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26500. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26501. markStatusToUpdate(_this);
  26502. } else if (isSelectChange) {
  26503. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26504. // geo still use 'geoselect'.
  26505. updateDirectly(_this, updateMethod, batchItem, 'series');
  26506. markStatusToUpdate(_this);
  26507. } else if (cptType) {
  26508. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26509. }
  26510. });
  26511. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26512. try {
  26513. // Still dirty
  26514. if (this[PENDING_UPDATE]) {
  26515. prepare(this);
  26516. updateMethods.update.call(this, payload);
  26517. this[PENDING_UPDATE] = null;
  26518. } else {
  26519. updateMethods[updateMethod].call(this, payload);
  26520. }
  26521. } catch (e) {
  26522. this[IN_MAIN_PROCESS_KEY] = false;
  26523. throw e;
  26524. }
  26525. } // Follow the rule of action batch
  26526. if (batched) {
  26527. eventObj = {
  26528. type: actionInfo.event || payloadType,
  26529. escapeConnect: escapeConnect,
  26530. batch: eventObjBatch
  26531. };
  26532. } else {
  26533. eventObj = eventObjBatch[0];
  26534. }
  26535. this[IN_MAIN_PROCESS_KEY] = false;
  26536. if (!silent) {
  26537. var messageCenter = this._messageCenter;
  26538. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26539. if (isSelectChange) {
  26540. var newObj = {
  26541. type: 'selectchanged',
  26542. escapeConnect: escapeConnect,
  26543. selected: getAllSelectedIndices(ecModel),
  26544. isFromClick: payload.isFromClick || false,
  26545. fromAction: payload.type,
  26546. fromActionPayload: payload
  26547. };
  26548. messageCenter.trigger(newObj.type, newObj);
  26549. }
  26550. }
  26551. };
  26552. flushPendingActions = function (silent) {
  26553. var pendingActions = this._pendingActions;
  26554. while (pendingActions.length) {
  26555. var payload = pendingActions.shift();
  26556. doDispatchAction.call(this, payload, silent);
  26557. }
  26558. };
  26559. triggerUpdatedEvent = function (silent) {
  26560. !silent && this.trigger('updated');
  26561. };
  26562. /**
  26563. * Event `rendered` is triggered when zr
  26564. * rendered. It is useful for realtime
  26565. * snapshot (reflect animation).
  26566. *
  26567. * Event `finished` is triggered when:
  26568. * (1) zrender rendering finished.
  26569. * (2) initial animation finished.
  26570. * (3) progressive rendering finished.
  26571. * (4) no pending action.
  26572. * (5) no delayed setOption needs to be processed.
  26573. */
  26574. bindRenderedEvent = function (zr, ecIns) {
  26575. zr.on('rendered', function (params) {
  26576. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatedly,
  26577. // so it should only be triggered when rendering indeed happens
  26578. // in zrender. (Consider the case that dipatchAction is keep
  26579. // triggering when mouse move).
  26580. if ( // Although zr is dirty if initial animation is not finished
  26581. // and this checking is called on frame, we also check
  26582. // animation finished for robustness.
  26583. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26584. ecIns.trigger('finished');
  26585. }
  26586. });
  26587. };
  26588. bindMouseEvent = function (zr, ecIns) {
  26589. zr.on('mouseover', function (e) {
  26590. var el = e.target;
  26591. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26592. if (dispatcher) {
  26593. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26594. markStatusToUpdate(ecIns);
  26595. }
  26596. }).on('mouseout', function (e) {
  26597. var el = e.target;
  26598. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26599. if (dispatcher) {
  26600. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26601. markStatusToUpdate(ecIns);
  26602. }
  26603. }).on('click', function (e) {
  26604. var el = e.target;
  26605. var dispatcher = findEventDispatcher(el, function (target) {
  26606. return getECData(target).dataIndex != null;
  26607. }, true);
  26608. if (dispatcher) {
  26609. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26610. var ecData = getECData(dispatcher);
  26611. ecIns._api.dispatchAction({
  26612. type: actionType,
  26613. dataType: ecData.dataType,
  26614. dataIndexInside: ecData.dataIndex,
  26615. seriesIndex: ecData.seriesIndex,
  26616. isFromClick: true
  26617. });
  26618. }
  26619. });
  26620. };
  26621. function clearColorPalette(ecModel) {
  26622. ecModel.clearColorPalette();
  26623. ecModel.eachSeries(function (seriesModel) {
  26624. seriesModel.clearColorPalette();
  26625. });
  26626. }
  26627. function allocateZlevels(ecModel) {
  26628. var componentZLevels = [];
  26629. var seriesZLevels = [];
  26630. var hasSeperateZLevel = false;
  26631. ecModel.eachComponent(function (componentType, componentModel) {
  26632. var zlevel = componentModel.get('zlevel') || 0;
  26633. var z = componentModel.get('z') || 0;
  26634. var zlevelKey = componentModel.getZLevelKey();
  26635. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  26636. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26637. zlevel: zlevel,
  26638. z: z,
  26639. idx: componentModel.componentIndex,
  26640. type: componentType,
  26641. key: zlevelKey
  26642. });
  26643. });
  26644. if (hasSeperateZLevel) {
  26645. // Series after component
  26646. var zLevels = componentZLevels.concat(seriesZLevels);
  26647. var lastSeriesZLevel_1;
  26648. var lastSeriesKey_1;
  26649. sort(zLevels, function (a, b) {
  26650. if (a.zlevel === b.zlevel) {
  26651. return a.z - b.z;
  26652. }
  26653. return a.zlevel - b.zlevel;
  26654. });
  26655. each(zLevels, function (item) {
  26656. var componentModel = ecModel.getComponent(item.type, item.idx);
  26657. var zlevel = item.zlevel;
  26658. var key = item.key;
  26659. if (lastSeriesZLevel_1 != null) {
  26660. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26661. }
  26662. if (key) {
  26663. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26664. zlevel++;
  26665. }
  26666. lastSeriesKey_1 = key;
  26667. } else if (lastSeriesKey_1) {
  26668. if (zlevel === lastSeriesZLevel_1) {
  26669. zlevel++;
  26670. }
  26671. lastSeriesKey_1 = '';
  26672. }
  26673. lastSeriesZLevel_1 = zlevel;
  26674. componentModel.setZLevel(zlevel);
  26675. });
  26676. }
  26677. }
  26678. render = function (ecIns, ecModel, api, payload, updateParams) {
  26679. allocateZlevels(ecModel);
  26680. renderComponents(ecIns, ecModel, api, payload, updateParams);
  26681. each(ecIns._chartsViews, function (chart) {
  26682. chart.__alive = false;
  26683. });
  26684. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  26685. each(ecIns._chartsViews, function (chart) {
  26686. if (!chart.__alive) {
  26687. chart.remove(ecModel, api);
  26688. }
  26689. });
  26690. };
  26691. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  26692. each(dirtyList || ecIns._componentsViews, function (componentView) {
  26693. var componentModel = componentView.__model;
  26694. clearStates(componentModel, componentView);
  26695. componentView.render(componentModel, ecModel, api, payload);
  26696. updateZ(componentModel, componentView);
  26697. updateStates(componentModel, componentView);
  26698. });
  26699. };
  26700. /**
  26701. * Render each chart and component
  26702. */
  26703. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  26704. // Render all charts
  26705. var scheduler = ecIns._scheduler;
  26706. updateParams = extend(updateParams || {}, {
  26707. updatedSeries: ecModel.getSeries()
  26708. }); // TODO progressive?
  26709. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  26710. var unfinished = false;
  26711. ecModel.eachSeries(function (seriesModel) {
  26712. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26713. chartView.__alive = true;
  26714. var renderTask = chartView.renderTask;
  26715. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  26716. clearStates(seriesModel, chartView);
  26717. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  26718. renderTask.dirty();
  26719. }
  26720. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  26721. unfinished = true;
  26722. }
  26723. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  26724. // incremental render (always render from the __startIndex each frame)
  26725. // chartView.group.markRedraw();
  26726. updateBlend(seriesModel, chartView);
  26727. updateSeriesElementSelection(seriesModel);
  26728. });
  26729. scheduler.unfinished = unfinished || scheduler.unfinished;
  26730. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  26731. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  26732. ecModel.eachSeries(function (seriesModel) {
  26733. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  26734. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  26735. // label should be in normal status when layouting.
  26736. updateStates(seriesModel, chartView);
  26737. }); // If use hover layer
  26738. updateHoverLayerStatus(ecIns, ecModel);
  26739. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  26740. };
  26741. markStatusToUpdate = function (ecIns) {
  26742. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  26743. ecIns.getZr().wakeUp();
  26744. };
  26745. applyChangedStates = function (ecIns) {
  26746. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  26747. return;
  26748. }
  26749. ecIns.getZr().storage.traverse(function (el) {
  26750. // Not applied on removed elements, it may still in fading.
  26751. if (isElementRemoved(el)) {
  26752. return;
  26753. }
  26754. applyElementStates(el);
  26755. });
  26756. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  26757. };
  26758. function applyElementStates(el) {
  26759. var newStates = [];
  26760. var oldStates = el.currentStates; // Keep other states.
  26761. for (var i = 0; i < oldStates.length; i++) {
  26762. var stateName = oldStates[i];
  26763. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  26764. newStates.push(stateName);
  26765. }
  26766. } // Only use states when it's exists.
  26767. if (el.selected && el.states.select) {
  26768. newStates.push('select');
  26769. }
  26770. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  26771. newStates.push('emphasis');
  26772. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  26773. newStates.push('blur');
  26774. }
  26775. el.useStates(newStates);
  26776. }
  26777. function updateHoverLayerStatus(ecIns, ecModel) {
  26778. var zr = ecIns._zr;
  26779. var storage = zr.storage;
  26780. var elCount = 0;
  26781. storage.traverse(function (el) {
  26782. if (!el.isGroup) {
  26783. elCount++;
  26784. }
  26785. });
  26786. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  26787. ecModel.eachSeries(function (seriesModel) {
  26788. if (seriesModel.preventUsingHoverLayer) {
  26789. return;
  26790. }
  26791. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26792. if (chartView.__alive) {
  26793. chartView.eachRendered(function (el) {
  26794. if (el.states.emphasis) {
  26795. el.states.emphasis.hoverLayer = true;
  26796. }
  26797. });
  26798. }
  26799. });
  26800. }
  26801. }
  26802. /**
  26803. * Update chart and blend.
  26804. */
  26805. function updateBlend(seriesModel, chartView) {
  26806. var blendMode = seriesModel.get('blendMode') || null;
  26807. chartView.eachRendered(function (el) {
  26808. // FIXME marker and other components
  26809. if (!el.isGroup) {
  26810. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  26811. el.style.blend = blendMode;
  26812. }
  26813. });
  26814. }
  26815. function updateZ(model, view) {
  26816. if (model.preventAutoZ) {
  26817. return;
  26818. }
  26819. var z = model.get('z') || 0;
  26820. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  26821. view.eachRendered(function (el) {
  26822. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  26823. return true;
  26824. });
  26825. }
  26826. function doUpdateZ(el, z, zlevel, maxZ2) {
  26827. // Group may also have textContent
  26828. var label = el.getTextContent();
  26829. var labelLine = el.getTextGuideLine();
  26830. var isGroup = el.isGroup;
  26831. if (isGroup) {
  26832. // set z & zlevel of children elements of Group
  26833. var children = el.childrenRef();
  26834. for (var i = 0; i < children.length; i++) {
  26835. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  26836. }
  26837. } else {
  26838. // not Group
  26839. el.z = z;
  26840. el.zlevel = zlevel;
  26841. maxZ2 = Math.max(el.z2, maxZ2);
  26842. } // always set z and zlevel if label/labelLine exists
  26843. if (label) {
  26844. label.z = z;
  26845. label.zlevel = zlevel; // lift z2 of text content
  26846. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  26847. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  26848. }
  26849. if (labelLine) {
  26850. var textGuideLineConfig = el.textGuideLineConfig;
  26851. labelLine.z = z;
  26852. labelLine.zlevel = zlevel;
  26853. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  26854. }
  26855. return maxZ2;
  26856. } // Clear states without animation.
  26857. // TODO States on component.
  26858. function clearStates(model, view) {
  26859. view.eachRendered(function (el) {
  26860. // Not applied on removed elements, it may still in fading.
  26861. if (isElementRemoved(el)) {
  26862. return;
  26863. }
  26864. var textContent = el.getTextContent();
  26865. var textGuide = el.getTextGuideLine();
  26866. if (el.stateTransition) {
  26867. el.stateTransition = null;
  26868. }
  26869. if (textContent && textContent.stateTransition) {
  26870. textContent.stateTransition = null;
  26871. }
  26872. if (textGuide && textGuide.stateTransition) {
  26873. textGuide.stateTransition = null;
  26874. } // TODO If el is incremental.
  26875. if (el.hasState()) {
  26876. el.prevStates = el.currentStates;
  26877. el.clearStates();
  26878. } else if (el.prevStates) {
  26879. el.prevStates = null;
  26880. }
  26881. });
  26882. }
  26883. function updateStates(model, view) {
  26884. var stateAnimationModel = model.getModel('stateAnimation');
  26885. var enableAnimation = model.isAnimationEnabled();
  26886. var duration = stateAnimationModel.get('duration');
  26887. var stateTransition = duration > 0 ? {
  26888. duration: duration,
  26889. delay: stateAnimationModel.get('delay'),
  26890. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  26891. } : null;
  26892. view.eachRendered(function (el) {
  26893. if (el.states && el.states.emphasis) {
  26894. // Not applied on removed elements, it may still in fading.
  26895. if (isElementRemoved(el)) {
  26896. return;
  26897. }
  26898. if (el instanceof Path) {
  26899. savePathStates(el);
  26900. } // Only updated on changed element. In case element is incremental and don't want to rerender.
  26901. // TODO, a more proper way?
  26902. if (el.__dirty) {
  26903. var prevStates = el.prevStates; // Restore states without animation
  26904. if (prevStates) {
  26905. el.useStates(prevStates);
  26906. }
  26907. } // Update state transition and enable animation again.
  26908. if (enableAnimation) {
  26909. el.stateTransition = stateTransition;
  26910. var textContent = el.getTextContent();
  26911. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  26912. if (textContent) {
  26913. textContent.stateTransition = stateTransition;
  26914. }
  26915. if (textGuide) {
  26916. textGuide.stateTransition = stateTransition;
  26917. }
  26918. } // Use highlighted and selected flag to toggle states.
  26919. if (el.__dirty) {
  26920. applyElementStates(el);
  26921. }
  26922. }
  26923. });
  26924. }
  26925. createExtensionAPI = function (ecIns) {
  26926. return new (
  26927. /** @class */
  26928. function (_super) {
  26929. __extends(class_1, _super);
  26930. function class_1() {
  26931. return _super !== null && _super.apply(this, arguments) || this;
  26932. }
  26933. class_1.prototype.getCoordinateSystems = function () {
  26934. return ecIns._coordSysMgr.getCoordinateSystems();
  26935. };
  26936. class_1.prototype.getComponentByElement = function (el) {
  26937. while (el) {
  26938. var modelInfo = el.__ecComponentInfo;
  26939. if (modelInfo != null) {
  26940. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  26941. }
  26942. el = el.parent;
  26943. }
  26944. };
  26945. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  26946. enterEmphasis(el, highlightDigit);
  26947. markStatusToUpdate(ecIns);
  26948. };
  26949. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  26950. leaveEmphasis(el, highlightDigit);
  26951. markStatusToUpdate(ecIns);
  26952. };
  26953. class_1.prototype.enterBlur = function (el) {
  26954. enterBlur(el);
  26955. markStatusToUpdate(ecIns);
  26956. };
  26957. class_1.prototype.leaveBlur = function (el) {
  26958. leaveBlur(el);
  26959. markStatusToUpdate(ecIns);
  26960. };
  26961. class_1.prototype.enterSelect = function (el) {
  26962. enterSelect(el);
  26963. markStatusToUpdate(ecIns);
  26964. };
  26965. class_1.prototype.leaveSelect = function (el) {
  26966. leaveSelect(el);
  26967. markStatusToUpdate(ecIns);
  26968. };
  26969. class_1.prototype.getModel = function () {
  26970. return ecIns.getModel();
  26971. };
  26972. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  26973. return ecIns.getViewOfComponentModel(componentModel);
  26974. };
  26975. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  26976. return ecIns.getViewOfSeriesModel(seriesModel);
  26977. };
  26978. return class_1;
  26979. }(ExtensionAPI))(ecIns);
  26980. };
  26981. enableConnect = function (chart) {
  26982. function updateConnectedChartsStatus(charts, status) {
  26983. for (var i = 0; i < charts.length; i++) {
  26984. var otherChart = charts[i];
  26985. otherChart[CONNECT_STATUS_KEY] = status;
  26986. }
  26987. }
  26988. each(eventActionMap, function (actionType, eventType) {
  26989. chart._messageCenter.on(eventType, function (event) {
  26990. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  26991. if (event && event.escapeConnect) {
  26992. return;
  26993. }
  26994. var action_1 = chart.makeActionFromEvent(event);
  26995. var otherCharts_1 = [];
  26996. each(instances$1, function (otherChart) {
  26997. if (otherChart !== chart && otherChart.group === chart.group) {
  26998. otherCharts_1.push(otherChart);
  26999. }
  27000. });
  27001. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27002. each(otherCharts_1, function (otherChart) {
  27003. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27004. otherChart.dispatchAction(action_1);
  27005. }
  27006. });
  27007. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27008. }
  27009. });
  27010. });
  27011. };
  27012. }();
  27013. return ECharts;
  27014. }(Eventful);
  27015. var echartsProto = ECharts.prototype;
  27016. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27017. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27018. /**
  27019. * @deprecated
  27020. */
  27021. // @ts-ignore
  27022. echartsProto.one = function (eventName, cb, ctx) {
  27023. var self = this;
  27024. deprecateLog('ECharts#one is deprecated.');
  27025. function wrapped() {
  27026. var args2 = [];
  27027. for (var _i = 0; _i < arguments.length; _i++) {
  27028. args2[_i] = arguments[_i];
  27029. }
  27030. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  27031. self.off(eventName, wrapped);
  27032. }
  27033. this.on.call(this, eventName, wrapped, ctx);
  27034. };
  27035. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27036. function disposedWarning(id) {
  27037. if ("development" !== 'production') {
  27038. warn('Instance ' + id + ' has been disposed');
  27039. }
  27040. }
  27041. var actions = {};
  27042. /**
  27043. * Map eventType to actionType
  27044. */
  27045. var eventActionMap = {};
  27046. var dataProcessorFuncs = [];
  27047. var optionPreprocessorFuncs = [];
  27048. var visualFuncs = [];
  27049. var themeStorage = {};
  27050. var loadingEffects = {};
  27051. var instances$1 = {};
  27052. var connectedGroups = {};
  27053. var idBase = +new Date() - 0;
  27054. var groupIdBase = +new Date() - 0;
  27055. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27056. /**
  27057. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27058. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27059. * @param opts.width Use clientWidth of the input `dom` by default.
  27060. * Can be 'auto' (the same as null/undefined)
  27061. * @param opts.height Use clientHeight of the input `dom` by default.
  27062. * Can be 'auto' (the same as null/undefined)
  27063. * @param opts.locale Specify the locale.
  27064. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27065. */
  27066. function init$1(dom, theme, opts) {
  27067. var isClient = !(opts && opts.ssr);
  27068. if (isClient) {
  27069. if ("development" !== 'production') {
  27070. if (!dom) {
  27071. throw new Error('Initialize failed: invalid dom.');
  27072. }
  27073. }
  27074. var existInstance = getInstanceByDom(dom);
  27075. if (existInstance) {
  27076. if ("development" !== 'production') {
  27077. warn('There is a chart instance already initialized on the dom.');
  27078. }
  27079. return existInstance;
  27080. }
  27081. if ("development" !== 'production') {
  27082. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27083. 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.');
  27084. }
  27085. }
  27086. }
  27087. var chart = new ECharts(dom, theme, opts);
  27088. chart.id = 'ec_' + idBase++;
  27089. instances$1[chart.id] = chart;
  27090. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27091. enableConnect(chart);
  27092. lifecycle.trigger('afterinit', chart);
  27093. return chart;
  27094. }
  27095. /**
  27096. * @usage
  27097. * (A)
  27098. * ```js
  27099. * let chart1 = echarts.init(dom1);
  27100. * let chart2 = echarts.init(dom2);
  27101. * chart1.group = 'xxx';
  27102. * chart2.group = 'xxx';
  27103. * echarts.connect('xxx');
  27104. * ```
  27105. * (B)
  27106. * ```js
  27107. * let chart1 = echarts.init(dom1);
  27108. * let chart2 = echarts.init(dom2);
  27109. * echarts.connect('xxx', [chart1, chart2]);
  27110. * ```
  27111. */
  27112. function connect(groupId) {
  27113. // Is array of charts
  27114. if (isArray(groupId)) {
  27115. var charts = groupId;
  27116. groupId = null; // If any chart has group
  27117. each(charts, function (chart) {
  27118. if (chart.group != null) {
  27119. groupId = chart.group;
  27120. }
  27121. });
  27122. groupId = groupId || 'g_' + groupIdBase++;
  27123. each(charts, function (chart) {
  27124. chart.group = groupId;
  27125. });
  27126. }
  27127. connectedGroups[groupId] = true;
  27128. return groupId;
  27129. }
  27130. /**
  27131. * @deprecated
  27132. */
  27133. function disConnect(groupId) {
  27134. connectedGroups[groupId] = false;
  27135. }
  27136. /**
  27137. * Alias and backward compatibility
  27138. */
  27139. var disconnect = disConnect;
  27140. /**
  27141. * Dispose a chart instance
  27142. */
  27143. function dispose$1(chart) {
  27144. if (isString(chart)) {
  27145. chart = instances$1[chart];
  27146. } else if (!(chart instanceof ECharts)) {
  27147. // Try to treat as dom
  27148. chart = getInstanceByDom(chart);
  27149. }
  27150. if (chart instanceof ECharts && !chart.isDisposed()) {
  27151. chart.dispose();
  27152. }
  27153. }
  27154. function getInstanceByDom(dom) {
  27155. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27156. }
  27157. function getInstanceById(key) {
  27158. return instances$1[key];
  27159. }
  27160. /**
  27161. * Register theme
  27162. */
  27163. function registerTheme(name, theme) {
  27164. themeStorage[name] = theme;
  27165. }
  27166. /**
  27167. * Register option preprocessor
  27168. */
  27169. function registerPreprocessor(preprocessorFunc) {
  27170. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27171. optionPreprocessorFuncs.push(preprocessorFunc);
  27172. }
  27173. }
  27174. function registerProcessor(priority, processor) {
  27175. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27176. }
  27177. /**
  27178. * Register postIniter
  27179. * @param {Function} postInitFunc
  27180. */
  27181. function registerPostInit(postInitFunc) {
  27182. registerUpdateLifecycle('afterinit', postInitFunc);
  27183. }
  27184. /**
  27185. * Register postUpdater
  27186. * @param {Function} postUpdateFunc
  27187. */
  27188. function registerPostUpdate(postUpdateFunc) {
  27189. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27190. }
  27191. function registerUpdateLifecycle(name, cb) {
  27192. lifecycle.on(name, cb);
  27193. }
  27194. function registerAction(actionInfo, eventName, action) {
  27195. if (isFunction(eventName)) {
  27196. action = eventName;
  27197. eventName = '';
  27198. }
  27199. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27200. event: eventName
  27201. }][0]; // Event name is all lowercase
  27202. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27203. eventName = actionInfo.event;
  27204. if (eventActionMap[eventName]) {
  27205. // Already registered.
  27206. return;
  27207. } // Validate action type and event name.
  27208. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27209. if (!actions[actionType]) {
  27210. actions[actionType] = {
  27211. action: action,
  27212. actionInfo: actionInfo
  27213. };
  27214. }
  27215. eventActionMap[eventName] = actionType;
  27216. }
  27217. function registerCoordinateSystem(type, coordSysCreator) {
  27218. CoordinateSystemManager.register(type, coordSysCreator);
  27219. }
  27220. /**
  27221. * Get dimensions of specified coordinate system.
  27222. * @param {string} type
  27223. * @return {Array.<string|Object>}
  27224. */
  27225. function getCoordinateSystemDimensions(type) {
  27226. var coordSysCreator = CoordinateSystemManager.get(type);
  27227. if (coordSysCreator) {
  27228. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27229. }
  27230. }
  27231. function registerLayout(priority, layoutTask) {
  27232. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27233. }
  27234. function registerVisual(priority, visualTask) {
  27235. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27236. }
  27237. var registeredTasks = [];
  27238. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27239. if (isFunction(priority) || isObject(priority)) {
  27240. fn = priority;
  27241. priority = defaultPriority;
  27242. }
  27243. if ("development" !== 'production') {
  27244. if (isNaN(priority) || priority == null) {
  27245. throw new Error('Illegal priority');
  27246. } // Check duplicate
  27247. each(targetList, function (wrap) {
  27248. assert(wrap.__raw !== fn);
  27249. });
  27250. } // Already registered
  27251. if (indexOf(registeredTasks, fn) >= 0) {
  27252. return;
  27253. }
  27254. registeredTasks.push(fn);
  27255. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27256. stageHandler.__prio = priority;
  27257. stageHandler.__raw = fn;
  27258. targetList.push(stageHandler);
  27259. }
  27260. function registerLoading(name, loadingFx) {
  27261. loadingEffects[name] = loadingFx;
  27262. }
  27263. /**
  27264. * ZRender need a canvas context to do measureText.
  27265. * But in node environment canvas may be created by node-canvas.
  27266. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27267. *
  27268. *
  27269. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27270. *
  27271. * @example
  27272. * let Canvas = require('canvas');
  27273. * let echarts = require('echarts');
  27274. * echarts.setCanvasCreator(function () {
  27275. * // Small size is enough.
  27276. * return new Canvas(32, 32);
  27277. * });
  27278. */
  27279. function setCanvasCreator(creator) {
  27280. if ("development" !== 'production') {
  27281. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27282. }
  27283. setPlatformAPI({
  27284. createCanvas: creator
  27285. });
  27286. }
  27287. /**
  27288. * The parameters and usage: see `geoSourceManager.registerMap`.
  27289. * Compatible with previous `echarts.registerMap`.
  27290. */
  27291. function registerMap(mapName, geoJson, specialAreas) {
  27292. var registerMap = getImpl('registerMap');
  27293. registerMap && registerMap(mapName, geoJson, specialAreas);
  27294. }
  27295. function getMap(mapName) {
  27296. var getMap = getImpl('getMap');
  27297. return getMap && getMap(mapName);
  27298. }
  27299. var registerTransform = registerExternalTransform;
  27300. /**
  27301. * Globa dispatchAction to a specified chart instance.
  27302. */
  27303. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27304. // if (!payload || !payload.chartId) {
  27305. // // Must have chartId to find chart
  27306. // return;
  27307. // }
  27308. // const chart = instances[payload.chartId];
  27309. // if (chart) {
  27310. // chart.dispatchAction(payload, opt);
  27311. // }
  27312. // }
  27313. // Builtin global visual
  27314. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27315. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27316. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27317. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27318. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27319. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27320. registerPreprocessor(globalBackwardCompat);
  27321. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27322. registerLoading('default', defaultLoading); // Default actions
  27323. registerAction({
  27324. type: HIGHLIGHT_ACTION_TYPE,
  27325. event: HIGHLIGHT_ACTION_TYPE,
  27326. update: HIGHLIGHT_ACTION_TYPE
  27327. }, noop);
  27328. registerAction({
  27329. type: DOWNPLAY_ACTION_TYPE,
  27330. event: DOWNPLAY_ACTION_TYPE,
  27331. update: DOWNPLAY_ACTION_TYPE
  27332. }, noop);
  27333. registerAction({
  27334. type: SELECT_ACTION_TYPE,
  27335. event: SELECT_ACTION_TYPE,
  27336. update: SELECT_ACTION_TYPE
  27337. }, noop);
  27338. registerAction({
  27339. type: UNSELECT_ACTION_TYPE,
  27340. event: UNSELECT_ACTION_TYPE,
  27341. update: UNSELECT_ACTION_TYPE
  27342. }, noop);
  27343. registerAction({
  27344. type: TOGGLE_SELECT_ACTION_TYPE,
  27345. event: TOGGLE_SELECT_ACTION_TYPE,
  27346. update: TOGGLE_SELECT_ACTION_TYPE
  27347. }, noop); // Default theme
  27348. registerTheme('light', lightTheme);
  27349. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  27350. // be mounted on `echarts` is the extension `dataTool` is imported.
  27351. var dataTool = {};
  27352. var extensions = [];
  27353. var extensionRegisters = {
  27354. registerPreprocessor: registerPreprocessor,
  27355. registerProcessor: registerProcessor,
  27356. registerPostInit: registerPostInit,
  27357. registerPostUpdate: registerPostUpdate,
  27358. registerUpdateLifecycle: registerUpdateLifecycle,
  27359. registerAction: registerAction,
  27360. registerCoordinateSystem: registerCoordinateSystem,
  27361. registerLayout: registerLayout,
  27362. registerVisual: registerVisual,
  27363. registerTransform: registerTransform,
  27364. registerLoading: registerLoading,
  27365. registerMap: registerMap,
  27366. registerImpl: registerImpl,
  27367. PRIORITY: PRIORITY,
  27368. ComponentModel: ComponentModel,
  27369. ComponentView: ComponentView,
  27370. SeriesModel: SeriesModel,
  27371. ChartView: ChartView,
  27372. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27373. registerComponentModel: function (ComponentModelClass) {
  27374. ComponentModel.registerClass(ComponentModelClass);
  27375. },
  27376. registerComponentView: function (ComponentViewClass) {
  27377. ComponentView.registerClass(ComponentViewClass);
  27378. },
  27379. registerSeriesModel: function (SeriesModelClass) {
  27380. SeriesModel.registerClass(SeriesModelClass);
  27381. },
  27382. registerChartView: function (ChartViewClass) {
  27383. ChartView.registerClass(ChartViewClass);
  27384. },
  27385. registerSubTypeDefaulter: function (componentType, defaulter) {
  27386. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27387. },
  27388. registerPainter: function (painterType, PainterCtor) {
  27389. registerPainter(painterType, PainterCtor);
  27390. }
  27391. };
  27392. function use(ext) {
  27393. if (isArray(ext)) {
  27394. // use([ChartLine, ChartBar]);
  27395. each(ext, function (singleExt) {
  27396. use(singleExt);
  27397. });
  27398. return;
  27399. }
  27400. if (indexOf(extensions, ext) >= 0) {
  27401. return;
  27402. }
  27403. extensions.push(ext);
  27404. if (isFunction(ext)) {
  27405. ext = {
  27406. install: ext
  27407. };
  27408. }
  27409. ext.install(extensionRegisters);
  27410. }
  27411. /*
  27412. * Licensed to the Apache Software Foundation (ASF) under one
  27413. * or more contributor license agreements. See the NOTICE file
  27414. * distributed with this work for additional information
  27415. * regarding copyright ownership. The ASF licenses this file
  27416. * to you under the Apache License, Version 2.0 (the
  27417. * "License"); you may not use this file except in compliance
  27418. * with the License. You may obtain a copy of the License at
  27419. *
  27420. * http://www.apache.org/licenses/LICENSE-2.0
  27421. *
  27422. * Unless required by applicable law or agreed to in writing,
  27423. * software distributed under the License is distributed on an
  27424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27425. * KIND, either express or implied. See the License for the
  27426. * specific language governing permissions and limitations
  27427. * under the License.
  27428. */
  27429. /**
  27430. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27431. */
  27432. /*
  27433. * Licensed to the Apache Software Foundation (ASF) under one
  27434. * or more contributor license agreements. See the NOTICE file
  27435. * distributed with this work for additional information
  27436. * regarding copyright ownership. The ASF licenses this file
  27437. * to you under the Apache License, Version 2.0 (the
  27438. * "License"); you may not use this file except in compliance
  27439. * with the License. You may obtain a copy of the License at
  27440. *
  27441. * http://www.apache.org/licenses/LICENSE-2.0
  27442. *
  27443. * Unless required by applicable law or agreed to in writing,
  27444. * software distributed under the License is distributed on an
  27445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27446. * KIND, either express or implied. See the License for the
  27447. * specific language governing permissions and limitations
  27448. * under the License.
  27449. */
  27450. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27451. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27452. }
  27453. function defaultKeyGetter(item) {
  27454. return item;
  27455. }
  27456. var DataDiffer =
  27457. /** @class */
  27458. function () {
  27459. /**
  27460. * @param context Can be visited by this.context in callback.
  27461. */
  27462. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27463. diffMode) {
  27464. this._old = oldArr;
  27465. this._new = newArr;
  27466. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27467. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27468. this.context = context;
  27469. this._diffModeMultiple = diffMode === 'multiple';
  27470. }
  27471. /**
  27472. * Callback function when add a data
  27473. */
  27474. DataDiffer.prototype.add = function (func) {
  27475. this._add = func;
  27476. return this;
  27477. };
  27478. /**
  27479. * Callback function when update a data
  27480. */
  27481. DataDiffer.prototype.update = function (func) {
  27482. this._update = func;
  27483. return this;
  27484. };
  27485. /**
  27486. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27487. */
  27488. DataDiffer.prototype.updateManyToOne = function (func) {
  27489. this._updateManyToOne = func;
  27490. return this;
  27491. };
  27492. /**
  27493. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27494. */
  27495. DataDiffer.prototype.updateOneToMany = function (func) {
  27496. this._updateOneToMany = func;
  27497. return this;
  27498. };
  27499. /**
  27500. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27501. */
  27502. DataDiffer.prototype.updateManyToMany = function (func) {
  27503. this._updateManyToMany = func;
  27504. return this;
  27505. };
  27506. /**
  27507. * Callback function when remove a data
  27508. */
  27509. DataDiffer.prototype.remove = function (func) {
  27510. this._remove = func;
  27511. return this;
  27512. };
  27513. DataDiffer.prototype.execute = function () {
  27514. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27515. };
  27516. DataDiffer.prototype._executeOneToOne = function () {
  27517. var oldArr = this._old;
  27518. var newArr = this._new;
  27519. var newDataIndexMap = {};
  27520. var oldDataKeyArr = new Array(oldArr.length);
  27521. var newDataKeyArr = new Array(newArr.length);
  27522. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27523. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27524. for (var i = 0; i < oldArr.length; i++) {
  27525. var oldKey = oldDataKeyArr[i];
  27526. var newIdxMapVal = newDataIndexMap[oldKey];
  27527. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27528. if (newIdxMapValLen > 1) {
  27529. // Consider there is duplicate key (for example, use dataItem.name as key).
  27530. // We should make sure every item in newArr and oldArr can be visited.
  27531. var newIdx = newIdxMapVal.shift();
  27532. if (newIdxMapVal.length === 1) {
  27533. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27534. }
  27535. this._update && this._update(newIdx, i);
  27536. } else if (newIdxMapValLen === 1) {
  27537. newDataIndexMap[oldKey] = null;
  27538. this._update && this._update(newIdxMapVal, i);
  27539. } else {
  27540. this._remove && this._remove(i);
  27541. }
  27542. }
  27543. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27544. };
  27545. /**
  27546. * For example, consider the case:
  27547. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27548. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27549. * Where:
  27550. * o0, o1, n0 has key 'a' (many to one)
  27551. * o5, n4, n5, n6 has key 'b' (one to many)
  27552. * o2, n1 has key 'c' (one to one)
  27553. * n2, n3 has key 'd' (add)
  27554. * o3, o4 has key 'e' (remove)
  27555. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27556. * Then:
  27557. * (The order of the following directives are not ensured.)
  27558. * this._updateManyToOne(n0, [o0, o1]);
  27559. * this._updateOneToMany([n4, n5, n6], o5);
  27560. * this._update(n1, o2);
  27561. * this._remove(o3);
  27562. * this._remove(o4);
  27563. * this._remove(o6);
  27564. * this._remove(o7);
  27565. * this._add(n2);
  27566. * this._add(n3);
  27567. * this._add(n7);
  27568. * this._add(n8);
  27569. */
  27570. DataDiffer.prototype._executeMultiple = function () {
  27571. var oldArr = this._old;
  27572. var newArr = this._new;
  27573. var oldDataIndexMap = {};
  27574. var newDataIndexMap = {};
  27575. var oldDataKeyArr = [];
  27576. var newDataKeyArr = [];
  27577. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27578. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27579. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27580. var oldKey = oldDataKeyArr[i];
  27581. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27582. var newIdxMapVal = newDataIndexMap[oldKey];
  27583. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27584. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27585. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27586. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27587. newDataIndexMap[oldKey] = null;
  27588. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27589. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27590. newDataIndexMap[oldKey] = null;
  27591. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27592. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27593. newDataIndexMap[oldKey] = null;
  27594. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27595. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27596. newDataIndexMap[oldKey] = null;
  27597. } else if (oldIdxMapValLen > 1) {
  27598. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27599. this._remove && this._remove(oldIdxMapVal[i_1]);
  27600. }
  27601. } else {
  27602. this._remove && this._remove(oldIdxMapVal);
  27603. }
  27604. }
  27605. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27606. };
  27607. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27608. for (var i = 0; i < newDataKeyArr.length; i++) {
  27609. var newKey = newDataKeyArr[i];
  27610. var newIdxMapVal = newDataIndexMap[newKey];
  27611. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27612. if (idxMapValLen > 1) {
  27613. for (var j = 0; j < idxMapValLen; j++) {
  27614. this._add && this._add(newIdxMapVal[j]);
  27615. }
  27616. } else if (idxMapValLen === 1) {
  27617. this._add && this._add(newIdxMapVal);
  27618. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27619. newDataIndexMap[newKey] = null;
  27620. }
  27621. };
  27622. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27623. map, // In 'byKey', the output `keyArr` is duplication removed.
  27624. // In 'byIndex', the output `keyArr` is not duplication removed and
  27625. // its indices are accurately corresponding to `arr`.
  27626. keyArr, keyGetterName) {
  27627. var cbModeMultiple = this._diffModeMultiple;
  27628. for (var i = 0; i < arr.length; i++) {
  27629. // Add prefix to avoid conflict with Object.prototype.
  27630. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27631. if (!cbModeMultiple) {
  27632. keyArr[i] = key;
  27633. }
  27634. if (!map) {
  27635. continue;
  27636. }
  27637. var idxMapVal = map[key];
  27638. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27639. if (idxMapValLen === 0) {
  27640. // Simple optimize: in most cases, one index has one key,
  27641. // do not need array.
  27642. map[key] = i;
  27643. if (cbModeMultiple) {
  27644. keyArr.push(key);
  27645. }
  27646. } else if (idxMapValLen === 1) {
  27647. map[key] = [idxMapVal, i];
  27648. } else {
  27649. idxMapVal.push(i);
  27650. }
  27651. }
  27652. };
  27653. return DataDiffer;
  27654. }();
  27655. var DimensionUserOuput =
  27656. /** @class */
  27657. function () {
  27658. function DimensionUserOuput(encode, dimRequest) {
  27659. this._encode = encode;
  27660. this._schema = dimRequest;
  27661. }
  27662. DimensionUserOuput.prototype.get = function () {
  27663. return {
  27664. // Do not generate full dimension name until fist used.
  27665. fullDimensions: this._getFullDimensionNames(),
  27666. encode: this._encode
  27667. };
  27668. };
  27669. /**
  27670. * Get all data store dimension names.
  27671. * Theoretically a series data store is defined both by series and used dataset (if any).
  27672. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27673. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27674. * In this case, the dimension name is `null`/`undefined`.
  27675. */
  27676. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27677. if (!this._cachedDimNames) {
  27678. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27679. }
  27680. return this._cachedDimNames;
  27681. };
  27682. return DimensionUserOuput;
  27683. }();
  27684. function summarizeDimensions(data, schema) {
  27685. var summary = {};
  27686. var encode = summary.encode = {};
  27687. var notExtraCoordDimMap = createHashMap();
  27688. var defaultedLabel = [];
  27689. var defaultedTooltip = [];
  27690. var userOutputEncode = {};
  27691. each(data.dimensions, function (dimName) {
  27692. var dimItem = data.getDimensionInfo(dimName);
  27693. var coordDim = dimItem.coordDim;
  27694. if (coordDim) {
  27695. if ("development" !== 'production') {
  27696. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  27697. }
  27698. var coordDimIndex = dimItem.coordDimIndex;
  27699. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  27700. if (!dimItem.isExtraCoord) {
  27701. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  27702. // because when dataset is used, it is hard to guess which dimension
  27703. // can be value dimension. If both show x, y on label is not look good,
  27704. // and conventionally y axis is focused more.
  27705. if (mayLabelDimType(dimItem.type)) {
  27706. defaultedLabel[0] = dimName;
  27707. } // User output encode do not contain generated coords.
  27708. // And it only has index. User can use index to retrieve value from the raw item array.
  27709. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  27710. }
  27711. if (dimItem.defaultTooltip) {
  27712. defaultedTooltip.push(dimName);
  27713. }
  27714. }
  27715. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  27716. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  27717. var dimIndex = dimItem.otherDims[otherDim];
  27718. if (dimIndex != null && dimIndex !== false) {
  27719. encodeArr[dimIndex] = dimItem.name;
  27720. }
  27721. });
  27722. });
  27723. var dataDimsOnCoord = [];
  27724. var encodeFirstDimNotExtra = {};
  27725. notExtraCoordDimMap.each(function (v, coordDim) {
  27726. var dimArr = encode[coordDim];
  27727. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  27728. // dim canot on more than one coordDim.
  27729. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  27730. });
  27731. summary.dataDimsOnCoord = dataDimsOnCoord;
  27732. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  27733. return data.getDimensionInfo(dimName).storeDimIndex;
  27734. });
  27735. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  27736. var encodeLabel = encode.label; // FIXME `encode.label` is not recommended, because formatter cannot be set
  27737. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  27738. if (encodeLabel && encodeLabel.length) {
  27739. defaultedLabel = encodeLabel.slice();
  27740. }
  27741. var encodeTooltip = encode.tooltip;
  27742. if (encodeTooltip && encodeTooltip.length) {
  27743. defaultedTooltip = encodeTooltip.slice();
  27744. } else if (!defaultedTooltip.length) {
  27745. defaultedTooltip = defaultedLabel.slice();
  27746. }
  27747. encode.defaultedLabel = defaultedLabel;
  27748. encode.defaultedTooltip = defaultedTooltip;
  27749. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  27750. return summary;
  27751. }
  27752. function getOrCreateEncodeArr(encode, dim) {
  27753. if (!encode.hasOwnProperty(dim)) {
  27754. encode[dim] = [];
  27755. }
  27756. return encode[dim];
  27757. } // FIXME:TS should be type `AxisType`
  27758. function getDimensionTypeByAxis(axisType) {
  27759. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  27760. }
  27761. function mayLabelDimType(dimType) {
  27762. // In most cases, ordinal and time do not suitable for label.
  27763. // Ordinal info can be displayed on axis. Time is too long.
  27764. return !(dimType === 'ordinal' || dimType === 'time');
  27765. } // function findTheLastDimMayLabel(data) {
  27766. // // Get last value dim
  27767. // let dimensions = data.dimensions.slice();
  27768. // let valueType;
  27769. // let valueDim;
  27770. // while (dimensions.length && (
  27771. // valueDim = dimensions.pop(),
  27772. // valueType = data.getDimensionInfo(valueDim).type,
  27773. // valueType === 'ordinal' || valueType === 'time'
  27774. // )) {} // jshint ignore:line
  27775. // return valueDim;
  27776. // }
  27777. var SeriesDimensionDefine =
  27778. /** @class */
  27779. function () {
  27780. /**
  27781. * @param opt All of the fields will be shallow copied.
  27782. */
  27783. function SeriesDimensionDefine(opt) {
  27784. /**
  27785. * The format of `otherDims` is:
  27786. * ```js
  27787. * {
  27788. * tooltip?: number
  27789. * label?: number
  27790. * itemName?: number
  27791. * seriesName?: number
  27792. * }
  27793. * ```
  27794. *
  27795. * A `series.encode` can specified these fields:
  27796. * ```js
  27797. * encode: {
  27798. * // "3, 1, 5" is the index of data dimension.
  27799. * tooltip: [3, 1, 5],
  27800. * label: [0, 3],
  27801. * ...
  27802. * }
  27803. * ```
  27804. * `otherDims` is the parse result of the `series.encode` above, like:
  27805. * ```js
  27806. * // Suppose the index of this data dimension is `3`.
  27807. * this.otherDims = {
  27808. * // `3` is at the index `0` of the `encode.tooltip`
  27809. * tooltip: 0,
  27810. * // `3` is at the index `1` of the `encode.label`
  27811. * label: 1
  27812. * };
  27813. * ```
  27814. *
  27815. * This prop should never be `null`/`undefined` after initialized.
  27816. */
  27817. this.otherDims = {};
  27818. if (opt != null) {
  27819. extend(this, opt);
  27820. }
  27821. }
  27822. return SeriesDimensionDefine;
  27823. }();
  27824. var inner$4 = makeInner();
  27825. var dimTypeShort = {
  27826. float: 'f',
  27827. int: 'i',
  27828. ordinal: 'o',
  27829. number: 'n',
  27830. time: 't'
  27831. };
  27832. /**
  27833. * Represents the dimension requirement of a series.
  27834. *
  27835. * NOTICE:
  27836. * When there are too many dimensions in dataset and many series, only the used dimensions
  27837. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  27838. * But users may query data by other unused dimension names.
  27839. * In this case, users can only query data if and only if they have defined dimension names
  27840. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  27841. * `source` dimensions.
  27842. */
  27843. var SeriesDataSchema =
  27844. /** @class */
  27845. function () {
  27846. function SeriesDataSchema(opt) {
  27847. this.dimensions = opt.dimensions;
  27848. this._dimOmitted = opt.dimensionOmitted;
  27849. this.source = opt.source;
  27850. this._fullDimCount = opt.fullDimensionCount;
  27851. this._updateDimOmitted(opt.dimensionOmitted);
  27852. }
  27853. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  27854. return this._dimOmitted;
  27855. };
  27856. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  27857. this._dimOmitted = dimensionOmitted;
  27858. if (!dimensionOmitted) {
  27859. return;
  27860. }
  27861. if (!this._dimNameMap) {
  27862. this._dimNameMap = ensureSourceDimNameMap(this.source);
  27863. }
  27864. };
  27865. /**
  27866. * @caution Can only be used when `dimensionOmitted: true`.
  27867. *
  27868. * Get index by user defined dimension name (i.e., not internal generate name).
  27869. * That is, get index from `dimensionsDefine`.
  27870. * If no `dimensionsDefine`, or no name get, return -1.
  27871. */
  27872. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  27873. return retrieve2(this._dimNameMap.get(dimName), -1);
  27874. };
  27875. /**
  27876. * @caution Can only be used when `dimensionOmitted: true`.
  27877. *
  27878. * Notice: may return `null`/`undefined` if user not specify dimension names.
  27879. */
  27880. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  27881. var dimensionsDefine = this.source.dimensionsDefine;
  27882. if (dimensionsDefine) {
  27883. return dimensionsDefine[dimIndex];
  27884. }
  27885. };
  27886. SeriesDataSchema.prototype.makeStoreSchema = function () {
  27887. var dimCount = this._fullDimCount;
  27888. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  27889. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  27890. // Generate from seriesDimList directly
  27891. var dimHash = '';
  27892. var dims = [];
  27893. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  27894. var property = void 0;
  27895. var type = void 0;
  27896. var ordinalMeta = void 0;
  27897. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  27898. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27899. property = willRetrieveDataByName ? seriesDimDef.name : null;
  27900. type = seriesDimDef.type;
  27901. ordinalMeta = seriesDimDef.ordinalMeta;
  27902. seriesDimIdx++;
  27903. } else {
  27904. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27905. if (sourceDimDef) {
  27906. property = willRetrieveDataByName ? sourceDimDef.name : null;
  27907. type = sourceDimDef.type;
  27908. }
  27909. }
  27910. dims.push({
  27911. property: property,
  27912. type: type,
  27913. ordinalMeta: ordinalMeta
  27914. }); // If retrieving data by index,
  27915. // use <index, type, ordinalMeta> to determine whether data can be shared.
  27916. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  27917. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  27918. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  27919. // use <property, type, ordinalMeta> in hash.
  27920. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  27921. // So we do not add property to hash to make sure they can share this store.
  27922. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  27923. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  27924. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  27925. : property;
  27926. }
  27927. dimHash += '$';
  27928. dimHash += dimTypeShort[type] || 'f';
  27929. if (ordinalMeta) {
  27930. dimHash += ordinalMeta.uid;
  27931. }
  27932. dimHash += '$';
  27933. } // Source from endpoint(usually series) will be read differently
  27934. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  27935. // So we use this three props as key.
  27936. var source = this.source;
  27937. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  27938. return {
  27939. dimensions: dims,
  27940. hash: hash
  27941. };
  27942. };
  27943. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  27944. var result = [];
  27945. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  27946. var name_1 = void 0;
  27947. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  27948. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27949. if (!seriesDimDef.isCalculationCoord) {
  27950. name_1 = seriesDimDef.name;
  27951. }
  27952. seriesDimIdx++;
  27953. } else {
  27954. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27955. if (sourceDimDef) {
  27956. name_1 = sourceDimDef.name;
  27957. }
  27958. }
  27959. result.push(name_1);
  27960. }
  27961. return result;
  27962. };
  27963. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  27964. this.dimensions.push(dimDef);
  27965. dimDef.isCalculationCoord = true;
  27966. this._fullDimCount++; // If append dimension on a data store, consider the store
  27967. // might be shared by different series, series dimensions not
  27968. // really map to store dimensions.
  27969. this._updateDimOmitted(true);
  27970. };
  27971. return SeriesDataSchema;
  27972. }();
  27973. function isSeriesDataSchema(schema) {
  27974. return schema instanceof SeriesDataSchema;
  27975. }
  27976. function createDimNameMap(dimsDef) {
  27977. var dataDimNameMap = createHashMap();
  27978. for (var i = 0; i < (dimsDef || []).length; i++) {
  27979. var dimDefItemRaw = dimsDef[i];
  27980. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  27981. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27982. dataDimNameMap.set(userDimName, i);
  27983. }
  27984. }
  27985. return dataDimNameMap;
  27986. }
  27987. function ensureSourceDimNameMap(source) {
  27988. var innerSource = inner$4(source);
  27989. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  27990. }
  27991. function shouldOmitUnusedDimensions(dimCount) {
  27992. return dimCount > 30;
  27993. }
  27994. var isObject$2 = isObject;
  27995. var map$1 = map;
  27996. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  27997. // which will cause weird update animation.
  27998. var ID_PREFIX = 'e\0\0';
  27999. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  28000. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28001. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  28002. // Internal method declarations:
  28003. // -----------------------------
  28004. var prepareInvertedIndex;
  28005. var getId;
  28006. var getIdNameFromStore;
  28007. var normalizeDimensions;
  28008. var transferProperties;
  28009. var cloneListForMapAndSample;
  28010. var makeIdFromName;
  28011. var SeriesData =
  28012. /** @class */
  28013. function () {
  28014. /**
  28015. * @param dimensionsInput.dimensions
  28016. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28017. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28018. */
  28019. function SeriesData(dimensionsInput, hostModel) {
  28020. this.type = 'list';
  28021. this._dimOmitted = false;
  28022. this._nameList = [];
  28023. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  28024. // Never used yet (not used yet).
  28025. // private _optionModels: Model[] = [];
  28026. // Global visual properties after visual coding
  28027. this._visual = {}; // Global layout properties.
  28028. this._layout = {}; // Item visual properties after visual coding
  28029. this._itemVisuals = []; // Item layout properties after layout
  28030. this._itemLayouts = []; // Graphic elements
  28031. this._graphicEls = []; // key: dim, value: extent
  28032. this._approximateExtent = {};
  28033. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  28034. // (in type `OptionDataItemObject`).
  28035. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28036. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28037. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  28038. // Notice that those method should `RETURN` the new list.
  28039. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  28040. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28041. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  28042. var dimensions;
  28043. var assignStoreDimIdx = false;
  28044. if (isSeriesDataSchema(dimensionsInput)) {
  28045. dimensions = dimensionsInput.dimensions;
  28046. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28047. this._schema = dimensionsInput;
  28048. } else {
  28049. assignStoreDimIdx = true;
  28050. dimensions = dimensionsInput;
  28051. }
  28052. dimensions = dimensions || ['x', 'y'];
  28053. var dimensionInfos = {};
  28054. var dimensionNames = [];
  28055. var invertedIndicesMap = {};
  28056. var needsHasOwn = false;
  28057. var emptyObj = {};
  28058. for (var i = 0; i < dimensions.length; i++) {
  28059. // Use the original dimensions[i], where other flag props may exists.
  28060. var dimInfoInput = dimensions[i];
  28061. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28062. name: dimInfoInput
  28063. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28064. var dimensionName = dimensionInfo.name;
  28065. dimensionInfo.type = dimensionInfo.type || 'float';
  28066. if (!dimensionInfo.coordDim) {
  28067. dimensionInfo.coordDim = dimensionName;
  28068. dimensionInfo.coordDimIndex = 0;
  28069. }
  28070. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28071. dimensionNames.push(dimensionName);
  28072. dimensionInfos[dimensionName] = dimensionInfo;
  28073. if (emptyObj[dimensionName] != null) {
  28074. needsHasOwn = true;
  28075. }
  28076. if (dimensionInfo.createInvertedIndices) {
  28077. invertedIndicesMap[dimensionName] = [];
  28078. }
  28079. if (otherDims.itemName === 0) {
  28080. this._nameDimIdx = i;
  28081. }
  28082. if (otherDims.itemId === 0) {
  28083. this._idDimIdx = i;
  28084. }
  28085. if ("development" !== 'production') {
  28086. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28087. }
  28088. if (assignStoreDimIdx) {
  28089. dimensionInfo.storeDimIndex = i;
  28090. }
  28091. }
  28092. this.dimensions = dimensionNames;
  28093. this._dimInfos = dimensionInfos;
  28094. this._initGetDimensionInfo(needsHasOwn);
  28095. this.hostModel = hostModel;
  28096. this._invertedIndicesMap = invertedIndicesMap;
  28097. if (this._dimOmitted) {
  28098. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28099. each(dimensionNames, function (dimName) {
  28100. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28101. });
  28102. }
  28103. }
  28104. /**
  28105. *
  28106. * Get concrete dimension name by dimension name or dimension index.
  28107. * If input a dimension name, do not validate whether the dimension name exits.
  28108. *
  28109. * @caution
  28110. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28111. * Because only those dimensions will have auto-generated dimension names if not
  28112. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28113. *
  28114. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28115. * ```js
  28116. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28117. * ```
  28118. *
  28119. * @return Concrete dim name.
  28120. */
  28121. SeriesData.prototype.getDimension = function (dim) {
  28122. var dimIdx = this._recognizeDimIndex(dim);
  28123. if (dimIdx == null) {
  28124. return dim;
  28125. }
  28126. dimIdx = dim;
  28127. if (!this._dimOmitted) {
  28128. return this.dimensions[dimIdx];
  28129. } // Retrieve from series dimension definition because it probably contains
  28130. // generated dimension name (like 'x', 'y').
  28131. var dimName = this._dimIdxToName.get(dimIdx);
  28132. if (dimName != null) {
  28133. return dimName;
  28134. }
  28135. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28136. if (sourceDimDef) {
  28137. return sourceDimDef.name;
  28138. }
  28139. };
  28140. /**
  28141. * Get dimension index in data store. Return -1 if not found.
  28142. * Can be used to index value from getRawValue.
  28143. */
  28144. SeriesData.prototype.getDimensionIndex = function (dim) {
  28145. var dimIdx = this._recognizeDimIndex(dim);
  28146. if (dimIdx != null) {
  28147. return dimIdx;
  28148. }
  28149. if (dim == null) {
  28150. return -1;
  28151. }
  28152. var dimInfo = this._getDimInfo(dim);
  28153. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28154. };
  28155. /**
  28156. * The meanings of the input parameter `dim`:
  28157. *
  28158. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28159. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28160. * + If dim is a number-like string (e.g., `"1"`):
  28161. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28162. * it means that concrete name.
  28163. * + If not, it will be converted to a number, which means the index of the dimension.
  28164. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28165. * dimension setting, although now it seems that it is not a good idea.)
  28166. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28167. * if no dimension name is defined as `"1"`.
  28168. * + If dim is a not-number-like string, it means the concrete dim name.
  28169. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28170. * or customized in `dimensions` property of option like `"age"`.
  28171. *
  28172. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28173. */
  28174. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28175. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  28176. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28177. return +dim;
  28178. }
  28179. };
  28180. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28181. var dimIdx = this.getDimensionIndex(dim);
  28182. if ("development" !== 'production') {
  28183. if (dimIdx == null) {
  28184. throw new Error('Unknown dimension ' + dim);
  28185. }
  28186. }
  28187. return dimIdx;
  28188. };
  28189. /**
  28190. * Get type and calculation info of particular dimension
  28191. * @param dim
  28192. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28193. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28194. */
  28195. SeriesData.prototype.getDimensionInfo = function (dim) {
  28196. // Do not clone, because there may be categories in dimInfo.
  28197. return this._getDimInfo(this.getDimension(dim));
  28198. };
  28199. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28200. var dimensionInfos = this._dimInfos;
  28201. this._getDimInfo = needsHasOwn ? function (dimName) {
  28202. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28203. } : function (dimName) {
  28204. return dimensionInfos[dimName];
  28205. };
  28206. };
  28207. /**
  28208. * concrete dimension name list on coord.
  28209. */
  28210. SeriesData.prototype.getDimensionsOnCoord = function () {
  28211. return this._dimSummary.dataDimsOnCoord.slice();
  28212. };
  28213. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28214. var dimensionsSummary = this._dimSummary;
  28215. if (idx == null) {
  28216. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28217. }
  28218. var dims = dimensionsSummary.encode[coordDim];
  28219. return dims ? dims[idx] : null;
  28220. };
  28221. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28222. var dimensionsSummary = this._dimSummary;
  28223. var dims = dimensionsSummary.encode[coordDim];
  28224. return (dims || []).slice();
  28225. };
  28226. SeriesData.prototype.getStore = function () {
  28227. return this._store;
  28228. };
  28229. /**
  28230. * Initialize from data
  28231. * @param data source or data or data store.
  28232. * @param nameList The name of a datum is used on data diff and
  28233. * default label/tooltip.
  28234. * A name can be specified in encode.itemName,
  28235. * or dataItem.name (only for series option data),
  28236. * or provided in nameList from outside.
  28237. */
  28238. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28239. var _this = this;
  28240. var store;
  28241. if (data instanceof DataStore) {
  28242. store = data;
  28243. }
  28244. if (!store) {
  28245. var dimensions = this.dimensions;
  28246. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28247. store = new DataStore();
  28248. var dimensionInfos = map$1(dimensions, function (dimName) {
  28249. return {
  28250. type: _this._dimInfos[dimName].type,
  28251. property: dimName
  28252. };
  28253. });
  28254. store.initData(provider, dimensionInfos, dimValueGetter);
  28255. }
  28256. this._store = store; // Reset
  28257. this._nameList = (nameList || []).slice();
  28258. this._idList = [];
  28259. this._nameRepeatCount = {};
  28260. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  28261. // Needs to be initialized after store is prepared.
  28262. this._dimSummary = summarizeDimensions(this, this._schema);
  28263. this.userOutput = this._dimSummary.userOutput;
  28264. };
  28265. /**
  28266. * Caution: Can be only called on raw data (before `this._indices` created).
  28267. */
  28268. SeriesData.prototype.appendData = function (data) {
  28269. var range = this._store.appendData(data);
  28270. this._doInit(range[0], range[1]);
  28271. };
  28272. /**
  28273. * Caution: Can be only called on raw data (before `this._indices` created).
  28274. * This method does not modify `rawData` (`dataProvider`), but only
  28275. * add values to store.
  28276. *
  28277. * The final count will be increased by `Math.max(values.length, names.length)`.
  28278. *
  28279. * @param values That is the SourceType: 'arrayRows', like
  28280. * [
  28281. * [12, 33, 44],
  28282. * [NaN, 43, 1],
  28283. * ['-', 'asdf', 0]
  28284. * ]
  28285. * Each item is exactly corresponding to a dimension.
  28286. */
  28287. SeriesData.prototype.appendValues = function (values, names) {
  28288. var _a = this._store.appendValues(values, names.length),
  28289. start = _a.start,
  28290. end = _a.end;
  28291. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28292. this._updateOrdinalMeta();
  28293. if (names) {
  28294. for (var idx = start; idx < end; idx++) {
  28295. var sourceIdx = idx - start;
  28296. this._nameList[idx] = names[sourceIdx];
  28297. if (shouldMakeIdFromName) {
  28298. makeIdFromName(this, idx);
  28299. }
  28300. }
  28301. }
  28302. };
  28303. SeriesData.prototype._updateOrdinalMeta = function () {
  28304. var store = this._store;
  28305. var dimensions = this.dimensions;
  28306. for (var i = 0; i < dimensions.length; i++) {
  28307. var dimInfo = this._dimInfos[dimensions[i]];
  28308. if (dimInfo.ordinalMeta) {
  28309. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28310. }
  28311. }
  28312. };
  28313. SeriesData.prototype._shouldMakeIdFromName = function () {
  28314. var provider = this._store.getProvider();
  28315. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28316. };
  28317. SeriesData.prototype._doInit = function (start, end) {
  28318. if (start >= end) {
  28319. return;
  28320. }
  28321. var store = this._store;
  28322. var provider = store.getProvider();
  28323. this._updateOrdinalMeta();
  28324. var nameList = this._nameList;
  28325. var idList = this._idList;
  28326. var sourceFormat = provider.getSource().sourceFormat;
  28327. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  28328. // [1, 2]
  28329. // 2
  28330. // Bar chart, line chart which uses category axis
  28331. // only gives the 'y' value. 'x' value is the indices of category
  28332. // Use a tempValue to normalize the value to be a (x, y) value
  28333. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28334. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28335. if (isFormatOriginal && !provider.pure) {
  28336. var sharedDataItem = [];
  28337. for (var idx = start; idx < end; idx++) {
  28338. // NOTICE: Try not to write things into dataItem
  28339. var dataItem = provider.getItem(idx, sharedDataItem);
  28340. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28341. this.hasItemOption = true;
  28342. }
  28343. if (dataItem) {
  28344. var itemName = dataItem.name;
  28345. if (nameList[idx] == null && itemName != null) {
  28346. nameList[idx] = convertOptionIdName(itemName, null);
  28347. }
  28348. var itemId = dataItem.id;
  28349. if (idList[idx] == null && itemId != null) {
  28350. idList[idx] = convertOptionIdName(itemId, null);
  28351. }
  28352. }
  28353. }
  28354. }
  28355. if (this._shouldMakeIdFromName()) {
  28356. for (var idx = start; idx < end; idx++) {
  28357. makeIdFromName(this, idx);
  28358. }
  28359. }
  28360. prepareInvertedIndex(this);
  28361. };
  28362. /**
  28363. * PENDING: In fact currently this function is only used to short-circuit
  28364. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28365. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28366. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28367. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28368. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28369. * be still needed.
  28370. *
  28371. * Optimize for the scenario that data is filtered by a given extent.
  28372. * Consider that if data amount is more than hundreds of thousand,
  28373. * extent calculation will cost more than 10ms and the cache will
  28374. * be erased because of the filtering.
  28375. */
  28376. SeriesData.prototype.getApproximateExtent = function (dim) {
  28377. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28378. };
  28379. /**
  28380. * Calculate extent on a filtered data might be time consuming.
  28381. * Approximate extent is only used for: calculate extent of filtered data outside.
  28382. */
  28383. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28384. dim = this.getDimension(dim);
  28385. this._approximateExtent[dim] = extent.slice();
  28386. };
  28387. SeriesData.prototype.getCalculationInfo = function (key) {
  28388. return this._calculationInfo[key];
  28389. };
  28390. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28391. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28392. };
  28393. /**
  28394. * @return Never be null/undefined. `number` will be converted to string. Because:
  28395. * In most cases, name is used in display, where returning a string is more convenient.
  28396. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28397. * rule that name `2` equals to name `'2'`.
  28398. */
  28399. SeriesData.prototype.getName = function (idx) {
  28400. var rawIndex = this.getRawIndex(idx);
  28401. var name = this._nameList[rawIndex];
  28402. if (name == null && this._nameDimIdx != null) {
  28403. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28404. }
  28405. if (name == null) {
  28406. name = '';
  28407. }
  28408. return name;
  28409. };
  28410. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28411. var ordinal = this._store.get(dimIdx, idx);
  28412. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28413. if (ordinalMeta) {
  28414. return ordinalMeta.categories[ordinal];
  28415. }
  28416. return ordinal;
  28417. };
  28418. /**
  28419. * @return Never null/undefined. `number` will be converted to string. Because:
  28420. * In all cases having encountered at present, id is used in making diff comparison, which
  28421. * are usually based on hash map. We can keep the rule that the internal id are always string
  28422. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28423. */
  28424. SeriesData.prototype.getId = function (idx) {
  28425. return getId(this, this.getRawIndex(idx));
  28426. };
  28427. SeriesData.prototype.count = function () {
  28428. return this._store.count();
  28429. };
  28430. /**
  28431. * Get value. Return NaN if idx is out of range.
  28432. *
  28433. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28434. */
  28435. SeriesData.prototype.get = function (dim, idx) {
  28436. var store = this._store;
  28437. var dimInfo = this._dimInfos[dim];
  28438. if (dimInfo) {
  28439. return store.get(dimInfo.storeDimIndex, idx);
  28440. }
  28441. };
  28442. /**
  28443. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28444. */
  28445. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28446. var store = this._store;
  28447. var dimInfo = this._dimInfos[dim];
  28448. if (dimInfo) {
  28449. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28450. }
  28451. };
  28452. SeriesData.prototype.getIndices = function () {
  28453. return this._store.getIndices();
  28454. };
  28455. SeriesData.prototype.getDataExtent = function (dim) {
  28456. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28457. };
  28458. SeriesData.prototype.getSum = function (dim) {
  28459. return this._store.getSum(this._getStoreDimIndex(dim));
  28460. };
  28461. SeriesData.prototype.getMedian = function (dim) {
  28462. return this._store.getMedian(this._getStoreDimIndex(dim));
  28463. };
  28464. SeriesData.prototype.getValues = function (dimensions, idx) {
  28465. var _this = this;
  28466. var store = this._store;
  28467. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28468. return _this._getStoreDimIndex(dim);
  28469. }), idx) : store.getValues(dimensions);
  28470. };
  28471. /**
  28472. * If value is NaN. Including '-'
  28473. * Only check the coord dimensions.
  28474. */
  28475. SeriesData.prototype.hasValue = function (idx) {
  28476. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28477. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28478. // Ordinal type originally can be string or number.
  28479. // But when an ordinal type is used on coord, it can
  28480. // not be string but only number. So we can also use isNaN.
  28481. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28482. return false;
  28483. }
  28484. }
  28485. return true;
  28486. };
  28487. /**
  28488. * Retrieve the index with given name
  28489. */
  28490. SeriesData.prototype.indexOfName = function (name) {
  28491. for (var i = 0, len = this._store.count(); i < len; i++) {
  28492. if (this.getName(i) === name) {
  28493. return i;
  28494. }
  28495. }
  28496. return -1;
  28497. };
  28498. SeriesData.prototype.getRawIndex = function (idx) {
  28499. return this._store.getRawIndex(idx);
  28500. };
  28501. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28502. return this._store.indexOfRawIndex(rawIndex);
  28503. };
  28504. /**
  28505. * Only support the dimension which inverted index created.
  28506. * Do not support other cases until required.
  28507. * @param dim concrete dim
  28508. * @param value ordinal index
  28509. * @return rawIndex
  28510. */
  28511. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28512. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28513. if ("development" !== 'production') {
  28514. if (!invertedIndices) {
  28515. throw new Error('Do not supported yet');
  28516. }
  28517. }
  28518. var rawIndex = invertedIndices[value];
  28519. if (rawIndex == null || isNaN(rawIndex)) {
  28520. return INDEX_NOT_FOUND;
  28521. }
  28522. return rawIndex;
  28523. };
  28524. /**
  28525. * Retrieve the index of nearest value
  28526. * @param dim
  28527. * @param value
  28528. * @param [maxDistance=Infinity]
  28529. * @return If and only if multiple indices has
  28530. * the same value, they are put to the result.
  28531. */
  28532. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28533. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28534. };
  28535. SeriesData.prototype.each = function (dims, cb, ctx) {
  28536. if (isFunction(dims)) {
  28537. ctx = cb;
  28538. cb = dims;
  28539. dims = [];
  28540. } // ctxCompat just for compat echarts3
  28541. var fCtx = ctx || this;
  28542. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28543. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28544. };
  28545. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28546. if (isFunction(dims)) {
  28547. ctx = cb;
  28548. cb = dims;
  28549. dims = [];
  28550. } // ctxCompat just for compat echarts3
  28551. var fCtx = ctx || this;
  28552. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28553. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28554. return this;
  28555. };
  28556. /**
  28557. * Select data in range. (For optimization of filter)
  28558. * (Manually inline code, support 5 million data filtering in data zoom.)
  28559. */
  28560. SeriesData.prototype.selectRange = function (range) {
  28561. var _this = this;
  28562. var innerRange = {};
  28563. var dims = keys(range);
  28564. each(dims, function (dim) {
  28565. var dimIdx = _this._getStoreDimIndex(dim);
  28566. innerRange[dimIdx] = range[dim];
  28567. });
  28568. this._store = this._store.selectRange(innerRange);
  28569. return this;
  28570. };
  28571. /* eslint-enable max-len */
  28572. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28573. if (isFunction(dims)) {
  28574. ctx = cb;
  28575. cb = dims;
  28576. dims = [];
  28577. } // ctxCompat just for compat echarts3
  28578. ctx = ctx || this;
  28579. var result = [];
  28580. this.each(dims, function () {
  28581. result.push(cb && cb.apply(this, arguments));
  28582. }, ctx);
  28583. return result;
  28584. };
  28585. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28586. var fCtx = ctx || ctxCompat || this;
  28587. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28588. var list = cloneListForMapAndSample(this);
  28589. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28590. return list;
  28591. };
  28592. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28593. var _this = this; // ctxCompat just for compat echarts3
  28594. var fCtx = ctx || ctxCompat || this;
  28595. if ("development" !== 'production') {
  28596. each(normalizeDimensions(dims), function (dim) {
  28597. var dimInfo = _this.getDimensionInfo(dim);
  28598. if (!dimInfo.isCalculationCoord) {
  28599. console.error('Danger: only stack dimension can be modified');
  28600. }
  28601. });
  28602. }
  28603. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  28604. // it still cost lots of memory, because `_store.dimensions` are not shared.
  28605. // We should consider there probably be shallow clone happen in each series
  28606. // in consequent filter/map.
  28607. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28608. };
  28609. /**
  28610. * Large data down sampling on given dimension
  28611. * @param sampleIndex Sample index for name and id
  28612. */
  28613. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28614. var list = cloneListForMapAndSample(this);
  28615. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28616. return list;
  28617. };
  28618. /**
  28619. * Large data down sampling using largest-triangle-three-buckets
  28620. * @param {string} valueDimension
  28621. * @param {number} targetCount
  28622. */
  28623. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28624. var list = cloneListForMapAndSample(this);
  28625. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28626. return list;
  28627. };
  28628. SeriesData.prototype.getRawDataItem = function (idx) {
  28629. return this._store.getRawDataItem(idx);
  28630. };
  28631. /**
  28632. * Get model of one data item.
  28633. */
  28634. // TODO: Type of data item
  28635. SeriesData.prototype.getItemModel = function (idx) {
  28636. var hostModel = this.hostModel;
  28637. var dataItem = this.getRawDataItem(idx);
  28638. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28639. };
  28640. /**
  28641. * Create a data differ
  28642. */
  28643. SeriesData.prototype.diff = function (otherList) {
  28644. var thisList = this;
  28645. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28646. return getId(otherList, idx);
  28647. }, function (idx) {
  28648. return getId(thisList, idx);
  28649. });
  28650. };
  28651. /**
  28652. * Get visual property.
  28653. */
  28654. SeriesData.prototype.getVisual = function (key) {
  28655. var visual = this._visual;
  28656. return visual && visual[key];
  28657. };
  28658. SeriesData.prototype.setVisual = function (kvObj, val) {
  28659. this._visual = this._visual || {};
  28660. if (isObject$2(kvObj)) {
  28661. extend(this._visual, kvObj);
  28662. } else {
  28663. this._visual[kvObj] = val;
  28664. }
  28665. };
  28666. /**
  28667. * Get visual property of single data item
  28668. */
  28669. // eslint-disable-next-line
  28670. SeriesData.prototype.getItemVisual = function (idx, key) {
  28671. var itemVisual = this._itemVisuals[idx];
  28672. var val = itemVisual && itemVisual[key];
  28673. if (val == null) {
  28674. // Use global visual property
  28675. return this.getVisual(key);
  28676. }
  28677. return val;
  28678. };
  28679. /**
  28680. * If exists visual property of single data item
  28681. */
  28682. SeriesData.prototype.hasItemVisual = function () {
  28683. return this._itemVisuals.length > 0;
  28684. };
  28685. /**
  28686. * Make sure itemVisual property is unique
  28687. */
  28688. // TODO: use key to save visual to reduce memory.
  28689. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  28690. var itemVisuals = this._itemVisuals;
  28691. var itemVisual = itemVisuals[idx];
  28692. if (!itemVisual) {
  28693. itemVisual = itemVisuals[idx] = {};
  28694. }
  28695. var val = itemVisual[key];
  28696. if (val == null) {
  28697. val = this.getVisual(key); // TODO Performance?
  28698. if (isArray(val)) {
  28699. val = val.slice();
  28700. } else if (isObject$2(val)) {
  28701. val = extend({}, val);
  28702. }
  28703. itemVisual[key] = val;
  28704. }
  28705. return val;
  28706. }; // eslint-disable-next-line
  28707. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  28708. var itemVisual = this._itemVisuals[idx] || {};
  28709. this._itemVisuals[idx] = itemVisual;
  28710. if (isObject$2(key)) {
  28711. extend(itemVisual, key);
  28712. } else {
  28713. itemVisual[key] = value;
  28714. }
  28715. };
  28716. /**
  28717. * Clear itemVisuals and list visual.
  28718. */
  28719. SeriesData.prototype.clearAllVisual = function () {
  28720. this._visual = {};
  28721. this._itemVisuals = [];
  28722. };
  28723. SeriesData.prototype.setLayout = function (key, val) {
  28724. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  28725. };
  28726. /**
  28727. * Get layout property.
  28728. */
  28729. SeriesData.prototype.getLayout = function (key) {
  28730. return this._layout[key];
  28731. };
  28732. /**
  28733. * Get layout of single data item
  28734. */
  28735. SeriesData.prototype.getItemLayout = function (idx) {
  28736. return this._itemLayouts[idx];
  28737. };
  28738. /**
  28739. * Set layout of single data item
  28740. */
  28741. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  28742. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  28743. };
  28744. /**
  28745. * Clear all layout of single data item
  28746. */
  28747. SeriesData.prototype.clearItemLayouts = function () {
  28748. this._itemLayouts.length = 0;
  28749. };
  28750. /**
  28751. * Set graphic element relative to data. It can be set as null
  28752. */
  28753. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  28754. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  28755. setCommonECData(seriesIndex, this.dataType, idx, el);
  28756. this._graphicEls[idx] = el;
  28757. };
  28758. SeriesData.prototype.getItemGraphicEl = function (idx) {
  28759. return this._graphicEls[idx];
  28760. };
  28761. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  28762. each(this._graphicEls, function (el, idx) {
  28763. if (el) {
  28764. cb && cb.call(context, el, idx);
  28765. }
  28766. });
  28767. };
  28768. /**
  28769. * Shallow clone a new list except visual and layout properties, and graph elements.
  28770. * New list only change the indices.
  28771. */
  28772. SeriesData.prototype.cloneShallow = function (list) {
  28773. if (!list) {
  28774. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  28775. }
  28776. transferProperties(list, this);
  28777. list._store = this._store;
  28778. return list;
  28779. };
  28780. /**
  28781. * Wrap some method to add more feature
  28782. */
  28783. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  28784. var originalMethod = this[methodName];
  28785. if (!isFunction(originalMethod)) {
  28786. return;
  28787. }
  28788. this.__wrappedMethods = this.__wrappedMethods || [];
  28789. this.__wrappedMethods.push(methodName);
  28790. this[methodName] = function () {
  28791. var res = originalMethod.apply(this, arguments);
  28792. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28793. };
  28794. }; // ----------------------------------------------------------
  28795. // A work around for internal method visiting private member.
  28796. // ----------------------------------------------------------
  28797. SeriesData.internalField = function () {
  28798. prepareInvertedIndex = function (data) {
  28799. var invertedIndicesMap = data._invertedIndicesMap;
  28800. each(invertedIndicesMap, function (invertedIndices, dim) {
  28801. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  28802. var ordinalMeta = dimInfo.ordinalMeta;
  28803. var store = data._store;
  28804. if (ordinalMeta) {
  28805. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  28806. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  28807. for (var i = 0; i < invertedIndices.length; i++) {
  28808. invertedIndices[i] = INDEX_NOT_FOUND;
  28809. }
  28810. for (var i = 0; i < store.count(); i++) {
  28811. // Only support the case that all values are distinct.
  28812. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  28813. }
  28814. }
  28815. });
  28816. };
  28817. getIdNameFromStore = function (data, dimIdx, idx) {
  28818. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  28819. };
  28820. /**
  28821. * @see the comment of `List['getId']`.
  28822. */
  28823. getId = function (data, rawIndex) {
  28824. var id = data._idList[rawIndex];
  28825. if (id == null && data._idDimIdx != null) {
  28826. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  28827. }
  28828. if (id == null) {
  28829. id = ID_PREFIX + rawIndex;
  28830. }
  28831. return id;
  28832. };
  28833. normalizeDimensions = function (dimensions) {
  28834. if (!isArray(dimensions)) {
  28835. dimensions = dimensions != null ? [dimensions] : [];
  28836. }
  28837. return dimensions;
  28838. };
  28839. /**
  28840. * Data in excludeDimensions is copied, otherwise transferred.
  28841. */
  28842. cloneListForMapAndSample = function (original) {
  28843. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  28844. transferProperties(list, original);
  28845. return list;
  28846. };
  28847. transferProperties = function (target, source) {
  28848. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  28849. if (source.hasOwnProperty(propName)) {
  28850. target[propName] = source[propName];
  28851. }
  28852. });
  28853. target.__wrappedMethods = source.__wrappedMethods;
  28854. each(CLONE_PROPERTIES, function (propName) {
  28855. target[propName] = clone(source[propName]);
  28856. });
  28857. target._calculationInfo = extend({}, source._calculationInfo);
  28858. };
  28859. makeIdFromName = function (data, idx) {
  28860. var nameList = data._nameList;
  28861. var idList = data._idList;
  28862. var nameDimIdx = data._nameDimIdx;
  28863. var idDimIdx = data._idDimIdx;
  28864. var name = nameList[idx];
  28865. var id = idList[idx];
  28866. if (name == null && nameDimIdx != null) {
  28867. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  28868. }
  28869. if (id == null && idDimIdx != null) {
  28870. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  28871. }
  28872. if (id == null && name != null) {
  28873. var nameRepeatCount = data._nameRepeatCount;
  28874. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  28875. id = name;
  28876. if (nmCnt > 1) {
  28877. id += '__ec__' + nmCnt;
  28878. }
  28879. idList[idx] = id;
  28880. }
  28881. };
  28882. }();
  28883. return SeriesData;
  28884. }();
  28885. /**
  28886. * For outside usage compat (like echarts-gl are using it).
  28887. */
  28888. function createDimensions(source, opt) {
  28889. return prepareSeriesDataSchema(source, opt).dimensions;
  28890. }
  28891. /**
  28892. * This method builds the relationship between:
  28893. * + "what the coord sys or series requires (see `coordDimensions`)",
  28894. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  28895. * + "what the data source provids (see `source`)".
  28896. *
  28897. * Some guess strategy will be adapted if user does not define something.
  28898. * If no 'value' dimension specified, the first no-named dimension will be
  28899. * named as 'value'.
  28900. *
  28901. * @return The results are always sorted by `storeDimIndex` asc.
  28902. */
  28903. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  28904. source, opt) {
  28905. if (!isSourceInstance(source)) {
  28906. source = createSourceFromSeriesDataOption(source);
  28907. }
  28908. opt = opt || {};
  28909. var sysDims = opt.coordDimensions || [];
  28910. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  28911. var coordDimNameMap = createHashMap();
  28912. var resultList = [];
  28913. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unused dimensions if sharing a high dimension datastore
  28914. // 30 is an experience value.
  28915. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  28916. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  28917. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  28918. var encodeDef = opt.encodeDefine;
  28919. if (!encodeDef && opt.encodeDefaulter) {
  28920. encodeDef = opt.encodeDefaulter(source, dimCount);
  28921. }
  28922. var encodeDefMap = createHashMap(encodeDef);
  28923. var indicesMap = new CtorInt32Array(dimCount);
  28924. for (var i = 0; i < indicesMap.length; i++) {
  28925. indicesMap[i] = -1;
  28926. }
  28927. function getResultItem(dimIdx) {
  28928. var idx = indicesMap[dimIdx];
  28929. if (idx < 0) {
  28930. var dimDefItemRaw = dimsDef[dimIdx];
  28931. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  28932. name: dimDefItemRaw
  28933. };
  28934. var resultItem = new SeriesDimensionDefine();
  28935. var userDimName = dimDefItem.name;
  28936. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  28937. // Only if `series.dimensions` is defined in option
  28938. // displayName, will be set, and dimension will be displayed vertically in
  28939. // tooltip by default.
  28940. resultItem.name = resultItem.displayName = userDimName;
  28941. }
  28942. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28943. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28944. var newIdx = resultList.length;
  28945. indicesMap[dimIdx] = newIdx;
  28946. resultItem.storeDimIndex = dimIdx;
  28947. resultList.push(resultItem);
  28948. return resultItem;
  28949. }
  28950. return resultList[idx];
  28951. }
  28952. if (!omitUnusedDimensions) {
  28953. for (var i = 0; i < dimCount; i++) {
  28954. getResultItem(i);
  28955. }
  28956. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  28957. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  28958. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28959. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28960. // this case.
  28961. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28962. encodeDefMap.set(coordDim, false);
  28963. return;
  28964. }
  28965. var validDataDims = encodeDefMap.set(coordDim, []);
  28966. each(dataDims, function (resultDimIdxOrName, idx) {
  28967. // The input resultDimIdx can be dim name or index.
  28968. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  28969. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28970. validDataDims[idx] = resultDimIdx;
  28971. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  28972. }
  28973. });
  28974. }); // Apply templates and default order from `sysDims`.
  28975. var availDimIdx = 0;
  28976. each(sysDims, function (sysDimItemRaw) {
  28977. var coordDim;
  28978. var sysDimItemDimsDef;
  28979. var sysDimItemOtherDims;
  28980. var sysDimItem;
  28981. if (isString(sysDimItemRaw)) {
  28982. coordDim = sysDimItemRaw;
  28983. sysDimItem = {};
  28984. } else {
  28985. sysDimItem = sysDimItemRaw;
  28986. coordDim = sysDimItem.name;
  28987. var ordinalMeta = sysDimItem.ordinalMeta;
  28988. sysDimItem.ordinalMeta = null;
  28989. sysDimItem = extend({}, sysDimItem);
  28990. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  28991. sysDimItemDimsDef = sysDimItem.dimsDef;
  28992. sysDimItemOtherDims = sysDimItem.otherDims;
  28993. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28994. }
  28995. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  28996. if (dataDims === false) {
  28997. return;
  28998. }
  28999. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  29000. if (!dataDims.length) {
  29001. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29002. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29003. availDimIdx++;
  29004. }
  29005. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29006. }
  29007. } // Apply templates.
  29008. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29009. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  29010. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29011. resultItem.type = sysDimItem.type;
  29012. }
  29013. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29014. if (resultItem.name == null && sysDimItemDimsDef) {
  29015. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29016. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29017. name: sysDimItemDimsDefItem
  29018. });
  29019. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29020. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29021. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29022. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29023. });
  29024. });
  29025. function applyDim(resultItem, coordDim, coordDimIndex) {
  29026. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29027. resultItem.otherDims[coordDim] = coordDimIndex;
  29028. } else {
  29029. resultItem.coordDim = coordDim;
  29030. resultItem.coordDimIndex = coordDimIndex;
  29031. coordDimNameMap.set(coordDim, true);
  29032. }
  29033. } // Make sure the first extra dim is 'value'.
  29034. var generateCoord = opt.generateCoord;
  29035. var generateCoordCount = opt.generateCoordCount;
  29036. var fromZero = generateCoordCount != null;
  29037. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29038. var extra = generateCoord || 'value';
  29039. function ifNoNameFillWithCoordName(resultItem) {
  29040. if (resultItem.name == null) {
  29041. // Duplication will be removed in the next step.
  29042. resultItem.name = resultItem.coordDim;
  29043. }
  29044. } // Set dim `name` and other `coordDim` and other props.
  29045. if (!omitUnusedDimensions) {
  29046. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29047. var resultItem = getResultItem(resultDimIdx);
  29048. var coordDim = resultItem.coordDim;
  29049. if (coordDim == null) {
  29050. // TODO no need to generate coordDim for isExtraCoord?
  29051. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29052. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  29053. if (!generateCoord || generateCoordCount <= 0) {
  29054. resultItem.isExtraCoord = true;
  29055. }
  29056. generateCoordCount--;
  29057. }
  29058. ifNoNameFillWithCoordName(resultItem);
  29059. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  29060. // {
  29061. // dataset: {source: [
  29062. // ['2001', 123],
  29063. // ['2002', 456],
  29064. // ...
  29065. // ['The others', 987],
  29066. // ]},
  29067. // series: {type: 'pie'}
  29068. // }
  29069. // The first column should better be treated as a "ordinal" although it
  29070. // might not be detected as an "ordinal" by `guessOrdinal`.
  29071. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29072. resultItem.type = 'ordinal';
  29073. }
  29074. }
  29075. } else {
  29076. each(resultList, function (resultItem) {
  29077. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29078. ifNoNameFillWithCoordName(resultItem);
  29079. }); // Sort dimensions: there are some rule that use the last dim as label,
  29080. // and for some latter travel process easier.
  29081. resultList.sort(function (item0, item1) {
  29082. return item0.storeDimIndex - item1.storeDimIndex;
  29083. });
  29084. }
  29085. removeDuplication(resultList);
  29086. return new SeriesDataSchema({
  29087. source: source,
  29088. dimensions: resultList,
  29089. fullDimensionCount: dimCount,
  29090. dimensionOmitted: omitUnusedDimensions
  29091. });
  29092. }
  29093. function removeDuplication(result) {
  29094. var duplicationMap = createHashMap();
  29095. for (var i = 0; i < result.length; i++) {
  29096. var dim = result[i];
  29097. var dimOriginalName = dim.name;
  29098. var count = duplicationMap.get(dimOriginalName) || 0;
  29099. if (count > 0) {
  29100. // Starts from 0.
  29101. dim.name = dimOriginalName + (count - 1);
  29102. }
  29103. count++;
  29104. duplicationMap.set(dimOriginalName, count);
  29105. }
  29106. } // ??? TODO
  29107. // Originally detect dimCount by data[0]. Should we
  29108. // optimize it to only by sysDims and dimensions and encode.
  29109. // So only necessary dims will be initialized.
  29110. // But
  29111. // (1) custom series should be considered. where other dims
  29112. // may be visited.
  29113. // (2) sometimes user need to calculate bubble size or use visualMap
  29114. // on other dimensions besides coordSys needed.
  29115. // So, dims that is not used by system, should be shared in data store?
  29116. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29117. // Note that the result dimCount should not small than columns count
  29118. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29119. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29120. each(sysDims, function (sysDimItem) {
  29121. var sysDimItemDimsDef;
  29122. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29123. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29124. }
  29125. });
  29126. return dimCount;
  29127. }
  29128. function genCoordDimName(name, map, fromZero) {
  29129. if (fromZero || map.hasKey(name)) {
  29130. var i = 0;
  29131. while (map.hasKey(name + i)) {
  29132. i++;
  29133. }
  29134. name += i;
  29135. }
  29136. map.set(name, true);
  29137. return name;
  29138. }
  29139. /**
  29140. * @class
  29141. * For example:
  29142. * {
  29143. * coordSysName: 'cartesian2d',
  29144. * coordSysDims: ['x', 'y', ...],
  29145. * axisMap: HashMap({
  29146. * x: xAxisModel,
  29147. * y: yAxisModel
  29148. * }),
  29149. * categoryAxisMap: HashMap({
  29150. * x: xAxisModel,
  29151. * y: undefined
  29152. * }),
  29153. * // The index of the first category axis in `coordSysDims`.
  29154. * // `null/undefined` means no category axis exists.
  29155. * firstCategoryDimIndex: 1,
  29156. * // To replace user specified encode.
  29157. * }
  29158. */
  29159. var CoordSysInfo =
  29160. /** @class */
  29161. function () {
  29162. function CoordSysInfo(coordSysName) {
  29163. this.coordSysDims = [];
  29164. this.axisMap = createHashMap();
  29165. this.categoryAxisMap = createHashMap();
  29166. this.coordSysName = coordSysName;
  29167. }
  29168. return CoordSysInfo;
  29169. }();
  29170. function getCoordSysInfoBySeries(seriesModel) {
  29171. var coordSysName = seriesModel.get('coordinateSystem');
  29172. var result = new CoordSysInfo(coordSysName);
  29173. var fetch = fetchers[coordSysName];
  29174. if (fetch) {
  29175. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29176. return result;
  29177. }
  29178. }
  29179. var fetchers = {
  29180. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29181. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29182. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29183. if ("development" !== 'production') {
  29184. if (!xAxisModel) {
  29185. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29186. }
  29187. if (!yAxisModel) {
  29188. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29189. }
  29190. }
  29191. result.coordSysDims = ['x', 'y'];
  29192. axisMap.set('x', xAxisModel);
  29193. axisMap.set('y', yAxisModel);
  29194. if (isCategory(xAxisModel)) {
  29195. categoryAxisMap.set('x', xAxisModel);
  29196. result.firstCategoryDimIndex = 0;
  29197. }
  29198. if (isCategory(yAxisModel)) {
  29199. categoryAxisMap.set('y', yAxisModel);
  29200. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29201. }
  29202. },
  29203. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29204. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29205. if ("development" !== 'production') {
  29206. if (!singleAxisModel) {
  29207. throw new Error('singleAxis should be specified.');
  29208. }
  29209. }
  29210. result.coordSysDims = ['single'];
  29211. axisMap.set('single', singleAxisModel);
  29212. if (isCategory(singleAxisModel)) {
  29213. categoryAxisMap.set('single', singleAxisModel);
  29214. result.firstCategoryDimIndex = 0;
  29215. }
  29216. },
  29217. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29218. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29219. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29220. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29221. if ("development" !== 'production') {
  29222. if (!angleAxisModel) {
  29223. throw new Error('angleAxis option not found');
  29224. }
  29225. if (!radiusAxisModel) {
  29226. throw new Error('radiusAxis option not found');
  29227. }
  29228. }
  29229. result.coordSysDims = ['radius', 'angle'];
  29230. axisMap.set('radius', radiusAxisModel);
  29231. axisMap.set('angle', angleAxisModel);
  29232. if (isCategory(radiusAxisModel)) {
  29233. categoryAxisMap.set('radius', radiusAxisModel);
  29234. result.firstCategoryDimIndex = 0;
  29235. }
  29236. if (isCategory(angleAxisModel)) {
  29237. categoryAxisMap.set('angle', angleAxisModel);
  29238. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29239. }
  29240. },
  29241. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29242. result.coordSysDims = ['lng', 'lat'];
  29243. },
  29244. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29245. var ecModel = seriesModel.ecModel;
  29246. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29247. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29248. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29249. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29250. var axisDim = coordSysDims[index];
  29251. axisMap.set(axisDim, axisModel);
  29252. if (isCategory(axisModel)) {
  29253. categoryAxisMap.set(axisDim, axisModel);
  29254. if (result.firstCategoryDimIndex == null) {
  29255. result.firstCategoryDimIndex = index;
  29256. }
  29257. }
  29258. });
  29259. }
  29260. };
  29261. function isCategory(axisModel) {
  29262. return axisModel.get('type') === 'category';
  29263. }
  29264. /**
  29265. * Note that it is too complicated to support 3d stack by value
  29266. * (have to create two-dimension inverted index), so in 3d case
  29267. * we just support that stacked by index.
  29268. *
  29269. * @param seriesModel
  29270. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29271. * The input will be modified.
  29272. * @param opt
  29273. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29274. * @param opt.byIndex=false
  29275. * @return calculationInfo
  29276. * {
  29277. * stackedDimension: string
  29278. * stackedByDimension: string
  29279. * isStackedByIndex: boolean
  29280. * stackedOverDimension: string
  29281. * stackResultDimension: string
  29282. * }
  29283. */
  29284. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29285. opt = opt || {};
  29286. var byIndex = opt.byIndex;
  29287. var stackedCoordDimension = opt.stackedCoordDimension;
  29288. var dimensionDefineList;
  29289. var schema;
  29290. var store;
  29291. if (isLegacyDimensionsInput(dimensionsInput)) {
  29292. dimensionDefineList = dimensionsInput;
  29293. } else {
  29294. schema = dimensionsInput.schema;
  29295. dimensionDefineList = schema.dimensions;
  29296. store = dimensionsInput.store;
  29297. } // Compatibal: when `stack` is set as '', do not stack.
  29298. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29299. var stackedByDimInfo;
  29300. var stackedDimInfo;
  29301. var stackResultDimension;
  29302. var stackedOverDimension;
  29303. each(dimensionDefineList, function (dimensionInfo, index) {
  29304. if (isString(dimensionInfo)) {
  29305. dimensionDefineList[index] = dimensionInfo = {
  29306. name: dimensionInfo
  29307. };
  29308. }
  29309. if (mayStack && !dimensionInfo.isExtraCoord) {
  29310. // Find the first ordinal dimension as the stackedByDimInfo.
  29311. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29312. stackedByDimInfo = dimensionInfo;
  29313. } // Find the first stackable dimension as the stackedDimInfo.
  29314. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29315. stackedDimInfo = dimensionInfo;
  29316. }
  29317. }
  29318. });
  29319. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29320. // Compatible with previous design, value axis (time axis) only stack by index.
  29321. // It may make sense if the user provides elaborately constructed data.
  29322. byIndex = true;
  29323. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29324. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29325. // might not be a good way.
  29326. if (stackedDimInfo) {
  29327. // Use a weird name that not duplicated with other names.
  29328. // Also need to use seriesModel.id as postfix because different
  29329. // series may share same data store. The stack dimension needs to be distinguished.
  29330. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29331. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  29332. if (stackedByDimInfo) {
  29333. stackedByDimInfo.createInvertedIndices = true;
  29334. }
  29335. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29336. var stackedDimType = stackedDimInfo.type;
  29337. var stackedDimCoordIndex_1 = 0;
  29338. each(dimensionDefineList, function (dimensionInfo) {
  29339. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29340. stackedDimCoordIndex_1++;
  29341. }
  29342. });
  29343. var stackedOverDimensionDefine = {
  29344. name: stackResultDimension,
  29345. coordDim: stackedDimCoordDim_1,
  29346. coordDimIndex: stackedDimCoordIndex_1,
  29347. type: stackedDimType,
  29348. isExtraCoord: true,
  29349. isCalculationCoord: true,
  29350. storeDimIndex: dimensionDefineList.length
  29351. };
  29352. var stackResultDimensionDefine = {
  29353. name: stackedOverDimension,
  29354. // This dimension contains stack base (generally, 0), so do not set it as
  29355. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29356. coordDim: stackedOverDimension,
  29357. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29358. type: stackedDimType,
  29359. isExtraCoord: true,
  29360. isCalculationCoord: true,
  29361. storeDimIndex: dimensionDefineList.length + 1
  29362. };
  29363. if (schema) {
  29364. if (store) {
  29365. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29366. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29367. }
  29368. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29369. schema.appendCalculationDimension(stackResultDimensionDefine);
  29370. } else {
  29371. dimensionDefineList.push(stackedOverDimensionDefine);
  29372. dimensionDefineList.push(stackResultDimensionDefine);
  29373. }
  29374. }
  29375. return {
  29376. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29377. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29378. isStackedByIndex: byIndex,
  29379. stackedOverDimension: stackedOverDimension,
  29380. stackResultDimension: stackResultDimension
  29381. };
  29382. }
  29383. function isLegacyDimensionsInput(dimensionsInput) {
  29384. return !isSeriesDataSchema(dimensionsInput.schema);
  29385. }
  29386. function isDimensionStacked(data, stackedDim) {
  29387. // Each single series only maps to one pair of axis. So we do not need to
  29388. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29389. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29390. }
  29391. function getStackedDimension(data, targetDim) {
  29392. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29393. }
  29394. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29395. var coordSysName = seriesModel.get('coordinateSystem');
  29396. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29397. var coordSysDimDefs;
  29398. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29399. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29400. var dimInfo = {
  29401. name: dim
  29402. };
  29403. var axisModel = coordSysInfo.axisMap.get(dim);
  29404. if (axisModel) {
  29405. var axisType = axisModel.get('type');
  29406. dimInfo.type = getDimensionTypeByAxis(axisType);
  29407. }
  29408. return dimInfo;
  29409. });
  29410. }
  29411. if (!coordSysDimDefs) {
  29412. // Get dimensions from registered coordinate system
  29413. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29414. }
  29415. return coordSysDimDefs;
  29416. }
  29417. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29418. var firstCategoryDimIndex;
  29419. var hasNameEncode;
  29420. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29421. var coordDim = dimInfo.coordDim;
  29422. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29423. if (categoryAxisModel) {
  29424. if (firstCategoryDimIndex == null) {
  29425. firstCategoryDimIndex = dimIndex;
  29426. }
  29427. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29428. if (createInvertedIndices) {
  29429. dimInfo.createInvertedIndices = true;
  29430. }
  29431. }
  29432. if (dimInfo.otherDims.itemName != null) {
  29433. hasNameEncode = true;
  29434. }
  29435. });
  29436. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29437. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29438. }
  29439. return firstCategoryDimIndex;
  29440. }
  29441. /**
  29442. * Caution: there are side effects to `sourceManager` in this method.
  29443. * Should better only be called in `Series['getInitialData']`.
  29444. */
  29445. function createSeriesData(sourceRaw, seriesModel, opt) {
  29446. opt = opt || {};
  29447. var sourceManager = seriesModel.getSourceManager();
  29448. var source;
  29449. var isOriginalSource = false;
  29450. if (sourceRaw) {
  29451. isOriginalSource = true;
  29452. source = createSourceFromSeriesDataOption(sourceRaw);
  29453. } else {
  29454. source = sourceManager.getSource(); // Is series.data. not dataset.
  29455. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29456. }
  29457. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29458. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29459. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29460. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29461. var createDimensionOptions = {
  29462. coordDimensions: coordSysDimDefs,
  29463. generateCoord: opt.generateCoord,
  29464. encodeDefine: seriesModel.getEncode(),
  29465. encodeDefaulter: encodeDefaulter,
  29466. canOmitUnusedDimensions: !isOriginalSource
  29467. };
  29468. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29469. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29470. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29471. var stackCalculationInfo = enableDataStack(seriesModel, {
  29472. schema: schema,
  29473. store: store
  29474. });
  29475. var data = new SeriesData(schema, seriesModel);
  29476. data.setCalculationInfo(stackCalculationInfo);
  29477. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29478. // Use dataIndex as ordinal value in categoryAxis
  29479. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29480. } : null;
  29481. data.hasItemOption = false;
  29482. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  29483. isOriginalSource ? source : store, null, dimValueGetter);
  29484. return data;
  29485. }
  29486. function isNeedCompleteOrdinalData(source) {
  29487. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29488. var sampleItem = firstDataNotNull(source.data || []);
  29489. return !isArray(getDataItemValue(sampleItem));
  29490. }
  29491. }
  29492. function firstDataNotNull(arr) {
  29493. var i = 0;
  29494. while (i < arr.length && arr[i] == null) {
  29495. i++;
  29496. }
  29497. return arr[i];
  29498. }
  29499. var Scale =
  29500. /** @class */
  29501. function () {
  29502. function Scale(setting) {
  29503. this._setting = setting || {};
  29504. this._extent = [Infinity, -Infinity];
  29505. }
  29506. Scale.prototype.getSetting = function (name) {
  29507. return this._setting[name];
  29508. };
  29509. /**
  29510. * Set extent from data
  29511. */
  29512. Scale.prototype.unionExtent = function (other) {
  29513. var extent = this._extent;
  29514. other[0] < extent[0] && (extent[0] = other[0]);
  29515. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29516. // this.setExtent(extent[0], extent[1]);
  29517. };
  29518. /**
  29519. * Set extent from data
  29520. */
  29521. Scale.prototype.unionExtentFromData = function (data, dim) {
  29522. this.unionExtent(data.getApproximateExtent(dim));
  29523. };
  29524. /**
  29525. * Get extent
  29526. *
  29527. * Extent is always in increase order.
  29528. */
  29529. Scale.prototype.getExtent = function () {
  29530. return this._extent.slice();
  29531. };
  29532. /**
  29533. * Set extent
  29534. */
  29535. Scale.prototype.setExtent = function (start, end) {
  29536. var thisExtent = this._extent;
  29537. if (!isNaN(start)) {
  29538. thisExtent[0] = start;
  29539. }
  29540. if (!isNaN(end)) {
  29541. thisExtent[1] = end;
  29542. }
  29543. };
  29544. /**
  29545. * If value is in extent range
  29546. */
  29547. Scale.prototype.isInExtentRange = function (value) {
  29548. return this._extent[0] <= value && this._extent[1] >= value;
  29549. };
  29550. /**
  29551. * When axis extent depends on data and no data exists,
  29552. * axis ticks should not be drawn, which is named 'blank'.
  29553. */
  29554. Scale.prototype.isBlank = function () {
  29555. return this._isBlank;
  29556. };
  29557. /**
  29558. * When axis extent depends on data and no data exists,
  29559. * axis ticks should not be drawn, which is named 'blank'.
  29560. */
  29561. Scale.prototype.setBlank = function (isBlank) {
  29562. this._isBlank = isBlank;
  29563. };
  29564. return Scale;
  29565. }();
  29566. enableClassManagement(Scale);
  29567. var uidBase = 0;
  29568. var OrdinalMeta =
  29569. /** @class */
  29570. function () {
  29571. function OrdinalMeta(opt) {
  29572. this.categories = opt.categories || [];
  29573. this._needCollect = opt.needCollect;
  29574. this._deduplication = opt.deduplication;
  29575. this.uid = ++uidBase;
  29576. }
  29577. OrdinalMeta.createByAxisModel = function (axisModel) {
  29578. var option = axisModel.option;
  29579. var data = option.data;
  29580. var categories = data && map(data, getName);
  29581. return new OrdinalMeta({
  29582. categories: categories,
  29583. needCollect: !categories,
  29584. // deduplication is default in axis.
  29585. deduplication: option.dedplication !== false
  29586. });
  29587. };
  29588. OrdinalMeta.prototype.getOrdinal = function (category) {
  29589. // @ts-ignore
  29590. return this._getOrCreateMap().get(category);
  29591. };
  29592. /**
  29593. * @return The ordinal. If not found, return NaN.
  29594. */
  29595. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29596. var index;
  29597. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29598. // This feature is only supported when !needCollect, because we should
  29599. // consider a common case: a value is 2017, which is a number but is
  29600. // expected to be tread as a category. This case usually happen in dataset,
  29601. // where it happent to be no need of the index feature.
  29602. if (!isString(category) && !needCollect) {
  29603. return category;
  29604. } // Optimize for the scenario:
  29605. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29606. // data has been ensured not duplicate and is large data.
  29607. // Notice, if a dataset dimension provide categroies, usually echarts
  29608. // should remove duplication except user tell echarts dont do that
  29609. // (set axis.deduplication = false), because echarts do not know whether
  29610. // the values in the category dimension has duplication (consider the
  29611. // parallel-aqi example)
  29612. if (needCollect && !this._deduplication) {
  29613. index = this.categories.length;
  29614. this.categories[index] = category;
  29615. return index;
  29616. }
  29617. var map = this._getOrCreateMap(); // @ts-ignore
  29618. index = map.get(category);
  29619. if (index == null) {
  29620. if (needCollect) {
  29621. index = this.categories.length;
  29622. this.categories[index] = category; // @ts-ignore
  29623. map.set(category, index);
  29624. } else {
  29625. index = NaN;
  29626. }
  29627. }
  29628. return index;
  29629. }; // Consider big data, do not create map until needed.
  29630. OrdinalMeta.prototype._getOrCreateMap = function () {
  29631. return this._map || (this._map = createHashMap(this.categories));
  29632. };
  29633. return OrdinalMeta;
  29634. }();
  29635. function getName(obj) {
  29636. if (isObject(obj) && obj.value != null) {
  29637. return obj.value;
  29638. } else {
  29639. return obj + '';
  29640. }
  29641. }
  29642. function isValueNice(val) {
  29643. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29644. var f = Math.abs(val / exp10);
  29645. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29646. }
  29647. function isIntervalOrLogScale(scale) {
  29648. return scale.type === 'interval' || scale.type === 'log';
  29649. }
  29650. /**
  29651. * @param extent Both extent[0] and extent[1] should be valid number.
  29652. * Should be extent[0] < extent[1].
  29653. * @param splitNumber splitNumber should be >= 1.
  29654. */
  29655. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29656. var result = {};
  29657. var span = extent[1] - extent[0];
  29658. var interval = result.interval = nice(span / splitNumber, true);
  29659. if (minInterval != null && interval < minInterval) {
  29660. interval = result.interval = minInterval;
  29661. }
  29662. if (maxInterval != null && interval > maxInterval) {
  29663. interval = result.interval = maxInterval;
  29664. } // Tow more digital for tick.
  29665. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29666. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29667. fixExtent(niceTickExtent, extent);
  29668. return result;
  29669. }
  29670. function increaseInterval(interval) {
  29671. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  29672. var f = interval / exp10;
  29673. if (!f) {
  29674. f = 1;
  29675. } else if (f === 2) {
  29676. f = 3;
  29677. } else if (f === 3) {
  29678. f = 5;
  29679. } else {
  29680. // f is 1 or 5
  29681. f *= 2;
  29682. }
  29683. return round(f * exp10);
  29684. }
  29685. /**
  29686. * @return interval precision
  29687. */
  29688. function getIntervalPrecision(interval) {
  29689. // Tow more digital for tick.
  29690. return getPrecision(interval) + 2;
  29691. }
  29692. function clamp(niceTickExtent, idx, extent) {
  29693. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29694. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29695. function fixExtent(niceTickExtent, extent) {
  29696. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29697. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29698. clamp(niceTickExtent, 0, extent);
  29699. clamp(niceTickExtent, 1, extent);
  29700. if (niceTickExtent[0] > niceTickExtent[1]) {
  29701. niceTickExtent[0] = niceTickExtent[1];
  29702. }
  29703. }
  29704. function contain$1(val, extent) {
  29705. return val >= extent[0] && val <= extent[1];
  29706. }
  29707. function normalize$1(val, extent) {
  29708. if (extent[1] === extent[0]) {
  29709. return 0.5;
  29710. }
  29711. return (val - extent[0]) / (extent[1] - extent[0]);
  29712. }
  29713. function scale$2(val, extent) {
  29714. return val * (extent[1] - extent[0]) + extent[0];
  29715. }
  29716. var OrdinalScale =
  29717. /** @class */
  29718. function (_super) {
  29719. __extends(OrdinalScale, _super);
  29720. function OrdinalScale(setting) {
  29721. var _this = _super.call(this, setting) || this;
  29722. _this.type = 'ordinal';
  29723. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  29724. // import approach to get OrdinalMeta class.
  29725. if (!ordinalMeta) {
  29726. ordinalMeta = new OrdinalMeta({});
  29727. }
  29728. if (isArray(ordinalMeta)) {
  29729. ordinalMeta = new OrdinalMeta({
  29730. categories: map(ordinalMeta, function (item) {
  29731. return isObject(item) ? item.value : item;
  29732. })
  29733. });
  29734. }
  29735. _this._ordinalMeta = ordinalMeta;
  29736. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  29737. return _this;
  29738. }
  29739. OrdinalScale.prototype.parse = function (val) {
  29740. // Caution: Math.round(null) will return `0` rather than `NaN`
  29741. if (val == null) {
  29742. return NaN;
  29743. }
  29744. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  29745. : Math.round(val);
  29746. };
  29747. OrdinalScale.prototype.contain = function (rank) {
  29748. rank = this.parse(rank);
  29749. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  29750. };
  29751. /**
  29752. * Normalize given rank or name to linear [0, 1]
  29753. * @param val raw ordinal number.
  29754. * @return normalized value in [0, 1].
  29755. */
  29756. OrdinalScale.prototype.normalize = function (val) {
  29757. val = this._getTickNumber(this.parse(val));
  29758. return normalize$1(val, this._extent);
  29759. };
  29760. /**
  29761. * @param val normalized value in [0, 1].
  29762. * @return raw ordinal number.
  29763. */
  29764. OrdinalScale.prototype.scale = function (val) {
  29765. val = Math.round(scale$2(val, this._extent));
  29766. return this.getRawOrdinalNumber(val);
  29767. };
  29768. OrdinalScale.prototype.getTicks = function () {
  29769. var ticks = [];
  29770. var extent = this._extent;
  29771. var rank = extent[0];
  29772. while (rank <= extent[1]) {
  29773. ticks.push({
  29774. value: rank
  29775. });
  29776. rank++;
  29777. }
  29778. return ticks;
  29779. };
  29780. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  29781. // Not support.
  29782. return;
  29783. };
  29784. /**
  29785. * @see `Ordinal['_ordinalNumbersByTick']`
  29786. */
  29787. OrdinalScale.prototype.setSortInfo = function (info) {
  29788. if (info == null) {
  29789. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  29790. return;
  29791. }
  29792. var infoOrdinalNumbers = info.ordinalNumbers;
  29793. var ordinalsByTick = this._ordinalNumbersByTick = [];
  29794. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  29795. var tickNum = 0;
  29796. var allCategoryLen = this._ordinalMeta.categories.length;
  29797. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  29798. var ordinalNumber = infoOrdinalNumbers[tickNum];
  29799. ordinalsByTick[tickNum] = ordinalNumber;
  29800. ticksByOrdinal[ordinalNumber] = tickNum;
  29801. } // Handle that `series.data` only covers part of the `axis.category.data`.
  29802. var unusedOrdinal = 0;
  29803. for (; tickNum < allCategoryLen; ++tickNum) {
  29804. while (ticksByOrdinal[unusedOrdinal] != null) {
  29805. unusedOrdinal++;
  29806. }
  29807. ordinalsByTick.push(unusedOrdinal);
  29808. ticksByOrdinal[unusedOrdinal] = tickNum;
  29809. }
  29810. };
  29811. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  29812. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  29813. // where ordinal numbers are used as tick value directly.
  29814. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  29815. };
  29816. /**
  29817. * @usage
  29818. * ```js
  29819. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  29820. *
  29821. * // case0
  29822. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  29823. * // case1
  29824. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  29825. * // case2
  29826. * const coord = axis.dataToCoord(ordinalNumber);
  29827. * ```
  29828. *
  29829. * @param {OrdinalNumber} tickNumber index of display
  29830. */
  29831. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  29832. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  29833. // where ordinal numbers are used as tick value directly.
  29834. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  29835. };
  29836. /**
  29837. * Get item on tick
  29838. */
  29839. OrdinalScale.prototype.getLabel = function (tick) {
  29840. if (!this.isBlank()) {
  29841. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  29842. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  29843. // Return empty if it's not exist.
  29844. return cateogry == null ? '' : cateogry + '';
  29845. }
  29846. };
  29847. OrdinalScale.prototype.count = function () {
  29848. return this._extent[1] - this._extent[0] + 1;
  29849. };
  29850. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  29851. this.unionExtent(data.getApproximateExtent(dim));
  29852. };
  29853. /**
  29854. * @override
  29855. * If value is in extent range
  29856. */
  29857. OrdinalScale.prototype.isInExtentRange = function (value) {
  29858. value = this._getTickNumber(value);
  29859. return this._extent[0] <= value && this._extent[1] >= value;
  29860. };
  29861. OrdinalScale.prototype.getOrdinalMeta = function () {
  29862. return this._ordinalMeta;
  29863. };
  29864. OrdinalScale.prototype.calcNiceTicks = function () {};
  29865. OrdinalScale.prototype.calcNiceExtent = function () {};
  29866. OrdinalScale.type = 'ordinal';
  29867. return OrdinalScale;
  29868. }(Scale);
  29869. Scale.registerClass(OrdinalScale);
  29870. var roundNumber = round;
  29871. var IntervalScale =
  29872. /** @class */
  29873. function (_super) {
  29874. __extends(IntervalScale, _super);
  29875. function IntervalScale() {
  29876. var _this = _super !== null && _super.apply(this, arguments) || this;
  29877. _this.type = 'interval'; // Step is calculated in adjustExtent.
  29878. _this._interval = 0;
  29879. _this._intervalPrecision = 2;
  29880. return _this;
  29881. }
  29882. IntervalScale.prototype.parse = function (val) {
  29883. return val;
  29884. };
  29885. IntervalScale.prototype.contain = function (val) {
  29886. return contain$1(val, this._extent);
  29887. };
  29888. IntervalScale.prototype.normalize = function (val) {
  29889. return normalize$1(val, this._extent);
  29890. };
  29891. IntervalScale.prototype.scale = function (val) {
  29892. return scale$2(val, this._extent);
  29893. };
  29894. IntervalScale.prototype.setExtent = function (start, end) {
  29895. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  29896. if (!isNaN(start)) {
  29897. thisExtent[0] = parseFloat(start);
  29898. }
  29899. if (!isNaN(end)) {
  29900. thisExtent[1] = parseFloat(end);
  29901. }
  29902. };
  29903. IntervalScale.prototype.unionExtent = function (other) {
  29904. var extent = this._extent;
  29905. other[0] < extent[0] && (extent[0] = other[0]);
  29906. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  29907. this.setExtent(extent[0], extent[1]);
  29908. };
  29909. IntervalScale.prototype.getInterval = function () {
  29910. return this._interval;
  29911. };
  29912. IntervalScale.prototype.setInterval = function (interval) {
  29913. this._interval = interval; // Dropped auto calculated niceExtent and use user-set extent.
  29914. // We assume user wants to set both interval, min, max to get a better result.
  29915. this._niceExtent = this._extent.slice();
  29916. this._intervalPrecision = getIntervalPrecision(interval);
  29917. };
  29918. /**
  29919. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29920. */
  29921. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  29922. var interval = this._interval;
  29923. var extent = this._extent;
  29924. var niceTickExtent = this._niceExtent;
  29925. var intervalPrecision = this._intervalPrecision;
  29926. var ticks = []; // If interval is 0, return [];
  29927. if (!interval) {
  29928. return ticks;
  29929. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  29930. var safeLimit = 10000;
  29931. if (extent[0] < niceTickExtent[0]) {
  29932. if (expandToNicedExtent) {
  29933. ticks.push({
  29934. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  29935. });
  29936. } else {
  29937. ticks.push({
  29938. value: extent[0]
  29939. });
  29940. }
  29941. }
  29942. var tick = niceTickExtent[0];
  29943. while (tick <= niceTickExtent[1]) {
  29944. ticks.push({
  29945. value: tick
  29946. }); // Avoid rounding error
  29947. tick = roundNumber(tick + interval, intervalPrecision);
  29948. if (tick === ticks[ticks.length - 1].value) {
  29949. // Consider out of safe float point, e.g.,
  29950. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29951. break;
  29952. }
  29953. if (ticks.length > safeLimit) {
  29954. return [];
  29955. }
  29956. } // Consider this case: the last item of ticks is smaller
  29957. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29958. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  29959. if (extent[1] > lastNiceTick) {
  29960. if (expandToNicedExtent) {
  29961. ticks.push({
  29962. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  29963. });
  29964. } else {
  29965. ticks.push({
  29966. value: extent[1]
  29967. });
  29968. }
  29969. }
  29970. return ticks;
  29971. };
  29972. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  29973. var ticks = this.getTicks(true);
  29974. var minorTicks = [];
  29975. var extent = this.getExtent();
  29976. for (var i = 1; i < ticks.length; i++) {
  29977. var nextTick = ticks[i];
  29978. var prevTick = ticks[i - 1];
  29979. var count = 0;
  29980. var minorTicksGroup = [];
  29981. var interval = nextTick.value - prevTick.value;
  29982. var minorInterval = interval / splitNumber;
  29983. while (count < splitNumber - 1) {
  29984. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  29985. if (minorTick > extent[0] && minorTick < extent[1]) {
  29986. minorTicksGroup.push(minorTick);
  29987. }
  29988. count++;
  29989. }
  29990. minorTicks.push(minorTicksGroup);
  29991. }
  29992. return minorTicks;
  29993. };
  29994. /**
  29995. * @param opt.precision If 'auto', use nice presision.
  29996. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  29997. */
  29998. IntervalScale.prototype.getLabel = function (data, opt) {
  29999. if (data == null) {
  30000. return '';
  30001. }
  30002. var precision = opt && opt.precision;
  30003. if (precision == null) {
  30004. precision = getPrecision(data.value) || 0;
  30005. } else if (precision === 'auto') {
  30006. // Should be more precise then tick.
  30007. precision = this._intervalPrecision;
  30008. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30009. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30010. var dataNum = roundNumber(data.value, precision, true);
  30011. return addCommas(dataNum);
  30012. };
  30013. /**
  30014. * @param splitNumber By default `5`.
  30015. */
  30016. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30017. splitNumber = splitNumber || 5;
  30018. var extent = this._extent;
  30019. var span = extent[1] - extent[0];
  30020. if (!isFinite(span)) {
  30021. return;
  30022. } // User may set axis min 0 and data are all negative
  30023. // FIXME If it needs to reverse ?
  30024. if (span < 0) {
  30025. span = -span;
  30026. extent.reverse();
  30027. }
  30028. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30029. this._intervalPrecision = result.intervalPrecision;
  30030. this._interval = result.interval;
  30031. this._niceExtent = result.niceTickExtent;
  30032. };
  30033. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30034. var extent = this._extent; // If extent start and end are same, expand them
  30035. if (extent[0] === extent[1]) {
  30036. if (extent[0] !== 0) {
  30037. // Expand extent
  30038. // Note that extents can be both negative. See #13154
  30039. var expandSize = Math.abs(extent[0]); // In the fowllowing case
  30040. // Axis has been fixed max 100
  30041. // Plus data are all 100 and axis extent are [100, 100].
  30042. // Extend to the both side will cause expanded max is larger than fixed max.
  30043. // So only expand to the smaller side.
  30044. if (!opt.fixMax) {
  30045. extent[1] += expandSize / 2;
  30046. extent[0] -= expandSize / 2;
  30047. } else {
  30048. extent[0] -= expandSize / 2;
  30049. }
  30050. } else {
  30051. extent[1] = 1;
  30052. }
  30053. }
  30054. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  30055. if (!isFinite(span)) {
  30056. extent[0] = 0;
  30057. extent[1] = 1;
  30058. }
  30059. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  30060. var interval = this._interval;
  30061. if (!opt.fixMin) {
  30062. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30063. }
  30064. if (!opt.fixMax) {
  30065. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30066. }
  30067. };
  30068. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30069. this._niceExtent = [min, max];
  30070. };
  30071. IntervalScale.type = 'interval';
  30072. return IntervalScale;
  30073. }(Scale);
  30074. Scale.registerClass(IntervalScale);
  30075. /* global Float32Array */
  30076. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30077. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30078. function createFloat32Array(arg) {
  30079. if (isArray(arg)) {
  30080. // Return self directly if don't support TypedArray.
  30081. return supportFloat32Array ? new Float32Array(arg) : arg;
  30082. } // Else is number
  30083. return new Float32ArrayCtor(arg);
  30084. }
  30085. var STACK_PREFIX = '__ec_stack_';
  30086. function getSeriesStackId(seriesModel) {
  30087. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30088. }
  30089. function getAxisKey(axis) {
  30090. return axis.dim + axis.index;
  30091. }
  30092. function prepareLayoutBarSeries(seriesType, ecModel) {
  30093. var seriesModels = [];
  30094. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30095. // Check series coordinate, do layout for cartesian2d only
  30096. if (isOnCartesian(seriesModel)) {
  30097. seriesModels.push(seriesModel);
  30098. }
  30099. });
  30100. return seriesModels;
  30101. }
  30102. /**
  30103. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30104. * values.
  30105. * This works for time axes, value axes, and log axes.
  30106. * For a single time axis, return value is in the form like
  30107. * {'x_0': [1000000]}.
  30108. * The value of 1000000 is in milliseconds.
  30109. */
  30110. function getValueAxesMinGaps(barSeries) {
  30111. /**
  30112. * Map from axis.index to values.
  30113. * For a single time axis, axisValues is in the form like
  30114. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30115. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30116. * series.
  30117. */
  30118. var axisValues = {};
  30119. each(barSeries, function (seriesModel) {
  30120. var cartesian = seriesModel.coordinateSystem;
  30121. var baseAxis = cartesian.getBaseAxis();
  30122. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30123. return;
  30124. }
  30125. var data = seriesModel.getData();
  30126. var key = baseAxis.dim + '_' + baseAxis.index;
  30127. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30128. var store = data.getStore();
  30129. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30130. var value = store.get(dimIdx, i);
  30131. if (!axisValues[key]) {
  30132. // No previous data for the axis
  30133. axisValues[key] = [value];
  30134. } else {
  30135. // No value in previous series
  30136. axisValues[key].push(value);
  30137. } // Ignore duplicated time values in the same axis
  30138. }
  30139. });
  30140. var axisMinGaps = {};
  30141. for (var key in axisValues) {
  30142. if (axisValues.hasOwnProperty(key)) {
  30143. var valuesInAxis = axisValues[key];
  30144. if (valuesInAxis) {
  30145. // Sort axis values into ascending order to calculate gaps
  30146. valuesInAxis.sort(function (a, b) {
  30147. return a - b;
  30148. });
  30149. var min = null;
  30150. for (var j = 1; j < valuesInAxis.length; ++j) {
  30151. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30152. if (delta > 0) {
  30153. // Ignore 0 delta because they are of the same axis value
  30154. min = min === null ? delta : Math.min(min, delta);
  30155. }
  30156. } // Set to null if only have one data
  30157. axisMinGaps[key] = min;
  30158. }
  30159. }
  30160. }
  30161. return axisMinGaps;
  30162. }
  30163. function makeColumnLayout(barSeries) {
  30164. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30165. var seriesInfoList = [];
  30166. each(barSeries, function (seriesModel) {
  30167. var cartesian = seriesModel.coordinateSystem;
  30168. var baseAxis = cartesian.getBaseAxis();
  30169. var axisExtent = baseAxis.getExtent();
  30170. var bandWidth;
  30171. if (baseAxis.type === 'category') {
  30172. bandWidth = baseAxis.getBandWidth();
  30173. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30174. var key = baseAxis.dim + '_' + baseAxis.index;
  30175. var minGap = axisMinGaps[key];
  30176. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30177. var scale = baseAxis.scale.getExtent();
  30178. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30179. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30180. } else {
  30181. var data = seriesModel.getData();
  30182. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30183. }
  30184. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30185. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30186. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30187. // the auto-calculated bar width might be less than 0.5 / 1.
  30188. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30189. var barGap = seriesModel.get('barGap');
  30190. var barCategoryGap = seriesModel.get('barCategoryGap');
  30191. seriesInfoList.push({
  30192. bandWidth: bandWidth,
  30193. barWidth: barWidth,
  30194. barMaxWidth: barMaxWidth,
  30195. barMinWidth: barMinWidth,
  30196. barGap: barGap,
  30197. barCategoryGap: barCategoryGap,
  30198. axisKey: getAxisKey(baseAxis),
  30199. stackId: getSeriesStackId(seriesModel)
  30200. });
  30201. });
  30202. return doCalBarWidthAndOffset(seriesInfoList);
  30203. }
  30204. function doCalBarWidthAndOffset(seriesInfoList) {
  30205. // Columns info on each category axis. Key is cartesian name
  30206. var columnsMap = {};
  30207. each(seriesInfoList, function (seriesInfo, idx) {
  30208. var axisKey = seriesInfo.axisKey;
  30209. var bandWidth = seriesInfo.bandWidth;
  30210. var columnsOnAxis = columnsMap[axisKey] || {
  30211. bandWidth: bandWidth,
  30212. remainedWidth: bandWidth,
  30213. autoWidthCount: 0,
  30214. categoryGap: null,
  30215. gap: '20%',
  30216. stacks: {}
  30217. };
  30218. var stacks = columnsOnAxis.stacks;
  30219. columnsMap[axisKey] = columnsOnAxis;
  30220. var stackId = seriesInfo.stackId;
  30221. if (!stacks[stackId]) {
  30222. columnsOnAxis.autoWidthCount++;
  30223. }
  30224. stacks[stackId] = stacks[stackId] || {
  30225. width: 0,
  30226. maxWidth: 0
  30227. }; // Caution: In a single coordinate system, these barGrid attributes
  30228. // will be shared by series. Consider that they have default values,
  30229. // only the attributes set on the last series will work.
  30230. // Do not change this fact unless there will be a break change.
  30231. var barWidth = seriesInfo.barWidth;
  30232. if (barWidth && !stacks[stackId].width) {
  30233. // See #6312, do not restrict width.
  30234. stacks[stackId].width = barWidth;
  30235. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30236. columnsOnAxis.remainedWidth -= barWidth;
  30237. }
  30238. var barMaxWidth = seriesInfo.barMaxWidth;
  30239. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30240. var barMinWidth = seriesInfo.barMinWidth;
  30241. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30242. var barGap = seriesInfo.barGap;
  30243. barGap != null && (columnsOnAxis.gap = barGap);
  30244. var barCategoryGap = seriesInfo.barCategoryGap;
  30245. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30246. });
  30247. var result = {};
  30248. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30249. result[coordSysName] = {};
  30250. var stacks = columnsOnAxis.stacks;
  30251. var bandWidth = columnsOnAxis.bandWidth;
  30252. var categoryGapPercent = columnsOnAxis.categoryGap;
  30253. if (categoryGapPercent == null) {
  30254. var columnCount = keys(stacks).length; // More columns in one group
  30255. // the spaces between group is smaller. Or the column will be too thin.
  30256. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30257. }
  30258. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30259. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30260. var remainedWidth = columnsOnAxis.remainedWidth;
  30261. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30262. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30263. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30264. each(stacks, function (column) {
  30265. var maxWidth = column.maxWidth;
  30266. var minWidth = column.minWidth;
  30267. if (!column.width) {
  30268. var finalWidth = autoWidth;
  30269. if (maxWidth && maxWidth < finalWidth) {
  30270. finalWidth = Math.min(maxWidth, remainedWidth);
  30271. } // `minWidth` has higher priority. `minWidth` decide that whether the
  30272. // bar is able to be visible. So `minWidth` should not be restricted
  30273. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30274. // the extreme cases for `value` axis, bars are allowed to overlap
  30275. // with each other if `minWidth` specified.
  30276. if (minWidth && minWidth > finalWidth) {
  30277. finalWidth = minWidth;
  30278. }
  30279. if (finalWidth !== autoWidth) {
  30280. column.width = finalWidth;
  30281. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30282. autoWidthCount--;
  30283. }
  30284. } else {
  30285. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30286. // CSS does. Because barWidth can be a percent value, where
  30287. // `barMaxWidth` can be used to restrict the final width.
  30288. var finalWidth = column.width;
  30289. if (maxWidth) {
  30290. finalWidth = Math.min(finalWidth, maxWidth);
  30291. } // `minWidth` has higher priority, as described above
  30292. if (minWidth) {
  30293. finalWidth = Math.max(finalWidth, minWidth);
  30294. }
  30295. column.width = finalWidth;
  30296. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30297. autoWidthCount--;
  30298. }
  30299. }); // Recalculate width again
  30300. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30301. autoWidth = Math.max(autoWidth, 0);
  30302. var widthSum = 0;
  30303. var lastColumn;
  30304. each(stacks, function (column, idx) {
  30305. if (!column.width) {
  30306. column.width = autoWidth;
  30307. }
  30308. lastColumn = column;
  30309. widthSum += column.width * (1 + barGapPercent);
  30310. });
  30311. if (lastColumn) {
  30312. widthSum -= lastColumn.width * barGapPercent;
  30313. }
  30314. var offset = -widthSum / 2;
  30315. each(stacks, function (column, stackId) {
  30316. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30317. bandWidth: bandWidth,
  30318. offset: offset,
  30319. width: column.width
  30320. };
  30321. offset += column.width * (1 + barGapPercent);
  30322. });
  30323. });
  30324. return result;
  30325. }
  30326. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30327. if (barWidthAndOffset && axis) {
  30328. var result = barWidthAndOffset[getAxisKey(axis)];
  30329. if (result != null && seriesModel != null) {
  30330. return result[getSeriesStackId(seriesModel)];
  30331. }
  30332. return result;
  30333. }
  30334. }
  30335. function layout(seriesType, ecModel) {
  30336. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30337. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30338. each(seriesModels, function (seriesModel) {
  30339. var data = seriesModel.getData();
  30340. var cartesian = seriesModel.coordinateSystem;
  30341. var baseAxis = cartesian.getBaseAxis();
  30342. var stackId = getSeriesStackId(seriesModel);
  30343. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30344. var columnOffset = columnLayoutInfo.offset;
  30345. var columnWidth = columnLayoutInfo.width;
  30346. data.setLayout({
  30347. bandWidth: columnLayoutInfo.bandWidth,
  30348. offset: columnOffset,
  30349. size: columnWidth
  30350. });
  30351. });
  30352. } // TODO: Do not support stack in large mode yet.
  30353. function createProgressiveLayout(seriesType) {
  30354. return {
  30355. seriesType: seriesType,
  30356. plan: createRenderPlanner(),
  30357. reset: function (seriesModel) {
  30358. if (!isOnCartesian(seriesModel)) {
  30359. return;
  30360. }
  30361. var data = seriesModel.getData();
  30362. var cartesian = seriesModel.coordinateSystem;
  30363. var baseAxis = cartesian.getBaseAxis();
  30364. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30365. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30366. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30367. var drawBackground = seriesModel.get('showBackground', true);
  30368. var valueDim = data.mapDimension(valueAxis.dim);
  30369. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30370. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30371. var isValueAxisH = valueAxis.isHorizontal();
  30372. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30373. var isLarge = isInLargeMode(seriesModel);
  30374. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30375. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  30376. var columnWidth = data.getLayout('size');
  30377. var columnOffset = data.getLayout('offset');
  30378. return {
  30379. progress: function (params, data) {
  30380. var count = params.count;
  30381. var largePoints = isLarge && createFloat32Array(count * 3);
  30382. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30383. var largeDataIndices = isLarge && createFloat32Array(count);
  30384. var coordLayout = cartesian.master.getRect();
  30385. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30386. var dataIndex;
  30387. var store = data.getStore();
  30388. var idxOffset = 0;
  30389. while ((dataIndex = params.next()) != null) {
  30390. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30391. var baseValue = store.get(baseDimIdx, dataIndex);
  30392. var baseCoord = valueAxisStart;
  30393. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  30394. // stackResultDimension directly.
  30395. if (stacked) {
  30396. startValue = +value - store.get(valueDimIdx, dataIndex);
  30397. }
  30398. var x = void 0;
  30399. var y = void 0;
  30400. var width = void 0;
  30401. var height = void 0;
  30402. if (isValueAxisH) {
  30403. var coord = cartesian.dataToPoint([value, baseValue]);
  30404. if (stacked) {
  30405. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  30406. baseCoord = startCoord[0];
  30407. }
  30408. x = baseCoord;
  30409. y = coord[1] + columnOffset;
  30410. width = coord[0] - baseCoord;
  30411. height = columnWidth;
  30412. if (Math.abs(width) < barMinHeight) {
  30413. width = (width < 0 ? -1 : 1) * barMinHeight;
  30414. }
  30415. } else {
  30416. var coord = cartesian.dataToPoint([baseValue, value]);
  30417. if (stacked) {
  30418. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  30419. baseCoord = startCoord[1];
  30420. }
  30421. x = coord[0] + columnOffset;
  30422. y = baseCoord;
  30423. width = columnWidth;
  30424. height = coord[1] - baseCoord;
  30425. if (Math.abs(height) < barMinHeight) {
  30426. // Include zero to has a positive bar
  30427. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30428. }
  30429. }
  30430. if (!isLarge) {
  30431. data.setItemLayout(dataIndex, {
  30432. x: x,
  30433. y: y,
  30434. width: width,
  30435. height: height
  30436. });
  30437. } else {
  30438. largePoints[idxOffset] = x;
  30439. largePoints[idxOffset + 1] = y;
  30440. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30441. if (largeBackgroundPoints) {
  30442. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30443. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30444. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30445. }
  30446. largeDataIndices[dataIndex] = dataIndex;
  30447. }
  30448. idxOffset += 3;
  30449. }
  30450. if (isLarge) {
  30451. data.setLayout({
  30452. largePoints: largePoints,
  30453. largeDataIndices: largeDataIndices,
  30454. largeBackgroundPoints: largeBackgroundPoints,
  30455. valueAxisHorizontal: isValueAxisH
  30456. });
  30457. }
  30458. }
  30459. };
  30460. }
  30461. };
  30462. }
  30463. function isOnCartesian(seriesModel) {
  30464. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30465. }
  30466. function isInLargeMode(seriesModel) {
  30467. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30468. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30469. function getValueAxisStart(baseAxis, valueAxis) {
  30470. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30471. }
  30472. var bisect = function (a, x, lo, hi) {
  30473. while (lo < hi) {
  30474. var mid = lo + hi >>> 1;
  30475. if (a[mid][1] < x) {
  30476. lo = mid + 1;
  30477. } else {
  30478. hi = mid;
  30479. }
  30480. }
  30481. return lo;
  30482. };
  30483. var TimeScale =
  30484. /** @class */
  30485. function (_super) {
  30486. __extends(TimeScale, _super);
  30487. function TimeScale(settings) {
  30488. var _this = _super.call(this, settings) || this;
  30489. _this.type = 'time';
  30490. return _this;
  30491. }
  30492. /**
  30493. * Get label is mainly for other components like dataZoom, tooltip.
  30494. */
  30495. TimeScale.prototype.getLabel = function (tick) {
  30496. var useUTC = this.getSetting('useUTC');
  30497. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30498. };
  30499. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30500. var isUTC = this.getSetting('useUTC');
  30501. var lang = this.getSetting('locale');
  30502. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30503. };
  30504. /**
  30505. * @override
  30506. */
  30507. TimeScale.prototype.getTicks = function () {
  30508. var interval = this._interval;
  30509. var extent = this._extent;
  30510. var ticks = []; // If interval is 0, return [];
  30511. if (!interval) {
  30512. return ticks;
  30513. }
  30514. ticks.push({
  30515. value: extent[0],
  30516. level: 0
  30517. });
  30518. var useUTC = this.getSetting('useUTC');
  30519. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30520. ticks = ticks.concat(innerTicks);
  30521. ticks.push({
  30522. value: extent[1],
  30523. level: 0
  30524. });
  30525. return ticks;
  30526. };
  30527. TimeScale.prototype.calcNiceExtent = function (opt) {
  30528. var extent = this._extent; // If extent start and end are same, expand them
  30529. if (extent[0] === extent[1]) {
  30530. // Expand extent
  30531. extent[0] -= ONE_DAY;
  30532. extent[1] += ONE_DAY;
  30533. } // If there are no data and extent are [Infinity, -Infinity]
  30534. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30535. var d = new Date();
  30536. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30537. extent[0] = extent[1] - ONE_DAY;
  30538. }
  30539. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30540. };
  30541. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30542. approxTickNum = approxTickNum || 10;
  30543. var extent = this._extent;
  30544. var span = extent[1] - extent[0];
  30545. this._approxInterval = span / approxTickNum;
  30546. if (minInterval != null && this._approxInterval < minInterval) {
  30547. this._approxInterval = minInterval;
  30548. }
  30549. if (maxInterval != null && this._approxInterval > maxInterval) {
  30550. this._approxInterval = maxInterval;
  30551. }
  30552. var scaleIntervalsLen = scaleIntervals.length;
  30553. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30554. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30555. // We check one more level to avoid the ticks are to sparse in some case.
  30556. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30557. };
  30558. TimeScale.prototype.parse = function (val) {
  30559. // val might be float.
  30560. return isNumber(val) ? val : +parseDate(val);
  30561. };
  30562. TimeScale.prototype.contain = function (val) {
  30563. return contain$1(this.parse(val), this._extent);
  30564. };
  30565. TimeScale.prototype.normalize = function (val) {
  30566. return normalize$1(this.parse(val), this._extent);
  30567. };
  30568. TimeScale.prototype.scale = function (val) {
  30569. return scale$2(val, this._extent);
  30570. };
  30571. TimeScale.type = 'time';
  30572. return TimeScale;
  30573. }(IntervalScale);
  30574. /**
  30575. * This implementation was originally copied from "d3.js"
  30576. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30577. * with some modifications made for this program.
  30578. * See the license statement at the head of this file.
  30579. */
  30580. var scaleIntervals = [// Format interval
  30581. ['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
  30582. ];
  30583. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30584. var dateA = parseDate(valueA);
  30585. var dateB = parseDate(valueB);
  30586. var isSame = function (unit) {
  30587. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30588. };
  30589. var isSameYear = function () {
  30590. return isSame('year');
  30591. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30592. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30593. var isSameMonth = function () {
  30594. return isSameYear() && isSame('month');
  30595. };
  30596. var isSameDay = function () {
  30597. return isSameMonth() && isSame('day');
  30598. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30599. var isSameHour = function () {
  30600. return isSameDay() && isSame('hour');
  30601. };
  30602. var isSameMinute = function () {
  30603. return isSameHour() && isSame('minute');
  30604. };
  30605. var isSameSecond = function () {
  30606. return isSameMinute() && isSame('second');
  30607. };
  30608. var isSameMilliSecond = function () {
  30609. return isSameSecond() && isSame('millisecond');
  30610. };
  30611. switch (unit) {
  30612. case 'year':
  30613. return isSameYear();
  30614. case 'month':
  30615. return isSameMonth();
  30616. case 'day':
  30617. return isSameDay();
  30618. case 'hour':
  30619. return isSameHour();
  30620. case 'minute':
  30621. return isSameMinute();
  30622. case 'second':
  30623. return isSameSecond();
  30624. case 'millisecond':
  30625. return isSameMilliSecond();
  30626. }
  30627. } // const primaryUnitGetters = {
  30628. // year: fullYearGetterName(),
  30629. // month: monthGetterName(),
  30630. // day: dateGetterName(),
  30631. // hour: hoursGetterName(),
  30632. // minute: minutesGetterName(),
  30633. // second: secondsGetterName(),
  30634. // millisecond: millisecondsGetterName()
  30635. // };
  30636. // const primaryUnitUTCGetters = {
  30637. // year: fullYearGetterName(true),
  30638. // month: monthGetterName(true),
  30639. // day: dateGetterName(true),
  30640. // hour: hoursGetterName(true),
  30641. // minute: minutesGetterName(true),
  30642. // second: secondsGetterName(true),
  30643. // millisecond: millisecondsGetterName(true)
  30644. // };
  30645. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30646. // step = step || 1;
  30647. // switch (getPrimaryTimeUnit(unitName)) {
  30648. // case 'year':
  30649. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30650. // break;
  30651. // case 'month':
  30652. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30653. // break;
  30654. // case 'day':
  30655. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30656. // break;
  30657. // case 'hour':
  30658. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30659. // break;
  30660. // case 'minute':
  30661. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30662. // break;
  30663. // case 'second':
  30664. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  30665. // break;
  30666. // case 'millisecond':
  30667. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  30668. // break;
  30669. // }
  30670. // return date.getTime();
  30671. // }
  30672. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  30673. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  30674. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  30675. function getDateInterval(approxInterval, daysInMonth) {
  30676. approxInterval /= ONE_DAY;
  30677. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  30678. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  30679. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  30680. }
  30681. function getMonthInterval(approxInterval) {
  30682. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  30683. approxInterval /= APPROX_ONE_MONTH;
  30684. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  30685. }
  30686. function getHourInterval(approxInterval) {
  30687. approxInterval /= ONE_HOUR;
  30688. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  30689. }
  30690. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  30691. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  30692. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  30693. }
  30694. function getMillisecondsInterval(approxInterval) {
  30695. return nice(approxInterval, true);
  30696. }
  30697. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  30698. var outDate = new Date(date);
  30699. switch (getPrimaryTimeUnit(unitName)) {
  30700. case 'year':
  30701. case 'month':
  30702. outDate[monthSetterName(isUTC)](0);
  30703. case 'day':
  30704. outDate[dateSetterName(isUTC)](1);
  30705. case 'hour':
  30706. outDate[hoursSetterName(isUTC)](0);
  30707. case 'minute':
  30708. outDate[minutesSetterName(isUTC)](0);
  30709. case 'second':
  30710. outDate[secondsSetterName(isUTC)](0);
  30711. outDate[millisecondsSetterName(isUTC)](0);
  30712. }
  30713. return outDate.getTime();
  30714. }
  30715. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  30716. var safeLimit = 10000;
  30717. var unitNames = timeUnits;
  30718. var iter = 0;
  30719. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  30720. var date = new Date(minTimestamp);
  30721. var dateTime = minTimestamp;
  30722. var d = date[getMethodName](); // if (isDate) {
  30723. // d -= 1; // Starts with 0; PENDING
  30724. // }
  30725. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  30726. out.push({
  30727. value: dateTime
  30728. });
  30729. d += interval;
  30730. date[setMethodName](d);
  30731. dateTime = date.getTime();
  30732. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  30733. out.push({
  30734. value: dateTime,
  30735. notAdd: true
  30736. });
  30737. }
  30738. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  30739. var newAddedTicks = [];
  30740. var isFirstLevel = !lastLevelTicks.length;
  30741. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  30742. return;
  30743. }
  30744. if (isFirstLevel) {
  30745. lastLevelTicks = [{
  30746. // TODO Optimize. Not include so may ticks.
  30747. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  30748. }, {
  30749. value: extent[1]
  30750. }];
  30751. }
  30752. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  30753. var startTick = lastLevelTicks[i].value;
  30754. var endTick = lastLevelTicks[i + 1].value;
  30755. if (startTick === endTick) {
  30756. continue;
  30757. }
  30758. var interval = void 0;
  30759. var getterName = void 0;
  30760. var setterName = void 0;
  30761. var isDate = false;
  30762. switch (unitName) {
  30763. case 'year':
  30764. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  30765. getterName = fullYearGetterName(isUTC);
  30766. setterName = fullYearSetterName(isUTC);
  30767. break;
  30768. case 'half-year':
  30769. case 'quarter':
  30770. case 'month':
  30771. interval = getMonthInterval(approxInterval);
  30772. getterName = monthGetterName(isUTC);
  30773. setterName = monthSetterName(isUTC);
  30774. break;
  30775. case 'week': // PENDING If week is added. Ignore day.
  30776. case 'half-week':
  30777. case 'day':
  30778. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  30779. getterName = dateGetterName(isUTC);
  30780. setterName = dateSetterName(isUTC);
  30781. isDate = true;
  30782. break;
  30783. case 'half-day':
  30784. case 'quarter-day':
  30785. case 'hour':
  30786. interval = getHourInterval(approxInterval);
  30787. getterName = hoursGetterName(isUTC);
  30788. setterName = hoursSetterName(isUTC);
  30789. break;
  30790. case 'minute':
  30791. interval = getMinutesAndSecondsInterval(approxInterval, true);
  30792. getterName = minutesGetterName(isUTC);
  30793. setterName = minutesSetterName(isUTC);
  30794. break;
  30795. case 'second':
  30796. interval = getMinutesAndSecondsInterval(approxInterval, false);
  30797. getterName = secondsGetterName(isUTC);
  30798. setterName = secondsSetterName(isUTC);
  30799. break;
  30800. case 'millisecond':
  30801. interval = getMillisecondsInterval(approxInterval);
  30802. getterName = millisecondsGetterName(isUTC);
  30803. setterName = millisecondsSetterName(isUTC);
  30804. break;
  30805. }
  30806. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  30807. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  30808. // Add nearest years to the left extent.
  30809. levelTicks.unshift({
  30810. value: levelTicks[0].value - interval
  30811. });
  30812. }
  30813. }
  30814. for (var i = 0; i < newAddedTicks.length; i++) {
  30815. levelTicks.push(newAddedTicks[i]);
  30816. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  30817. return newAddedTicks;
  30818. }
  30819. var levelsTicks = [];
  30820. var currentLevelTicks = [];
  30821. var tickCount = 0;
  30822. var lastLevelTickCount = 0;
  30823. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  30824. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  30825. if (!isPrimaryTimeUnit(unitNames[i])) {
  30826. // TODO
  30827. continue;
  30828. }
  30829. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  30830. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  30831. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  30832. if (currentLevelTicks.length) {
  30833. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  30834. currentLevelTicks.sort(function (a, b) {
  30835. return a.value - b.value;
  30836. });
  30837. var levelTicksRemoveDuplicated = [];
  30838. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  30839. var tickValue = currentLevelTicks[i_1].value;
  30840. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  30841. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  30842. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  30843. tickCount++;
  30844. }
  30845. }
  30846. }
  30847. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  30848. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  30849. break;
  30850. } // Only treat primary time unit as one level.
  30851. levelsTicks.push(levelTicksRemoveDuplicated);
  30852. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  30853. break;
  30854. }
  30855. } // Reset if next unitName is primary
  30856. currentLevelTicks = [];
  30857. }
  30858. }
  30859. if ("development" !== 'production') {
  30860. if (iter >= safeLimit) {
  30861. warn('Exceed safe limit.');
  30862. }
  30863. }
  30864. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  30865. return filter(levelTicks, function (tick) {
  30866. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  30867. });
  30868. }), function (levelTicks) {
  30869. return levelTicks.length > 0;
  30870. });
  30871. var ticks = [];
  30872. var maxLevel = levelsTicksInExtent.length - 1;
  30873. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  30874. var levelTicks = levelsTicksInExtent[i];
  30875. for (var k = 0; k < levelTicks.length; ++k) {
  30876. ticks.push({
  30877. value: levelTicks[k].value,
  30878. level: maxLevel - i
  30879. });
  30880. }
  30881. }
  30882. ticks.sort(function (a, b) {
  30883. return a.value - b.value;
  30884. }); // Remove duplicates
  30885. var result = [];
  30886. for (var i = 0; i < ticks.length; ++i) {
  30887. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  30888. result.push(ticks[i]);
  30889. }
  30890. }
  30891. return result;
  30892. }
  30893. Scale.registerClass(TimeScale);
  30894. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  30895. var intervalScaleProto = IntervalScale.prototype;
  30896. var roundingErrorFix = round;
  30897. var mathFloor = Math.floor;
  30898. var mathCeil = Math.ceil;
  30899. var mathPow$1 = Math.pow;
  30900. var mathLog = Math.log;
  30901. var LogScale =
  30902. /** @class */
  30903. function (_super) {
  30904. __extends(LogScale, _super);
  30905. function LogScale() {
  30906. var _this = _super !== null && _super.apply(this, arguments) || this;
  30907. _this.type = 'log';
  30908. _this.base = 10;
  30909. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  30910. _this._interval = 0;
  30911. return _this;
  30912. }
  30913. /**
  30914. * @param Whether expand the ticks to niced extent.
  30915. */
  30916. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  30917. var originalScale = this._originalScale;
  30918. var extent = this._extent;
  30919. var originalExtent = originalScale.getExtent();
  30920. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  30921. return map(ticks, function (tick) {
  30922. var val = tick.value;
  30923. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  30924. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  30925. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  30926. return {
  30927. value: powVal
  30928. };
  30929. }, this);
  30930. };
  30931. LogScale.prototype.setExtent = function (start, end) {
  30932. var base = mathLog(this.base); // log(-Infinity) is NaN, so safe guard here
  30933. start = mathLog(Math.max(0, start)) / base;
  30934. end = mathLog(Math.max(0, end)) / base;
  30935. intervalScaleProto.setExtent.call(this, start, end);
  30936. };
  30937. /**
  30938. * @return {number} end
  30939. */
  30940. LogScale.prototype.getExtent = function () {
  30941. var base = this.base;
  30942. var extent = scaleProto.getExtent.call(this);
  30943. extent[0] = mathPow$1(base, extent[0]);
  30944. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  30945. var originalScale = this._originalScale;
  30946. var originalExtent = originalScale.getExtent();
  30947. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30948. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30949. return extent;
  30950. };
  30951. LogScale.prototype.unionExtent = function (extent) {
  30952. this._originalScale.unionExtent(extent);
  30953. var base = this.base;
  30954. extent[0] = mathLog(extent[0]) / mathLog(base);
  30955. extent[1] = mathLog(extent[1]) / mathLog(base);
  30956. scaleProto.unionExtent.call(this, extent);
  30957. };
  30958. LogScale.prototype.unionExtentFromData = function (data, dim) {
  30959. // TODO
  30960. // filter value that <= 0
  30961. this.unionExtent(data.getApproximateExtent(dim));
  30962. };
  30963. /**
  30964. * Update interval and extent of intervals for nice ticks
  30965. * @param approxTickNum default 10 Given approx tick number
  30966. */
  30967. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  30968. approxTickNum = approxTickNum || 10;
  30969. var extent = this._extent;
  30970. var span = extent[1] - extent[0];
  30971. if (span === Infinity || span <= 0) {
  30972. return;
  30973. }
  30974. var interval = quantity(span);
  30975. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  30976. if (err <= 0.5) {
  30977. interval *= 10;
  30978. } // Interval should be integer
  30979. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30980. interval *= 10;
  30981. }
  30982. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  30983. this._interval = interval;
  30984. this._niceExtent = niceExtent;
  30985. };
  30986. LogScale.prototype.calcNiceExtent = function (opt) {
  30987. intervalScaleProto.calcNiceExtent.call(this, opt);
  30988. this._fixMin = opt.fixMin;
  30989. this._fixMax = opt.fixMax;
  30990. };
  30991. LogScale.prototype.parse = function (val) {
  30992. return val;
  30993. };
  30994. LogScale.prototype.contain = function (val) {
  30995. val = mathLog(val) / mathLog(this.base);
  30996. return contain$1(val, this._extent);
  30997. };
  30998. LogScale.prototype.normalize = function (val) {
  30999. val = mathLog(val) / mathLog(this.base);
  31000. return normalize$1(val, this._extent);
  31001. };
  31002. LogScale.prototype.scale = function (val) {
  31003. val = scale$2(val, this._extent);
  31004. return mathPow$1(this.base, val);
  31005. };
  31006. LogScale.type = 'log';
  31007. return LogScale;
  31008. }(Scale);
  31009. var proto = LogScale.prototype;
  31010. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31011. proto.getLabel = intervalScaleProto.getLabel;
  31012. function fixRoundingError(val, originalVal) {
  31013. return roundingErrorFix(val, getPrecision(originalVal));
  31014. }
  31015. Scale.registerClass(LogScale);
  31016. var ScaleRawExtentInfo =
  31017. /** @class */
  31018. function () {
  31019. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31020. originalExtent) {
  31021. this._prepareParams(scale, model, originalExtent);
  31022. }
  31023. /**
  31024. * Parameters depending on outside (like model, user callback)
  31025. * are prepared and fixed here.
  31026. */
  31027. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  31028. dataExtent) {
  31029. if (dataExtent[1] < dataExtent[0]) {
  31030. dataExtent = [NaN, NaN];
  31031. }
  31032. this._dataMin = dataExtent[0];
  31033. this._dataMax = dataExtent[1];
  31034. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31035. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31036. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  31037. if (isFunction(modelMinRaw)) {
  31038. // This callback always provides users the full data extent (before data is filtered).
  31039. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31040. min: dataExtent[0],
  31041. max: dataExtent[1]
  31042. }));
  31043. } else if (modelMinRaw !== 'dataMin') {
  31044. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31045. }
  31046. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31047. if (isFunction(modelMaxRaw)) {
  31048. // This callback always provides users the full data extent (before data is filtered).
  31049. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31050. min: dataExtent[0],
  31051. max: dataExtent[1]
  31052. }));
  31053. } else if (modelMaxRaw !== 'dataMax') {
  31054. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31055. }
  31056. if (isOrdinal) {
  31057. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31058. // and progressive rendering is using, here the category result might just only contain
  31059. // the processed chunk rather than the entire result.
  31060. this._axisDataLen = model.getCategories().length;
  31061. } else {
  31062. var boundaryGap = model.get('boundaryGap');
  31063. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31064. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31065. if ("development" !== 'production') {
  31066. 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.');
  31067. }
  31068. this._boundaryGapInner = [0, 0];
  31069. } else {
  31070. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31071. }
  31072. }
  31073. };
  31074. /**
  31075. * Calculate extent by prepared parameters.
  31076. * This method has no external dependency and can be called duplicatedly,
  31077. * getting the same result.
  31078. * If parameters changed, should call this method to recalcuate.
  31079. */
  31080. ScaleRawExtentInfo.prototype.calculate = function () {
  31081. // Notice: When min/max is not set (that is, when there are null/undefined,
  31082. // which is the most common case), these cases should be ensured:
  31083. // (1) For 'ordinal', show all axis.data.
  31084. // (2) For others:
  31085. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31086. // disabled).
  31087. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31088. // be the result that originalExtent enlarged by boundaryGap.
  31089. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31090. var isOrdinal = this._isOrdinal;
  31091. var dataMin = this._dataMin;
  31092. var dataMax = this._dataMax;
  31093. var axisDataLen = this._axisDataLen;
  31094. var boundaryGapInner = this._boundaryGapInner;
  31095. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31096. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31097. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31098. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31099. var minFixed = min != null;
  31100. var maxFixed = max != null;
  31101. if (min == null) {
  31102. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31103. }
  31104. if (max == null) {
  31105. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31106. }
  31107. (min == null || !isFinite(min)) && (min = NaN);
  31108. (max == null || !isFinite(max)) && (max = NaN);
  31109. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  31110. if (this._needCrossZero) {
  31111. // Axis is over zero and min is not set
  31112. if (min > 0 && max > 0 && !minFixed) {
  31113. min = 0; // minFixed = true;
  31114. } // Axis is under zero and max is not set
  31115. if (min < 0 && max < 0 && !maxFixed) {
  31116. max = 0; // maxFixed = true;
  31117. } // PENDING:
  31118. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31119. // that the results processed by boundaryGap are positive/negative?
  31120. // If so, here `minFixed`/`maxFixed` need to be set.
  31121. }
  31122. var determinedMin = this._determinedMin;
  31123. var determinedMax = this._determinedMax;
  31124. if (determinedMin != null) {
  31125. min = determinedMin;
  31126. minFixed = true;
  31127. }
  31128. if (determinedMax != null) {
  31129. max = determinedMax;
  31130. maxFixed = true;
  31131. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31132. // `NaN` means min/max axis is blank.
  31133. return {
  31134. min: min,
  31135. max: max,
  31136. minFixed: minFixed,
  31137. maxFixed: maxFixed,
  31138. isBlank: isBlank
  31139. };
  31140. };
  31141. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31142. if ("development" !== 'production') {
  31143. assert(!this.frozen);
  31144. }
  31145. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31146. };
  31147. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31148. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31149. if ("development" !== 'production') {
  31150. assert(!this.frozen // Earse them usually means logic flaw.
  31151. && this[attr] == null);
  31152. }
  31153. this[attr] = val;
  31154. };
  31155. ScaleRawExtentInfo.prototype.freeze = function () {
  31156. // @ts-ignore
  31157. this.frozen = true;
  31158. };
  31159. return ScaleRawExtentInfo;
  31160. }();
  31161. var DETERMINED_MIN_MAX_ATTR = {
  31162. min: '_determinedMin',
  31163. max: '_determinedMax'
  31164. };
  31165. var DATA_MIN_MAX_ATTR = {
  31166. min: '_dataMin',
  31167. max: '_dataMax'
  31168. };
  31169. /**
  31170. * Get scale min max and related info only depends on model settings.
  31171. * This method can be called after coordinate system created.
  31172. * For example, in data processing stage.
  31173. *
  31174. * Scale extent info probably be required multiple times during a workflow.
  31175. * For example:
  31176. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31177. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31178. * (3) `coordSys.update` use it to finally decide the scale extent.
  31179. * But the callback of `min`/`max` should not be called multiple times.
  31180. * The code below should not be implemented repeatedly either.
  31181. * So we cache the result in the scale instance, which will be recreated at the beginning
  31182. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31183. */
  31184. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31185. originalExtent) {
  31186. // Do not permit to recreate.
  31187. var rawExtentInfo = scale.rawExtentInfo;
  31188. if (rawExtentInfo) {
  31189. return rawExtentInfo;
  31190. }
  31191. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31192. scale.rawExtentInfo = rawExtentInfo;
  31193. return rawExtentInfo;
  31194. }
  31195. function parseAxisModelMinMax(scale, minMax) {
  31196. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31197. }
  31198. /**
  31199. * Get axis scale extent before niced.
  31200. * Item of returned array can only be number (including Infinity and NaN).
  31201. *
  31202. * Caution:
  31203. * Precondition of calling this method:
  31204. * The scale extent has been initialized using series data extent via
  31205. * `scale.setExtent` or `scale.unionExtentFromData`;
  31206. */
  31207. function getScaleExtent(scale, model) {
  31208. var scaleType = scale.type;
  31209. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31210. scale.setBlank(rawExtentResult.isBlank);
  31211. var min = rawExtentResult.min;
  31212. var max = rawExtentResult.max; // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31213. // is base axis
  31214. // FIXME
  31215. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31216. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31217. // Should not depend on series type `bar`?
  31218. // (3) Fix that might overlap when using dataZoom.
  31219. // (4) Consider other chart types using `barGrid`?
  31220. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31221. var ecModel = model.ecModel;
  31222. if (ecModel && scaleType === 'time'
  31223. /* || scaleType === 'interval' */
  31224. ) {
  31225. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31226. var isBaseAxisAndHasBarSeries_1 = false;
  31227. each(barSeriesModels, function (seriesModel) {
  31228. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31229. });
  31230. if (isBaseAxisAndHasBarSeries_1) {
  31231. // Calculate placement of bars on axis. TODO should be decoupled
  31232. // with barLayout
  31233. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31234. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31235. min = adjustedScale.min;
  31236. max = adjustedScale.max;
  31237. }
  31238. }
  31239. return {
  31240. extent: [min, max],
  31241. // "fix" means "fixed", the value should not be
  31242. // changed in the subsequent steps.
  31243. fixMin: rawExtentResult.minFixed,
  31244. fixMax: rawExtentResult.maxFixed
  31245. };
  31246. }
  31247. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31248. barWidthAndOffset) {
  31249. // Get Axis Length
  31250. var axisExtent = model.axis.getExtent();
  31251. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31252. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31253. if (barsOnCurrentAxis === undefined) {
  31254. return {
  31255. min: min,
  31256. max: max
  31257. };
  31258. }
  31259. var minOverflow = Infinity;
  31260. each(barsOnCurrentAxis, function (item) {
  31261. minOverflow = Math.min(item.offset, minOverflow);
  31262. });
  31263. var maxOverflow = -Infinity;
  31264. each(barsOnCurrentAxis, function (item) {
  31265. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31266. });
  31267. minOverflow = Math.abs(minOverflow);
  31268. maxOverflow = Math.abs(maxOverflow);
  31269. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31270. var oldRange = max - min;
  31271. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31272. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31273. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31274. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31275. return {
  31276. min: min,
  31277. max: max
  31278. };
  31279. } // Precondition of calling this method:
  31280. // The scale extent has been initialized using series data extent via
  31281. // `scale.setExtent` or `scale.unionExtentFromData`;
  31282. function niceScaleExtent(scale, inModel) {
  31283. var model = inModel;
  31284. var extentInfo = getScaleExtent(scale, model);
  31285. var extent = extentInfo.extent;
  31286. var splitNumber = model.get('splitNumber');
  31287. if (scale instanceof LogScale) {
  31288. scale.base = model.get('logBase');
  31289. }
  31290. var scaleType = scale.type;
  31291. var interval = model.get('interval');
  31292. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31293. scale.setExtent(extent[0], extent[1]);
  31294. scale.calcNiceExtent({
  31295. splitNumber: splitNumber,
  31296. fixMin: extentInfo.fixMin,
  31297. fixMax: extentInfo.fixMax,
  31298. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31299. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31300. }); // If some one specified the min, max. And the default calculated interval
  31301. // is not good enough. He can specify the interval. It is often appeared
  31302. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31303. // to be 60.
  31304. // FIXME
  31305. if (interval != null) {
  31306. scale.setInterval && scale.setInterval(interval);
  31307. }
  31308. }
  31309. /**
  31310. * @param axisType Default retrieve from model.type
  31311. */
  31312. function createScaleByModel(model, axisType) {
  31313. axisType = axisType || model.get('type');
  31314. if (axisType) {
  31315. switch (axisType) {
  31316. // Buildin scale
  31317. case 'category':
  31318. return new OrdinalScale({
  31319. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31320. extent: [Infinity, -Infinity]
  31321. });
  31322. case 'time':
  31323. return new TimeScale({
  31324. locale: model.ecModel.getLocaleModel(),
  31325. useUTC: model.ecModel.get('useUTC')
  31326. });
  31327. default:
  31328. // case 'value'/'interval', 'log', or others.
  31329. return new (Scale.getClass(axisType) || IntervalScale)();
  31330. }
  31331. }
  31332. }
  31333. /**
  31334. * Check if the axis cross 0
  31335. */
  31336. function ifAxisCrossZero(axis) {
  31337. var dataExtent = axis.scale.getExtent();
  31338. var min = dataExtent[0];
  31339. var max = dataExtent[1];
  31340. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31341. }
  31342. /**
  31343. * @param axis
  31344. * @return Label formatter function.
  31345. * param: {number} tickValue,
  31346. * param: {number} idx, the index in all ticks.
  31347. * If category axis, this param is not required.
  31348. * return: {string} label string.
  31349. */
  31350. function makeLabelFormatter(axis) {
  31351. var labelFormatter = axis.getLabelModel().get('formatter');
  31352. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31353. if (axis.scale.type === 'time') {
  31354. return function (tpl) {
  31355. return function (tick, idx) {
  31356. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31357. };
  31358. }(labelFormatter);
  31359. } else if (isString(labelFormatter)) {
  31360. return function (tpl) {
  31361. return function (tick) {
  31362. // For category axis, get raw value; for numeric axis,
  31363. // get formatted label like '1,333,444'.
  31364. var label = axis.scale.getLabel(tick);
  31365. var text = tpl.replace('{value}', label != null ? label : '');
  31366. return text;
  31367. };
  31368. }(labelFormatter);
  31369. } else if (isFunction(labelFormatter)) {
  31370. return function (cb) {
  31371. return function (tick, idx) {
  31372. // The original intention of `idx` is "the index of the tick in all ticks".
  31373. // But the previous implementation of category axis do not consider the
  31374. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31375. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31376. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31377. // the definition here for back compatibility.
  31378. if (categoryTickStart != null) {
  31379. idx = tick.value - categoryTickStart;
  31380. }
  31381. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31382. level: tick.level
  31383. } : null);
  31384. };
  31385. }(labelFormatter);
  31386. } else {
  31387. return function (tick) {
  31388. return axis.scale.getLabel(tick);
  31389. };
  31390. }
  31391. }
  31392. function getAxisRawValue(axis, tick) {
  31393. // In category axis with data zoom, tick is not the original
  31394. // index of axis.data. So tick should not be exposed to user
  31395. // in category axis.
  31396. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31397. }
  31398. /**
  31399. * @param axis
  31400. * @return Be null/undefined if no labels.
  31401. */
  31402. function estimateLabelUnionRect(axis) {
  31403. var axisModel = axis.model;
  31404. var scale = axis.scale;
  31405. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31406. return;
  31407. }
  31408. var realNumberScaleTicks;
  31409. var tickCount;
  31410. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31411. if (scale instanceof OrdinalScale) {
  31412. tickCount = scale.count();
  31413. } else {
  31414. realNumberScaleTicks = scale.getTicks();
  31415. tickCount = realNumberScaleTicks.length;
  31416. }
  31417. var axisLabelModel = axis.getLabelModel();
  31418. var labelFormatter = makeLabelFormatter(axis);
  31419. var rect;
  31420. var step = 1; // Simple optimization for large amount of labels
  31421. if (tickCount > 40) {
  31422. step = Math.ceil(tickCount / 40);
  31423. }
  31424. for (var i = 0; i < tickCount; i += step) {
  31425. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31426. value: categoryScaleExtent[0] + i
  31427. };
  31428. var label = labelFormatter(tick, i);
  31429. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31430. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31431. rect ? rect.union(singleRect) : rect = singleRect;
  31432. }
  31433. return rect;
  31434. }
  31435. function rotateTextRect(textRect, rotate) {
  31436. var rotateRadians = rotate * Math.PI / 180;
  31437. var beforeWidth = textRect.width;
  31438. var beforeHeight = textRect.height;
  31439. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31440. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31441. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31442. return rotatedRect;
  31443. }
  31444. /**
  31445. * @param model axisLabelModel or axisTickModel
  31446. * @return {number|String} Can be null|'auto'|number|function
  31447. */
  31448. function getOptionCategoryInterval(model) {
  31449. var interval = model.get('interval');
  31450. return interval == null ? 'auto' : interval;
  31451. }
  31452. /**
  31453. * Set `categoryInterval` as 0 implicitly indicates that
  31454. * show all labels regardless of overlap.
  31455. * @param {Object} axis axisModel.axis
  31456. */
  31457. function shouldShowAllLabels(axis) {
  31458. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31459. }
  31460. function getDataDimensionsOnAxis(data, axisDim) {
  31461. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31462. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31463. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31464. // there has been stacked result dim?
  31465. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31466. // For example, the extent of the original dimension
  31467. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31468. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31469. // because there is no graphic corresponding to [0.1, 0.5].
  31470. // See the case in `test/area-stack.html` `main1`, where area line
  31471. // stack needs `yAxis` not start from 0.
  31472. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31473. });
  31474. return keys(dataDimMap);
  31475. }
  31476. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31477. if (data) {
  31478. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31479. var seriesExtent = data.getApproximateExtent(dim);
  31480. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31481. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31482. });
  31483. }
  31484. }
  31485. /*
  31486. * Licensed to the Apache Software Foundation (ASF) under one
  31487. * or more contributor license agreements. See the NOTICE file
  31488. * distributed with this work for additional information
  31489. * regarding copyright ownership. The ASF licenses this file
  31490. * to you under the Apache License, Version 2.0 (the
  31491. * "License"); you may not use this file except in compliance
  31492. * with the License. You may obtain a copy of the License at
  31493. *
  31494. * http://www.apache.org/licenses/LICENSE-2.0
  31495. *
  31496. * Unless required by applicable law or agreed to in writing,
  31497. * software distributed under the License is distributed on an
  31498. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31499. * KIND, either express or implied. See the License for the
  31500. * specific language governing permissions and limitations
  31501. * under the License.
  31502. */
  31503. /**
  31504. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31505. */
  31506. /*
  31507. * Licensed to the Apache Software Foundation (ASF) under one
  31508. * or more contributor license agreements. See the NOTICE file
  31509. * distributed with this work for additional information
  31510. * regarding copyright ownership. The ASF licenses this file
  31511. * to you under the Apache License, Version 2.0 (the
  31512. * "License"); you may not use this file except in compliance
  31513. * with the License. You may obtain a copy of the License at
  31514. *
  31515. * http://www.apache.org/licenses/LICENSE-2.0
  31516. *
  31517. * Unless required by applicable law or agreed to in writing,
  31518. * software distributed under the License is distributed on an
  31519. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31520. * KIND, either express or implied. See the License for the
  31521. * specific language governing permissions and limitations
  31522. * under the License.
  31523. */
  31524. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31525. var AxisModelCommonMixin =
  31526. /** @class */
  31527. function () {
  31528. function AxisModelCommonMixin() {}
  31529. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31530. var option = this.option;
  31531. return !option.scale;
  31532. };
  31533. /**
  31534. * Should be implemented by each axis model if necessary.
  31535. * @return coordinate system model
  31536. */
  31537. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31538. return;
  31539. };
  31540. return AxisModelCommonMixin;
  31541. }();
  31542. /**
  31543. * Create a multi dimension List structure from seriesModel.
  31544. */
  31545. function createList(seriesModel) {
  31546. return createSeriesData(null, seriesModel);
  31547. } // export function createGraph(seriesModel) {
  31548. var dataStack$1 = {
  31549. isDimensionStacked: isDimensionStacked,
  31550. enableDataStack: enableDataStack,
  31551. getStackedDimension: getStackedDimension
  31552. };
  31553. /**
  31554. * Create scale
  31555. * @param {Array.<number>} dataExtent
  31556. * @param {Object|module:echarts/Model} option If `optoin.type`
  31557. * is secified, it can only be `'value'` currently.
  31558. */
  31559. function createScale(dataExtent, option) {
  31560. var axisModel = option;
  31561. if (!(option instanceof Model)) {
  31562. axisModel = new Model(option); // FIXME
  31563. // Currently AxisModelCommonMixin has nothing to do with the
  31564. // the requirements of `axisHelper.createScaleByModel`. For
  31565. // example the methods `getCategories` and `getOrdinalMeta`
  31566. // are required for `'category'` axis, and ecModel is required
  31567. // for `'time'` axis. But occasionally echarts-gl happened
  31568. // to only use `'value'` axis.
  31569. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31570. }
  31571. var scale = createScaleByModel(axisModel);
  31572. scale.setExtent(dataExtent[0], dataExtent[1]);
  31573. niceScaleExtent(scale, axisModel);
  31574. return scale;
  31575. }
  31576. /**
  31577. * Mixin common methods to axis model,
  31578. *
  31579. * Include methods
  31580. * `getFormattedLabels() => Array.<string>`
  31581. * `getCategories() => Array.<string>`
  31582. * `getMin(origin: boolean) => number`
  31583. * `getMax(origin: boolean) => number`
  31584. * `getNeedCrossZero() => boolean`
  31585. */
  31586. function mixinAxisModelCommonMethods(Model) {
  31587. mixin(Model, AxisModelCommonMixin);
  31588. }
  31589. function createTextStyle$1(textStyleModel, opts) {
  31590. opts = opts || {};
  31591. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31592. }
  31593. var helper = /*#__PURE__*/Object.freeze({
  31594. __proto__: null,
  31595. createList: createList,
  31596. getLayoutRect: getLayoutRect,
  31597. dataStack: dataStack$1,
  31598. createScale: createScale,
  31599. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31600. getECData: getECData,
  31601. createTextStyle: createTextStyle$1,
  31602. createDimensions: createDimensions,
  31603. createSymbol: createSymbol,
  31604. enableHoverEmphasis: enableHoverEmphasis
  31605. });
  31606. var EPSILON$4 = 1e-8;
  31607. function isAroundEqual$1(a, b) {
  31608. return Math.abs(a - b) < EPSILON$4;
  31609. }
  31610. function contain$2(points, x, y) {
  31611. var w = 0;
  31612. var p = points[0];
  31613. if (!p) {
  31614. return false;
  31615. }
  31616. for (var i = 1; i < points.length; i++) {
  31617. var p2 = points[i];
  31618. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31619. p = p2;
  31620. }
  31621. var p0 = points[0];
  31622. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31623. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31624. }
  31625. return w !== 0;
  31626. }
  31627. var TMP_TRANSFORM = [];
  31628. function transformPoints(points, transform) {
  31629. for (var p = 0; p < points.length; p++) {
  31630. applyTransform(points[p], points[p], transform);
  31631. }
  31632. }
  31633. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31634. for (var i = 0; i < points.length; i++) {
  31635. var p = points[i];
  31636. if (projection) {
  31637. // projection may return null point.
  31638. p = projection.project(p);
  31639. }
  31640. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31641. min(min$1, min$1, p);
  31642. max(max$1, max$1, p);
  31643. }
  31644. }
  31645. }
  31646. function centroid(points) {
  31647. var signedArea = 0;
  31648. var cx = 0;
  31649. var cy = 0;
  31650. var len = points.length;
  31651. var x0 = points[len - 1][0];
  31652. var y0 = points[len - 1][1]; // Polygon should been closed.
  31653. for (var i = 0; i < len; i++) {
  31654. var x1 = points[i][0];
  31655. var y1 = points[i][1];
  31656. var a = x0 * y1 - x1 * y0;
  31657. signedArea += a;
  31658. cx += (x0 + x1) * a;
  31659. cy += (y0 + y1) * a;
  31660. x0 = x1;
  31661. y0 = y1;
  31662. }
  31663. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  31664. }
  31665. var Region =
  31666. /** @class */
  31667. function () {
  31668. function Region(name) {
  31669. this.name = name;
  31670. }
  31671. Region.prototype.setCenter = function (center) {
  31672. this._center = center;
  31673. };
  31674. /**
  31675. * Get center point in data unit. That is,
  31676. * for GeoJSONRegion, the unit is lat/lng,
  31677. * for GeoSVGRegion, the unit is SVG local coord.
  31678. */
  31679. Region.prototype.getCenter = function () {
  31680. var center = this._center;
  31681. if (!center) {
  31682. // In most cases there are no need to calculate this center.
  31683. // So calculate only when called.
  31684. center = this._center = this.calcCenter();
  31685. }
  31686. return center;
  31687. };
  31688. return Region;
  31689. }();
  31690. var GeoJSONPolygonGeometry =
  31691. /** @class */
  31692. function () {
  31693. function GeoJSONPolygonGeometry(exterior, interiors) {
  31694. this.type = 'polygon';
  31695. this.exterior = exterior;
  31696. this.interiors = interiors;
  31697. }
  31698. return GeoJSONPolygonGeometry;
  31699. }();
  31700. var GeoJSONLineStringGeometry =
  31701. /** @class */
  31702. function () {
  31703. function GeoJSONLineStringGeometry(points) {
  31704. this.type = 'linestring';
  31705. this.points = points;
  31706. }
  31707. return GeoJSONLineStringGeometry;
  31708. }();
  31709. var GeoJSONRegion =
  31710. /** @class */
  31711. function (_super) {
  31712. __extends(GeoJSONRegion, _super);
  31713. function GeoJSONRegion(name, geometries, cp) {
  31714. var _this = _super.call(this, name) || this;
  31715. _this.type = 'geoJSON';
  31716. _this.geometries = geometries;
  31717. _this._center = cp && [cp[0], cp[1]];
  31718. return _this;
  31719. }
  31720. GeoJSONRegion.prototype.calcCenter = function () {
  31721. var geometries = this.geometries;
  31722. var largestGeo;
  31723. var largestGeoSize = 0;
  31724. for (var i = 0; i < geometries.length; i++) {
  31725. var geo = geometries[i];
  31726. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  31727. // Ignore linestring
  31728. var size = exterior && exterior.length;
  31729. if (size > largestGeoSize) {
  31730. largestGeo = geo;
  31731. largestGeoSize = size;
  31732. }
  31733. }
  31734. if (largestGeo) {
  31735. return centroid(largestGeo.exterior);
  31736. } // from bounding rect by default.
  31737. var rect = this.getBoundingRect();
  31738. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31739. };
  31740. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  31741. var rect = this._rect; // Always recalculate if using projection.
  31742. if (rect && !projection) {
  31743. return rect;
  31744. }
  31745. var min = [Infinity, Infinity];
  31746. var max = [-Infinity, -Infinity];
  31747. var geometries = this.geometries;
  31748. each(geometries, function (geo) {
  31749. if (geo.type === 'polygon') {
  31750. // Doesn't consider hole
  31751. updateBBoxFromPoints(geo.exterior, min, max, projection);
  31752. } else {
  31753. each(geo.points, function (points) {
  31754. updateBBoxFromPoints(points, min, max, projection);
  31755. });
  31756. }
  31757. }); // Normalie invalid bounding.
  31758. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  31759. min[0] = min[1] = max[0] = max[1] = 0;
  31760. }
  31761. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  31762. if (!projection) {
  31763. this._rect = rect;
  31764. }
  31765. return rect;
  31766. };
  31767. GeoJSONRegion.prototype.contain = function (coord) {
  31768. var rect = this.getBoundingRect();
  31769. var geometries = this.geometries;
  31770. if (!rect.contain(coord[0], coord[1])) {
  31771. return false;
  31772. }
  31773. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  31774. var geo = geometries[i]; // Only support polygon.
  31775. if (geo.type !== 'polygon') {
  31776. continue;
  31777. }
  31778. var exterior = geo.exterior;
  31779. var interiors = geo.interiors;
  31780. if (contain$2(exterior, coord[0], coord[1])) {
  31781. // Not in the region if point is in the hole.
  31782. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31783. if (contain$2(interiors[k], coord[0], coord[1])) {
  31784. continue loopGeo;
  31785. }
  31786. }
  31787. return true;
  31788. }
  31789. }
  31790. return false;
  31791. };
  31792. /**
  31793. * Transform the raw coords to target bounding.
  31794. * @param x
  31795. * @param y
  31796. * @param width
  31797. * @param height
  31798. */
  31799. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  31800. var rect = this.getBoundingRect();
  31801. var aspect = rect.width / rect.height;
  31802. if (!width) {
  31803. width = aspect * height;
  31804. } else if (!height) {
  31805. height = width / aspect;
  31806. }
  31807. var target = new BoundingRect(x, y, width, height);
  31808. var transform = rect.calculateTransform(target);
  31809. var geometries = this.geometries;
  31810. for (var i = 0; i < geometries.length; i++) {
  31811. var geo = geometries[i];
  31812. if (geo.type === 'polygon') {
  31813. transformPoints(geo.exterior, transform);
  31814. each(geo.interiors, function (interior) {
  31815. transformPoints(interior, transform);
  31816. });
  31817. } else {
  31818. each(geo.points, function (points) {
  31819. transformPoints(points, transform);
  31820. });
  31821. }
  31822. }
  31823. rect = this._rect;
  31824. rect.copy(target); // Update center
  31825. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31826. };
  31827. GeoJSONRegion.prototype.cloneShallow = function (name) {
  31828. name == null && (name = this.name);
  31829. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  31830. newRegion._rect = this._rect;
  31831. newRegion.transformTo = null; // Simply avoid to be called.
  31832. return newRegion;
  31833. };
  31834. return GeoJSONRegion;
  31835. }(Region);
  31836. var GeoSVGRegion =
  31837. /** @class */
  31838. function (_super) {
  31839. __extends(GeoSVGRegion, _super);
  31840. function GeoSVGRegion(name, elOnlyForCalculate) {
  31841. var _this = _super.call(this, name) || this;
  31842. _this.type = 'geoSVG';
  31843. _this._elOnlyForCalculate = elOnlyForCalculate;
  31844. return _this;
  31845. }
  31846. GeoSVGRegion.prototype.calcCenter = function () {
  31847. var el = this._elOnlyForCalculate;
  31848. var rect = el.getBoundingRect();
  31849. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31850. var mat = identity(TMP_TRANSFORM);
  31851. var target = el;
  31852. while (target && !target.isGeoSVGGraphicRoot) {
  31853. mul$1(mat, target.getLocalTransform(), mat);
  31854. target = target.parent;
  31855. }
  31856. invert(mat, mat);
  31857. applyTransform(center, center, mat);
  31858. return center;
  31859. };
  31860. return GeoSVGRegion;
  31861. }(Region);
  31862. function decode(json) {
  31863. if (!json.UTF8Encoding) {
  31864. return json;
  31865. }
  31866. var jsonCompressed = json;
  31867. var encodeScale = jsonCompressed.UTF8Scale;
  31868. if (encodeScale == null) {
  31869. encodeScale = 1024;
  31870. }
  31871. var features = jsonCompressed.features;
  31872. each(features, function (feature) {
  31873. var geometry = feature.geometry;
  31874. var encodeOffsets = geometry.encodeOffsets;
  31875. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  31876. // In this case this geometry is usually not encoded.
  31877. if (!encodeOffsets) {
  31878. return;
  31879. }
  31880. switch (geometry.type) {
  31881. case 'LineString':
  31882. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  31883. break;
  31884. case 'Polygon':
  31885. decodeRings(coordinates, encodeOffsets, encodeScale);
  31886. break;
  31887. case 'MultiLineString':
  31888. decodeRings(coordinates, encodeOffsets, encodeScale);
  31889. break;
  31890. case 'MultiPolygon':
  31891. each(coordinates, function (rings, idx) {
  31892. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  31893. });
  31894. }
  31895. }); // Has been decoded
  31896. jsonCompressed.UTF8Encoding = false;
  31897. return jsonCompressed;
  31898. }
  31899. function decodeRings(rings, encodeOffsets, encodeScale) {
  31900. for (var c = 0; c < rings.length; c++) {
  31901. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  31902. }
  31903. }
  31904. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  31905. var result = [];
  31906. var prevX = encodeOffsets[0];
  31907. var prevY = encodeOffsets[1];
  31908. for (var i = 0; i < coordinate.length; i += 2) {
  31909. var x = coordinate.charCodeAt(i) - 64;
  31910. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  31911. x = x >> 1 ^ -(x & 1);
  31912. y = y >> 1 ^ -(y & 1); // Delta deocding
  31913. x += prevX;
  31914. y += prevY;
  31915. prevX = x;
  31916. prevY = y; // Dequantize
  31917. result.push([x / encodeScale, y / encodeScale]);
  31918. }
  31919. return result;
  31920. }
  31921. function parseGeoJSON(geoJson, nameProperty) {
  31922. geoJson = decode(geoJson);
  31923. return map(filter(geoJson.features, function (featureObj) {
  31924. // Output of mapshaper may have geometry null
  31925. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  31926. }), function (featureObj) {
  31927. var properties = featureObj.properties;
  31928. var geo = featureObj.geometry;
  31929. var geometries = [];
  31930. switch (geo.type) {
  31931. case 'Polygon':
  31932. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  31933. // First must be exterior, and the rest are all interior(holes).
  31934. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  31935. break;
  31936. case 'MultiPolygon':
  31937. each(geo.coordinates, function (item) {
  31938. if (item[0]) {
  31939. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  31940. }
  31941. });
  31942. break;
  31943. case 'LineString':
  31944. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  31945. break;
  31946. case 'MultiLineString':
  31947. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  31948. }
  31949. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  31950. region.properties = properties;
  31951. return region;
  31952. });
  31953. }
  31954. var number = /*#__PURE__*/Object.freeze({
  31955. __proto__: null,
  31956. linearMap: linearMap,
  31957. round: round,
  31958. asc: asc,
  31959. getPrecision: getPrecision,
  31960. getPrecisionSafe: getPrecisionSafe,
  31961. getPixelPrecision: getPixelPrecision,
  31962. getPercentWithPrecision: getPercentWithPrecision,
  31963. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  31964. remRadian: remRadian,
  31965. isRadianAroundZero: isRadianAroundZero,
  31966. parseDate: parseDate,
  31967. quantity: quantity,
  31968. quantityExponent: quantityExponent,
  31969. nice: nice,
  31970. quantile: quantile,
  31971. reformIntervals: reformIntervals,
  31972. isNumeric: isNumeric,
  31973. numericToNumber: numericToNumber
  31974. });
  31975. var time = /*#__PURE__*/Object.freeze({
  31976. __proto__: null,
  31977. parse: parseDate,
  31978. format: format
  31979. });
  31980. var graphic$1 = /*#__PURE__*/Object.freeze({
  31981. __proto__: null,
  31982. extendShape: extendShape,
  31983. extendPath: extendPath,
  31984. makePath: makePath,
  31985. makeImage: makeImage,
  31986. mergePath: mergePath$1,
  31987. resizePath: resizePath,
  31988. createIcon: createIcon,
  31989. updateProps: updateProps,
  31990. initProps: initProps,
  31991. getTransform: getTransform,
  31992. clipPointsByRect: clipPointsByRect,
  31993. clipRectByRect: clipRectByRect,
  31994. registerShape: registerShape,
  31995. getShapeClass: getShapeClass,
  31996. Group: Group,
  31997. Image: ZRImage,
  31998. Text: ZRText,
  31999. Circle: Circle,
  32000. Ellipse: Ellipse,
  32001. Sector: Sector,
  32002. Ring: Ring,
  32003. Polygon: Polygon,
  32004. Polyline: Polyline,
  32005. Rect: Rect,
  32006. Line: Line,
  32007. BezierCurve: BezierCurve,
  32008. Arc: Arc,
  32009. IncrementalDisplayable: IncrementalDisplayable,
  32010. CompoundPath: CompoundPath,
  32011. LinearGradient: LinearGradient,
  32012. RadialGradient: RadialGradient,
  32013. BoundingRect: BoundingRect
  32014. });
  32015. var format$1 = /*#__PURE__*/Object.freeze({
  32016. __proto__: null,
  32017. addCommas: addCommas,
  32018. toCamelCase: toCamelCase,
  32019. normalizeCssArray: normalizeCssArray$1,
  32020. encodeHTML: encodeHTML,
  32021. formatTpl: formatTpl,
  32022. getTooltipMarker: getTooltipMarker,
  32023. formatTime: formatTime,
  32024. capitalFirst: capitalFirst,
  32025. truncateText: truncateText,
  32026. getTextRect: getTextRect
  32027. });
  32028. var util$1 = /*#__PURE__*/Object.freeze({
  32029. __proto__: null,
  32030. map: map,
  32031. each: each,
  32032. indexOf: indexOf,
  32033. inherits: inherits,
  32034. reduce: reduce,
  32035. filter: filter,
  32036. bind: bind,
  32037. curry: curry,
  32038. isArray: isArray,
  32039. isString: isString,
  32040. isObject: isObject,
  32041. isFunction: isFunction,
  32042. extend: extend,
  32043. defaults: defaults,
  32044. clone: clone,
  32045. merge: merge
  32046. });
  32047. var inner$5 = makeInner();
  32048. function createAxisLabels(axis) {
  32049. // Only ordinal scale support tick interval
  32050. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32051. }
  32052. /**
  32053. * @param {module:echats/coord/Axis} axis
  32054. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32055. * @return {Object} {
  32056. * ticks: Array.<number>
  32057. * tickCategoryInterval: number
  32058. * }
  32059. */
  32060. function createAxisTicks(axis, tickModel) {
  32061. // Only ordinal scale support tick interval
  32062. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32063. ticks: map(axis.scale.getTicks(), function (tick) {
  32064. return tick.value;
  32065. })
  32066. };
  32067. }
  32068. function makeCategoryLabels(axis) {
  32069. var labelModel = axis.getLabelModel();
  32070. var result = makeCategoryLabelsActually(axis, labelModel);
  32071. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32072. labels: [],
  32073. labelCategoryInterval: result.labelCategoryInterval
  32074. } : result;
  32075. }
  32076. function makeCategoryLabelsActually(axis, labelModel) {
  32077. var labelsCache = getListCache(axis, 'labels');
  32078. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32079. var result = listCacheGet(labelsCache, optionLabelInterval);
  32080. if (result) {
  32081. return result;
  32082. }
  32083. var labels;
  32084. var numericLabelInterval;
  32085. if (isFunction(optionLabelInterval)) {
  32086. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32087. } else {
  32088. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32089. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32090. } // Cache to avoid calling interval function repeatedly.
  32091. return listCacheSet(labelsCache, optionLabelInterval, {
  32092. labels: labels,
  32093. labelCategoryInterval: numericLabelInterval
  32094. });
  32095. }
  32096. function makeCategoryTicks(axis, tickModel) {
  32097. var ticksCache = getListCache(axis, 'ticks');
  32098. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32099. var result = listCacheGet(ticksCache, optionTickInterval);
  32100. if (result) {
  32101. return result;
  32102. }
  32103. var ticks;
  32104. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  32105. // we should not return all ticks.
  32106. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32107. ticks = [];
  32108. }
  32109. if (isFunction(optionTickInterval)) {
  32110. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32111. } // Always use label interval by default despite label show. Consider this
  32112. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32113. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32114. else if (optionTickInterval === 'auto') {
  32115. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32116. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32117. ticks = map(labelsResult.labels, function (labelItem) {
  32118. return labelItem.tickValue;
  32119. });
  32120. } else {
  32121. tickCategoryInterval = optionTickInterval;
  32122. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32123. } // Cache to avoid calling interval function repeatedly.
  32124. return listCacheSet(ticksCache, optionTickInterval, {
  32125. ticks: ticks,
  32126. tickCategoryInterval: tickCategoryInterval
  32127. });
  32128. }
  32129. function makeRealNumberLabels(axis) {
  32130. var ticks = axis.scale.getTicks();
  32131. var labelFormatter = makeLabelFormatter(axis);
  32132. return {
  32133. labels: map(ticks, function (tick, idx) {
  32134. return {
  32135. level: tick.level,
  32136. formattedLabel: labelFormatter(tick, idx),
  32137. rawLabel: axis.scale.getLabel(tick),
  32138. tickValue: tick.value
  32139. };
  32140. })
  32141. };
  32142. }
  32143. function getListCache(axis, prop) {
  32144. // Because key can be a function, and cache size always is small, we use array cache.
  32145. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32146. }
  32147. function listCacheGet(cache, key) {
  32148. for (var i = 0; i < cache.length; i++) {
  32149. if (cache[i].key === key) {
  32150. return cache[i].value;
  32151. }
  32152. }
  32153. }
  32154. function listCacheSet(cache, key, value) {
  32155. cache.push({
  32156. key: key,
  32157. value: value
  32158. });
  32159. return value;
  32160. }
  32161. function makeAutoCategoryInterval(axis) {
  32162. var result = inner$5(axis).autoInterval;
  32163. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32164. }
  32165. /**
  32166. * Calculate interval for category axis ticks and labels.
  32167. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32168. * should be implemented in axis.
  32169. */
  32170. function calculateCategoryInterval(axis) {
  32171. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32172. var labelFormatter = makeLabelFormatter(axis);
  32173. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32174. var ordinalScale = axis.scale;
  32175. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  32176. // avoid generating a long array by `getTicks`
  32177. // in large category data case.
  32178. var tickCount = ordinalScale.count();
  32179. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32180. return 0;
  32181. }
  32182. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  32183. if (tickCount > 40) {
  32184. step = Math.max(1, Math.floor(tickCount / 40));
  32185. }
  32186. var tickValue = ordinalExtent[0];
  32187. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32188. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32189. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32190. var maxW = 0;
  32191. var maxH = 0; // Caution: Performance sensitive for large category data.
  32192. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32193. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32194. var width = 0;
  32195. var height = 0; // Not precise, do not consider align and vertical align
  32196. // and each distance from axis line yet.
  32197. var rect = getBoundingRect(labelFormatter({
  32198. value: tickValue
  32199. }), params.font, 'center', 'top'); // Magic number
  32200. width = rect.width * 1.3;
  32201. height = rect.height * 1.3; // Min size, void long loop.
  32202. maxW = Math.max(maxW, width, 7);
  32203. maxH = Math.max(maxH, height, 7);
  32204. }
  32205. var dw = maxW / unitW;
  32206. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  32207. isNaN(dw) && (dw = Infinity);
  32208. isNaN(dh) && (dh = Infinity);
  32209. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32210. var cache = inner$5(axis.model);
  32211. var axisExtent = axis.getExtent();
  32212. var lastAutoInterval = cache.lastAutoInterval;
  32213. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  32214. // otherwise the calculated interval might jitter when the zoom
  32215. // window size is close to the interval-changing size.
  32216. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32217. // The jitter will cause that sometimes the displayed labels are
  32218. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32219. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  32220. // point is not the same when zooming in or zooming out.
  32221. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  32222. // be used. Otherwise some hidden labels might not be shown again.
  32223. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32224. interval = lastAutoInterval;
  32225. } // Only update cache if cache not used, otherwise the
  32226. // changing of interval is too insensitive.
  32227. else {
  32228. cache.lastTickCount = tickCount;
  32229. cache.lastAutoInterval = interval;
  32230. cache.axisExtent0 = axisExtent[0];
  32231. cache.axisExtent1 = axisExtent[1];
  32232. }
  32233. return interval;
  32234. }
  32235. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32236. var labelModel = axis.getLabelModel();
  32237. return {
  32238. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32239. labelRotate: labelModel.get('rotate') || 0,
  32240. font: labelModel.getFont()
  32241. };
  32242. }
  32243. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32244. var labelFormatter = makeLabelFormatter(axis);
  32245. var ordinalScale = axis.scale;
  32246. var ordinalExtent = ordinalScale.getExtent();
  32247. var labelModel = axis.getLabelModel();
  32248. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32249. var step = Math.max((categoryInterval || 0) + 1, 1);
  32250. var startTick = ordinalExtent[0];
  32251. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32252. // while zooming and moving while interval > 0. Otherwise the selection
  32253. // of displayable ticks and symbols probably keep changing.
  32254. // 3 is empirical value.
  32255. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32256. startTick = Math.round(Math.ceil(startTick / step) * step);
  32257. } // (1) Only add min max label here but leave overlap checking
  32258. // to render stage, which also ensure the returned list
  32259. // suitable for splitLine and splitArea rendering.
  32260. // (2) Scales except category always contain min max label so
  32261. // do not need to perform this process.
  32262. var showAllLabel = shouldShowAllLabels(axis);
  32263. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32264. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32265. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32266. addItem(ordinalExtent[0]);
  32267. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32268. var tickValue = startTick;
  32269. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32270. addItem(tickValue);
  32271. }
  32272. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32273. addItem(ordinalExtent[1]);
  32274. }
  32275. function addItem(tickValue) {
  32276. var tickObj = {
  32277. value: tickValue
  32278. };
  32279. result.push(onlyTick ? tickValue : {
  32280. formattedLabel: labelFormatter(tickObj),
  32281. rawLabel: ordinalScale.getLabel(tickObj),
  32282. tickValue: tickValue
  32283. });
  32284. }
  32285. return result;
  32286. }
  32287. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32288. var ordinalScale = axis.scale;
  32289. var labelFormatter = makeLabelFormatter(axis);
  32290. var result = [];
  32291. each(ordinalScale.getTicks(), function (tick) {
  32292. var rawLabel = ordinalScale.getLabel(tick);
  32293. var tickValue = tick.value;
  32294. if (categoryInterval(tick.value, rawLabel)) {
  32295. result.push(onlyTick ? tickValue : {
  32296. formattedLabel: labelFormatter(tick),
  32297. rawLabel: rawLabel,
  32298. tickValue: tickValue
  32299. });
  32300. }
  32301. });
  32302. return result;
  32303. }
  32304. var NORMALIZED_EXTENT = [0, 1];
  32305. /**
  32306. * Base class of Axis.
  32307. */
  32308. var Axis =
  32309. /** @class */
  32310. function () {
  32311. function Axis(dim, scale, extent) {
  32312. this.onBand = false;
  32313. this.inverse = false;
  32314. this.dim = dim;
  32315. this.scale = scale;
  32316. this._extent = extent || [0, 0];
  32317. }
  32318. /**
  32319. * If axis extent contain given coord
  32320. */
  32321. Axis.prototype.contain = function (coord) {
  32322. var extent = this._extent;
  32323. var min = Math.min(extent[0], extent[1]);
  32324. var max = Math.max(extent[0], extent[1]);
  32325. return coord >= min && coord <= max;
  32326. };
  32327. /**
  32328. * If axis extent contain given data
  32329. */
  32330. Axis.prototype.containData = function (data) {
  32331. return this.scale.contain(data);
  32332. };
  32333. /**
  32334. * Get coord extent.
  32335. */
  32336. Axis.prototype.getExtent = function () {
  32337. return this._extent.slice();
  32338. };
  32339. /**
  32340. * Get precision used for formatting
  32341. */
  32342. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32343. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32344. };
  32345. /**
  32346. * Set coord extent
  32347. */
  32348. Axis.prototype.setExtent = function (start, end) {
  32349. var extent = this._extent;
  32350. extent[0] = start;
  32351. extent[1] = end;
  32352. };
  32353. /**
  32354. * Convert data to coord. Data is the rank if it has an ordinal scale
  32355. */
  32356. Axis.prototype.dataToCoord = function (data, clamp) {
  32357. var extent = this._extent;
  32358. var scale = this.scale;
  32359. data = scale.normalize(data);
  32360. if (this.onBand && scale.type === 'ordinal') {
  32361. extent = extent.slice();
  32362. fixExtentWithBands(extent, scale.count());
  32363. }
  32364. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32365. };
  32366. /**
  32367. * Convert coord to data. Data is the rank if it has an ordinal scale
  32368. */
  32369. Axis.prototype.coordToData = function (coord, clamp) {
  32370. var extent = this._extent;
  32371. var scale = this.scale;
  32372. if (this.onBand && scale.type === 'ordinal') {
  32373. extent = extent.slice();
  32374. fixExtentWithBands(extent, scale.count());
  32375. }
  32376. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32377. return this.scale.scale(t);
  32378. };
  32379. /**
  32380. * Convert pixel point to data in axis
  32381. */
  32382. Axis.prototype.pointToData = function (point, clamp) {
  32383. // Should be implemented in derived class if necessary.
  32384. return;
  32385. };
  32386. /**
  32387. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32388. * `axis.getTicksCoords` considers `onBand`, which is used by
  32389. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32390. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32391. * @param opt.clamp If `true`, the first and the last
  32392. * tick must be at the axis end points. Otherwise, clip ticks
  32393. * that outside the axis extent.
  32394. */
  32395. Axis.prototype.getTicksCoords = function (opt) {
  32396. opt = opt || {};
  32397. var tickModel = opt.tickModel || this.getTickModel();
  32398. var result = createAxisTicks(this, tickModel);
  32399. var ticks = result.ticks;
  32400. var ticksCoords = map(ticks, function (tickVal) {
  32401. return {
  32402. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32403. tickValue: tickVal
  32404. };
  32405. }, this);
  32406. var alignWithLabel = tickModel.get('alignWithLabel');
  32407. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32408. return ticksCoords;
  32409. };
  32410. Axis.prototype.getMinorTicksCoords = function () {
  32411. if (this.scale.type === 'ordinal') {
  32412. // Category axis doesn't support minor ticks
  32413. return [];
  32414. }
  32415. var minorTickModel = this.model.getModel('minorTick');
  32416. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32417. if (!(splitNumber > 0 && splitNumber < 100)) {
  32418. splitNumber = 5;
  32419. }
  32420. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32421. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32422. return map(minorTicksGroup, function (minorTick) {
  32423. return {
  32424. coord: this.dataToCoord(minorTick),
  32425. tickValue: minorTick
  32426. };
  32427. }, this);
  32428. }, this);
  32429. return minorTicksCoords;
  32430. };
  32431. Axis.prototype.getViewLabels = function () {
  32432. return createAxisLabels(this).labels;
  32433. };
  32434. Axis.prototype.getLabelModel = function () {
  32435. return this.model.getModel('axisLabel');
  32436. };
  32437. /**
  32438. * Notice here we only get the default tick model. For splitLine
  32439. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32440. * manually when calling `getTicksCoords`.
  32441. * In GL, this method may be overridden to:
  32442. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32443. */
  32444. Axis.prototype.getTickModel = function () {
  32445. return this.model.getModel('axisTick');
  32446. };
  32447. /**
  32448. * Get width of band
  32449. */
  32450. Axis.prototype.getBandWidth = function () {
  32451. var axisExtent = this._extent;
  32452. var dataExtent = this.scale.getExtent();
  32453. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32454. len === 0 && (len = 1);
  32455. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32456. return Math.abs(size) / len;
  32457. };
  32458. /**
  32459. * Only be called in category axis.
  32460. * Can be overridden, consider other axes like in 3D.
  32461. * @return Auto interval for cateogry axis tick and label
  32462. */
  32463. Axis.prototype.calculateCategoryInterval = function () {
  32464. return calculateCategoryInterval(this);
  32465. };
  32466. return Axis;
  32467. }();
  32468. function fixExtentWithBands(extent, nTick) {
  32469. var size = extent[1] - extent[0];
  32470. var len = nTick;
  32471. var margin = size / len / 2;
  32472. extent[0] += margin;
  32473. extent[1] -= margin;
  32474. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32475. // |---1---|---2---|---3---|---4---|.
  32476. // So the displayed ticks and splitLine/splitArea should between
  32477. // each data item, otherwise cause misleading (e.g., split tow bars
  32478. // of a single data item when there are two bar series).
  32479. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32480. // splitLine/spliteArea should layout appropriately corresponding
  32481. // to displayed labels. (So we should not use `getBandWidth` in this
  32482. // case).
  32483. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32484. var ticksLen = ticksCoords.length;
  32485. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32486. return;
  32487. }
  32488. var axisExtent = axis.getExtent();
  32489. var last;
  32490. var diffSize;
  32491. if (ticksLen === 1) {
  32492. ticksCoords[0].coord = axisExtent[0];
  32493. last = ticksCoords[1] = {
  32494. coord: axisExtent[0]
  32495. };
  32496. } else {
  32497. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32498. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32499. each(ticksCoords, function (ticksItem) {
  32500. ticksItem.coord -= shift_1 / 2;
  32501. });
  32502. var dataExtent = axis.scale.getExtent();
  32503. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32504. last = {
  32505. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32506. };
  32507. ticksCoords.push(last);
  32508. }
  32509. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32510. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32511. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32512. }
  32513. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32514. ticksCoords.unshift({
  32515. coord: axisExtent[0]
  32516. });
  32517. }
  32518. if (littleThan(axisExtent[1], last.coord)) {
  32519. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32520. }
  32521. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32522. ticksCoords.push({
  32523. coord: axisExtent[1]
  32524. });
  32525. }
  32526. function littleThan(a, b) {
  32527. // Avoid rounding error cause calculated tick coord different with extent.
  32528. // It may cause an extra unnecessary tick added.
  32529. a = round(a);
  32530. b = round(b);
  32531. return inverse ? a > b : a < b;
  32532. }
  32533. }
  32534. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32535. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32536. // class Bar3DModel extends ComponentModel {}
  32537. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  32538. // echarts.use(install);
  32539. function extendComponentModel(proto) {
  32540. var Model = ComponentModel.extend(proto);
  32541. ComponentModel.registerClass(Model);
  32542. return Model;
  32543. }
  32544. function extendComponentView(proto) {
  32545. var View = ComponentView.extend(proto);
  32546. ComponentView.registerClass(View);
  32547. return View;
  32548. }
  32549. function extendSeriesModel(proto) {
  32550. var Model = SeriesModel.extend(proto);
  32551. SeriesModel.registerClass(Model);
  32552. return Model;
  32553. }
  32554. function extendChartView(proto) {
  32555. var View = ChartView.extend(proto);
  32556. ChartView.registerClass(View);
  32557. return View;
  32558. }
  32559. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32560. var dx = x - x1;
  32561. var dy = y - y1;
  32562. var dx1 = x2 - x1;
  32563. var dy1 = y2 - y1;
  32564. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32565. dx1 /= lineLen;
  32566. dy1 /= lineLen; // dot product
  32567. var projectedLen = dx * dx1 + dy * dy1;
  32568. var t = projectedLen / lineLen;
  32569. if (limitToEnds) {
  32570. t = Math.min(Math.max(t, 0), 1);
  32571. }
  32572. t *= lineLen;
  32573. var ox = out[0] = x1 + t * dx1;
  32574. var oy = out[1] = y1 + t * dy1;
  32575. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32576. }
  32577. var pt0 = new Point();
  32578. var pt1 = new Point();
  32579. var pt2 = new Point();
  32580. var dir = new Point();
  32581. var dir2 = new Point();
  32582. var tmpArr = [];
  32583. var tmpProjPoint = new Point();
  32584. /**
  32585. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  32586. * @param linePoints
  32587. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  32588. */
  32589. function limitTurnAngle(linePoints, minTurnAngle) {
  32590. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  32591. return;
  32592. }
  32593. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  32594. // /pt1----pt2 (label)
  32595. // /
  32596. // pt0/
  32597. pt0.fromArray(linePoints[0]);
  32598. pt1.fromArray(linePoints[1]);
  32599. pt2.fromArray(linePoints[2]);
  32600. Point.sub(dir, pt0, pt1);
  32601. Point.sub(dir2, pt2, pt1);
  32602. var len1 = dir.len();
  32603. var len2 = dir2.len();
  32604. if (len1 < 1e-3 || len2 < 1e-3) {
  32605. return;
  32606. }
  32607. dir.scale(1 / len1);
  32608. dir2.scale(1 / len2);
  32609. var angleCos = dir.dot(dir2);
  32610. var minTurnAngleCos = Math.cos(minTurnAngle);
  32611. if (minTurnAngleCos < angleCos) {
  32612. // Smaller than minTurnAngle
  32613. // Calculate project point of pt0 on pt1-pt2
  32614. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32615. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  32616. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  32617. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32618. if (isNaN(t)) {
  32619. return;
  32620. }
  32621. if (t < 0) {
  32622. Point.copy(tmpProjPoint, pt1);
  32623. } else if (t > 1) {
  32624. Point.copy(tmpProjPoint, pt2);
  32625. }
  32626. tmpProjPoint.toArray(linePoints[1]);
  32627. }
  32628. }
  32629. /**
  32630. * Limit the angle of line and the surface
  32631. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  32632. */
  32633. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  32634. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  32635. return;
  32636. }
  32637. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  32638. pt0.fromArray(linePoints[0]);
  32639. pt1.fromArray(linePoints[1]);
  32640. pt2.fromArray(linePoints[2]);
  32641. Point.sub(dir, pt1, pt0);
  32642. Point.sub(dir2, pt2, pt1);
  32643. var len1 = dir.len();
  32644. var len2 = dir2.len();
  32645. if (len1 < 1e-3 || len2 < 1e-3) {
  32646. return;
  32647. }
  32648. dir.scale(1 / len1);
  32649. dir2.scale(1 / len2);
  32650. var angleCos = dir.dot(surfaceNormal);
  32651. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  32652. if (angleCos < maxSurfaceAngleCos) {
  32653. // Calculate project point of pt0 on pt1-pt2
  32654. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32655. tmpProjPoint.fromArray(tmpArr);
  32656. var HALF_PI = Math.PI / 2;
  32657. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  32658. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  32659. if (newAngle >= HALF_PI) {
  32660. // parallel
  32661. Point.copy(tmpProjPoint, pt2);
  32662. } else {
  32663. // Calculate new projected length with limited minTurnAngle and get the new connect point
  32664. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  32665. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32666. if (isNaN(t)) {
  32667. return;
  32668. }
  32669. if (t < 0) {
  32670. Point.copy(tmpProjPoint, pt1);
  32671. } else if (t > 1) {
  32672. Point.copy(tmpProjPoint, pt2);
  32673. }
  32674. }
  32675. tmpProjPoint.toArray(linePoints[1]);
  32676. }
  32677. }
  32678. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  32679. var isNormal = stateName === 'normal';
  32680. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  32681. stateObj.ignore = ignore; // Set smooth
  32682. var smooth = stateModel.get('smooth');
  32683. if (smooth && smooth === true) {
  32684. smooth = 0.3;
  32685. }
  32686. stateObj.shape = stateObj.shape || {};
  32687. if (smooth > 0) {
  32688. stateObj.shape.smooth = smooth;
  32689. }
  32690. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  32691. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  32692. }
  32693. function buildLabelLinePath(path, shape) {
  32694. var smooth = shape.smooth;
  32695. var points = shape.points;
  32696. if (!points) {
  32697. return;
  32698. }
  32699. path.moveTo(points[0][0], points[0][1]);
  32700. if (smooth > 0 && points.length >= 3) {
  32701. var len1 = dist(points[0], points[1]);
  32702. var len2 = dist(points[1], points[2]);
  32703. if (!len1 || !len2) {
  32704. path.lineTo(points[1][0], points[1][1]);
  32705. path.lineTo(points[2][0], points[2][1]);
  32706. return;
  32707. }
  32708. var moveLen = Math.min(len1, len2) * smooth;
  32709. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  32710. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  32711. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  32712. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  32713. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  32714. } else {
  32715. for (var i = 1; i < points.length; i++) {
  32716. path.lineTo(points[i][0], points[i][1]);
  32717. }
  32718. }
  32719. }
  32720. /**
  32721. * Create a label line if necessary and set it's style.
  32722. */
  32723. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  32724. var labelLine = targetEl.getTextGuideLine();
  32725. var label = targetEl.getTextContent();
  32726. if (!label) {
  32727. // Not show label line if there is no label.
  32728. if (labelLine) {
  32729. targetEl.removeTextGuideLine();
  32730. }
  32731. return;
  32732. }
  32733. var normalModel = statesModels.normal;
  32734. var showNormal = normalModel.get('show');
  32735. var labelIgnoreNormal = label.ignore;
  32736. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  32737. var stateName = DISPLAY_STATES[i];
  32738. var stateModel = statesModels[stateName];
  32739. var isNormal = stateName === 'normal';
  32740. if (stateModel) {
  32741. var stateShow = stateModel.get('show');
  32742. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  32743. if (isLabelIgnored // Not show when label is not shown in this state.
  32744. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  32745. ) {
  32746. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  32747. if (stateObj) {
  32748. stateObj.ignore = true;
  32749. }
  32750. continue;
  32751. } // Create labelLine if not exists
  32752. if (!labelLine) {
  32753. labelLine = new Polyline();
  32754. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  32755. // NOTE: NORMAL should always been the first!
  32756. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  32757. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  32758. } // Use same state proxy.
  32759. if (targetEl.stateProxy) {
  32760. labelLine.stateProxy = targetEl.stateProxy;
  32761. }
  32762. }
  32763. setLabelLineState(labelLine, false, stateName, stateModel);
  32764. }
  32765. }
  32766. if (labelLine) {
  32767. defaults(labelLine.style, defaultStyle); // Not fill.
  32768. labelLine.style.fill = null;
  32769. var showAbove = normalModel.get('showAbove');
  32770. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  32771. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  32772. labelLine.buildPath = buildLabelLinePath;
  32773. }
  32774. }
  32775. function getLabelLineStatesModels(itemModel, labelLineName) {
  32776. labelLineName = labelLineName || 'labelLine';
  32777. var statesModels = {
  32778. normal: itemModel.getModel(labelLineName)
  32779. };
  32780. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  32781. var stateName = SPECIAL_STATES[i];
  32782. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  32783. }
  32784. return statesModels;
  32785. }
  32786. function prepareLayoutList(input) {
  32787. var list = [];
  32788. for (var i = 0; i < input.length; i++) {
  32789. var rawItem = input[i];
  32790. if (rawItem.defaultAttr.ignore) {
  32791. continue;
  32792. }
  32793. var label = rawItem.label;
  32794. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  32795. var localRect = label.getBoundingRect();
  32796. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  32797. var minMargin = label.style.margin || 0;
  32798. var globalRect = localRect.clone();
  32799. globalRect.applyTransform(transform);
  32800. globalRect.x -= minMargin / 2;
  32801. globalRect.y -= minMargin / 2;
  32802. globalRect.width += minMargin;
  32803. globalRect.height += minMargin;
  32804. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  32805. list.push({
  32806. label: label,
  32807. labelLine: rawItem.labelLine,
  32808. rect: globalRect,
  32809. localRect: localRect,
  32810. obb: obb,
  32811. priority: rawItem.priority,
  32812. defaultAttr: rawItem.defaultAttr,
  32813. layoutOption: rawItem.computedLayoutOption,
  32814. axisAligned: isAxisAligned,
  32815. transform: transform
  32816. });
  32817. }
  32818. return list;
  32819. }
  32820. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  32821. var len = list.length;
  32822. if (len < 2) {
  32823. return;
  32824. }
  32825. list.sort(function (a, b) {
  32826. return a.rect[xyDim] - b.rect[xyDim];
  32827. });
  32828. var lastPos = 0;
  32829. var delta;
  32830. var adjusted = false;
  32831. var totalShifts = 0;
  32832. for (var i = 0; i < len; i++) {
  32833. var item = list[i];
  32834. var rect = item.rect;
  32835. delta = rect[xyDim] - lastPos;
  32836. if (delta < 0) {
  32837. // shiftForward(i, len, -delta);
  32838. rect[xyDim] -= delta;
  32839. item.label[xyDim] -= delta;
  32840. adjusted = true;
  32841. }
  32842. var shift = Math.max(-delta, 0);
  32843. totalShifts += shift;
  32844. lastPos = rect[xyDim] + rect[sizeDim];
  32845. }
  32846. if (totalShifts > 0 && balanceShift) {
  32847. // Shift back to make the distribution more equally.
  32848. shiftList(-totalShifts / len, 0, len);
  32849. } // TODO bleedMargin?
  32850. var first = list[0];
  32851. var last = list[len - 1];
  32852. var minGap;
  32853. var maxGap;
  32854. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  32855. minGap < 0 && squeezeGaps(-minGap, 0.8);
  32856. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  32857. updateMinMaxGap();
  32858. takeBoundsGap(minGap, maxGap, 1);
  32859. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  32860. updateMinMaxGap();
  32861. if (minGap < 0) {
  32862. squeezeWhenBailout(-minGap);
  32863. }
  32864. if (maxGap < 0) {
  32865. squeezeWhenBailout(maxGap);
  32866. }
  32867. function updateMinMaxGap() {
  32868. minGap = first.rect[xyDim] - minBound;
  32869. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  32870. }
  32871. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  32872. if (gapThisBound < 0) {
  32873. // Move from other gap if can.
  32874. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  32875. if (moveFromMaxGap > 0) {
  32876. shiftList(moveFromMaxGap * moveDir, 0, len);
  32877. var remained = moveFromMaxGap + gapThisBound;
  32878. if (remained < 0) {
  32879. squeezeGaps(-remained * moveDir, 1);
  32880. }
  32881. } else {
  32882. squeezeGaps(-gapThisBound * moveDir, 1);
  32883. }
  32884. }
  32885. }
  32886. function shiftList(delta, start, end) {
  32887. if (delta !== 0) {
  32888. adjusted = true;
  32889. }
  32890. for (var i = start; i < end; i++) {
  32891. var item = list[i];
  32892. var rect = item.rect;
  32893. rect[xyDim] += delta;
  32894. item.label[xyDim] += delta;
  32895. }
  32896. } // Squeeze gaps if the labels exceed margin.
  32897. function squeezeGaps(delta, maxSqeezePercent) {
  32898. var gaps = [];
  32899. var totalGaps = 0;
  32900. for (var i = 1; i < len; i++) {
  32901. var prevItemRect = list[i - 1].rect;
  32902. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  32903. gaps.push(gap);
  32904. totalGaps += gap;
  32905. }
  32906. if (!totalGaps) {
  32907. return;
  32908. }
  32909. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  32910. if (delta > 0) {
  32911. for (var i = 0; i < len - 1; i++) {
  32912. // Distribute the shift delta to all gaps.
  32913. var movement = gaps[i] * squeezePercent; // Forward
  32914. shiftList(movement, 0, i + 1);
  32915. }
  32916. } else {
  32917. // Backward
  32918. for (var i = len - 1; i > 0; i--) {
  32919. // Distribute the shift delta to all gaps.
  32920. var movement = gaps[i - 1] * squeezePercent;
  32921. shiftList(-movement, i, len);
  32922. }
  32923. }
  32924. }
  32925. /**
  32926. * Squeeze to allow overlap if there is no more space available.
  32927. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  32928. */
  32929. function squeezeWhenBailout(delta) {
  32930. var dir = delta < 0 ? -1 : 1;
  32931. delta = Math.abs(delta);
  32932. var moveForEachLabel = Math.ceil(delta / (len - 1));
  32933. for (var i = 0; i < len - 1; i++) {
  32934. if (dir > 0) {
  32935. // Forward
  32936. shiftList(moveForEachLabel, 0, i + 1);
  32937. } else {
  32938. // Backward
  32939. shiftList(-moveForEachLabel, len - i - 1, len);
  32940. }
  32941. delta -= moveForEachLabel;
  32942. if (delta <= 0) {
  32943. return;
  32944. }
  32945. }
  32946. }
  32947. return adjusted;
  32948. }
  32949. /**
  32950. * Adjust labels on y direction to avoid overlap.
  32951. */
  32952. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  32953. balanceShift) {
  32954. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  32955. }
  32956. function hideOverlap(labelList) {
  32957. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  32958. labelList.sort(function (a, b) {
  32959. return b.priority - a.priority;
  32960. });
  32961. var globalRect = new BoundingRect(0, 0, 0, 0);
  32962. function hideEl(el) {
  32963. if (!el.ignore) {
  32964. // Show on emphasis.
  32965. var emphasisState = el.ensureState('emphasis');
  32966. if (emphasisState.ignore == null) {
  32967. emphasisState.ignore = false;
  32968. }
  32969. }
  32970. el.ignore = true;
  32971. }
  32972. for (var i = 0; i < labelList.length; i++) {
  32973. var labelItem = labelList[i];
  32974. var isAxisAligned = labelItem.axisAligned;
  32975. var localRect = labelItem.localRect;
  32976. var transform = labelItem.transform;
  32977. var label = labelItem.label;
  32978. var labelLine = labelItem.labelLine;
  32979. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  32980. globalRect.width -= 0.1;
  32981. globalRect.height -= 0.1;
  32982. globalRect.x += 0.05;
  32983. globalRect.y += 0.05;
  32984. var obb = labelItem.obb;
  32985. var overlapped = false;
  32986. for (var j = 0; j < displayedLabels.length; j++) {
  32987. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  32988. if (!globalRect.intersect(existsTextCfg.rect)) {
  32989. continue;
  32990. }
  32991. if (isAxisAligned && existsTextCfg.axisAligned) {
  32992. // Is overlapped
  32993. overlapped = true;
  32994. break;
  32995. }
  32996. if (!existsTextCfg.obb) {
  32997. // If self is not axis aligned. But other is.
  32998. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  32999. }
  33000. if (!obb) {
  33001. // If self is axis aligned. But other is not.
  33002. obb = new OrientedBoundingRect(localRect, transform);
  33003. }
  33004. if (obb.intersect(existsTextCfg.obb)) {
  33005. overlapped = true;
  33006. break;
  33007. }
  33008. } // TODO Callback to determine if this overlap should be handled?
  33009. if (overlapped) {
  33010. hideEl(label);
  33011. labelLine && hideEl(labelLine);
  33012. } else {
  33013. label.attr('ignore', labelItem.defaultAttr.ignore);
  33014. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33015. displayedLabels.push(labelItem);
  33016. }
  33017. }
  33018. }
  33019. var mathSin$4 = Math.sin;
  33020. var mathCos$4 = Math.cos;
  33021. var PI$4 = Math.PI;
  33022. var PI2$6 = Math.PI * 2;
  33023. var degree = 180 / PI$4;
  33024. var SVGPathRebuilder = (function () {
  33025. function SVGPathRebuilder() {
  33026. }
  33027. SVGPathRebuilder.prototype.reset = function (precision) {
  33028. this._start = true;
  33029. this._d = [];
  33030. this._str = '';
  33031. this._p = Math.pow(10, precision || 4);
  33032. };
  33033. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  33034. this._add('M', x, y);
  33035. };
  33036. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  33037. this._add('L', x, y);
  33038. };
  33039. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  33040. this._add('C', x, y, x2, y2, x3, y3);
  33041. };
  33042. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  33043. this._add('Q', x, y, x2, y2);
  33044. };
  33045. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  33046. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  33047. };
  33048. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  33049. var dTheta = endAngle - startAngle;
  33050. var clockwise = !anticlockwise;
  33051. var dThetaPositive = Math.abs(dTheta);
  33052. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  33053. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  33054. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  33055. var large = false;
  33056. if (isCircle) {
  33057. large = true;
  33058. }
  33059. else if (isAroundZero$1(dThetaPositive)) {
  33060. large = false;
  33061. }
  33062. else {
  33063. large = (unifiedTheta >= PI$4) === !!clockwise;
  33064. }
  33065. var x0 = cx + rx * mathCos$4(startAngle);
  33066. var y0 = cy + ry * mathSin$4(startAngle);
  33067. if (this._start) {
  33068. this._add('M', x0, y0);
  33069. }
  33070. var xRot = Math.round(psi * degree);
  33071. if (isCircle) {
  33072. var p = 1 / this._p;
  33073. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$6 - p);
  33074. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  33075. if (p > 1e-2) {
  33076. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  33077. }
  33078. }
  33079. else {
  33080. var x = cx + rx * mathCos$4(endAngle);
  33081. var y = cy + ry * mathSin$4(endAngle);
  33082. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  33083. }
  33084. };
  33085. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  33086. this._add('M', x, y);
  33087. this._add('l', w, 0);
  33088. this._add('l', 0, h);
  33089. this._add('l', -w, 0);
  33090. this._add('Z');
  33091. };
  33092. SVGPathRebuilder.prototype.closePath = function () {
  33093. if (this._d.length > 0) {
  33094. this._add('Z');
  33095. }
  33096. };
  33097. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  33098. var vals = [];
  33099. var p = this._p;
  33100. for (var i = 1; i < arguments.length; i++) {
  33101. var val = arguments[i];
  33102. if (isNaN(val)) {
  33103. this._invalid = true;
  33104. return;
  33105. }
  33106. vals.push(Math.round(val * p) / p);
  33107. }
  33108. this._d.push(cmd + vals.join(' '));
  33109. this._start = cmd === 'Z';
  33110. };
  33111. SVGPathRebuilder.prototype.generateStr = function () {
  33112. this._str = this._invalid ? '' : this._d.join('');
  33113. this._d = [];
  33114. };
  33115. SVGPathRebuilder.prototype.getStr = function () {
  33116. return this._str;
  33117. };
  33118. return SVGPathRebuilder;
  33119. }());
  33120. var NONE = 'none';
  33121. var mathRound$1 = Math.round;
  33122. function pathHasFill(style) {
  33123. var fill = style.fill;
  33124. return fill != null && fill !== NONE;
  33125. }
  33126. function pathHasStroke(style) {
  33127. var stroke = style.stroke;
  33128. return stroke != null && stroke !== NONE;
  33129. }
  33130. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  33131. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  33132. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  33133. var opacity = style.opacity == null ? 1 : style.opacity;
  33134. if (el instanceof ZRImage) {
  33135. updateAttr('opacity', opacity);
  33136. return;
  33137. }
  33138. if (pathHasFill(style)) {
  33139. var fill = normalizeColor(style.fill);
  33140. updateAttr('fill', fill.color);
  33141. var fillOpacity = style.fillOpacity != null
  33142. ? style.fillOpacity * fill.opacity * opacity
  33143. : fill.opacity * opacity;
  33144. if (forceUpdate || fillOpacity < 1) {
  33145. updateAttr('fill-opacity', fillOpacity);
  33146. }
  33147. }
  33148. else {
  33149. updateAttr('fill', NONE);
  33150. }
  33151. if (pathHasStroke(style)) {
  33152. var stroke = normalizeColor(style.stroke);
  33153. updateAttr('stroke', stroke.color);
  33154. var strokeScale = style.strokeNoScale
  33155. ? el.getLineScale()
  33156. : 1;
  33157. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  33158. var strokeOpacity = style.strokeOpacity != null
  33159. ? style.strokeOpacity * stroke.opacity * opacity
  33160. : stroke.opacity * opacity;
  33161. var strokeFirst = style.strokeFirst;
  33162. if (forceUpdate || strokeWidth !== 1) {
  33163. updateAttr('stroke-width', strokeWidth);
  33164. }
  33165. if (forceUpdate || strokeFirst) {
  33166. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  33167. }
  33168. if (forceUpdate || strokeOpacity < 1) {
  33169. updateAttr('stroke-opacity', strokeOpacity);
  33170. }
  33171. if (style.lineDash) {
  33172. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  33173. if (lineDash) {
  33174. lineDashOffset = mathRound$1(lineDashOffset || 0);
  33175. updateAttr('stroke-dasharray', lineDash.join(','));
  33176. if (lineDashOffset || forceUpdate) {
  33177. updateAttr('stroke-dashoffset', lineDashOffset);
  33178. }
  33179. }
  33180. }
  33181. else if (forceUpdate) {
  33182. updateAttr('stroke-dasharray', NONE);
  33183. }
  33184. for (var i = 0; i < strokeProps.length; i++) {
  33185. var propName = strokeProps[i];
  33186. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  33187. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  33188. val && updateAttr(svgStrokeProps[i], val);
  33189. }
  33190. }
  33191. }
  33192. else if (forceUpdate) {
  33193. updateAttr('stroke', NONE);
  33194. }
  33195. }
  33196. var SVGNS = 'http://www.w3.org/2000/svg';
  33197. var XLINKNS = 'http://www.w3.org/1999/xlink';
  33198. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  33199. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  33200. function createElement(name) {
  33201. return document.createElementNS(SVGNS, name);
  33202. }
  33203. function createVNode(tag, key, attrs, children, text) {
  33204. return {
  33205. tag: tag,
  33206. attrs: attrs || {},
  33207. children: children,
  33208. text: text,
  33209. key: key
  33210. };
  33211. }
  33212. function createElementOpen(name, attrs) {
  33213. var attrsStr = [];
  33214. if (attrs) {
  33215. for (var key in attrs) {
  33216. var val = attrs[key];
  33217. var part = key;
  33218. if (val === false) {
  33219. continue;
  33220. }
  33221. else if (val !== true && val != null) {
  33222. part += "=\"" + val + "\"";
  33223. }
  33224. attrsStr.push(part);
  33225. }
  33226. }
  33227. return "<" + name + " " + attrsStr.join(' ') + ">";
  33228. }
  33229. function createElementClose(name) {
  33230. return "</" + name + ">";
  33231. }
  33232. function vNodeToString(el, opts) {
  33233. opts = opts || {};
  33234. var S = opts.newline ? '\n' : '';
  33235. function convertElToString(el) {
  33236. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  33237. return createElementOpen(tag, attrs)
  33238. + (tag !== 'style' ? encodeHTML(text) : text || '')
  33239. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  33240. + createElementClose(tag);
  33241. }
  33242. return convertElToString(el);
  33243. }
  33244. function getCssString(selectorNodes, animationNodes, opts) {
  33245. opts = opts || {};
  33246. var S = opts.newline ? '\n' : '';
  33247. var bracketBegin = " {" + S;
  33248. var bracketEnd = S + "}";
  33249. var selectors = map(keys(selectorNodes), function (className) {
  33250. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  33251. return attrName + ":" + selectorNodes[className][attrName] + ";";
  33252. }).join(S) + bracketEnd;
  33253. }).join(S);
  33254. var animations = map(keys(animationNodes), function (animationName) {
  33255. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  33256. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  33257. var val = animationNodes[animationName][percent][attrName];
  33258. if (attrName === 'd') {
  33259. val = "path(\"" + val + "\")";
  33260. }
  33261. return attrName + ":" + val + ";";
  33262. }).join(S) + bracketEnd;
  33263. }).join(S) + bracketEnd;
  33264. }).join(S);
  33265. if (!selectors && !animations) {
  33266. return '';
  33267. }
  33268. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  33269. }
  33270. function createBrushScope(zrId) {
  33271. return {
  33272. zrId: zrId,
  33273. shadowCache: {},
  33274. patternCache: {},
  33275. gradientCache: {},
  33276. clipPathCache: {},
  33277. defs: {},
  33278. cssNodes: {},
  33279. cssAnims: {},
  33280. cssClassIdx: 0,
  33281. cssAnimIdx: 0,
  33282. shadowIdx: 0,
  33283. gradientIdx: 0,
  33284. patternIdx: 0,
  33285. clipPathIdx: 0
  33286. };
  33287. }
  33288. function createSVGVNode(width, height, children, useViewBox) {
  33289. return createVNode('svg', 'root', {
  33290. 'width': width,
  33291. 'height': height,
  33292. 'xmlns': SVGNS,
  33293. 'xmlns:xlink': XLINKNS,
  33294. 'version': '1.1',
  33295. 'baseProfile': 'full',
  33296. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  33297. }, children);
  33298. }
  33299. var EASING_MAP = {
  33300. cubicIn: '0.32,0,0.67,0',
  33301. cubicOut: '0.33,1,0.68,1',
  33302. cubicInOut: '0.65,0,0.35,1',
  33303. quadraticIn: '0.11,0,0.5,0',
  33304. quadraticOut: '0.5,1,0.89,1',
  33305. quadraticInOut: '0.45,0,0.55,1',
  33306. quarticIn: '0.5,0,0.75,0',
  33307. quarticOut: '0.25,1,0.5,1',
  33308. quarticInOut: '0.76,0,0.24,1',
  33309. quinticIn: '0.64,0,0.78,0',
  33310. quinticOut: '0.22,1,0.36,1',
  33311. quinticInOut: '0.83,0,0.17,1',
  33312. sinusoidalIn: '0.12,0,0.39,0',
  33313. sinusoidalOut: '0.61,1,0.88,1',
  33314. sinusoidalInOut: '0.37,0,0.63,1',
  33315. exponentialIn: '0.7,0,0.84,0',
  33316. exponentialOut: '0.16,1,0.3,1',
  33317. exponentialInOut: '0.87,0,0.13,1',
  33318. circularIn: '0.55,0,1,0.45',
  33319. circularOut: '0,0.55,0.45,1',
  33320. circularInOut: '0.85,0,0.15,1'
  33321. };
  33322. var transformOriginKey = 'transform-origin';
  33323. function buildPathString(el, kfShape, path) {
  33324. var shape = extend({}, el.shape);
  33325. extend(shape, kfShape);
  33326. el.buildPath(path, shape);
  33327. var svgPathBuilder = new SVGPathRebuilder();
  33328. svgPathBuilder.reset(getPathPrecision(el));
  33329. path.rebuildPath(svgPathBuilder, 1);
  33330. svgPathBuilder.generateStr();
  33331. return svgPathBuilder.getStr();
  33332. }
  33333. function setTransformOrigin(target, transform) {
  33334. var originX = transform.originX, originY = transform.originY;
  33335. if (originX || originY) {
  33336. target[transformOriginKey] = originX + "px " + originY + "px";
  33337. }
  33338. }
  33339. var ANIMATE_STYLE_MAP = {
  33340. fill: 'fill',
  33341. opacity: 'opacity',
  33342. lineWidth: 'stroke-width',
  33343. lineDashOffset: 'stroke-dashoffset'
  33344. };
  33345. function addAnimation(cssAnim, scope) {
  33346. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  33347. scope.cssAnims[animationName] = cssAnim;
  33348. return animationName;
  33349. }
  33350. function createCompoundPathCSSAnimation(el, attrs, scope) {
  33351. var paths = el.shape.paths;
  33352. var composedAnim = {};
  33353. var cssAnimationCfg;
  33354. var cssAnimationName;
  33355. each(paths, function (path) {
  33356. var subScope = createBrushScope(scope.zrId);
  33357. subScope.animation = true;
  33358. createCSSAnimation(path, {}, subScope, true);
  33359. var cssAnims = subScope.cssAnims;
  33360. var cssNodes = subScope.cssNodes;
  33361. var animNames = keys(cssAnims);
  33362. var len = animNames.length;
  33363. if (!len) {
  33364. return;
  33365. }
  33366. cssAnimationName = animNames[len - 1];
  33367. var lastAnim = cssAnims[cssAnimationName];
  33368. for (var percent in lastAnim) {
  33369. var kf = lastAnim[percent];
  33370. composedAnim[percent] = composedAnim[percent] || { d: '' };
  33371. composedAnim[percent].d += kf.d || '';
  33372. }
  33373. for (var className in cssNodes) {
  33374. var val = cssNodes[className].animation;
  33375. if (val.indexOf(cssAnimationName) >= 0) {
  33376. cssAnimationCfg = val;
  33377. }
  33378. }
  33379. });
  33380. if (!cssAnimationCfg) {
  33381. return;
  33382. }
  33383. attrs.d = false;
  33384. var animationName = addAnimation(composedAnim, scope);
  33385. return cssAnimationCfg.replace(cssAnimationName, animationName);
  33386. }
  33387. function getEasingFunc(easing) {
  33388. return isString(easing)
  33389. ? EASING_MAP[easing]
  33390. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  33391. : createCubicEasingFunc(easing) ? easing : ''
  33392. : '';
  33393. }
  33394. function createCSSAnimation(el, attrs, scope, onlyShape) {
  33395. var animators = el.animators;
  33396. var len = animators.length;
  33397. var cssAnimations = [];
  33398. if (el instanceof CompoundPath) {
  33399. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  33400. if (animationCfg) {
  33401. cssAnimations.push(animationCfg);
  33402. }
  33403. else if (!len) {
  33404. return;
  33405. }
  33406. }
  33407. else if (!len) {
  33408. return;
  33409. }
  33410. var groupAnimators = {};
  33411. for (var i = 0; i < len; i++) {
  33412. var animator = animators[i];
  33413. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  33414. var easing = getEasingFunc(animator.getClip().easing);
  33415. var delay = animator.getDelay();
  33416. if (easing) {
  33417. cfgArr.push(easing);
  33418. }
  33419. else {
  33420. cfgArr.push('linear');
  33421. }
  33422. if (delay) {
  33423. cfgArr.push(delay / 1000 + 's');
  33424. }
  33425. if (animator.getLoop()) {
  33426. cfgArr.push('infinite');
  33427. }
  33428. var cfg = cfgArr.join(' ');
  33429. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  33430. groupAnimators[cfg][1].push(animator);
  33431. }
  33432. function createSingleCSSAnimation(groupAnimator) {
  33433. var animators = groupAnimator[1];
  33434. var len = animators.length;
  33435. var transformKfs = {};
  33436. var shapeKfs = {};
  33437. var finalKfs = {};
  33438. var animationTimingFunctionAttrName = 'animation-timing-function';
  33439. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  33440. var tracks = animator.getTracks();
  33441. var maxTime = animator.getMaxTime();
  33442. for (var k = 0; k < tracks.length; k++) {
  33443. var track = tracks[k];
  33444. if (track.needsAnimate()) {
  33445. var kfs = track.keyframes;
  33446. var attrName = track.propName;
  33447. toCssAttrName && (attrName = toCssAttrName(attrName));
  33448. if (attrName) {
  33449. for (var i = 0; i < kfs.length; i++) {
  33450. var kf = kfs[i];
  33451. var percent = Math.round(kf.time / maxTime * 100) + '%';
  33452. var kfEasing = getEasingFunc(kf.easing);
  33453. var rawValue = kf.rawValue;
  33454. if (isString(rawValue) || isNumber(rawValue)) {
  33455. cssKfs[percent] = cssKfs[percent] || {};
  33456. cssKfs[percent][attrName] = kf.rawValue;
  33457. if (kfEasing) {
  33458. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  33459. }
  33460. }
  33461. }
  33462. }
  33463. }
  33464. }
  33465. }
  33466. for (var i = 0; i < len; i++) {
  33467. var animator = animators[i];
  33468. var targetProp = animator.targetName;
  33469. if (!targetProp) {
  33470. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  33471. }
  33472. else if (targetProp === 'shape') {
  33473. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  33474. }
  33475. }
  33476. for (var percent in transformKfs) {
  33477. var transform = {};
  33478. copyTransform(transform, el);
  33479. extend(transform, transformKfs[percent]);
  33480. var str = getSRTTransformString(transform);
  33481. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  33482. finalKfs[percent] = str ? {
  33483. transform: str
  33484. } : {};
  33485. setTransformOrigin(finalKfs[percent], transform);
  33486. if (timingFunction) {
  33487. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  33488. }
  33489. }
  33490. var path;
  33491. var canAnimateShape = true;
  33492. for (var percent in shapeKfs) {
  33493. finalKfs[percent] = finalKfs[percent] || {};
  33494. var isFirst = !path;
  33495. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  33496. if (isFirst) {
  33497. path = new PathProxy();
  33498. }
  33499. var len_1 = path.len();
  33500. path.reset();
  33501. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  33502. var newLen = path.len();
  33503. if (!isFirst && len_1 !== newLen) {
  33504. canAnimateShape = false;
  33505. break;
  33506. }
  33507. if (timingFunction) {
  33508. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  33509. }
  33510. }
  33511. if (!canAnimateShape) {
  33512. for (var percent in finalKfs) {
  33513. delete finalKfs[percent].d;
  33514. }
  33515. }
  33516. if (!onlyShape) {
  33517. for (var i = 0; i < len; i++) {
  33518. var animator = animators[i];
  33519. var targetProp = animator.targetName;
  33520. if (targetProp === 'style') {
  33521. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  33522. }
  33523. }
  33524. }
  33525. var percents = keys(finalKfs);
  33526. var allTransformOriginSame = true;
  33527. var transformOrigin;
  33528. for (var i = 1; i < percents.length; i++) {
  33529. var p0 = percents[i - 1];
  33530. var p1 = percents[i];
  33531. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  33532. allTransformOriginSame = false;
  33533. break;
  33534. }
  33535. transformOrigin = finalKfs[p0][transformOriginKey];
  33536. }
  33537. if (allTransformOriginSame && transformOrigin) {
  33538. for (var percent in finalKfs) {
  33539. if (finalKfs[percent][transformOriginKey]) {
  33540. delete finalKfs[percent][transformOriginKey];
  33541. }
  33542. }
  33543. attrs[transformOriginKey] = transformOrigin;
  33544. }
  33545. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  33546. var animationName = addAnimation(finalKfs, scope);
  33547. return animationName + " " + groupAnimator[0] + " both";
  33548. }
  33549. }
  33550. for (var key in groupAnimators) {
  33551. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  33552. if (animationCfg) {
  33553. cssAnimations.push(animationCfg);
  33554. }
  33555. }
  33556. if (cssAnimations.length) {
  33557. var className = scope.zrId + '-cls-' + scope.cssClassIdx++;
  33558. scope.cssNodes['.' + className] = {
  33559. animation: cssAnimations.join(',')
  33560. };
  33561. attrs["class"] = className;
  33562. }
  33563. }
  33564. var round$2 = Math.round;
  33565. function isImageLike$1(val) {
  33566. return val && isString(val.src);
  33567. }
  33568. function isCanvasLike(val) {
  33569. return val && isFunction(val.toDataURL);
  33570. }
  33571. function setStyleAttrs(attrs, style, el, scope) {
  33572. mapStyleToAttrs(function (key, val) {
  33573. var isFillStroke = key === 'fill' || key === 'stroke';
  33574. if (isFillStroke && isGradient(val)) {
  33575. setGradient(style, attrs, key, scope);
  33576. }
  33577. else if (isFillStroke && isPattern(val)) {
  33578. setPattern(el, attrs, key, scope);
  33579. }
  33580. else {
  33581. attrs[key] = val;
  33582. }
  33583. }, style, el, false);
  33584. setShadow(el, attrs, scope);
  33585. }
  33586. function noRotateScale(m) {
  33587. return isAroundZero$1(m[0] - 1)
  33588. && isAroundZero$1(m[1])
  33589. && isAroundZero$1(m[2])
  33590. && isAroundZero$1(m[3] - 1);
  33591. }
  33592. function noTranslate(m) {
  33593. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  33594. }
  33595. function setTransform(attrs, m, compress) {
  33596. if (m && !(noTranslate(m) && noRotateScale(m))) {
  33597. var mul = compress ? 10 : 1e4;
  33598. attrs.transform = noRotateScale(m)
  33599. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  33600. }
  33601. }
  33602. function convertPolyShape(shape, attrs, mul) {
  33603. var points = shape.points;
  33604. var strArr = [];
  33605. for (var i = 0; i < points.length; i++) {
  33606. strArr.push(round$2(points[i][0] * mul) / mul);
  33607. strArr.push(round$2(points[i][1] * mul) / mul);
  33608. }
  33609. attrs.points = strArr.join(' ');
  33610. }
  33611. function validatePolyShape(shape) {
  33612. return !shape.smooth;
  33613. }
  33614. function createAttrsConvert(desc) {
  33615. var normalizedDesc = map(desc, function (item) {
  33616. return (typeof item === 'string' ? [item, item] : item);
  33617. });
  33618. return function (shape, attrs, mul) {
  33619. for (var i = 0; i < normalizedDesc.length; i++) {
  33620. var item = normalizedDesc[i];
  33621. var val = shape[item[0]];
  33622. if (val != null) {
  33623. attrs[item[1]] = round$2(val * mul) / mul;
  33624. }
  33625. }
  33626. };
  33627. }
  33628. var builtinShapesDef = {
  33629. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  33630. polyline: [convertPolyShape, validatePolyShape],
  33631. polygon: [convertPolyShape, validatePolyShape]
  33632. };
  33633. function hasShapeAnimation(el) {
  33634. var animators = el.animators;
  33635. for (var i = 0; i < animators.length; i++) {
  33636. if (animators[i].targetName === 'shape') {
  33637. return true;
  33638. }
  33639. }
  33640. return false;
  33641. }
  33642. function brushSVGPath(el, scope) {
  33643. var style = el.style;
  33644. var shape = el.shape;
  33645. var builtinShpDef = builtinShapesDef[el.type];
  33646. var attrs = {};
  33647. var needsAnimate = scope.animation;
  33648. var svgElType = 'path';
  33649. var strokePercent = el.style.strokePercent;
  33650. var precision = (scope.compress && getPathPrecision(el)) || 4;
  33651. if (builtinShpDef
  33652. && !scope.willUpdate
  33653. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  33654. && !(needsAnimate && hasShapeAnimation(el))
  33655. && !(strokePercent < 1)) {
  33656. svgElType = el.type;
  33657. var mul = Math.pow(10, precision);
  33658. builtinShpDef[0](shape, attrs, mul);
  33659. }
  33660. else {
  33661. var needBuildPath = !el.path || el.shapeChanged();
  33662. if (!el.path) {
  33663. el.createPathProxy();
  33664. }
  33665. var path = el.path;
  33666. if (needBuildPath) {
  33667. path.beginPath();
  33668. el.buildPath(path, el.shape);
  33669. el.pathUpdated();
  33670. }
  33671. var pathVersion = path.getVersion();
  33672. var elExt = el;
  33673. var svgPathBuilder = elExt.__svgPathBuilder;
  33674. if (elExt.__svgPathVersion !== pathVersion
  33675. || !svgPathBuilder
  33676. || strokePercent !== elExt.__svgPathStrokePercent) {
  33677. if (!svgPathBuilder) {
  33678. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  33679. }
  33680. svgPathBuilder.reset(precision);
  33681. path.rebuildPath(svgPathBuilder, strokePercent);
  33682. svgPathBuilder.generateStr();
  33683. elExt.__svgPathVersion = pathVersion;
  33684. elExt.__svgPathStrokePercent = strokePercent;
  33685. }
  33686. attrs.d = svgPathBuilder.getStr();
  33687. }
  33688. setTransform(attrs, el.transform);
  33689. setStyleAttrs(attrs, style, el, scope);
  33690. scope.animation && createCSSAnimation(el, attrs, scope);
  33691. return createVNode(svgElType, el.id + '', attrs);
  33692. }
  33693. function brushSVGImage(el, scope) {
  33694. var style = el.style;
  33695. var image = style.image;
  33696. if (image && !isString(image)) {
  33697. if (isImageLike$1(image)) {
  33698. image = image.src;
  33699. }
  33700. else if (isCanvasLike(image)) {
  33701. image = image.toDataURL();
  33702. }
  33703. }
  33704. if (!image) {
  33705. return;
  33706. }
  33707. var x = style.x || 0;
  33708. var y = style.y || 0;
  33709. var dw = style.width;
  33710. var dh = style.height;
  33711. var attrs = {
  33712. href: image,
  33713. width: dw,
  33714. height: dh
  33715. };
  33716. if (x) {
  33717. attrs.x = x;
  33718. }
  33719. if (y) {
  33720. attrs.y = y;
  33721. }
  33722. setTransform(attrs, el.transform);
  33723. setStyleAttrs(attrs, style, el, scope);
  33724. scope.animation && createCSSAnimation(el, attrs, scope);
  33725. return createVNode('image', el.id + '', attrs);
  33726. }
  33727. function brushSVGTSpan(el, scope) {
  33728. var style = el.style;
  33729. var text = style.text;
  33730. text != null && (text += '');
  33731. if (!text || isNaN(style.x) || isNaN(style.y)) {
  33732. return;
  33733. }
  33734. var font = style.font || DEFAULT_FONT;
  33735. var x = style.x || 0;
  33736. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  33737. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  33738. || style.textAlign;
  33739. var attrs = {
  33740. 'dominant-baseline': 'central',
  33741. 'text-anchor': textAlign
  33742. };
  33743. if (hasSeparateFont(style)) {
  33744. var separatedFontStr = '';
  33745. var fontStyle = style.fontStyle;
  33746. var fontSize = parseFontSize(style.fontSize);
  33747. if (!parseFloat(fontSize)) {
  33748. return;
  33749. }
  33750. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  33751. var fontWeight = style.fontWeight;
  33752. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  33753. if (fontStyle && fontStyle !== 'normal') {
  33754. separatedFontStr += "font-style:" + fontStyle + ";";
  33755. }
  33756. if (fontWeight && fontWeight !== 'normal') {
  33757. separatedFontStr += "font-weight:" + fontWeight + ";";
  33758. }
  33759. attrs.style = separatedFontStr;
  33760. }
  33761. else {
  33762. attrs.style = "font: " + font;
  33763. }
  33764. if (text.match(/\s/)) {
  33765. attrs['xml:space'] = 'preserve';
  33766. }
  33767. if (x) {
  33768. attrs.x = x;
  33769. }
  33770. if (y) {
  33771. attrs.y = y;
  33772. }
  33773. setTransform(attrs, el.transform);
  33774. setStyleAttrs(attrs, style, el, scope);
  33775. scope.animation && createCSSAnimation(el, attrs, scope);
  33776. return createVNode('text', el.id + '', attrs, undefined, text);
  33777. }
  33778. function brush$1(el, scope) {
  33779. if (el instanceof Path) {
  33780. return brushSVGPath(el, scope);
  33781. }
  33782. else if (el instanceof ZRImage) {
  33783. return brushSVGImage(el, scope);
  33784. }
  33785. else if (el instanceof TSpan) {
  33786. return brushSVGTSpan(el, scope);
  33787. }
  33788. }
  33789. function setShadow(el, attrs, scope) {
  33790. var style = el.style;
  33791. if (hasShadow(style)) {
  33792. var shadowKey = getShadowKey(el);
  33793. var shadowCache = scope.shadowCache;
  33794. var shadowId = shadowCache[shadowKey];
  33795. if (!shadowId) {
  33796. var globalScale = el.getGlobalScale();
  33797. var scaleX = globalScale[0];
  33798. var scaleY = globalScale[1];
  33799. if (!scaleX || !scaleY) {
  33800. return;
  33801. }
  33802. var offsetX = style.shadowOffsetX || 0;
  33803. var offsetY = style.shadowOffsetY || 0;
  33804. var blur_1 = style.shadowBlur;
  33805. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  33806. var stdDx = blur_1 / 2 / scaleX;
  33807. var stdDy = blur_1 / 2 / scaleY;
  33808. var stdDeviation = stdDx + ' ' + stdDy;
  33809. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  33810. scope.defs[shadowId] = createVNode('filter', shadowId, {
  33811. 'id': shadowId,
  33812. 'x': '-100%',
  33813. 'y': '-100%',
  33814. 'width': '300%',
  33815. 'height': '300%'
  33816. }, [
  33817. createVNode('feDropShadow', '', {
  33818. 'dx': offsetX / scaleX,
  33819. 'dy': offsetY / scaleY,
  33820. 'stdDeviation': stdDeviation,
  33821. 'flood-color': color,
  33822. 'flood-opacity': opacity
  33823. })
  33824. ]);
  33825. shadowCache[shadowKey] = shadowId;
  33826. }
  33827. attrs.filter = getIdURL(shadowId);
  33828. }
  33829. }
  33830. function setGradient(style, attrs, target, scope) {
  33831. var val = style[target];
  33832. var gradientTag;
  33833. var gradientAttrs = {
  33834. 'gradientUnits': val.global
  33835. ? 'userSpaceOnUse'
  33836. : 'objectBoundingBox'
  33837. };
  33838. if (isLinearGradient(val)) {
  33839. gradientTag = 'linearGradient';
  33840. gradientAttrs.x1 = val.x;
  33841. gradientAttrs.y1 = val.y;
  33842. gradientAttrs.x2 = val.x2;
  33843. gradientAttrs.y2 = val.y2;
  33844. }
  33845. else if (isRadialGradient(val)) {
  33846. gradientTag = 'radialGradient';
  33847. gradientAttrs.cx = retrieve2(val.x, 0.5);
  33848. gradientAttrs.cy = retrieve2(val.y, 0.5);
  33849. gradientAttrs.r = retrieve2(val.r, 0.5);
  33850. }
  33851. else {
  33852. if ("development" !== 'production') {
  33853. logError('Illegal gradient type.');
  33854. }
  33855. return;
  33856. }
  33857. var colors = val.colorStops;
  33858. var colorStops = [];
  33859. for (var i = 0, len = colors.length; i < len; ++i) {
  33860. var offset = round4(colors[i].offset) * 100 + '%';
  33861. var stopColor = colors[i].color;
  33862. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  33863. var stopsAttrs = {
  33864. 'offset': offset
  33865. };
  33866. stopsAttrs['stop-color'] = color;
  33867. if (opacity < 1) {
  33868. stopsAttrs['stop-opacity'] = opacity;
  33869. }
  33870. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  33871. }
  33872. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  33873. var gradientKey = vNodeToString(gradientVNode);
  33874. var gradientCache = scope.gradientCache;
  33875. var gradientId = gradientCache[gradientKey];
  33876. if (!gradientId) {
  33877. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  33878. gradientCache[gradientKey] = gradientId;
  33879. gradientAttrs.id = gradientId;
  33880. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  33881. }
  33882. attrs[target] = getIdURL(gradientId);
  33883. }
  33884. function setPattern(el, attrs, target, scope) {
  33885. var val = el.style[target];
  33886. var boundingRect = el.getBoundingRect();
  33887. var patternAttrs = {};
  33888. var repeat = val.repeat;
  33889. var noRepeat = repeat === 'no-repeat';
  33890. var repeatX = repeat === 'repeat-x';
  33891. var repeatY = repeat === 'repeat-y';
  33892. var child;
  33893. if (isImagePattern(val)) {
  33894. var imageWidth_1 = val.imageWidth;
  33895. var imageHeight_1 = val.imageHeight;
  33896. var imageSrc = void 0;
  33897. var patternImage = val.image;
  33898. if (isString(patternImage)) {
  33899. imageSrc = patternImage;
  33900. }
  33901. else if (isImageLike$1(patternImage)) {
  33902. imageSrc = patternImage.src;
  33903. }
  33904. else if (isCanvasLike(patternImage)) {
  33905. imageSrc = patternImage.toDataURL();
  33906. }
  33907. if (typeof Image === 'undefined') {
  33908. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  33909. assert(imageWidth_1, errMsg);
  33910. assert(imageHeight_1, errMsg);
  33911. }
  33912. else if (imageWidth_1 == null || imageHeight_1 == null) {
  33913. var setSizeToVNode_1 = function (vNode, img) {
  33914. if (vNode) {
  33915. var svgEl = vNode.elm;
  33916. var width = imageWidth_1 || img.width;
  33917. var height = imageHeight_1 || img.height;
  33918. if (vNode.tag === 'pattern') {
  33919. if (repeatX) {
  33920. height = 1;
  33921. width /= boundingRect.width;
  33922. }
  33923. else if (repeatY) {
  33924. width = 1;
  33925. height /= boundingRect.height;
  33926. }
  33927. }
  33928. vNode.attrs.width = width;
  33929. vNode.attrs.height = height;
  33930. if (svgEl) {
  33931. svgEl.setAttribute('width', width);
  33932. svgEl.setAttribute('height', height);
  33933. }
  33934. }
  33935. };
  33936. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  33937. noRepeat || setSizeToVNode_1(patternVNode, img);
  33938. setSizeToVNode_1(child, img);
  33939. });
  33940. if (createdImage && createdImage.width && createdImage.height) {
  33941. imageWidth_1 = imageWidth_1 || createdImage.width;
  33942. imageHeight_1 = imageHeight_1 || createdImage.height;
  33943. }
  33944. }
  33945. child = createVNode('image', 'img', {
  33946. href: imageSrc,
  33947. width: imageWidth_1,
  33948. height: imageHeight_1
  33949. });
  33950. patternAttrs.width = imageWidth_1;
  33951. patternAttrs.height = imageHeight_1;
  33952. }
  33953. else if (val.svgElement) {
  33954. child = clone(val.svgElement);
  33955. patternAttrs.width = val.svgWidth;
  33956. patternAttrs.height = val.svgHeight;
  33957. }
  33958. if (!child) {
  33959. return;
  33960. }
  33961. var patternWidth;
  33962. var patternHeight;
  33963. if (noRepeat) {
  33964. patternWidth = patternHeight = 1;
  33965. }
  33966. else if (repeatX) {
  33967. patternHeight = 1;
  33968. patternWidth = patternAttrs.width / boundingRect.width;
  33969. }
  33970. else if (repeatY) {
  33971. patternWidth = 1;
  33972. patternHeight = patternAttrs.height / boundingRect.height;
  33973. }
  33974. else {
  33975. patternAttrs.patternUnits = 'userSpaceOnUse';
  33976. }
  33977. if (patternWidth != null && !isNaN(patternWidth)) {
  33978. patternAttrs.width = patternWidth;
  33979. }
  33980. if (patternHeight != null && !isNaN(patternHeight)) {
  33981. patternAttrs.height = patternHeight;
  33982. }
  33983. var patternTransform = getSRTTransformString(val);
  33984. patternTransform && (patternAttrs.patternTransform = patternTransform);
  33985. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  33986. var patternKey = vNodeToString(patternVNode);
  33987. var patternCache = scope.patternCache;
  33988. var patternId = patternCache[patternKey];
  33989. if (!patternId) {
  33990. patternId = scope.zrId + '-p' + scope.patternIdx++;
  33991. patternCache[patternKey] = patternId;
  33992. patternAttrs.id = patternId;
  33993. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  33994. }
  33995. attrs[target] = getIdURL(patternId);
  33996. }
  33997. function setClipPath(clipPath, attrs, scope) {
  33998. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  33999. var clipPathId = clipPathCache[clipPath.id];
  34000. if (!clipPathId) {
  34001. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  34002. var clipPathAttrs = {
  34003. id: clipPathId
  34004. };
  34005. clipPathCache[clipPath.id] = clipPathId;
  34006. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  34007. }
  34008. attrs['clip-path'] = getIdURL(clipPathId);
  34009. }
  34010. function createTextNode(text) {
  34011. return document.createTextNode(text);
  34012. }
  34013. function insertBefore(parentNode, newNode, referenceNode) {
  34014. parentNode.insertBefore(newNode, referenceNode);
  34015. }
  34016. function removeChild(node, child) {
  34017. node.removeChild(child);
  34018. }
  34019. function appendChild(node, child) {
  34020. node.appendChild(child);
  34021. }
  34022. function parentNode(node) {
  34023. return node.parentNode;
  34024. }
  34025. function nextSibling(node) {
  34026. return node.nextSibling;
  34027. }
  34028. function setTextContent(node, text) {
  34029. node.textContent = text;
  34030. }
  34031. var colonChar = 58;
  34032. var xChar = 120;
  34033. var emptyNode = createVNode('', '');
  34034. function isUndef(s) {
  34035. return s === undefined;
  34036. }
  34037. function isDef(s) {
  34038. return s !== undefined;
  34039. }
  34040. function createKeyToOldIdx(children, beginIdx, endIdx) {
  34041. var map = {};
  34042. for (var i = beginIdx; i <= endIdx; ++i) {
  34043. var key = children[i].key;
  34044. if (key !== undefined) {
  34045. if ("development" !== 'production') {
  34046. if (map[key] != null) {
  34047. console.error("Duplicate key " + key);
  34048. }
  34049. }
  34050. map[key] = i;
  34051. }
  34052. }
  34053. return map;
  34054. }
  34055. function sameVnode(vnode1, vnode2) {
  34056. var isSameKey = vnode1.key === vnode2.key;
  34057. var isSameTag = vnode1.tag === vnode2.tag;
  34058. return isSameTag && isSameKey;
  34059. }
  34060. function createElm(vnode) {
  34061. var i;
  34062. var children = vnode.children;
  34063. var tag = vnode.tag;
  34064. if (isDef(tag)) {
  34065. var elm = (vnode.elm = createElement(tag));
  34066. updateAttrs(emptyNode, vnode);
  34067. if (isArray(children)) {
  34068. for (i = 0; i < children.length; ++i) {
  34069. var ch = children[i];
  34070. if (ch != null) {
  34071. appendChild(elm, createElm(ch));
  34072. }
  34073. }
  34074. }
  34075. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  34076. appendChild(elm, createTextNode(vnode.text));
  34077. }
  34078. }
  34079. else {
  34080. vnode.elm = createTextNode(vnode.text);
  34081. }
  34082. return vnode.elm;
  34083. }
  34084. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  34085. for (; startIdx <= endIdx; ++startIdx) {
  34086. var ch = vnodes[startIdx];
  34087. if (ch != null) {
  34088. insertBefore(parentElm, createElm(ch), before);
  34089. }
  34090. }
  34091. }
  34092. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  34093. for (; startIdx <= endIdx; ++startIdx) {
  34094. var ch = vnodes[startIdx];
  34095. if (ch != null) {
  34096. if (isDef(ch.tag)) {
  34097. var parent_1 = parentNode(ch.elm);
  34098. removeChild(parent_1, ch.elm);
  34099. }
  34100. else {
  34101. removeChild(parentElm, ch.elm);
  34102. }
  34103. }
  34104. }
  34105. }
  34106. function updateAttrs(oldVnode, vnode) {
  34107. var key;
  34108. var elm = vnode.elm;
  34109. var oldAttrs = oldVnode && oldVnode.attrs || {};
  34110. var attrs = vnode.attrs || {};
  34111. if (oldAttrs === attrs) {
  34112. return;
  34113. }
  34114. for (key in attrs) {
  34115. var cur = attrs[key];
  34116. var old = oldAttrs[key];
  34117. if (old !== cur) {
  34118. if (cur === true) {
  34119. elm.setAttribute(key, '');
  34120. }
  34121. else if (cur === false) {
  34122. elm.removeAttribute(key);
  34123. }
  34124. else {
  34125. if (key.charCodeAt(0) !== xChar) {
  34126. elm.setAttribute(key, cur);
  34127. }
  34128. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  34129. elm.setAttributeNS(XMLNS, key, cur);
  34130. }
  34131. else if (key.charCodeAt(3) === colonChar) {
  34132. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  34133. }
  34134. else if (key.charCodeAt(5) === colonChar) {
  34135. elm.setAttributeNS(XLINKNS, key, cur);
  34136. }
  34137. else {
  34138. elm.setAttribute(key, cur);
  34139. }
  34140. }
  34141. }
  34142. }
  34143. for (key in oldAttrs) {
  34144. if (!(key in attrs)) {
  34145. elm.removeAttribute(key);
  34146. }
  34147. }
  34148. }
  34149. function updateChildren(parentElm, oldCh, newCh) {
  34150. var oldStartIdx = 0;
  34151. var newStartIdx = 0;
  34152. var oldEndIdx = oldCh.length - 1;
  34153. var oldStartVnode = oldCh[0];
  34154. var oldEndVnode = oldCh[oldEndIdx];
  34155. var newEndIdx = newCh.length - 1;
  34156. var newStartVnode = newCh[0];
  34157. var newEndVnode = newCh[newEndIdx];
  34158. var oldKeyToIdx;
  34159. var idxInOld;
  34160. var elmToMove;
  34161. var before;
  34162. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  34163. if (oldStartVnode == null) {
  34164. oldStartVnode = oldCh[++oldStartIdx];
  34165. }
  34166. else if (oldEndVnode == null) {
  34167. oldEndVnode = oldCh[--oldEndIdx];
  34168. }
  34169. else if (newStartVnode == null) {
  34170. newStartVnode = newCh[++newStartIdx];
  34171. }
  34172. else if (newEndVnode == null) {
  34173. newEndVnode = newCh[--newEndIdx];
  34174. }
  34175. else if (sameVnode(oldStartVnode, newStartVnode)) {
  34176. patchVnode(oldStartVnode, newStartVnode);
  34177. oldStartVnode = oldCh[++oldStartIdx];
  34178. newStartVnode = newCh[++newStartIdx];
  34179. }
  34180. else if (sameVnode(oldEndVnode, newEndVnode)) {
  34181. patchVnode(oldEndVnode, newEndVnode);
  34182. oldEndVnode = oldCh[--oldEndIdx];
  34183. newEndVnode = newCh[--newEndIdx];
  34184. }
  34185. else if (sameVnode(oldStartVnode, newEndVnode)) {
  34186. patchVnode(oldStartVnode, newEndVnode);
  34187. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  34188. oldStartVnode = oldCh[++oldStartIdx];
  34189. newEndVnode = newCh[--newEndIdx];
  34190. }
  34191. else if (sameVnode(oldEndVnode, newStartVnode)) {
  34192. patchVnode(oldEndVnode, newStartVnode);
  34193. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  34194. oldEndVnode = oldCh[--oldEndIdx];
  34195. newStartVnode = newCh[++newStartIdx];
  34196. }
  34197. else {
  34198. if (isUndef(oldKeyToIdx)) {
  34199. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  34200. }
  34201. idxInOld = oldKeyToIdx[newStartVnode.key];
  34202. if (isUndef(idxInOld)) {
  34203. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  34204. }
  34205. else {
  34206. elmToMove = oldCh[idxInOld];
  34207. if (elmToMove.tag !== newStartVnode.tag) {
  34208. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  34209. }
  34210. else {
  34211. patchVnode(elmToMove, newStartVnode);
  34212. oldCh[idxInOld] = undefined;
  34213. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  34214. }
  34215. }
  34216. newStartVnode = newCh[++newStartIdx];
  34217. }
  34218. }
  34219. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  34220. if (oldStartIdx > oldEndIdx) {
  34221. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  34222. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  34223. }
  34224. else {
  34225. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  34226. }
  34227. }
  34228. }
  34229. function patchVnode(oldVnode, vnode) {
  34230. var elm = (vnode.elm = oldVnode.elm);
  34231. var oldCh = oldVnode.children;
  34232. var ch = vnode.children;
  34233. if (oldVnode === vnode) {
  34234. return;
  34235. }
  34236. updateAttrs(oldVnode, vnode);
  34237. if (isUndef(vnode.text)) {
  34238. if (isDef(oldCh) && isDef(ch)) {
  34239. if (oldCh !== ch) {
  34240. updateChildren(elm, oldCh, ch);
  34241. }
  34242. }
  34243. else if (isDef(ch)) {
  34244. if (isDef(oldVnode.text)) {
  34245. setTextContent(elm, '');
  34246. }
  34247. addVnodes(elm, null, ch, 0, ch.length - 1);
  34248. }
  34249. else if (isDef(oldCh)) {
  34250. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  34251. }
  34252. else if (isDef(oldVnode.text)) {
  34253. setTextContent(elm, '');
  34254. }
  34255. }
  34256. else if (oldVnode.text !== vnode.text) {
  34257. if (isDef(oldCh)) {
  34258. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  34259. }
  34260. setTextContent(elm, vnode.text);
  34261. }
  34262. }
  34263. function patch(oldVnode, vnode) {
  34264. if (sameVnode(oldVnode, vnode)) {
  34265. patchVnode(oldVnode, vnode);
  34266. }
  34267. else {
  34268. var elm = oldVnode.elm;
  34269. var parent_2 = parentNode(elm);
  34270. createElm(vnode);
  34271. if (parent_2 !== null) {
  34272. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  34273. removeVnodes(parent_2, [oldVnode], 0, 0);
  34274. }
  34275. }
  34276. return vnode;
  34277. }
  34278. var svgId = 0;
  34279. var SVGPainter = (function () {
  34280. function SVGPainter(root, storage, opts) {
  34281. this.type = 'svg';
  34282. this.refreshHover = createMethodNotSupport('refreshHover');
  34283. this.configLayer = createMethodNotSupport('configLayer');
  34284. this.storage = storage;
  34285. this._opts = opts = extend({}, opts);
  34286. this.root = root;
  34287. this._id = 'zr' + svgId++;
  34288. this._oldVNode = createSVGVNode(opts.width, opts.height);
  34289. if (root && !opts.ssr) {
  34290. var viewport = this._viewport = document.createElement('div');
  34291. viewport.style.cssText = 'position:relative;overflow:hidden';
  34292. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  34293. updateAttrs(null, this._oldVNode);
  34294. viewport.appendChild(svgDom);
  34295. root.appendChild(viewport);
  34296. }
  34297. this.resize(opts.width, opts.height);
  34298. }
  34299. SVGPainter.prototype.getType = function () {
  34300. return this.type;
  34301. };
  34302. SVGPainter.prototype.getViewportRoot = function () {
  34303. return this._viewport;
  34304. };
  34305. SVGPainter.prototype.getViewportRootOffset = function () {
  34306. var viewportRoot = this.getViewportRoot();
  34307. if (viewportRoot) {
  34308. return {
  34309. offsetLeft: viewportRoot.offsetLeft || 0,
  34310. offsetTop: viewportRoot.offsetTop || 0
  34311. };
  34312. }
  34313. };
  34314. SVGPainter.prototype.getSvgDom = function () {
  34315. return this._svgDom;
  34316. };
  34317. SVGPainter.prototype.refresh = function () {
  34318. if (this.root) {
  34319. var vnode = this.renderToVNode({
  34320. willUpdate: true
  34321. });
  34322. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  34323. patch(this._oldVNode, vnode);
  34324. this._oldVNode = vnode;
  34325. }
  34326. };
  34327. SVGPainter.prototype.renderOneToVNode = function (el) {
  34328. return brush$1(el, createBrushScope(this._id));
  34329. };
  34330. SVGPainter.prototype.renderToVNode = function (opts) {
  34331. opts = opts || {};
  34332. var list = this.storage.getDisplayList(true);
  34333. var width = this._width;
  34334. var height = this._height;
  34335. var scope = createBrushScope(this._id);
  34336. scope.animation = opts.animation;
  34337. scope.willUpdate = opts.willUpdate;
  34338. scope.compress = opts.compress;
  34339. var children = [];
  34340. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  34341. bgVNode && children.push(bgVNode);
  34342. var mainVNode = !opts.compress
  34343. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  34344. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  34345. mainVNode && children.push(mainVNode);
  34346. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  34347. if (defs.length) {
  34348. children.push(createVNode('defs', 'defs', {}, defs));
  34349. }
  34350. if (opts.animation) {
  34351. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  34352. if (animationCssStr) {
  34353. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  34354. children.push(styleNode);
  34355. }
  34356. }
  34357. return createSVGVNode(width, height, children, opts.useViewBox);
  34358. };
  34359. SVGPainter.prototype.renderToString = function (opts) {
  34360. opts = opts || {};
  34361. return vNodeToString(this.renderToVNode({
  34362. animation: retrieve2(opts.cssAnimation, true),
  34363. willUpdate: false,
  34364. compress: true,
  34365. useViewBox: retrieve2(opts.useViewBox, true)
  34366. }), { newline: true });
  34367. };
  34368. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  34369. this._backgroundColor = backgroundColor;
  34370. };
  34371. SVGPainter.prototype.getSvgRoot = function () {
  34372. return this._mainVNode && this._mainVNode.elm;
  34373. };
  34374. SVGPainter.prototype._paintList = function (list, scope, out) {
  34375. var listLen = list.length;
  34376. var clipPathsGroupsStack = [];
  34377. var clipPathsGroupsStackDepth = 0;
  34378. var currentClipPathGroup;
  34379. var prevClipPaths;
  34380. var clipGroupNodeIdx = 0;
  34381. for (var i = 0; i < listLen; i++) {
  34382. var displayable = list[i];
  34383. if (!displayable.invisible) {
  34384. var clipPaths = displayable.__clipPaths;
  34385. var len = clipPaths && clipPaths.length || 0;
  34386. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  34387. var lca = void 0;
  34388. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  34389. if (clipPaths && prevClipPaths
  34390. && clipPaths[lca] === prevClipPaths[lca]) {
  34391. break;
  34392. }
  34393. }
  34394. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  34395. clipPathsGroupsStackDepth--;
  34396. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  34397. }
  34398. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  34399. var groupAttrs = {};
  34400. setClipPath(clipPaths[i_2], groupAttrs, scope);
  34401. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  34402. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  34403. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  34404. currentClipPathGroup = g;
  34405. }
  34406. prevClipPaths = clipPaths;
  34407. var ret = brush$1(displayable, scope);
  34408. if (ret) {
  34409. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  34410. }
  34411. }
  34412. }
  34413. };
  34414. SVGPainter.prototype.resize = function (width, height) {
  34415. var opts = this._opts;
  34416. var root = this.root;
  34417. var viewport = this._viewport;
  34418. width != null && (opts.width = width);
  34419. height != null && (opts.height = height);
  34420. if (root && viewport) {
  34421. viewport.style.display = 'none';
  34422. width = getSize(root, 0, opts);
  34423. height = getSize(root, 1, opts);
  34424. viewport.style.display = '';
  34425. }
  34426. if (this._width !== width || this._height !== height) {
  34427. this._width = width;
  34428. this._height = height;
  34429. if (viewport) {
  34430. var viewportStyle = viewport.style;
  34431. viewportStyle.width = width + 'px';
  34432. viewportStyle.height = height + 'px';
  34433. }
  34434. if (!isPattern(this._backgroundColor)) {
  34435. var svgDom = this._svgDom;
  34436. if (svgDom) {
  34437. svgDom.setAttribute('width', width);
  34438. svgDom.setAttribute('height', height);
  34439. }
  34440. var bgEl = this._bgVNode && this._bgVNode.elm;
  34441. if (bgEl) {
  34442. bgEl.setAttribute('width', width);
  34443. bgEl.setAttribute('height', height);
  34444. }
  34445. }
  34446. else {
  34447. this.refresh();
  34448. }
  34449. }
  34450. };
  34451. SVGPainter.prototype.getWidth = function () {
  34452. return this._width;
  34453. };
  34454. SVGPainter.prototype.getHeight = function () {
  34455. return this._height;
  34456. };
  34457. SVGPainter.prototype.dispose = function () {
  34458. if (this.root) {
  34459. this.root.innerHTML = '';
  34460. }
  34461. this._svgDom =
  34462. this._viewport =
  34463. this.storage =
  34464. this._oldVNode =
  34465. this._bgVNode =
  34466. this._mainVNode = null;
  34467. };
  34468. SVGPainter.prototype.clear = function () {
  34469. if (this._svgDom) {
  34470. this._svgDom.innerHTML = null;
  34471. }
  34472. this._oldVNode = null;
  34473. };
  34474. SVGPainter.prototype.toDataURL = function (base64) {
  34475. var str = this.renderToString();
  34476. var prefix = 'data:image/svg+xml;';
  34477. if (base64) {
  34478. str = encodeBase64(str);
  34479. return str && prefix + 'base64,' + str;
  34480. }
  34481. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  34482. };
  34483. return SVGPainter;
  34484. }());
  34485. function createMethodNotSupport(method) {
  34486. return function () {
  34487. if ("development" !== 'production') {
  34488. logError('In SVG mode painter not support method "' + method + '"');
  34489. }
  34490. };
  34491. }
  34492. function createBackgroundVNode(width, height, backgroundColor, scope) {
  34493. var bgVNode;
  34494. if (backgroundColor && backgroundColor !== 'none') {
  34495. bgVNode = createVNode('rect', 'bg', {
  34496. width: width,
  34497. height: height,
  34498. x: '0',
  34499. y: '0',
  34500. id: '0'
  34501. });
  34502. if (isGradient(backgroundColor)) {
  34503. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  34504. }
  34505. else if (isPattern(backgroundColor)) {
  34506. setPattern({
  34507. style: {
  34508. fill: backgroundColor
  34509. },
  34510. dirty: noop,
  34511. getBoundingRect: function () { return ({ width: width, height: height }); }
  34512. }, bgVNode.attrs, 'fill', scope);
  34513. }
  34514. else {
  34515. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  34516. bgVNode.attrs.fill = color;
  34517. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  34518. }
  34519. }
  34520. return bgVNode;
  34521. }
  34522. function install(registers) {
  34523. registers.registerPainter('svg', SVGPainter);
  34524. }
  34525. function createDom(id, painter, dpr) {
  34526. var newDom = platformApi.createCanvas();
  34527. var width = painter.getWidth();
  34528. var height = painter.getHeight();
  34529. var newDomStyle = newDom.style;
  34530. if (newDomStyle) {
  34531. newDomStyle.position = 'absolute';
  34532. newDomStyle.left = '0';
  34533. newDomStyle.top = '0';
  34534. newDomStyle.width = width + 'px';
  34535. newDomStyle.height = height + 'px';
  34536. newDom.setAttribute('data-zr-dom-id', id);
  34537. }
  34538. newDom.width = width * dpr;
  34539. newDom.height = height * dpr;
  34540. return newDom;
  34541. }
  34542. var Layer = (function (_super) {
  34543. __extends(Layer, _super);
  34544. function Layer(id, painter, dpr) {
  34545. var _this = _super.call(this) || this;
  34546. _this.motionBlur = false;
  34547. _this.lastFrameAlpha = 0.7;
  34548. _this.dpr = 1;
  34549. _this.virtual = false;
  34550. _this.config = {};
  34551. _this.incremental = false;
  34552. _this.zlevel = 0;
  34553. _this.maxRepaintRectCount = 5;
  34554. _this.__dirty = true;
  34555. _this.__firstTimePaint = true;
  34556. _this.__used = false;
  34557. _this.__drawIndex = 0;
  34558. _this.__startIndex = 0;
  34559. _this.__endIndex = 0;
  34560. _this.__prevStartIndex = null;
  34561. _this.__prevEndIndex = null;
  34562. var dom;
  34563. dpr = dpr || devicePixelRatio;
  34564. if (typeof id === 'string') {
  34565. dom = createDom(id, painter, dpr);
  34566. }
  34567. else if (isObject(id)) {
  34568. dom = id;
  34569. id = dom.id;
  34570. }
  34571. _this.id = id;
  34572. _this.dom = dom;
  34573. var domStyle = dom.style;
  34574. if (domStyle) {
  34575. disableUserSelect(dom);
  34576. dom.onselectstart = function () { return false; };
  34577. domStyle.padding = '0';
  34578. domStyle.margin = '0';
  34579. domStyle.borderWidth = '0';
  34580. }
  34581. _this.painter = painter;
  34582. _this.dpr = dpr;
  34583. return _this;
  34584. }
  34585. Layer.prototype.getElementCount = function () {
  34586. return this.__endIndex - this.__startIndex;
  34587. };
  34588. Layer.prototype.afterBrush = function () {
  34589. this.__prevStartIndex = this.__startIndex;
  34590. this.__prevEndIndex = this.__endIndex;
  34591. };
  34592. Layer.prototype.initContext = function () {
  34593. this.ctx = this.dom.getContext('2d');
  34594. this.ctx.dpr = this.dpr;
  34595. };
  34596. Layer.prototype.setUnpainted = function () {
  34597. this.__firstTimePaint = true;
  34598. };
  34599. Layer.prototype.createBackBuffer = function () {
  34600. var dpr = this.dpr;
  34601. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  34602. this.ctxBack = this.domBack.getContext('2d');
  34603. if (dpr !== 1) {
  34604. this.ctxBack.scale(dpr, dpr);
  34605. }
  34606. };
  34607. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  34608. if (this.__firstTimePaint) {
  34609. this.__firstTimePaint = false;
  34610. return null;
  34611. }
  34612. var mergedRepaintRects = [];
  34613. var maxRepaintRectCount = this.maxRepaintRectCount;
  34614. var full = false;
  34615. var pendingRect = new BoundingRect(0, 0, 0, 0);
  34616. function addRectToMergePool(rect) {
  34617. if (!rect.isFinite() || rect.isZero()) {
  34618. return;
  34619. }
  34620. if (mergedRepaintRects.length === 0) {
  34621. var boundingRect = new BoundingRect(0, 0, 0, 0);
  34622. boundingRect.copy(rect);
  34623. mergedRepaintRects.push(boundingRect);
  34624. }
  34625. else {
  34626. var isMerged = false;
  34627. var minDeltaArea = Infinity;
  34628. var bestRectToMergeIdx = 0;
  34629. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  34630. var mergedRect = mergedRepaintRects[i];
  34631. if (mergedRect.intersect(rect)) {
  34632. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  34633. pendingRect_1.copy(mergedRect);
  34634. pendingRect_1.union(rect);
  34635. mergedRepaintRects[i] = pendingRect_1;
  34636. isMerged = true;
  34637. break;
  34638. }
  34639. else if (full) {
  34640. pendingRect.copy(rect);
  34641. pendingRect.union(mergedRect);
  34642. var aArea = rect.width * rect.height;
  34643. var bArea = mergedRect.width * mergedRect.height;
  34644. var pendingArea = pendingRect.width * pendingRect.height;
  34645. var deltaArea = pendingArea - aArea - bArea;
  34646. if (deltaArea < minDeltaArea) {
  34647. minDeltaArea = deltaArea;
  34648. bestRectToMergeIdx = i;
  34649. }
  34650. }
  34651. }
  34652. if (full) {
  34653. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  34654. isMerged = true;
  34655. }
  34656. if (!isMerged) {
  34657. var boundingRect = new BoundingRect(0, 0, 0, 0);
  34658. boundingRect.copy(rect);
  34659. mergedRepaintRects.push(boundingRect);
  34660. }
  34661. if (!full) {
  34662. full = mergedRepaintRects.length >= maxRepaintRectCount;
  34663. }
  34664. }
  34665. }
  34666. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  34667. var el = displayList[i];
  34668. if (el) {
  34669. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  34670. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  34671. ? el.getPrevPaintRect()
  34672. : null;
  34673. if (prevRect) {
  34674. addRectToMergePool(prevRect);
  34675. }
  34676. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  34677. ? el.getPaintRect()
  34678. : null;
  34679. if (curRect) {
  34680. addRectToMergePool(curRect);
  34681. }
  34682. }
  34683. }
  34684. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  34685. var el = prevList[i];
  34686. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  34687. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  34688. var prevRect = el.getPrevPaintRect();
  34689. if (prevRect) {
  34690. addRectToMergePool(prevRect);
  34691. }
  34692. }
  34693. }
  34694. var hasIntersections;
  34695. do {
  34696. hasIntersections = false;
  34697. for (var i = 0; i < mergedRepaintRects.length;) {
  34698. if (mergedRepaintRects[i].isZero()) {
  34699. mergedRepaintRects.splice(i, 1);
  34700. continue;
  34701. }
  34702. for (var j = i + 1; j < mergedRepaintRects.length;) {
  34703. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  34704. hasIntersections = true;
  34705. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  34706. mergedRepaintRects.splice(j, 1);
  34707. }
  34708. else {
  34709. j++;
  34710. }
  34711. }
  34712. i++;
  34713. }
  34714. } while (hasIntersections);
  34715. this._paintRects = mergedRepaintRects;
  34716. return mergedRepaintRects;
  34717. };
  34718. Layer.prototype.debugGetPaintRects = function () {
  34719. return (this._paintRects || []).slice();
  34720. };
  34721. Layer.prototype.resize = function (width, height) {
  34722. var dpr = this.dpr;
  34723. var dom = this.dom;
  34724. var domStyle = dom.style;
  34725. var domBack = this.domBack;
  34726. if (domStyle) {
  34727. domStyle.width = width + 'px';
  34728. domStyle.height = height + 'px';
  34729. }
  34730. dom.width = width * dpr;
  34731. dom.height = height * dpr;
  34732. if (domBack) {
  34733. domBack.width = width * dpr;
  34734. domBack.height = height * dpr;
  34735. if (dpr !== 1) {
  34736. this.ctxBack.scale(dpr, dpr);
  34737. }
  34738. }
  34739. };
  34740. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  34741. var dom = this.dom;
  34742. var ctx = this.ctx;
  34743. var width = dom.width;
  34744. var height = dom.height;
  34745. clearColor = clearColor || this.clearColor;
  34746. var haveMotionBLur = this.motionBlur && !clearAll;
  34747. var lastFrameAlpha = this.lastFrameAlpha;
  34748. var dpr = this.dpr;
  34749. var self = this;
  34750. if (haveMotionBLur) {
  34751. if (!this.domBack) {
  34752. this.createBackBuffer();
  34753. }
  34754. this.ctxBack.globalCompositeOperation = 'copy';
  34755. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  34756. }
  34757. var domBack = this.domBack;
  34758. function doClear(x, y, width, height) {
  34759. ctx.clearRect(x, y, width, height);
  34760. if (clearColor && clearColor !== 'transparent') {
  34761. var clearColorGradientOrPattern = void 0;
  34762. if (isGradientObject(clearColor)) {
  34763. var shouldCache = clearColor.global || (clearColor.__width === width
  34764. && clearColor.__height === height);
  34765. clearColorGradientOrPattern = shouldCache
  34766. && clearColor.__canvasGradient
  34767. || getCanvasGradient(ctx, clearColor, {
  34768. x: 0,
  34769. y: 0,
  34770. width: width,
  34771. height: height
  34772. });
  34773. clearColor.__canvasGradient = clearColorGradientOrPattern;
  34774. clearColor.__width = width;
  34775. clearColor.__height = height;
  34776. }
  34777. else if (isImagePatternObject(clearColor)) {
  34778. clearColor.scaleX = clearColor.scaleX || dpr;
  34779. clearColor.scaleY = clearColor.scaleY || dpr;
  34780. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  34781. dirty: function () {
  34782. self.setUnpainted();
  34783. self.__painter.refresh();
  34784. }
  34785. });
  34786. }
  34787. ctx.save();
  34788. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  34789. ctx.fillRect(x, y, width, height);
  34790. ctx.restore();
  34791. }
  34792. if (haveMotionBLur) {
  34793. ctx.save();
  34794. ctx.globalAlpha = lastFrameAlpha;
  34795. ctx.drawImage(domBack, x, y, width, height);
  34796. ctx.restore();
  34797. }
  34798. }
  34799. if (!repaintRects || haveMotionBLur) {
  34800. doClear(0, 0, width, height);
  34801. }
  34802. else if (repaintRects.length) {
  34803. each(repaintRects, function (rect) {
  34804. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34805. });
  34806. }
  34807. };
  34808. return Layer;
  34809. }(Eventful));
  34810. var HOVER_LAYER_ZLEVEL = 1e5;
  34811. var CANVAS_ZLEVEL = 314159;
  34812. var EL_AFTER_INCREMENTAL_INC = 0.01;
  34813. var INCREMENTAL_INC = 0.001;
  34814. function isLayerValid(layer) {
  34815. if (!layer) {
  34816. return false;
  34817. }
  34818. if (layer.__builtin__) {
  34819. return true;
  34820. }
  34821. if (typeof (layer.resize) !== 'function'
  34822. || typeof (layer.refresh) !== 'function') {
  34823. return false;
  34824. }
  34825. return true;
  34826. }
  34827. function createRoot(width, height) {
  34828. var domRoot = document.createElement('div');
  34829. domRoot.style.cssText = [
  34830. 'position:relative',
  34831. 'width:' + width + 'px',
  34832. 'height:' + height + 'px',
  34833. 'padding:0',
  34834. 'margin:0',
  34835. 'border-width:0'
  34836. ].join(';') + ';';
  34837. return domRoot;
  34838. }
  34839. var CanvasPainter = (function () {
  34840. function CanvasPainter(root, storage, opts, id) {
  34841. this.type = 'canvas';
  34842. this._zlevelList = [];
  34843. this._prevDisplayList = [];
  34844. this._layers = {};
  34845. this._layerConfig = {};
  34846. this._needsManuallyCompositing = false;
  34847. this.type = 'canvas';
  34848. var singleCanvas = !root.nodeName
  34849. || root.nodeName.toUpperCase() === 'CANVAS';
  34850. this._opts = opts = extend({}, opts || {});
  34851. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  34852. this._singleCanvas = singleCanvas;
  34853. this.root = root;
  34854. var rootStyle = root.style;
  34855. if (rootStyle) {
  34856. disableUserSelect(root);
  34857. root.innerHTML = '';
  34858. }
  34859. this.storage = storage;
  34860. var zlevelList = this._zlevelList;
  34861. this._prevDisplayList = [];
  34862. var layers = this._layers;
  34863. if (!singleCanvas) {
  34864. this._width = getSize(root, 0, opts);
  34865. this._height = getSize(root, 1, opts);
  34866. var domRoot = this._domRoot = createRoot(this._width, this._height);
  34867. root.appendChild(domRoot);
  34868. }
  34869. else {
  34870. var rootCanvas = root;
  34871. var width = rootCanvas.width;
  34872. var height = rootCanvas.height;
  34873. if (opts.width != null) {
  34874. width = opts.width;
  34875. }
  34876. if (opts.height != null) {
  34877. height = opts.height;
  34878. }
  34879. this.dpr = opts.devicePixelRatio || 1;
  34880. rootCanvas.width = width * this.dpr;
  34881. rootCanvas.height = height * this.dpr;
  34882. this._width = width;
  34883. this._height = height;
  34884. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  34885. mainLayer.__builtin__ = true;
  34886. mainLayer.initContext();
  34887. layers[CANVAS_ZLEVEL] = mainLayer;
  34888. mainLayer.zlevel = CANVAS_ZLEVEL;
  34889. zlevelList.push(CANVAS_ZLEVEL);
  34890. this._domRoot = root;
  34891. }
  34892. }
  34893. CanvasPainter.prototype.getType = function () {
  34894. return 'canvas';
  34895. };
  34896. CanvasPainter.prototype.isSingleCanvas = function () {
  34897. return this._singleCanvas;
  34898. };
  34899. CanvasPainter.prototype.getViewportRoot = function () {
  34900. return this._domRoot;
  34901. };
  34902. CanvasPainter.prototype.getViewportRootOffset = function () {
  34903. var viewportRoot = this.getViewportRoot();
  34904. if (viewportRoot) {
  34905. return {
  34906. offsetLeft: viewportRoot.offsetLeft || 0,
  34907. offsetTop: viewportRoot.offsetTop || 0
  34908. };
  34909. }
  34910. };
  34911. CanvasPainter.prototype.refresh = function (paintAll) {
  34912. var list = this.storage.getDisplayList(true);
  34913. var prevList = this._prevDisplayList;
  34914. var zlevelList = this._zlevelList;
  34915. this._redrawId = Math.random();
  34916. this._paintList(list, prevList, paintAll, this._redrawId);
  34917. for (var i = 0; i < zlevelList.length; i++) {
  34918. var z = zlevelList[i];
  34919. var layer = this._layers[z];
  34920. if (!layer.__builtin__ && layer.refresh) {
  34921. var clearColor = i === 0 ? this._backgroundColor : null;
  34922. layer.refresh(clearColor);
  34923. }
  34924. }
  34925. if (this._opts.useDirtyRect) {
  34926. this._prevDisplayList = list.slice();
  34927. }
  34928. return this;
  34929. };
  34930. CanvasPainter.prototype.refreshHover = function () {
  34931. this._paintHoverList(this.storage.getDisplayList(false));
  34932. };
  34933. CanvasPainter.prototype._paintHoverList = function (list) {
  34934. var len = list.length;
  34935. var hoverLayer = this._hoverlayer;
  34936. hoverLayer && hoverLayer.clear();
  34937. if (!len) {
  34938. return;
  34939. }
  34940. var scope = {
  34941. inHover: true,
  34942. viewWidth: this._width,
  34943. viewHeight: this._height
  34944. };
  34945. var ctx;
  34946. for (var i = 0; i < len; i++) {
  34947. var el = list[i];
  34948. if (el.__inHover) {
  34949. if (!hoverLayer) {
  34950. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  34951. }
  34952. if (!ctx) {
  34953. ctx = hoverLayer.ctx;
  34954. ctx.save();
  34955. }
  34956. brush(ctx, el, scope, i === len - 1);
  34957. }
  34958. }
  34959. if (ctx) {
  34960. ctx.restore();
  34961. }
  34962. };
  34963. CanvasPainter.prototype.getHoverLayer = function () {
  34964. return this.getLayer(HOVER_LAYER_ZLEVEL);
  34965. };
  34966. CanvasPainter.prototype.paintOne = function (ctx, el) {
  34967. brushSingle(ctx, el);
  34968. };
  34969. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  34970. if (this._redrawId !== redrawId) {
  34971. return;
  34972. }
  34973. paintAll = paintAll || false;
  34974. this._updateLayerStatus(list);
  34975. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  34976. if (this._needsManuallyCompositing) {
  34977. this._compositeManually();
  34978. }
  34979. if (needsRefreshHover) {
  34980. this._paintHoverList(list);
  34981. }
  34982. if (!finished) {
  34983. var self_1 = this;
  34984. requestAnimationFrame$1(function () {
  34985. self_1._paintList(list, prevList, paintAll, redrawId);
  34986. });
  34987. }
  34988. else {
  34989. this.eachLayer(function (layer) {
  34990. layer.afterBrush && layer.afterBrush();
  34991. });
  34992. }
  34993. };
  34994. CanvasPainter.prototype._compositeManually = function () {
  34995. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  34996. var width = this._domRoot.width;
  34997. var height = this._domRoot.height;
  34998. ctx.clearRect(0, 0, width, height);
  34999. this.eachBuiltinLayer(function (layer) {
  35000. if (layer.virtual) {
  35001. ctx.drawImage(layer.dom, 0, 0, width, height);
  35002. }
  35003. });
  35004. };
  35005. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  35006. var _this = this;
  35007. var layerList = [];
  35008. var useDirtyRect = this._opts.useDirtyRect;
  35009. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  35010. var zlevel = this._zlevelList[zi];
  35011. var layer = this._layers[zlevel];
  35012. if (layer.__builtin__
  35013. && layer !== this._hoverlayer
  35014. && (layer.__dirty || paintAll)) {
  35015. layerList.push(layer);
  35016. }
  35017. }
  35018. var finished = true;
  35019. var needsRefreshHover = false;
  35020. var _loop_1 = function (k) {
  35021. var layer = layerList[k];
  35022. var ctx = layer.ctx;
  35023. var repaintRects = useDirtyRect
  35024. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  35025. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  35026. var useTimer = !paintAll && layer.incremental && Date.now;
  35027. var startTime = useTimer && Date.now();
  35028. var clearColor = layer.zlevel === this_1._zlevelList[0]
  35029. ? this_1._backgroundColor : null;
  35030. if (layer.__startIndex === layer.__endIndex) {
  35031. layer.clear(false, clearColor, repaintRects);
  35032. }
  35033. else if (start === layer.__startIndex) {
  35034. var firstEl = list[start];
  35035. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  35036. layer.clear(false, clearColor, repaintRects);
  35037. }
  35038. }
  35039. if (start === -1) {
  35040. console.error('For some unknown reason. drawIndex is -1');
  35041. start = layer.__startIndex;
  35042. }
  35043. var i;
  35044. var repaint = function (repaintRect) {
  35045. var scope = {
  35046. inHover: false,
  35047. allClipped: false,
  35048. prevEl: null,
  35049. viewWidth: _this._width,
  35050. viewHeight: _this._height
  35051. };
  35052. for (i = start; i < layer.__endIndex; i++) {
  35053. var el = list[i];
  35054. if (el.__inHover) {
  35055. needsRefreshHover = true;
  35056. }
  35057. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  35058. if (useTimer) {
  35059. var dTime = Date.now() - startTime;
  35060. if (dTime > 15) {
  35061. break;
  35062. }
  35063. }
  35064. }
  35065. if (scope.prevElClipPaths) {
  35066. ctx.restore();
  35067. }
  35068. };
  35069. if (repaintRects) {
  35070. if (repaintRects.length === 0) {
  35071. i = layer.__endIndex;
  35072. }
  35073. else {
  35074. var dpr = this_1.dpr;
  35075. for (var r = 0; r < repaintRects.length; ++r) {
  35076. var rect = repaintRects[r];
  35077. ctx.save();
  35078. ctx.beginPath();
  35079. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35080. ctx.clip();
  35081. repaint(rect);
  35082. ctx.restore();
  35083. }
  35084. }
  35085. }
  35086. else {
  35087. ctx.save();
  35088. repaint();
  35089. ctx.restore();
  35090. }
  35091. layer.__drawIndex = i;
  35092. if (layer.__drawIndex < layer.__endIndex) {
  35093. finished = false;
  35094. }
  35095. };
  35096. var this_1 = this;
  35097. for (var k = 0; k < layerList.length; k++) {
  35098. _loop_1(k);
  35099. }
  35100. if (env.wxa) {
  35101. each(this._layers, function (layer) {
  35102. if (layer && layer.ctx && layer.ctx.draw) {
  35103. layer.ctx.draw();
  35104. }
  35105. });
  35106. }
  35107. return {
  35108. finished: finished,
  35109. needsRefreshHover: needsRefreshHover
  35110. };
  35111. };
  35112. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  35113. var ctx = currentLayer.ctx;
  35114. if (useDirtyRect) {
  35115. var paintRect = el.getPaintRect();
  35116. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  35117. brush(ctx, el, scope, isLast);
  35118. el.setPrevPaintRect(paintRect);
  35119. }
  35120. }
  35121. else {
  35122. brush(ctx, el, scope, isLast);
  35123. }
  35124. };
  35125. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  35126. if (this._singleCanvas && !this._needsManuallyCompositing) {
  35127. zlevel = CANVAS_ZLEVEL;
  35128. }
  35129. var layer = this._layers[zlevel];
  35130. if (!layer) {
  35131. layer = new Layer('zr_' + zlevel, this, this.dpr);
  35132. layer.zlevel = zlevel;
  35133. layer.__builtin__ = true;
  35134. if (this._layerConfig[zlevel]) {
  35135. merge(layer, this._layerConfig[zlevel], true);
  35136. }
  35137. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  35138. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  35139. }
  35140. if (virtual) {
  35141. layer.virtual = virtual;
  35142. }
  35143. this.insertLayer(zlevel, layer);
  35144. layer.initContext();
  35145. }
  35146. return layer;
  35147. };
  35148. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  35149. var layersMap = this._layers;
  35150. var zlevelList = this._zlevelList;
  35151. var len = zlevelList.length;
  35152. var domRoot = this._domRoot;
  35153. var prevLayer = null;
  35154. var i = -1;
  35155. if (layersMap[zlevel]) {
  35156. if ("development" !== 'production') {
  35157. logError('ZLevel ' + zlevel + ' has been used already');
  35158. }
  35159. return;
  35160. }
  35161. if (!isLayerValid(layer)) {
  35162. if ("development" !== 'production') {
  35163. logError('Layer of zlevel ' + zlevel + ' is not valid');
  35164. }
  35165. return;
  35166. }
  35167. if (len > 0 && zlevel > zlevelList[0]) {
  35168. for (i = 0; i < len - 1; i++) {
  35169. if (zlevelList[i] < zlevel
  35170. && zlevelList[i + 1] > zlevel) {
  35171. break;
  35172. }
  35173. }
  35174. prevLayer = layersMap[zlevelList[i]];
  35175. }
  35176. zlevelList.splice(i + 1, 0, zlevel);
  35177. layersMap[zlevel] = layer;
  35178. if (!layer.virtual) {
  35179. if (prevLayer) {
  35180. var prevDom = prevLayer.dom;
  35181. if (prevDom.nextSibling) {
  35182. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  35183. }
  35184. else {
  35185. domRoot.appendChild(layer.dom);
  35186. }
  35187. }
  35188. else {
  35189. if (domRoot.firstChild) {
  35190. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  35191. }
  35192. else {
  35193. domRoot.appendChild(layer.dom);
  35194. }
  35195. }
  35196. }
  35197. layer.__painter = this;
  35198. };
  35199. CanvasPainter.prototype.eachLayer = function (cb, context) {
  35200. var zlevelList = this._zlevelList;
  35201. for (var i = 0; i < zlevelList.length; i++) {
  35202. var z = zlevelList[i];
  35203. cb.call(context, this._layers[z], z);
  35204. }
  35205. };
  35206. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  35207. var zlevelList = this._zlevelList;
  35208. for (var i = 0; i < zlevelList.length; i++) {
  35209. var z = zlevelList[i];
  35210. var layer = this._layers[z];
  35211. if (layer.__builtin__) {
  35212. cb.call(context, layer, z);
  35213. }
  35214. }
  35215. };
  35216. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  35217. var zlevelList = this._zlevelList;
  35218. for (var i = 0; i < zlevelList.length; i++) {
  35219. var z = zlevelList[i];
  35220. var layer = this._layers[z];
  35221. if (!layer.__builtin__) {
  35222. cb.call(context, layer, z);
  35223. }
  35224. }
  35225. };
  35226. CanvasPainter.prototype.getLayers = function () {
  35227. return this._layers;
  35228. };
  35229. CanvasPainter.prototype._updateLayerStatus = function (list) {
  35230. this.eachBuiltinLayer(function (layer, z) {
  35231. layer.__dirty = layer.__used = false;
  35232. });
  35233. function updatePrevLayer(idx) {
  35234. if (prevLayer) {
  35235. if (prevLayer.__endIndex !== idx) {
  35236. prevLayer.__dirty = true;
  35237. }
  35238. prevLayer.__endIndex = idx;
  35239. }
  35240. }
  35241. if (this._singleCanvas) {
  35242. for (var i_1 = 1; i_1 < list.length; i_1++) {
  35243. var el = list[i_1];
  35244. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  35245. this._needsManuallyCompositing = true;
  35246. break;
  35247. }
  35248. }
  35249. }
  35250. var prevLayer = null;
  35251. var incrementalLayerCount = 0;
  35252. var prevZlevel;
  35253. var i;
  35254. for (i = 0; i < list.length; i++) {
  35255. var el = list[i];
  35256. var zlevel = el.zlevel;
  35257. var layer = void 0;
  35258. if (prevZlevel !== zlevel) {
  35259. prevZlevel = zlevel;
  35260. incrementalLayerCount = 0;
  35261. }
  35262. if (el.incremental) {
  35263. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  35264. layer.incremental = true;
  35265. incrementalLayerCount = 1;
  35266. }
  35267. else {
  35268. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  35269. }
  35270. if (!layer.__builtin__) {
  35271. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  35272. }
  35273. if (layer !== prevLayer) {
  35274. layer.__used = true;
  35275. if (layer.__startIndex !== i) {
  35276. layer.__dirty = true;
  35277. }
  35278. layer.__startIndex = i;
  35279. if (!layer.incremental) {
  35280. layer.__drawIndex = i;
  35281. }
  35282. else {
  35283. layer.__drawIndex = -1;
  35284. }
  35285. updatePrevLayer(i);
  35286. prevLayer = layer;
  35287. }
  35288. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  35289. layer.__dirty = true;
  35290. if (layer.incremental && layer.__drawIndex < 0) {
  35291. layer.__drawIndex = i;
  35292. }
  35293. }
  35294. }
  35295. updatePrevLayer(i);
  35296. this.eachBuiltinLayer(function (layer, z) {
  35297. if (!layer.__used && layer.getElementCount() > 0) {
  35298. layer.__dirty = true;
  35299. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  35300. }
  35301. if (layer.__dirty && layer.__drawIndex < 0) {
  35302. layer.__drawIndex = layer.__startIndex;
  35303. }
  35304. });
  35305. };
  35306. CanvasPainter.prototype.clear = function () {
  35307. this.eachBuiltinLayer(this._clearLayer);
  35308. return this;
  35309. };
  35310. CanvasPainter.prototype._clearLayer = function (layer) {
  35311. layer.clear();
  35312. };
  35313. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35314. this._backgroundColor = backgroundColor;
  35315. each(this._layers, function (layer) {
  35316. layer.setUnpainted();
  35317. });
  35318. };
  35319. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  35320. if (config) {
  35321. var layerConfig = this._layerConfig;
  35322. if (!layerConfig[zlevel]) {
  35323. layerConfig[zlevel] = config;
  35324. }
  35325. else {
  35326. merge(layerConfig[zlevel], config, true);
  35327. }
  35328. for (var i = 0; i < this._zlevelList.length; i++) {
  35329. var _zlevel = this._zlevelList[i];
  35330. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  35331. var layer = this._layers[_zlevel];
  35332. merge(layer, layerConfig[zlevel], true);
  35333. }
  35334. }
  35335. }
  35336. };
  35337. CanvasPainter.prototype.delLayer = function (zlevel) {
  35338. var layers = this._layers;
  35339. var zlevelList = this._zlevelList;
  35340. var layer = layers[zlevel];
  35341. if (!layer) {
  35342. return;
  35343. }
  35344. layer.dom.parentNode.removeChild(layer.dom);
  35345. delete layers[zlevel];
  35346. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  35347. };
  35348. CanvasPainter.prototype.resize = function (width, height) {
  35349. if (!this._domRoot.style) {
  35350. if (width == null || height == null) {
  35351. return;
  35352. }
  35353. this._width = width;
  35354. this._height = height;
  35355. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  35356. }
  35357. else {
  35358. var domRoot = this._domRoot;
  35359. domRoot.style.display = 'none';
  35360. var opts = this._opts;
  35361. var root = this.root;
  35362. width != null && (opts.width = width);
  35363. height != null && (opts.height = height);
  35364. width = getSize(root, 0, opts);
  35365. height = getSize(root, 1, opts);
  35366. domRoot.style.display = '';
  35367. if (this._width !== width || height !== this._height) {
  35368. domRoot.style.width = width + 'px';
  35369. domRoot.style.height = height + 'px';
  35370. for (var id in this._layers) {
  35371. if (this._layers.hasOwnProperty(id)) {
  35372. this._layers[id].resize(width, height);
  35373. }
  35374. }
  35375. this.refresh(true);
  35376. }
  35377. this._width = width;
  35378. this._height = height;
  35379. }
  35380. return this;
  35381. };
  35382. CanvasPainter.prototype.clearLayer = function (zlevel) {
  35383. var layer = this._layers[zlevel];
  35384. if (layer) {
  35385. layer.clear();
  35386. }
  35387. };
  35388. CanvasPainter.prototype.dispose = function () {
  35389. this.root.innerHTML = '';
  35390. this.root =
  35391. this.storage =
  35392. this._domRoot =
  35393. this._layers = null;
  35394. };
  35395. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  35396. opts = opts || {};
  35397. if (this._singleCanvas && !this._compositeManually) {
  35398. return this._layers[CANVAS_ZLEVEL].dom;
  35399. }
  35400. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  35401. imageLayer.initContext();
  35402. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  35403. var ctx = imageLayer.ctx;
  35404. if (opts.pixelRatio <= this.dpr) {
  35405. this.refresh();
  35406. var width_1 = imageLayer.dom.width;
  35407. var height_1 = imageLayer.dom.height;
  35408. this.eachLayer(function (layer) {
  35409. if (layer.__builtin__) {
  35410. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  35411. }
  35412. else if (layer.renderToCanvas) {
  35413. ctx.save();
  35414. layer.renderToCanvas(ctx);
  35415. ctx.restore();
  35416. }
  35417. });
  35418. }
  35419. else {
  35420. var scope = {
  35421. inHover: false,
  35422. viewWidth: this._width,
  35423. viewHeight: this._height
  35424. };
  35425. var displayList = this.storage.getDisplayList(true);
  35426. for (var i = 0, len = displayList.length; i < len; i++) {
  35427. var el = displayList[i];
  35428. brush(ctx, el, scope, i === len - 1);
  35429. }
  35430. }
  35431. return imageLayer.dom;
  35432. };
  35433. CanvasPainter.prototype.getWidth = function () {
  35434. return this._width;
  35435. };
  35436. CanvasPainter.prototype.getHeight = function () {
  35437. return this._height;
  35438. };
  35439. return CanvasPainter;
  35440. }());
  35441. function install$1(registers) {
  35442. registers.registerPainter('canvas', CanvasPainter);
  35443. }
  35444. var LineSeriesModel =
  35445. /** @class */
  35446. function (_super) {
  35447. __extends(LineSeriesModel, _super);
  35448. function LineSeriesModel() {
  35449. var _this = _super !== null && _super.apply(this, arguments) || this;
  35450. _this.type = LineSeriesModel.type;
  35451. _this.hasSymbolVisual = true;
  35452. return _this;
  35453. }
  35454. LineSeriesModel.prototype.getInitialData = function (option) {
  35455. if ("development" !== 'production') {
  35456. var coordSys = option.coordinateSystem;
  35457. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  35458. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  35459. }
  35460. }
  35461. return createSeriesData(null, this, {
  35462. useEncodeDefaulter: true
  35463. });
  35464. };
  35465. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  35466. var group = new Group();
  35467. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  35468. group.add(line);
  35469. line.setStyle(opt.lineStyle);
  35470. var visualType = this.getData().getVisual('symbol');
  35471. var visualRotate = this.getData().getVisual('symbolRotate');
  35472. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  35473. var size = opt.itemHeight * 0.8;
  35474. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  35475. group.add(symbol);
  35476. symbol.setStyle(opt.itemStyle);
  35477. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  35478. symbol.rotation = symbolRotate * Math.PI / 180;
  35479. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  35480. if (symbolType.indexOf('empty') > -1) {
  35481. symbol.style.stroke = symbol.style.fill;
  35482. symbol.style.fill = '#fff';
  35483. symbol.style.lineWidth = 2;
  35484. }
  35485. return group;
  35486. };
  35487. LineSeriesModel.type = 'series.line';
  35488. LineSeriesModel.dependencies = ['grid', 'polar'];
  35489. LineSeriesModel.defaultOption = {
  35490. // zlevel: 0,
  35491. z: 3,
  35492. coordinateSystem: 'cartesian2d',
  35493. legendHoverLink: true,
  35494. clip: true,
  35495. label: {
  35496. position: 'top'
  35497. },
  35498. // itemStyle: {
  35499. // },
  35500. endLabel: {
  35501. show: false,
  35502. valueAnimation: true,
  35503. distance: 8
  35504. },
  35505. lineStyle: {
  35506. width: 2,
  35507. type: 'solid'
  35508. },
  35509. emphasis: {
  35510. scale: true
  35511. },
  35512. // areaStyle: {
  35513. // origin of areaStyle. Valid values:
  35514. // `'auto'/null/undefined`: from axisLine to data
  35515. // `'start'`: from min to data
  35516. // `'end'`: from data to max
  35517. // origin: 'auto'
  35518. // },
  35519. // false, 'start', 'end', 'middle'
  35520. step: false,
  35521. // Disabled if step is true
  35522. smooth: false,
  35523. smoothMonotone: null,
  35524. symbol: 'emptyCircle',
  35525. symbolSize: 4,
  35526. symbolRotate: null,
  35527. showSymbol: true,
  35528. // `false`: follow the label interval strategy.
  35529. // `true`: show all symbols.
  35530. // `'auto'`: If possible, show all symbols, otherwise
  35531. // follow the label interval strategy.
  35532. showAllSymbol: 'auto',
  35533. // Whether to connect break point.
  35534. connectNulls: false,
  35535. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  35536. sampling: 'none',
  35537. animationEasing: 'linear',
  35538. // Disable progressive
  35539. progressive: 0,
  35540. hoverLayerThreshold: Infinity,
  35541. universalTransition: {
  35542. divideShape: 'clone'
  35543. },
  35544. triggerLineEvent: false
  35545. };
  35546. return LineSeriesModel;
  35547. }(SeriesModel);
  35548. /**
  35549. * @return label string. Not null/undefined
  35550. */
  35551. function getDefaultLabel(data, dataIndex) {
  35552. var labelDims = data.mapDimensionsAll('defaultedLabel');
  35553. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  35554. if (len === 1) {
  35555. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  35556. return rawVal != null ? rawVal + '' : null;
  35557. } else if (len) {
  35558. var vals = [];
  35559. for (var i = 0; i < labelDims.length; i++) {
  35560. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  35561. }
  35562. return vals.join(' ');
  35563. }
  35564. }
  35565. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  35566. var labelDims = data.mapDimensionsAll('defaultedLabel');
  35567. if (!isArray(interpolatedValue)) {
  35568. return interpolatedValue + '';
  35569. }
  35570. var vals = [];
  35571. for (var i = 0; i < labelDims.length; i++) {
  35572. var dimIndex = data.getDimensionIndex(labelDims[i]);
  35573. if (dimIndex >= 0) {
  35574. vals.push(interpolatedValue[dimIndex]);
  35575. }
  35576. }
  35577. return vals.join(' ');
  35578. }
  35579. var Symbol =
  35580. /** @class */
  35581. function (_super) {
  35582. __extends(Symbol, _super);
  35583. function Symbol(data, idx, seriesScope, opts) {
  35584. var _this = _super.call(this) || this;
  35585. _this.updateData(data, idx, seriesScope, opts);
  35586. return _this;
  35587. }
  35588. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  35589. // Remove paths created before
  35590. this.removeAll(); // let symbolPath = createSymbol(
  35591. // symbolType, -0.5, -0.5, 1, 1, color
  35592. // );
  35593. // If width/height are set too small (e.g., set to 1) on ios10
  35594. // and macOS Sierra, a circle stroke become a rect, no matter what
  35595. // the scale is set. So we set width/height as 2. See #4150.
  35596. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  35597. symbolPath.attr({
  35598. z2: 100,
  35599. culling: true,
  35600. scaleX: symbolSize[0] / 2,
  35601. scaleY: symbolSize[1] / 2
  35602. }); // Rewrite drift method
  35603. symbolPath.drift = driftSymbol;
  35604. this._symbolType = symbolType;
  35605. this.add(symbolPath);
  35606. };
  35607. /**
  35608. * Stop animation
  35609. * @param {boolean} toLastFrame
  35610. */
  35611. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  35612. this.childAt(0).stopAnimation(null, toLastFrame);
  35613. };
  35614. Symbol.prototype.getSymbolType = function () {
  35615. return this._symbolType;
  35616. };
  35617. /**
  35618. * FIXME:
  35619. * Caution: This method breaks the encapsulation of this module,
  35620. * but it indeed brings convenience. So do not use the method
  35621. * unless you detailedly know all the implements of `Symbol`,
  35622. * especially animation.
  35623. *
  35624. * Get symbol path element.
  35625. */
  35626. Symbol.prototype.getSymbolPath = function () {
  35627. return this.childAt(0);
  35628. };
  35629. /**
  35630. * Highlight symbol
  35631. */
  35632. Symbol.prototype.highlight = function () {
  35633. enterEmphasis(this.childAt(0));
  35634. };
  35635. /**
  35636. * Downplay symbol
  35637. */
  35638. Symbol.prototype.downplay = function () {
  35639. leaveEmphasis(this.childAt(0));
  35640. };
  35641. /**
  35642. * @param {number} zlevel
  35643. * @param {number} z
  35644. */
  35645. Symbol.prototype.setZ = function (zlevel, z) {
  35646. var symbolPath = this.childAt(0);
  35647. symbolPath.zlevel = zlevel;
  35648. symbolPath.z = z;
  35649. };
  35650. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  35651. var symbolPath = this.childAt(0);
  35652. symbolPath.draggable = draggable;
  35653. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  35654. };
  35655. /**
  35656. * Update symbol properties
  35657. */
  35658. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  35659. this.silent = false;
  35660. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  35661. var seriesModel = data.hostModel;
  35662. var symbolSize = Symbol.getSymbolSize(data, idx);
  35663. var isInit = symbolType !== this._symbolType;
  35664. var disableAnimation = opts && opts.disableAnimation;
  35665. if (isInit) {
  35666. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  35667. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  35668. } else {
  35669. var symbolPath = this.childAt(0);
  35670. symbolPath.silent = false;
  35671. var target = {
  35672. scaleX: symbolSize[0] / 2,
  35673. scaleY: symbolSize[1] / 2
  35674. };
  35675. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  35676. saveOldStyle(symbolPath);
  35677. }
  35678. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  35679. if (isInit) {
  35680. var symbolPath = this.childAt(0);
  35681. if (!disableAnimation) {
  35682. var target = {
  35683. scaleX: this._sizeX,
  35684. scaleY: this._sizeY,
  35685. style: {
  35686. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  35687. opacity: symbolPath.style.opacity
  35688. }
  35689. };
  35690. symbolPath.scaleX = symbolPath.scaleY = 0;
  35691. symbolPath.style.opacity = 0;
  35692. initProps(symbolPath, target, seriesModel, idx);
  35693. }
  35694. }
  35695. if (disableAnimation) {
  35696. // Must stop leave transition manually if don't call initProps or updateProps.
  35697. this.childAt(0).stopAnimation('leave');
  35698. }
  35699. };
  35700. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  35701. var symbolPath = this.childAt(0);
  35702. var seriesModel = data.hostModel;
  35703. var emphasisItemStyle;
  35704. var blurItemStyle;
  35705. var selectItemStyle;
  35706. var focus;
  35707. var blurScope;
  35708. var emphasisDisabled;
  35709. var labelStatesModels;
  35710. var hoverScale;
  35711. var cursorStyle;
  35712. if (seriesScope) {
  35713. emphasisItemStyle = seriesScope.emphasisItemStyle;
  35714. blurItemStyle = seriesScope.blurItemStyle;
  35715. selectItemStyle = seriesScope.selectItemStyle;
  35716. focus = seriesScope.focus;
  35717. blurScope = seriesScope.blurScope;
  35718. labelStatesModels = seriesScope.labelStatesModels;
  35719. hoverScale = seriesScope.hoverScale;
  35720. cursorStyle = seriesScope.cursorStyle;
  35721. emphasisDisabled = seriesScope.emphasisDisabled;
  35722. }
  35723. if (!seriesScope || data.hasItemOption) {
  35724. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  35725. var emphasisModel = itemModel.getModel('emphasis');
  35726. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  35727. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  35728. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  35729. focus = emphasisModel.get('focus');
  35730. blurScope = emphasisModel.get('blurScope');
  35731. emphasisDisabled = emphasisModel.get('disabled');
  35732. labelStatesModels = getLabelStatesModels(itemModel);
  35733. hoverScale = emphasisModel.getShallow('scale');
  35734. cursorStyle = itemModel.getShallow('cursor');
  35735. }
  35736. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  35737. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  35738. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  35739. if (symbolOffset) {
  35740. symbolPath.x = symbolOffset[0];
  35741. symbolPath.y = symbolOffset[1];
  35742. }
  35743. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  35744. var symbolStyle = data.getItemVisual(idx, 'style');
  35745. var visualColor = symbolStyle.fill;
  35746. if (symbolPath instanceof ZRImage) {
  35747. var pathStyle = symbolPath.style;
  35748. symbolPath.useStyle(extend({
  35749. // TODO other properties like x, y ?
  35750. image: pathStyle.image,
  35751. x: pathStyle.x,
  35752. y: pathStyle.y,
  35753. width: pathStyle.width,
  35754. height: pathStyle.height
  35755. }, symbolStyle));
  35756. } else {
  35757. if (symbolPath.__isEmptyBrush) {
  35758. // fill and stroke will be swapped if it's empty.
  35759. // So we cloned a new style to avoid it affecting the original style in visual storage.
  35760. // TODO Better implementation. No empty logic!
  35761. symbolPath.useStyle(extend({}, symbolStyle));
  35762. } else {
  35763. symbolPath.useStyle(symbolStyle);
  35764. } // Disable decal because symbol scale will been applied on the decal.
  35765. symbolPath.style.decal = null;
  35766. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  35767. symbolPath.style.strokeNoScale = true;
  35768. }
  35769. var liftZ = data.getItemVisual(idx, 'liftZ');
  35770. var z2Origin = this._z2;
  35771. if (liftZ != null) {
  35772. if (z2Origin == null) {
  35773. this._z2 = symbolPath.z2;
  35774. symbolPath.z2 += liftZ;
  35775. }
  35776. } else if (z2Origin != null) {
  35777. symbolPath.z2 = z2Origin;
  35778. this._z2 = null;
  35779. }
  35780. var useNameLabel = opts && opts.useNameLabel;
  35781. setLabelStyle(symbolPath, labelStatesModels, {
  35782. labelFetcher: seriesModel,
  35783. labelDataIndex: idx,
  35784. defaultText: getLabelDefaultText,
  35785. inheritColor: visualColor,
  35786. defaultOpacity: symbolStyle.opacity
  35787. }); // Do not execute util needed.
  35788. function getLabelDefaultText(idx) {
  35789. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  35790. }
  35791. this._sizeX = symbolSize[0] / 2;
  35792. this._sizeY = symbolSize[1] / 2;
  35793. var emphasisState = symbolPath.ensureState('emphasis');
  35794. emphasisState.style = emphasisItemStyle;
  35795. symbolPath.ensureState('select').style = selectItemStyle;
  35796. symbolPath.ensureState('blur').style = blurItemStyle; // null / undefined / true means to use default strategy.
  35797. // 0 / false / negative number / NaN / Infinity means no scale.
  35798. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY) // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  35799. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1; // always set scale to allow resetting
  35800. emphasisState.scaleX = this._sizeX * scaleRatio;
  35801. emphasisState.scaleY = this._sizeY * scaleRatio;
  35802. this.setSymbolScale(1);
  35803. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  35804. };
  35805. Symbol.prototype.setSymbolScale = function (scale) {
  35806. this.scaleX = this.scaleY = scale;
  35807. };
  35808. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  35809. var symbolPath = this.childAt(0);
  35810. var dataIndex = getECData(this).dataIndex;
  35811. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  35812. this.silent = symbolPath.silent = true; // Not show text when animating
  35813. if (opt && opt.fadeLabel) {
  35814. var textContent = symbolPath.getTextContent();
  35815. if (textContent) {
  35816. removeElement(textContent, {
  35817. style: {
  35818. opacity: 0
  35819. }
  35820. }, seriesModel, {
  35821. dataIndex: dataIndex,
  35822. removeOpt: animationOpt,
  35823. cb: function () {
  35824. symbolPath.removeTextContent();
  35825. }
  35826. });
  35827. }
  35828. } else {
  35829. symbolPath.removeTextContent();
  35830. }
  35831. removeElement(symbolPath, {
  35832. style: {
  35833. opacity: 0
  35834. },
  35835. scaleX: 0,
  35836. scaleY: 0
  35837. }, seriesModel, {
  35838. dataIndex: dataIndex,
  35839. cb: cb,
  35840. removeOpt: animationOpt
  35841. });
  35842. };
  35843. Symbol.getSymbolSize = function (data, idx) {
  35844. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  35845. };
  35846. return Symbol;
  35847. }(Group);
  35848. function driftSymbol(dx, dy) {
  35849. this.parent.drift(dx, dy);
  35850. }
  35851. function symbolNeedsDraw(data, point, idx, opt) {
  35852. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will cut part of
  35853. // the symbol element shape. We use the same clip shape here as
  35854. // the line clip.
  35855. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  35856. }
  35857. function normalizeUpdateOpt(opt) {
  35858. if (opt != null && !isObject(opt)) {
  35859. opt = {
  35860. isIgnore: opt
  35861. };
  35862. }
  35863. return opt || {};
  35864. }
  35865. function makeSeriesScope(data) {
  35866. var seriesModel = data.hostModel;
  35867. var emphasisModel = seriesModel.getModel('emphasis');
  35868. return {
  35869. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  35870. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  35871. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  35872. focus: emphasisModel.get('focus'),
  35873. blurScope: emphasisModel.get('blurScope'),
  35874. emphasisDisabled: emphasisModel.get('disabled'),
  35875. hoverScale: emphasisModel.get('scale'),
  35876. labelStatesModels: getLabelStatesModels(seriesModel),
  35877. cursorStyle: seriesModel.get('cursor')
  35878. };
  35879. }
  35880. var SymbolDraw =
  35881. /** @class */
  35882. function () {
  35883. function SymbolDraw(SymbolCtor) {
  35884. this.group = new Group();
  35885. this._SymbolCtor = SymbolCtor || Symbol;
  35886. }
  35887. /**
  35888. * Update symbols draw by new data
  35889. */
  35890. SymbolDraw.prototype.updateData = function (data, opt) {
  35891. // Remove progressive els.
  35892. this._progressiveEls = null;
  35893. opt = normalizeUpdateOpt(opt);
  35894. var group = this.group;
  35895. var seriesModel = data.hostModel;
  35896. var oldData = this._data;
  35897. var SymbolCtor = this._SymbolCtor;
  35898. var disableAnimation = opt.disableAnimation;
  35899. var seriesScope = makeSeriesScope(data);
  35900. var symbolUpdateOpt = {
  35901. disableAnimation: disableAnimation
  35902. };
  35903. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  35904. return data.getItemLayout(idx);
  35905. }; // There is no oldLineData only when first rendering or switching from
  35906. // stream mode to normal mode, where previous elements should be removed.
  35907. if (!oldData) {
  35908. group.removeAll();
  35909. }
  35910. data.diff(oldData).add(function (newIdx) {
  35911. var point = getSymbolPoint(newIdx);
  35912. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  35913. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  35914. symbolEl.setPosition(point);
  35915. data.setItemGraphicEl(newIdx, symbolEl);
  35916. group.add(symbolEl);
  35917. }
  35918. }).update(function (newIdx, oldIdx) {
  35919. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  35920. var point = getSymbolPoint(newIdx);
  35921. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  35922. group.remove(symbolEl);
  35923. return;
  35924. }
  35925. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  35926. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  35927. if (!symbolEl // Create a new if symbol type changed.
  35928. || oldSymbolType && oldSymbolType !== newSymbolType) {
  35929. group.remove(symbolEl);
  35930. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  35931. symbolEl.setPosition(point);
  35932. } else {
  35933. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  35934. var target = {
  35935. x: point[0],
  35936. y: point[1]
  35937. };
  35938. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  35939. } // Add back
  35940. group.add(symbolEl);
  35941. data.setItemGraphicEl(newIdx, symbolEl);
  35942. }).remove(function (oldIdx) {
  35943. var el = oldData.getItemGraphicEl(oldIdx);
  35944. el && el.fadeOut(function () {
  35945. group.remove(el);
  35946. }, seriesModel);
  35947. }).execute();
  35948. this._getSymbolPoint = getSymbolPoint;
  35949. this._data = data;
  35950. };
  35951. SymbolDraw.prototype.updateLayout = function () {
  35952. var _this = this;
  35953. var data = this._data;
  35954. if (data) {
  35955. // Not use animation
  35956. data.eachItemGraphicEl(function (el, idx) {
  35957. var point = _this._getSymbolPoint(idx);
  35958. el.setPosition(point);
  35959. el.markRedraw();
  35960. });
  35961. }
  35962. };
  35963. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  35964. this._seriesScope = makeSeriesScope(data);
  35965. this._data = null;
  35966. this.group.removeAll();
  35967. };
  35968. /**
  35969. * Update symbols draw by new data
  35970. */
  35971. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  35972. // Clear
  35973. this._progressiveEls = [];
  35974. opt = normalizeUpdateOpt(opt);
  35975. function updateIncrementalAndHover(el) {
  35976. if (!el.isGroup) {
  35977. el.incremental = true;
  35978. el.ensureState('emphasis').hoverLayer = true;
  35979. }
  35980. }
  35981. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  35982. var point = data.getItemLayout(idx);
  35983. if (symbolNeedsDraw(data, point, idx, opt)) {
  35984. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  35985. el.traverse(updateIncrementalAndHover);
  35986. el.setPosition(point);
  35987. this.group.add(el);
  35988. data.setItemGraphicEl(idx, el);
  35989. this._progressiveEls.push(el);
  35990. }
  35991. }
  35992. };
  35993. SymbolDraw.prototype.eachRendered = function (cb) {
  35994. traverseElements(this._progressiveEls || this.group, cb);
  35995. };
  35996. SymbolDraw.prototype.remove = function (enableAnimation) {
  35997. var group = this.group;
  35998. var data = this._data; // Incremental model do not have this._data.
  35999. if (data && enableAnimation) {
  36000. data.eachItemGraphicEl(function (el) {
  36001. el.fadeOut(function () {
  36002. group.remove(el);
  36003. }, data.hostModel);
  36004. });
  36005. } else {
  36006. group.removeAll();
  36007. }
  36008. };
  36009. return SymbolDraw;
  36010. }();
  36011. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  36012. var baseAxis = coordSys.getBaseAxis();
  36013. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36014. var valueStart = getValueStart(valueAxis, valueOrigin);
  36015. var baseAxisDim = baseAxis.dim;
  36016. var valueAxisDim = valueAxis.dim;
  36017. var valueDim = data.mapDimension(valueAxisDim);
  36018. var baseDim = data.mapDimension(baseAxisDim);
  36019. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  36020. var dims = map(coordSys.dimensions, function (coordDim) {
  36021. return data.mapDimension(coordDim);
  36022. });
  36023. var stacked = false;
  36024. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36025. if (isDimensionStacked(data, dims[0]
  36026. /* , dims[1] */
  36027. )) {
  36028. // jshint ignore:line
  36029. stacked = true;
  36030. dims[0] = stackResultDim;
  36031. }
  36032. if (isDimensionStacked(data, dims[1]
  36033. /* , dims[0] */
  36034. )) {
  36035. // jshint ignore:line
  36036. stacked = true;
  36037. dims[1] = stackResultDim;
  36038. }
  36039. return {
  36040. dataDimsForPoint: dims,
  36041. valueStart: valueStart,
  36042. valueAxisDim: valueAxisDim,
  36043. baseAxisDim: baseAxisDim,
  36044. stacked: !!stacked,
  36045. valueDim: valueDim,
  36046. baseDim: baseDim,
  36047. baseDataOffset: baseDataOffset,
  36048. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  36049. };
  36050. }
  36051. function getValueStart(valueAxis, valueOrigin) {
  36052. var valueStart = 0;
  36053. var extent = valueAxis.scale.getExtent();
  36054. if (valueOrigin === 'start') {
  36055. valueStart = extent[0];
  36056. } else if (valueOrigin === 'end') {
  36057. valueStart = extent[1];
  36058. } // If origin is specified as a number, use it as
  36059. // valueStart directly
  36060. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  36061. valueStart = valueOrigin;
  36062. } // auto
  36063. else {
  36064. // Both positive
  36065. if (extent[0] > 0) {
  36066. valueStart = extent[0];
  36067. } // Both negative
  36068. else if (extent[1] < 0) {
  36069. valueStart = extent[1];
  36070. } // If is one positive, and one negative, onZero shall be true
  36071. }
  36072. return valueStart;
  36073. }
  36074. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  36075. var value = NaN;
  36076. if (dataCoordInfo.stacked) {
  36077. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  36078. }
  36079. if (isNaN(value)) {
  36080. value = dataCoordInfo.valueStart;
  36081. }
  36082. var baseDataOffset = dataCoordInfo.baseDataOffset;
  36083. var stackedData = [];
  36084. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  36085. stackedData[1 - baseDataOffset] = value;
  36086. return coordSys.dataToPoint(stackedData);
  36087. }
  36088. function diffData(oldData, newData) {
  36089. var diffResult = [];
  36090. newData.diff(oldData).add(function (idx) {
  36091. diffResult.push({
  36092. cmd: '+',
  36093. idx: idx
  36094. });
  36095. }).update(function (newIdx, oldIdx) {
  36096. diffResult.push({
  36097. cmd: '=',
  36098. idx: oldIdx,
  36099. idx1: newIdx
  36100. });
  36101. }).remove(function (idx) {
  36102. diffResult.push({
  36103. cmd: '-',
  36104. idx: idx
  36105. });
  36106. }).execute();
  36107. return diffResult;
  36108. }
  36109. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  36110. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  36111. // let oldIdList = oldData.mapArray(oldData.getId);
  36112. // convertToIntId(newIdList, oldIdList);
  36113. // // FIXME One data ?
  36114. // diff = arrayDiff(oldIdList, newIdList);
  36115. var currPoints = [];
  36116. var nextPoints = []; // Points for stacking base line
  36117. var currStackedPoints = [];
  36118. var nextStackedPoints = [];
  36119. var status = [];
  36120. var sortedIndices = [];
  36121. var rawIndices = [];
  36122. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  36123. var oldPoints = oldData.getLayout('points') || [];
  36124. var newPoints = newData.getLayout('points') || [];
  36125. for (var i = 0; i < diff.length; i++) {
  36126. var diffItem = diff[i];
  36127. var pointAdded = true;
  36128. var oldIdx2 = void 0;
  36129. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  36130. // Which is in case remvoing or add more than one data in the tail or head
  36131. switch (diffItem.cmd) {
  36132. case '=':
  36133. oldIdx2 = diffItem.idx * 2;
  36134. newIdx2 = diffItem.idx1 * 2;
  36135. var currentX = oldPoints[oldIdx2];
  36136. var currentY = oldPoints[oldIdx2 + 1];
  36137. var nextX = newPoints[newIdx2];
  36138. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  36139. if (isNaN(currentX) || isNaN(currentY)) {
  36140. currentX = nextX;
  36141. currentY = nextY;
  36142. }
  36143. currPoints.push(currentX, currentY);
  36144. nextPoints.push(nextX, nextY);
  36145. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  36146. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  36147. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  36148. break;
  36149. case '+':
  36150. var newIdx = diffItem.idx;
  36151. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  36152. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  36153. newIdx2 = newIdx * 2;
  36154. currPoints.push(oldPt[0], oldPt[1]);
  36155. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  36156. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  36157. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  36158. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  36159. rawIndices.push(newData.getRawIndex(newIdx));
  36160. break;
  36161. case '-':
  36162. pointAdded = false;
  36163. } // Original indices
  36164. if (pointAdded) {
  36165. status.push(diffItem);
  36166. sortedIndices.push(sortedIndices.length);
  36167. }
  36168. } // Diff result may be crossed if all items are changed
  36169. // Sort by data index
  36170. sortedIndices.sort(function (a, b) {
  36171. return rawIndices[a] - rawIndices[b];
  36172. });
  36173. var len = currPoints.length;
  36174. var sortedCurrPoints = createFloat32Array(len);
  36175. var sortedNextPoints = createFloat32Array(len);
  36176. var sortedCurrStackedPoints = createFloat32Array(len);
  36177. var sortedNextStackedPoints = createFloat32Array(len);
  36178. var sortedStatus = [];
  36179. for (var i = 0; i < sortedIndices.length; i++) {
  36180. var idx = sortedIndices[i];
  36181. var i2 = i * 2;
  36182. var idx2 = idx * 2;
  36183. sortedCurrPoints[i2] = currPoints[idx2];
  36184. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  36185. sortedNextPoints[i2] = nextPoints[idx2];
  36186. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  36187. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  36188. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  36189. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  36190. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  36191. sortedStatus[i] = status[idx];
  36192. }
  36193. return {
  36194. current: sortedCurrPoints,
  36195. next: sortedNextPoints,
  36196. stackedOnCurrent: sortedCurrStackedPoints,
  36197. stackedOnNext: sortedNextStackedPoints,
  36198. status: sortedStatus
  36199. };
  36200. }
  36201. var mathMin$5 = Math.min;
  36202. var mathMax$5 = Math.max;
  36203. function isPointNull(x, y) {
  36204. return isNaN(x) || isNaN(y);
  36205. }
  36206. /**
  36207. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  36208. * situations. This should be used when points are non-monotone neither in x or
  36209. * y dimension.
  36210. */
  36211. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  36212. var prevX;
  36213. var prevY;
  36214. var cpx0;
  36215. var cpy0;
  36216. var cpx1;
  36217. var cpy1;
  36218. var idx = start;
  36219. var k = 0;
  36220. for (; k < segLen; k++) {
  36221. var x = points[idx * 2];
  36222. var y = points[idx * 2 + 1];
  36223. if (idx >= allLen || idx < 0) {
  36224. break;
  36225. }
  36226. if (isPointNull(x, y)) {
  36227. if (connectNulls) {
  36228. idx += dir;
  36229. continue;
  36230. }
  36231. break;
  36232. }
  36233. if (idx === start) {
  36234. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  36235. cpx0 = x;
  36236. cpy0 = y;
  36237. } else {
  36238. var dx = x - prevX;
  36239. var dy = y - prevY; // Ignore tiny segment.
  36240. if (dx * dx + dy * dy < 0.5) {
  36241. idx += dir;
  36242. continue;
  36243. }
  36244. if (smooth > 0) {
  36245. var nextIdx = idx + dir;
  36246. var nextX = points[nextIdx * 2];
  36247. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  36248. while (nextX === x && nextY === y && k < segLen) {
  36249. k++;
  36250. nextIdx += dir;
  36251. idx += dir;
  36252. nextX = points[nextIdx * 2];
  36253. nextY = points[nextIdx * 2 + 1];
  36254. x = points[idx * 2];
  36255. y = points[idx * 2 + 1];
  36256. dx = x - prevX;
  36257. dy = y - prevY;
  36258. }
  36259. var tmpK = k + 1;
  36260. if (connectNulls) {
  36261. // Find next point not null
  36262. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  36263. tmpK++;
  36264. nextIdx += dir;
  36265. nextX = points[nextIdx * 2];
  36266. nextY = points[nextIdx * 2 + 1];
  36267. }
  36268. }
  36269. var ratioNextSeg = 0.5;
  36270. var vx = 0;
  36271. var vy = 0;
  36272. var nextCpx0 = void 0;
  36273. var nextCpy0 = void 0; // Is last point
  36274. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  36275. cpx1 = x;
  36276. cpy1 = y;
  36277. } else {
  36278. vx = nextX - prevX;
  36279. vy = nextY - prevY;
  36280. var dx0 = x - prevX;
  36281. var dx1 = nextX - x;
  36282. var dy0 = y - prevY;
  36283. var dy1 = nextY - y;
  36284. var lenPrevSeg = void 0;
  36285. var lenNextSeg = void 0;
  36286. if (smoothMonotone === 'x') {
  36287. lenPrevSeg = Math.abs(dx0);
  36288. lenNextSeg = Math.abs(dx1);
  36289. var dir_1 = vx > 0 ? 1 : -1;
  36290. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  36291. cpy1 = y;
  36292. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  36293. nextCpy0 = y;
  36294. } else if (smoothMonotone === 'y') {
  36295. lenPrevSeg = Math.abs(dy0);
  36296. lenNextSeg = Math.abs(dy1);
  36297. var dir_2 = vy > 0 ? 1 : -1;
  36298. cpx1 = x;
  36299. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  36300. nextCpx0 = x;
  36301. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  36302. } else {
  36303. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  36304. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  36305. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  36306. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  36307. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  36308. nextCpx0 = x + vx * smooth * ratioNextSeg;
  36309. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  36310. // Avoid exceeding extreme after smoothing.
  36311. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  36312. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  36313. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  36314. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  36315. vx = nextCpx0 - x;
  36316. vy = nextCpy0 - y;
  36317. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  36318. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  36319. // Avoid exceeding extreme after smoothing.
  36320. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  36321. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  36322. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  36323. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  36324. vx = x - cpx1;
  36325. vy = y - cpy1;
  36326. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  36327. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  36328. }
  36329. }
  36330. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  36331. cpx0 = nextCpx0;
  36332. cpy0 = nextCpy0;
  36333. } else {
  36334. ctx.lineTo(x, y);
  36335. }
  36336. }
  36337. prevX = x;
  36338. prevY = y;
  36339. idx += dir;
  36340. }
  36341. return k;
  36342. }
  36343. var ECPolylineShape =
  36344. /** @class */
  36345. function () {
  36346. function ECPolylineShape() {
  36347. this.smooth = 0;
  36348. this.smoothConstraint = true;
  36349. }
  36350. return ECPolylineShape;
  36351. }();
  36352. var ECPolyline =
  36353. /** @class */
  36354. function (_super) {
  36355. __extends(ECPolyline, _super);
  36356. function ECPolyline(opts) {
  36357. var _this = _super.call(this, opts) || this;
  36358. _this.type = 'ec-polyline';
  36359. return _this;
  36360. }
  36361. ECPolyline.prototype.getDefaultStyle = function () {
  36362. return {
  36363. stroke: '#000',
  36364. fill: null
  36365. };
  36366. };
  36367. ECPolyline.prototype.getDefaultShape = function () {
  36368. return new ECPolylineShape();
  36369. };
  36370. ECPolyline.prototype.buildPath = function (ctx, shape) {
  36371. var points = shape.points;
  36372. var i = 0;
  36373. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  36374. if (shape.connectNulls) {
  36375. // Must remove first and last null values avoid draw error in polygon
  36376. for (; len > 0; len--) {
  36377. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  36378. break;
  36379. }
  36380. }
  36381. for (; i < len; i++) {
  36382. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  36383. break;
  36384. }
  36385. }
  36386. }
  36387. while (i < len) {
  36388. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  36389. }
  36390. };
  36391. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  36392. if (!this.path) {
  36393. this.createPathProxy();
  36394. this.buildPath(this.path, this.shape);
  36395. }
  36396. var path = this.path;
  36397. var data = path.data;
  36398. var CMD = PathProxy.CMD;
  36399. var x0;
  36400. var y0;
  36401. var isDimX = dim === 'x';
  36402. var roots = [];
  36403. for (var i = 0; i < data.length;) {
  36404. var cmd = data[i++];
  36405. var x = void 0;
  36406. var y = void 0;
  36407. var x2 = void 0;
  36408. var y2 = void 0;
  36409. var x3 = void 0;
  36410. var y3 = void 0;
  36411. var t = void 0;
  36412. switch (cmd) {
  36413. case CMD.M:
  36414. x0 = data[i++];
  36415. y0 = data[i++];
  36416. break;
  36417. case CMD.L:
  36418. x = data[i++];
  36419. y = data[i++];
  36420. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  36421. if (t <= 1 && t >= 0) {
  36422. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  36423. return isDimX ? [xOrY, val] : [val, xOrY];
  36424. }
  36425. x0 = x;
  36426. y0 = y;
  36427. break;
  36428. case CMD.C:
  36429. x = data[i++];
  36430. y = data[i++];
  36431. x2 = data[i++];
  36432. y2 = data[i++];
  36433. x3 = data[i++];
  36434. y3 = data[i++];
  36435. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  36436. if (nRoot > 0) {
  36437. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  36438. var t_1 = roots[i_1];
  36439. if (t_1 <= 1 && t_1 >= 0) {
  36440. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  36441. return isDimX ? [xOrY, val] : [val, xOrY];
  36442. }
  36443. }
  36444. }
  36445. x0 = x3;
  36446. y0 = y3;
  36447. break;
  36448. }
  36449. }
  36450. };
  36451. return ECPolyline;
  36452. }(Path);
  36453. var ECPolygonShape =
  36454. /** @class */
  36455. function (_super) {
  36456. __extends(ECPolygonShape, _super);
  36457. function ECPolygonShape() {
  36458. return _super !== null && _super.apply(this, arguments) || this;
  36459. }
  36460. return ECPolygonShape;
  36461. }(ECPolylineShape);
  36462. var ECPolygon =
  36463. /** @class */
  36464. function (_super) {
  36465. __extends(ECPolygon, _super);
  36466. function ECPolygon(opts) {
  36467. var _this = _super.call(this, opts) || this;
  36468. _this.type = 'ec-polygon';
  36469. return _this;
  36470. }
  36471. ECPolygon.prototype.getDefaultShape = function () {
  36472. return new ECPolygonShape();
  36473. };
  36474. ECPolygon.prototype.buildPath = function (ctx, shape) {
  36475. var points = shape.points;
  36476. var stackedOnPoints = shape.stackedOnPoints;
  36477. var i = 0;
  36478. var len = points.length / 2;
  36479. var smoothMonotone = shape.smoothMonotone;
  36480. if (shape.connectNulls) {
  36481. // Must remove first and last null values avoid draw error in polygon
  36482. for (; len > 0; len--) {
  36483. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  36484. break;
  36485. }
  36486. }
  36487. for (; i < len; i++) {
  36488. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  36489. break;
  36490. }
  36491. }
  36492. }
  36493. while (i < len) {
  36494. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  36495. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  36496. i += k + 1;
  36497. ctx.closePath();
  36498. }
  36499. };
  36500. return ECPolygon;
  36501. }(Path);
  36502. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  36503. var rect = cartesian.getArea();
  36504. var x = rect.x;
  36505. var y = rect.y;
  36506. var width = rect.width;
  36507. var height = rect.height;
  36508. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  36509. x -= lineWidth / 2;
  36510. y -= lineWidth / 2;
  36511. width += lineWidth;
  36512. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  36513. x = Math.floor(x);
  36514. width = Math.round(width);
  36515. var clipPath = new Rect({
  36516. shape: {
  36517. x: x,
  36518. y: y,
  36519. width: width,
  36520. height: height
  36521. }
  36522. });
  36523. if (hasAnimation) {
  36524. var baseAxis = cartesian.getBaseAxis();
  36525. var isHorizontal = baseAxis.isHorizontal();
  36526. var isAxisInversed = baseAxis.inverse;
  36527. if (isHorizontal) {
  36528. if (isAxisInversed) {
  36529. clipPath.shape.x += width;
  36530. }
  36531. clipPath.shape.width = 0;
  36532. } else {
  36533. if (!isAxisInversed) {
  36534. clipPath.shape.y += height;
  36535. }
  36536. clipPath.shape.height = 0;
  36537. }
  36538. var duringCb = isFunction(during) ? function (percent) {
  36539. during(percent, clipPath);
  36540. } : null;
  36541. initProps(clipPath, {
  36542. shape: {
  36543. width: width,
  36544. height: height,
  36545. x: x,
  36546. y: y
  36547. }
  36548. }, seriesModel, null, done, duringCb);
  36549. }
  36550. return clipPath;
  36551. }
  36552. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  36553. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  36554. var r0 = round(sectorArea.r0, 1);
  36555. var r = round(sectorArea.r, 1);
  36556. var clipPath = new Sector({
  36557. shape: {
  36558. cx: round(polar.cx, 1),
  36559. cy: round(polar.cy, 1),
  36560. r0: r0,
  36561. r: r,
  36562. startAngle: sectorArea.startAngle,
  36563. endAngle: sectorArea.endAngle,
  36564. clockwise: sectorArea.clockwise
  36565. }
  36566. });
  36567. if (hasAnimation) {
  36568. var isRadial = polar.getBaseAxis().dim === 'angle';
  36569. if (isRadial) {
  36570. clipPath.shape.endAngle = sectorArea.startAngle;
  36571. } else {
  36572. clipPath.shape.r = r0;
  36573. }
  36574. initProps(clipPath, {
  36575. shape: {
  36576. endAngle: sectorArea.endAngle,
  36577. r: r
  36578. }
  36579. }, seriesModel);
  36580. }
  36581. return clipPath;
  36582. }
  36583. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  36584. if (!coordSys) {
  36585. return null;
  36586. } else if (coordSys.type === 'polar') {
  36587. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  36588. } else if (coordSys.type === 'cartesian2d') {
  36589. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  36590. }
  36591. return null;
  36592. }
  36593. /*
  36594. * Licensed to the Apache Software Foundation (ASF) under one
  36595. * or more contributor license agreements. See the NOTICE file
  36596. * distributed with this work for additional information
  36597. * regarding copyright ownership. The ASF licenses this file
  36598. * to you under the Apache License, Version 2.0 (the
  36599. * "License"); you may not use this file except in compliance
  36600. * with the License. You may obtain a copy of the License at
  36601. *
  36602. * http://www.apache.org/licenses/LICENSE-2.0
  36603. *
  36604. * Unless required by applicable law or agreed to in writing,
  36605. * software distributed under the License is distributed on an
  36606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36607. * KIND, either express or implied. See the License for the
  36608. * specific language governing permissions and limitations
  36609. * under the License.
  36610. */
  36611. /**
  36612. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36613. */
  36614. /*
  36615. * Licensed to the Apache Software Foundation (ASF) under one
  36616. * or more contributor license agreements. See the NOTICE file
  36617. * distributed with this work for additional information
  36618. * regarding copyright ownership. The ASF licenses this file
  36619. * to you under the Apache License, Version 2.0 (the
  36620. * "License"); you may not use this file except in compliance
  36621. * with the License. You may obtain a copy of the License at
  36622. *
  36623. * http://www.apache.org/licenses/LICENSE-2.0
  36624. *
  36625. * Unless required by applicable law or agreed to in writing,
  36626. * software distributed under the License is distributed on an
  36627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36628. * KIND, either express or implied. See the License for the
  36629. * specific language governing permissions and limitations
  36630. * under the License.
  36631. */
  36632. function isCoordinateSystemType(coordSys, type) {
  36633. return coordSys.type === type;
  36634. }
  36635. function isPointsSame(points1, points2) {
  36636. if (points1.length !== points2.length) {
  36637. return;
  36638. }
  36639. for (var i = 0; i < points1.length; i++) {
  36640. if (points1[i] !== points2[i]) {
  36641. return;
  36642. }
  36643. }
  36644. return true;
  36645. }
  36646. function bboxFromPoints(points) {
  36647. var minX = Infinity;
  36648. var minY = Infinity;
  36649. var maxX = -Infinity;
  36650. var maxY = -Infinity;
  36651. for (var i = 0; i < points.length;) {
  36652. var x = points[i++];
  36653. var y = points[i++];
  36654. if (!isNaN(x)) {
  36655. minX = Math.min(x, minX);
  36656. maxX = Math.max(x, maxX);
  36657. }
  36658. if (!isNaN(y)) {
  36659. minY = Math.min(y, minY);
  36660. maxY = Math.max(y, maxY);
  36661. }
  36662. }
  36663. return [[minX, minY], [maxX, maxY]];
  36664. }
  36665. function getBoundingDiff(points1, points2) {
  36666. var _a = bboxFromPoints(points1),
  36667. min1 = _a[0],
  36668. max1 = _a[1];
  36669. var _b = bboxFromPoints(points2),
  36670. min2 = _b[0],
  36671. max2 = _b[1]; // Get a max value from each corner of two boundings.
  36672. 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]));
  36673. }
  36674. function getSmooth(smooth) {
  36675. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  36676. }
  36677. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  36678. if (!dataCoordInfo.valueDim) {
  36679. return [];
  36680. }
  36681. var len = data.count();
  36682. var points = createFloat32Array(len * 2);
  36683. for (var idx = 0; idx < len; idx++) {
  36684. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  36685. points[idx * 2] = pt[0];
  36686. points[idx * 2 + 1] = pt[1];
  36687. }
  36688. return points;
  36689. }
  36690. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  36691. var baseAxis = coordSys.getBaseAxis();
  36692. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  36693. var stepPoints = [];
  36694. var i = 0;
  36695. var stepPt = [];
  36696. var pt = [];
  36697. var nextPt = [];
  36698. var filteredPoints = [];
  36699. if (connectNulls) {
  36700. for (i = 0; i < points.length; i += 2) {
  36701. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  36702. filteredPoints.push(points[i], points[i + 1]);
  36703. }
  36704. }
  36705. points = filteredPoints;
  36706. }
  36707. for (i = 0; i < points.length - 2; i += 2) {
  36708. nextPt[0] = points[i + 2];
  36709. nextPt[1] = points[i + 3];
  36710. pt[0] = points[i];
  36711. pt[1] = points[i + 1];
  36712. stepPoints.push(pt[0], pt[1]);
  36713. switch (stepTurnAt) {
  36714. case 'end':
  36715. stepPt[baseIndex] = nextPt[baseIndex];
  36716. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  36717. stepPoints.push(stepPt[0], stepPt[1]);
  36718. break;
  36719. case 'middle':
  36720. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  36721. var stepPt2 = [];
  36722. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  36723. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  36724. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  36725. stepPoints.push(stepPt[0], stepPt[1]);
  36726. stepPoints.push(stepPt2[0], stepPt2[1]);
  36727. break;
  36728. default:
  36729. // default is start
  36730. stepPt[baseIndex] = pt[baseIndex];
  36731. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  36732. stepPoints.push(stepPt[0], stepPt[1]);
  36733. }
  36734. } // Last points
  36735. stepPoints.push(points[i++], points[i++]);
  36736. return stepPoints;
  36737. }
  36738. /**
  36739. * Clip color stops to edge. Avoid creating too large gradients.
  36740. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  36741. *
  36742. * The stops has been sorted from small to large.
  36743. */
  36744. function clipColorStops(colorStops, maxSize) {
  36745. var newColorStops = [];
  36746. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  36747. var prevOutOfRangeColorStop;
  36748. var prevInRangeColorStop;
  36749. function lerpStop(stop0, stop1, clippedCoord) {
  36750. var coord0 = stop0.coord;
  36751. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  36752. var color = lerp$1(p, [stop0.color, stop1.color]);
  36753. return {
  36754. coord: clippedCoord,
  36755. color: color
  36756. };
  36757. }
  36758. for (var i = 0; i < len; i++) {
  36759. var stop_1 = colorStops[i];
  36760. var coord = stop_1.coord;
  36761. if (coord < 0) {
  36762. prevOutOfRangeColorStop = stop_1;
  36763. } else if (coord > maxSize) {
  36764. if (prevInRangeColorStop) {
  36765. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  36766. } else if (prevOutOfRangeColorStop) {
  36767. // If there are two stops and coord range is between these two stops
  36768. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  36769. } // All following stop will be out of range. So just ignore them.
  36770. break;
  36771. } else {
  36772. if (prevOutOfRangeColorStop) {
  36773. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  36774. prevOutOfRangeColorStop = null;
  36775. }
  36776. newColorStops.push(stop_1);
  36777. prevInRangeColorStop = stop_1;
  36778. }
  36779. }
  36780. return newColorStops;
  36781. }
  36782. function getVisualGradient(data, coordSys, api) {
  36783. var visualMetaList = data.getVisual('visualMeta');
  36784. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  36785. // When data.count() is 0, gradient range can not be calculated.
  36786. return;
  36787. }
  36788. if (coordSys.type !== 'cartesian2d') {
  36789. if ("development" !== 'production') {
  36790. console.warn('Visual map on line style is only supported on cartesian2d.');
  36791. }
  36792. return;
  36793. }
  36794. var coordDim;
  36795. var visualMeta;
  36796. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  36797. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  36798. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  36799. if (coordDim === 'x' || coordDim === 'y') {
  36800. visualMeta = visualMetaList[i];
  36801. break;
  36802. }
  36803. }
  36804. if (!visualMeta) {
  36805. if ("development" !== 'production') {
  36806. console.warn('Visual map on line style only support x or y dimension.');
  36807. }
  36808. return;
  36809. } // If the area to be rendered is bigger than area defined by LinearGradient,
  36810. // the canvas spec prescribes that the color of the first stop and the last
  36811. // stop should be used. But if two stops are added at offset 0, in effect
  36812. // browsers use the color of the second stop to render area outside
  36813. // LinearGradient. So we can only infinitesimally extend area defined in
  36814. // LinearGradient to render `outerColors`.
  36815. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  36816. var colorStops = map(visualMeta.stops, function (stop) {
  36817. // offset will be calculated later.
  36818. return {
  36819. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  36820. color: stop.color
  36821. };
  36822. });
  36823. var stopLen = colorStops.length;
  36824. var outerColors = visualMeta.outerColors.slice();
  36825. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  36826. colorStops.reverse();
  36827. outerColors.reverse();
  36828. }
  36829. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  36830. var inRangeStopLen = colorStopsInRange.length;
  36831. if (!inRangeStopLen && stopLen) {
  36832. // All stops are out of range. All will be the same color.
  36833. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  36834. }
  36835. var tinyExtent = 10; // Arbitrary value: 10px
  36836. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  36837. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  36838. var coordSpan = maxCoord - minCoord;
  36839. if (coordSpan < 1e-3) {
  36840. return 'transparent';
  36841. }
  36842. each(colorStopsInRange, function (stop) {
  36843. stop.offset = (stop.coord - minCoord) / coordSpan;
  36844. });
  36845. colorStopsInRange.push({
  36846. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  36847. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  36848. color: outerColors[1] || 'transparent'
  36849. });
  36850. colorStopsInRange.unshift({
  36851. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  36852. color: outerColors[0] || 'transparent'
  36853. });
  36854. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  36855. gradient[coordDim] = minCoord;
  36856. gradient[coordDim + '2'] = maxCoord;
  36857. return gradient;
  36858. }
  36859. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  36860. var showAllSymbol = seriesModel.get('showAllSymbol');
  36861. var isAuto = showAllSymbol === 'auto';
  36862. if (showAllSymbol && !isAuto) {
  36863. return;
  36864. }
  36865. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  36866. if (!categoryAxis) {
  36867. return;
  36868. } // Note that category label interval strategy might bring some weird effect
  36869. // in some scenario: users may wonder why some of the symbols are not
  36870. // displayed. So we show all symbols as possible as we can.
  36871. if (isAuto // Simplify the logic, do not determine label overlap here.
  36872. && canShowAllSymbolForCategory(categoryAxis, data)) {
  36873. return;
  36874. } // Otherwise follow the label interval strategy on category axis.
  36875. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  36876. var labelMap = {};
  36877. each(categoryAxis.getViewLabels(), function (labelItem) {
  36878. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  36879. labelMap[ordinalNumber] = 1;
  36880. });
  36881. return function (dataIndex) {
  36882. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  36883. };
  36884. }
  36885. function canShowAllSymbolForCategory(categoryAxis, data) {
  36886. // In most cases, line is monotonous on category axis, and the label size
  36887. // is close with each other. So we check the symbol size and some of the
  36888. // label size alone with the category axis to estimate whether all symbol
  36889. // can be shown without overlap.
  36890. var axisExtent = categoryAxis.getExtent();
  36891. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  36892. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  36893. // Sampling some points, max 5.
  36894. var dataLen = data.count();
  36895. var step = Math.max(1, Math.round(dataLen / 5));
  36896. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  36897. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  36898. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  36899. * 1.5 > availSize) {
  36900. return false;
  36901. }
  36902. }
  36903. return true;
  36904. }
  36905. function isPointNull$1(x, y) {
  36906. return isNaN(x) || isNaN(y);
  36907. }
  36908. function getLastIndexNotNull(points) {
  36909. var len = points.length / 2;
  36910. for (; len > 0; len--) {
  36911. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  36912. break;
  36913. }
  36914. }
  36915. return len - 1;
  36916. }
  36917. function getPointAtIndex(points, idx) {
  36918. return [points[idx * 2], points[idx * 2 + 1]];
  36919. }
  36920. function getIndexRange(points, xOrY, dim) {
  36921. var len = points.length / 2;
  36922. var dimIdx = dim === 'x' ? 0 : 1;
  36923. var a;
  36924. var b;
  36925. var prevIndex = 0;
  36926. var nextIndex = -1;
  36927. for (var i = 0; i < len; i++) {
  36928. b = points[i * 2 + dimIdx];
  36929. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  36930. continue;
  36931. }
  36932. if (i === 0) {
  36933. a = b;
  36934. continue;
  36935. }
  36936. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  36937. nextIndex = i;
  36938. break;
  36939. }
  36940. prevIndex = i;
  36941. a = b;
  36942. }
  36943. return {
  36944. range: [prevIndex, nextIndex],
  36945. t: (xOrY - a) / (b - a)
  36946. };
  36947. }
  36948. function anyStateShowEndLabel(seriesModel) {
  36949. if (seriesModel.get(['endLabel', 'show'])) {
  36950. return true;
  36951. }
  36952. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  36953. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  36954. return true;
  36955. }
  36956. }
  36957. return false;
  36958. }
  36959. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  36960. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  36961. var endLabelModel_1 = seriesModel.getModel('endLabel');
  36962. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  36963. var data_1 = seriesModel.getData();
  36964. var labelAnimationRecord_1 = {
  36965. lastFrameIndex: 0
  36966. };
  36967. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  36968. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  36969. } : null;
  36970. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  36971. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  36972. var endLabel = lineView._endLabel;
  36973. if (endLabel && hasAnimation) {
  36974. if (labelAnimationRecord_1.originalX != null) {
  36975. endLabel.attr({
  36976. x: labelAnimationRecord_1.originalX,
  36977. y: labelAnimationRecord_1.originalY
  36978. });
  36979. }
  36980. }
  36981. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  36982. if (!seriesModel.get('clip', true)) {
  36983. var rectShape = clipPath.shape;
  36984. var expandSize = Math.max(rectShape.width, rectShape.height);
  36985. if (isHorizontal) {
  36986. rectShape.y -= expandSize;
  36987. rectShape.height += expandSize * 2;
  36988. } else {
  36989. rectShape.x -= expandSize;
  36990. rectShape.width += expandSize * 2;
  36991. }
  36992. } // Set to the final frame. To make sure label layout is right.
  36993. if (during) {
  36994. during(1, clipPath);
  36995. }
  36996. return clipPath;
  36997. } else {
  36998. if ("development" !== 'production') {
  36999. if (seriesModel.get(['endLabel', 'show'])) {
  37000. console.warn('endLabel is not supported for lines in polar systems.');
  37001. }
  37002. }
  37003. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37004. }
  37005. }
  37006. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  37007. var baseAxis = coordSys.getBaseAxis();
  37008. var isHorizontal = baseAxis.isHorizontal();
  37009. var isBaseInversed = baseAxis.inverse;
  37010. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  37011. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  37012. return {
  37013. normal: {
  37014. align: endLabelModel.get('align') || align,
  37015. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  37016. }
  37017. };
  37018. }
  37019. var LineView =
  37020. /** @class */
  37021. function (_super) {
  37022. __extends(LineView, _super);
  37023. function LineView() {
  37024. return _super !== null && _super.apply(this, arguments) || this;
  37025. }
  37026. LineView.prototype.init = function () {
  37027. var lineGroup = new Group();
  37028. var symbolDraw = new SymbolDraw();
  37029. this.group.add(symbolDraw.group);
  37030. this._symbolDraw = symbolDraw;
  37031. this._lineGroup = lineGroup;
  37032. };
  37033. LineView.prototype.render = function (seriesModel, ecModel, api) {
  37034. var _this = this;
  37035. var coordSys = seriesModel.coordinateSystem;
  37036. var group = this.group;
  37037. var data = seriesModel.getData();
  37038. var lineStyleModel = seriesModel.getModel('lineStyle');
  37039. var areaStyleModel = seriesModel.getModel('areaStyle');
  37040. var points = data.getLayout('points') || [];
  37041. var isCoordSysPolar = coordSys.type === 'polar';
  37042. var prevCoordSys = this._coordSys;
  37043. var symbolDraw = this._symbolDraw;
  37044. var polyline = this._polyline;
  37045. var polygon = this._polygon;
  37046. var lineGroup = this._lineGroup;
  37047. var hasAnimation = !ecModel.ssr && seriesModel.isAnimationEnabled();
  37048. var isAreaChart = !areaStyleModel.isEmpty();
  37049. var valueOrigin = areaStyleModel.get('origin');
  37050. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  37051. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  37052. var showSymbol = seriesModel.get('showSymbol');
  37053. var connectNulls = seriesModel.get('connectNulls');
  37054. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  37055. var oldData = this._data;
  37056. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  37057. if (el.__temp) {
  37058. group.remove(el);
  37059. oldData.setItemGraphicEl(idx, null);
  37060. }
  37061. }); // Remove previous created symbols if showSymbol changed to false
  37062. if (!showSymbol) {
  37063. symbolDraw.remove();
  37064. }
  37065. group.add(lineGroup); // FIXME step not support polar
  37066. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  37067. var clipShapeForSymbol;
  37068. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  37069. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  37070. // See #7913 and `test/dataZoom-clip.html`.
  37071. if (clipShapeForSymbol.width != null) {
  37072. clipShapeForSymbol.x -= 0.1;
  37073. clipShapeForSymbol.y -= 0.1;
  37074. clipShapeForSymbol.width += 0.2;
  37075. clipShapeForSymbol.height += 0.2;
  37076. } else if (clipShapeForSymbol.r0) {
  37077. clipShapeForSymbol.r0 -= 0.5;
  37078. clipShapeForSymbol.r += 0.5;
  37079. }
  37080. }
  37081. this._clipShapeForSymbol = clipShapeForSymbol;
  37082. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  37083. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  37084. showSymbol && symbolDraw.updateData(data, {
  37085. isIgnore: isIgnoreFunc,
  37086. clipShape: clipShapeForSymbol,
  37087. disableAnimation: true,
  37088. getSymbolPoint: function (idx) {
  37089. return [points[idx * 2], points[idx * 2 + 1]];
  37090. }
  37091. });
  37092. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  37093. if (step) {
  37094. // TODO If stacked series is not step
  37095. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  37096. if (stackedOnPoints) {
  37097. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  37098. }
  37099. }
  37100. polyline = this._newPolyline(points);
  37101. if (isAreaChart) {
  37102. polygon = this._newPolygon(points, stackedOnPoints);
  37103. } // If areaStyle is removed
  37104. else if (polygon) {
  37105. lineGroup.remove(polygon);
  37106. polygon = this._polygon = null;
  37107. } // NOTE: Must update _endLabel before setClipPath.
  37108. if (!isCoordSysPolar) {
  37109. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  37110. }
  37111. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  37112. } else {
  37113. if (isAreaChart && !polygon) {
  37114. // If areaStyle is added
  37115. polygon = this._newPolygon(points, stackedOnPoints);
  37116. } else if (polygon && !isAreaChart) {
  37117. // If areaStyle is removed
  37118. lineGroup.remove(polygon);
  37119. polygon = this._polygon = null;
  37120. } // NOTE: Must update _endLabel before setClipPath.
  37121. if (!isCoordSysPolar) {
  37122. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  37123. } // Update clipPath
  37124. var oldClipPath = lineGroup.getClipPath();
  37125. if (oldClipPath) {
  37126. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  37127. initProps(oldClipPath, {
  37128. shape: newClipPath.shape
  37129. }, seriesModel);
  37130. } else {
  37131. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  37132. } // Always update, or it is wrong in the case turning on legend
  37133. // because points are not changed.
  37134. showSymbol && symbolDraw.updateData(data, {
  37135. isIgnore: isIgnoreFunc,
  37136. clipShape: clipShapeForSymbol,
  37137. disableAnimation: true,
  37138. getSymbolPoint: function (idx) {
  37139. return [points[idx * 2], points[idx * 2 + 1]];
  37140. }
  37141. }); // In the case data zoom triggered refreshing frequently
  37142. // Data may not change if line has a category axis. So it should animate nothing.
  37143. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  37144. if (hasAnimation) {
  37145. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  37146. } else {
  37147. // Not do it in update with animation
  37148. if (step) {
  37149. // TODO If stacked series is not step
  37150. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  37151. if (stackedOnPoints) {
  37152. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  37153. }
  37154. }
  37155. polyline.setShape({
  37156. points: points
  37157. });
  37158. polygon && polygon.setShape({
  37159. points: points,
  37160. stackedOnPoints: stackedOnPoints
  37161. });
  37162. }
  37163. }
  37164. }
  37165. var emphasisModel = seriesModel.getModel('emphasis');
  37166. var focus = emphasisModel.get('focus');
  37167. var blurScope = emphasisModel.get('blurScope');
  37168. var emphasisDisabled = emphasisModel.get('disabled');
  37169. polyline.useStyle(defaults( // Use color in lineStyle first
  37170. lineStyleModel.getLineStyle(), {
  37171. fill: 'none',
  37172. stroke: visualColor,
  37173. lineJoin: 'bevel'
  37174. }));
  37175. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  37176. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  37177. var emphasisLineStyle = polyline.getState('emphasis').style;
  37178. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  37179. } // Needs seriesIndex for focus
  37180. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  37181. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  37182. var smooth = getSmooth(seriesModel.get('smooth'));
  37183. var smoothMonotone = seriesModel.get('smoothMonotone');
  37184. polyline.setShape({
  37185. smooth: smooth,
  37186. smoothMonotone: smoothMonotone,
  37187. connectNulls: connectNulls
  37188. });
  37189. if (polygon) {
  37190. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  37191. var stackedOnSmooth = 0;
  37192. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  37193. fill: visualColor,
  37194. opacity: 0.7,
  37195. lineJoin: 'bevel',
  37196. decal: data.getVisual('style').decal
  37197. }));
  37198. if (stackedOnSeries) {
  37199. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  37200. }
  37201. polygon.setShape({
  37202. smooth: smooth,
  37203. stackedOnSmooth: stackedOnSmooth,
  37204. smoothMonotone: smoothMonotone,
  37205. connectNulls: connectNulls
  37206. });
  37207. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  37208. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  37209. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  37210. }
  37211. var changePolyState = function (toState) {
  37212. _this._changePolyState(toState);
  37213. };
  37214. data.eachItemGraphicEl(function (el) {
  37215. // Switch polyline / polygon state if element changed its state.
  37216. el && (el.onHoverStateChange = changePolyState);
  37217. });
  37218. this._polyline.onHoverStateChange = changePolyState;
  37219. this._data = data; // Save the coordinate system for transition animation when data changed
  37220. this._coordSys = coordSys;
  37221. this._stackedOnPoints = stackedOnPoints;
  37222. this._points = points;
  37223. this._step = step;
  37224. this._valueOrigin = valueOrigin;
  37225. if (seriesModel.get('triggerLineEvent')) {
  37226. this.packEventData(seriesModel, polyline);
  37227. polygon && this.packEventData(seriesModel, polygon);
  37228. }
  37229. };
  37230. LineView.prototype.packEventData = function (seriesModel, el) {
  37231. getECData(el).eventData = {
  37232. componentType: 'series',
  37233. componentSubType: 'line',
  37234. componentIndex: seriesModel.componentIndex,
  37235. seriesIndex: seriesModel.seriesIndex,
  37236. seriesName: seriesModel.name,
  37237. seriesType: 'line'
  37238. };
  37239. };
  37240. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  37241. var data = seriesModel.getData();
  37242. var dataIndex = queryDataIndex(data, payload);
  37243. this._changePolyState('emphasis');
  37244. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  37245. var points = data.getLayout('points');
  37246. var symbol = data.getItemGraphicEl(dataIndex);
  37247. if (!symbol) {
  37248. // Create a temporary symbol if it is not exists
  37249. var x = points[dataIndex * 2];
  37250. var y = points[dataIndex * 2 + 1];
  37251. if (isNaN(x) || isNaN(y)) {
  37252. // Null data
  37253. return;
  37254. } // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  37255. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  37256. return;
  37257. }
  37258. var zlevel = seriesModel.get('zlevel') || 0;
  37259. var z = seriesModel.get('z') || 0;
  37260. symbol = new Symbol(data, dataIndex);
  37261. symbol.x = x;
  37262. symbol.y = y;
  37263. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  37264. var symbolLabel = symbol.getSymbolPath().getTextContent();
  37265. if (symbolLabel) {
  37266. symbolLabel.zlevel = zlevel;
  37267. symbolLabel.z = z;
  37268. symbolLabel.z2 = this._polyline.z2 + 1;
  37269. }
  37270. symbol.__temp = true;
  37271. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  37272. symbol.stopSymbolAnimation(true);
  37273. this.group.add(symbol);
  37274. }
  37275. symbol.highlight();
  37276. } else {
  37277. // Highlight whole series
  37278. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  37279. }
  37280. };
  37281. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  37282. var data = seriesModel.getData();
  37283. var dataIndex = queryDataIndex(data, payload);
  37284. this._changePolyState('normal');
  37285. if (dataIndex != null && dataIndex >= 0) {
  37286. var symbol = data.getItemGraphicEl(dataIndex);
  37287. if (symbol) {
  37288. if (symbol.__temp) {
  37289. data.setItemGraphicEl(dataIndex, null);
  37290. this.group.remove(symbol);
  37291. } else {
  37292. symbol.downplay();
  37293. }
  37294. }
  37295. } else {
  37296. // FIXME
  37297. // can not downplay completely.
  37298. // Downplay whole series
  37299. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  37300. }
  37301. };
  37302. LineView.prototype._changePolyState = function (toState) {
  37303. var polygon = this._polygon;
  37304. setStatesFlag(this._polyline, toState);
  37305. polygon && setStatesFlag(polygon, toState);
  37306. };
  37307. LineView.prototype._newPolyline = function (points) {
  37308. var polyline = this._polyline; // Remove previous created polyline
  37309. if (polyline) {
  37310. this._lineGroup.remove(polyline);
  37311. }
  37312. polyline = new ECPolyline({
  37313. shape: {
  37314. points: points
  37315. },
  37316. segmentIgnoreThreshold: 2,
  37317. z2: 10
  37318. });
  37319. this._lineGroup.add(polyline);
  37320. this._polyline = polyline;
  37321. return polyline;
  37322. };
  37323. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  37324. var polygon = this._polygon; // Remove previous created polygon
  37325. if (polygon) {
  37326. this._lineGroup.remove(polygon);
  37327. }
  37328. polygon = new ECPolygon({
  37329. shape: {
  37330. points: points,
  37331. stackedOnPoints: stackedOnPoints
  37332. },
  37333. segmentIgnoreThreshold: 2
  37334. });
  37335. this._lineGroup.add(polygon);
  37336. this._polygon = polygon;
  37337. return polygon;
  37338. };
  37339. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  37340. var isHorizontalOrRadial;
  37341. var isCoordSysPolar;
  37342. var baseAxis = coordSys.getBaseAxis();
  37343. var isAxisInverse = baseAxis.inverse;
  37344. if (coordSys.type === 'cartesian2d') {
  37345. isHorizontalOrRadial = baseAxis.isHorizontal();
  37346. isCoordSysPolar = false;
  37347. } else if (coordSys.type === 'polar') {
  37348. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37349. isCoordSysPolar = true;
  37350. }
  37351. var seriesModel = data.hostModel;
  37352. var seriesDuration = seriesModel.get('animationDuration');
  37353. if (isFunction(seriesDuration)) {
  37354. seriesDuration = seriesDuration(null);
  37355. }
  37356. var seriesDelay = seriesModel.get('animationDelay') || 0;
  37357. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  37358. data.eachItemGraphicEl(function (symbol, idx) {
  37359. var el = symbol;
  37360. if (el) {
  37361. var point = [symbol.x, symbol.y];
  37362. var start = void 0;
  37363. var end = void 0;
  37364. var current = void 0;
  37365. if (clipShape) {
  37366. if (isCoordSysPolar) {
  37367. var polarClip = clipShape;
  37368. var coord = coordSys.pointToCoord(point);
  37369. if (isHorizontalOrRadial) {
  37370. start = polarClip.startAngle;
  37371. end = polarClip.endAngle;
  37372. current = -coord[1] / 180 * Math.PI;
  37373. } else {
  37374. start = polarClip.r0;
  37375. end = polarClip.r;
  37376. current = coord[0];
  37377. }
  37378. } else {
  37379. var gridClip = clipShape;
  37380. if (isHorizontalOrRadial) {
  37381. start = gridClip.x;
  37382. end = gridClip.x + gridClip.width;
  37383. current = symbol.x;
  37384. } else {
  37385. start = gridClip.y + gridClip.height;
  37386. end = gridClip.y;
  37387. current = symbol.y;
  37388. }
  37389. }
  37390. }
  37391. var ratio = end === start ? 0 : (current - start) / (end - start);
  37392. if (isAxisInverse) {
  37393. ratio = 1 - ratio;
  37394. }
  37395. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  37396. var symbolPath = el.getSymbolPath();
  37397. var text = symbolPath.getTextContent();
  37398. el.attr({
  37399. scaleX: 0,
  37400. scaleY: 0
  37401. });
  37402. el.animateTo({
  37403. scaleX: 1,
  37404. scaleY: 1
  37405. }, {
  37406. duration: 200,
  37407. setToFinal: true,
  37408. delay: delay
  37409. });
  37410. if (text) {
  37411. text.animateFrom({
  37412. style: {
  37413. opacity: 0
  37414. }
  37415. }, {
  37416. duration: 300,
  37417. delay: delay
  37418. });
  37419. }
  37420. symbolPath.disableLabelAnimation = true;
  37421. }
  37422. });
  37423. };
  37424. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  37425. var endLabelModel = seriesModel.getModel('endLabel');
  37426. if (anyStateShowEndLabel(seriesModel)) {
  37427. var data_2 = seriesModel.getData();
  37428. var polyline = this._polyline; // series may be filtered.
  37429. var points = data_2.getLayout('points');
  37430. if (!points) {
  37431. polyline.removeTextContent();
  37432. this._endLabel = null;
  37433. return;
  37434. }
  37435. var endLabel = this._endLabel;
  37436. if (!endLabel) {
  37437. endLabel = this._endLabel = new ZRText({
  37438. z2: 200 // should be higher than item symbol
  37439. });
  37440. endLabel.ignoreClip = true;
  37441. polyline.setTextContent(this._endLabel);
  37442. polyline.disableLabelAnimation = true;
  37443. } // Find last non-NaN data to display data
  37444. var dataIndex = getLastIndexNotNull(points);
  37445. if (dataIndex >= 0) {
  37446. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  37447. inheritColor: inheritColor,
  37448. labelFetcher: seriesModel,
  37449. labelDataIndex: dataIndex,
  37450. defaultText: function (dataIndex, opt, interpolatedValue) {
  37451. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  37452. },
  37453. enableTextSetter: true
  37454. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  37455. polyline.textConfig.position = null;
  37456. }
  37457. } else if (this._endLabel) {
  37458. this._polyline.removeTextContent();
  37459. this._endLabel = null;
  37460. }
  37461. };
  37462. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  37463. var endLabel = this._endLabel;
  37464. var polyline = this._polyline;
  37465. if (endLabel) {
  37466. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  37467. // The label is not prepared at this time.
  37468. if (percent < 1 && animationRecord.originalX == null) {
  37469. animationRecord.originalX = endLabel.x;
  37470. animationRecord.originalY = endLabel.y;
  37471. }
  37472. var points = data.getLayout('points');
  37473. var seriesModel = data.hostModel;
  37474. var connectNulls = seriesModel.get('connectNulls');
  37475. var precision = endLabelModel.get('precision');
  37476. var distance = endLabelModel.get('distance') || 0;
  37477. var baseAxis = coordSys.getBaseAxis();
  37478. var isHorizontal = baseAxis.isHorizontal();
  37479. var isBaseInversed = baseAxis.inverse;
  37480. var clipShape = clipRect.shape;
  37481. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  37482. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  37483. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  37484. var dim = isHorizontal ? 'x' : 'y';
  37485. var dataIndexRange = getIndexRange(points, xOrY, dim);
  37486. var indices = dataIndexRange.range;
  37487. var diff = indices[1] - indices[0];
  37488. var value = void 0;
  37489. if (diff >= 1) {
  37490. // diff > 1 && connectNulls, which is on the null data.
  37491. if (diff > 1 && !connectNulls) {
  37492. var pt = getPointAtIndex(points, indices[0]);
  37493. endLabel.attr({
  37494. x: pt[0] + distanceX,
  37495. y: pt[1] + distanceY
  37496. });
  37497. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  37498. } else {
  37499. var pt = polyline.getPointOn(xOrY, dim);
  37500. pt && endLabel.attr({
  37501. x: pt[0] + distanceX,
  37502. y: pt[1] + distanceY
  37503. });
  37504. var startValue = seriesModel.getRawValue(indices[0]);
  37505. var endValue = seriesModel.getRawValue(indices[1]);
  37506. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  37507. }
  37508. animationRecord.lastFrameIndex = indices[0];
  37509. } else {
  37510. // If diff <= 0, which is the range is not found(Include NaN)
  37511. // Choose the first point or last point.
  37512. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  37513. var pt = getPointAtIndex(points, idx);
  37514. valueAnimation && (value = seriesModel.getRawValue(idx));
  37515. endLabel.attr({
  37516. x: pt[0] + distanceX,
  37517. y: pt[1] + distanceY
  37518. });
  37519. }
  37520. if (valueAnimation) {
  37521. labelInner(endLabel).setLabelText(value);
  37522. }
  37523. }
  37524. };
  37525. /**
  37526. * @private
  37527. */
  37528. // FIXME Two value axis
  37529. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  37530. var polyline = this._polyline;
  37531. var polygon = this._polygon;
  37532. var seriesModel = data.hostModel;
  37533. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  37534. var current = diff.current;
  37535. var stackedOnCurrent = diff.stackedOnCurrent;
  37536. var next = diff.next;
  37537. var stackedOnNext = diff.stackedOnNext;
  37538. if (step) {
  37539. // TODO If stacked series is not step
  37540. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  37541. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  37542. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  37543. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  37544. } // Don't apply animation if diff is large.
  37545. // For better result and avoid memory explosion problems like
  37546. // https://github.com/apache/incubator-echarts/issues/12229
  37547. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  37548. polyline.stopAnimation();
  37549. polyline.setShape({
  37550. points: next
  37551. });
  37552. if (polygon) {
  37553. polygon.stopAnimation();
  37554. polygon.setShape({
  37555. points: next,
  37556. stackedOnPoints: stackedOnNext
  37557. });
  37558. }
  37559. return;
  37560. }
  37561. polyline.shape.__points = diff.current;
  37562. polyline.shape.points = current;
  37563. var target = {
  37564. shape: {
  37565. points: next
  37566. }
  37567. }; // Also animate the original points.
  37568. // If points reference is changed when turning into step line.
  37569. if (diff.current !== current) {
  37570. target.shape.__points = diff.next;
  37571. } // Stop previous animation.
  37572. polyline.stopAnimation();
  37573. updateProps(polyline, target, seriesModel);
  37574. if (polygon) {
  37575. polygon.setShape({
  37576. // Reuse the points with polyline.
  37577. points: current,
  37578. stackedOnPoints: stackedOnCurrent
  37579. });
  37580. polygon.stopAnimation();
  37581. updateProps(polygon, {
  37582. shape: {
  37583. stackedOnPoints: stackedOnNext
  37584. }
  37585. }, seriesModel); // If use attr directly in updateProps.
  37586. if (polyline.shape.points !== polygon.shape.points) {
  37587. polygon.shape.points = polyline.shape.points;
  37588. }
  37589. }
  37590. var updatedDataInfo = [];
  37591. var diffStatus = diff.status;
  37592. for (var i = 0; i < diffStatus.length; i++) {
  37593. var cmd = diffStatus[i].cmd;
  37594. if (cmd === '=') {
  37595. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  37596. if (el) {
  37597. updatedDataInfo.push({
  37598. el: el,
  37599. ptIdx: i // Index of points
  37600. });
  37601. }
  37602. }
  37603. }
  37604. if (polyline.animators && polyline.animators.length) {
  37605. polyline.animators[0].during(function () {
  37606. polygon && polygon.dirtyShape();
  37607. var points = polyline.shape.__points;
  37608. for (var i = 0; i < updatedDataInfo.length; i++) {
  37609. var el = updatedDataInfo[i].el;
  37610. var offset = updatedDataInfo[i].ptIdx * 2;
  37611. el.x = points[offset];
  37612. el.y = points[offset + 1];
  37613. el.markRedraw();
  37614. }
  37615. });
  37616. }
  37617. };
  37618. LineView.prototype.remove = function (ecModel) {
  37619. var group = this.group;
  37620. var oldData = this._data;
  37621. this._lineGroup.removeAll();
  37622. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  37623. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  37624. if (el.__temp) {
  37625. group.remove(el);
  37626. oldData.setItemGraphicEl(idx, null);
  37627. }
  37628. });
  37629. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  37630. };
  37631. LineView.type = 'line';
  37632. return LineView;
  37633. }(ChartView);
  37634. function pointsLayout(seriesType, forceStoreInTypedArray) {
  37635. return {
  37636. seriesType: seriesType,
  37637. plan: createRenderPlanner(),
  37638. reset: function (seriesModel) {
  37639. var data = seriesModel.getData();
  37640. var coordSys = seriesModel.coordinateSystem;
  37641. var pipelineContext = seriesModel.pipelineContext;
  37642. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  37643. if (!coordSys) {
  37644. return;
  37645. }
  37646. var dims = map(coordSys.dimensions, function (dim) {
  37647. return data.mapDimension(dim);
  37648. }).slice(0, 2);
  37649. var dimLen = dims.length;
  37650. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  37651. if (isDimensionStacked(data, dims[0])) {
  37652. dims[0] = stackResultDim;
  37653. }
  37654. if (isDimensionStacked(data, dims[1])) {
  37655. dims[1] = stackResultDim;
  37656. }
  37657. var store = data.getStore();
  37658. var dimIdx0 = data.getDimensionIndex(dims[0]);
  37659. var dimIdx1 = data.getDimensionIndex(dims[1]);
  37660. return dimLen && {
  37661. progress: function (params, data) {
  37662. var segCount = params.end - params.start;
  37663. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  37664. var tmpIn = [];
  37665. var tmpOut = [];
  37666. for (var i = params.start, offset = 0; i < params.end; i++) {
  37667. var point = void 0;
  37668. if (dimLen === 1) {
  37669. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  37670. point = coordSys.dataToPoint(x, null, tmpOut);
  37671. } else {
  37672. tmpIn[0] = store.get(dimIdx0, i);
  37673. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  37674. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  37675. }
  37676. if (useTypedArray) {
  37677. points[offset++] = point[0];
  37678. points[offset++] = point[1];
  37679. } else {
  37680. data.setItemLayout(i, point.slice());
  37681. }
  37682. }
  37683. useTypedArray && data.setLayout('points', points);
  37684. }
  37685. };
  37686. }
  37687. };
  37688. }
  37689. var samplers = {
  37690. average: function (frame) {
  37691. var sum = 0;
  37692. var count = 0;
  37693. for (var i = 0; i < frame.length; i++) {
  37694. if (!isNaN(frame[i])) {
  37695. sum += frame[i];
  37696. count++;
  37697. }
  37698. } // Return NaN if count is 0
  37699. return count === 0 ? NaN : sum / count;
  37700. },
  37701. sum: function (frame) {
  37702. var sum = 0;
  37703. for (var i = 0; i < frame.length; i++) {
  37704. // Ignore NaN
  37705. sum += frame[i] || 0;
  37706. }
  37707. return sum;
  37708. },
  37709. max: function (frame) {
  37710. var max = -Infinity;
  37711. for (var i = 0; i < frame.length; i++) {
  37712. frame[i] > max && (max = frame[i]);
  37713. } // NaN will cause illegal axis extent.
  37714. return isFinite(max) ? max : NaN;
  37715. },
  37716. min: function (frame) {
  37717. var min = Infinity;
  37718. for (var i = 0; i < frame.length; i++) {
  37719. frame[i] < min && (min = frame[i]);
  37720. } // NaN will cause illegal axis extent.
  37721. return isFinite(min) ? min : NaN;
  37722. },
  37723. // TODO
  37724. // Median
  37725. nearest: function (frame) {
  37726. return frame[0];
  37727. }
  37728. };
  37729. var indexSampler = function (frame) {
  37730. return Math.round(frame.length / 2);
  37731. };
  37732. function dataSample(seriesType) {
  37733. return {
  37734. seriesType: seriesType,
  37735. // FIXME:TS never used, so comment it
  37736. // modifyOutputEnd: true,
  37737. reset: function (seriesModel, ecModel, api) {
  37738. var data = seriesModel.getData();
  37739. var sampling = seriesModel.get('sampling');
  37740. var coordSys = seriesModel.coordinateSystem;
  37741. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  37742. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  37743. var baseAxis = coordSys.getBaseAxis();
  37744. var valueAxis = coordSys.getOtherAxis(baseAxis);
  37745. var extent = baseAxis.getExtent();
  37746. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  37747. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  37748. var rate = Math.round(count / size);
  37749. if (isFinite(rate) && rate > 1) {
  37750. if (sampling === 'lttb') {
  37751. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  37752. }
  37753. var sampler = void 0;
  37754. if (isString(sampling)) {
  37755. sampler = samplers[sampling];
  37756. } else if (isFunction(sampling)) {
  37757. sampler = sampling;
  37758. }
  37759. if (sampler) {
  37760. // Only support sample the first dim mapped from value axis.
  37761. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  37762. }
  37763. }
  37764. }
  37765. }
  37766. };
  37767. }
  37768. function install$2(registers) {
  37769. registers.registerChartView(LineView);
  37770. registers.registerSeriesModel(LineSeriesModel);
  37771. registers.registerLayout(pointsLayout('line', true));
  37772. registers.registerVisual({
  37773. seriesType: 'line',
  37774. reset: function (seriesModel) {
  37775. var data = seriesModel.getData(); // Visual coding for legend
  37776. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  37777. if (lineStyle && !lineStyle.stroke) {
  37778. // Fill in visual should be palette color if
  37779. // has color callback
  37780. lineStyle.stroke = data.getVisual('style').fill;
  37781. }
  37782. data.setVisual('legendLineStyle', lineStyle);
  37783. }
  37784. }); // Down sample after filter
  37785. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  37786. }
  37787. var BaseBarSeriesModel =
  37788. /** @class */
  37789. function (_super) {
  37790. __extends(BaseBarSeriesModel, _super);
  37791. function BaseBarSeriesModel() {
  37792. var _this = _super !== null && _super.apply(this, arguments) || this;
  37793. _this.type = BaseBarSeriesModel.type;
  37794. return _this;
  37795. }
  37796. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  37797. return createSeriesData(null, this, {
  37798. useEncodeDefaulter: true
  37799. });
  37800. };
  37801. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  37802. var coordSys = this.coordinateSystem;
  37803. if (coordSys && coordSys.clampData) {
  37804. // PENDING if clamp ?
  37805. var clampData_1 = coordSys.clampData(value);
  37806. var pt_1 = coordSys.dataToPoint(clampData_1);
  37807. if (startingAtTick) {
  37808. each(coordSys.getAxes(), function (axis, idx) {
  37809. // If axis type is category, use tick coords instead
  37810. if (axis.type === 'category' && dims != null) {
  37811. var tickCoords = axis.getTicksCoords();
  37812. var targetTickId = clampData_1[idx]; // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  37813. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  37814. if (isEnd) {
  37815. targetTickId += 1;
  37816. } // The only contains one tick, tickCoords is
  37817. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  37818. // to the length should always be larger than 1
  37819. if (tickCoords.length < 2) {
  37820. return;
  37821. } else if (tickCoords.length === 2) {
  37822. // The left value and right value of the axis are
  37823. // the same. coord is 0 in both items. Use the max
  37824. // value of the axis as the coord
  37825. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  37826. return;
  37827. }
  37828. var leftCoord = void 0;
  37829. var coord = void 0;
  37830. var stepTickValue = 1;
  37831. for (var i = 0; i < tickCoords.length; i++) {
  37832. var tickCoord = tickCoords[i].coord; // The last item of tickCoords doesn't contain
  37833. // tickValue
  37834. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  37835. if (tickValue === targetTickId) {
  37836. coord = tickCoord;
  37837. break;
  37838. } else if (tickValue < targetTickId) {
  37839. leftCoord = tickCoord;
  37840. } else if (leftCoord != null && tickValue > targetTickId) {
  37841. coord = (tickCoord + leftCoord) / 2;
  37842. break;
  37843. }
  37844. if (i === 1) {
  37845. // Here we assume the step of category axes is
  37846. // the same
  37847. stepTickValue = tickValue - tickCoords[0].tickValue;
  37848. }
  37849. }
  37850. if (coord == null) {
  37851. if (!leftCoord) {
  37852. // targetTickId is smaller than all tick ids in the
  37853. // visible area, use the leftmost tick coord
  37854. coord = tickCoords[0].coord;
  37855. } else if (leftCoord) {
  37856. // targetTickId is larger than all tick ids in the
  37857. // visible area, use the rightmost tick coord
  37858. coord = tickCoords[tickCoords.length - 1].coord;
  37859. }
  37860. }
  37861. pt_1[idx] = axis.toGlobalCoord(coord);
  37862. }
  37863. });
  37864. } else {
  37865. var data = this.getData();
  37866. var offset = data.getLayout('offset');
  37867. var size = data.getLayout('size');
  37868. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37869. pt_1[offsetIndex] += offset + size / 2;
  37870. }
  37871. return pt_1;
  37872. }
  37873. return [NaN, NaN];
  37874. };
  37875. BaseBarSeriesModel.type = 'series.__base_bar__';
  37876. BaseBarSeriesModel.defaultOption = {
  37877. // zlevel: 0,
  37878. z: 2,
  37879. coordinateSystem: 'cartesian2d',
  37880. legendHoverLink: true,
  37881. // stack: null
  37882. // Cartesian coordinate system
  37883. // xAxisIndex: 0,
  37884. // yAxisIndex: 0,
  37885. barMinHeight: 0,
  37886. barMinAngle: 0,
  37887. // cursor: null,
  37888. large: false,
  37889. largeThreshold: 400,
  37890. progressive: 3e3,
  37891. progressiveChunkMode: 'mod'
  37892. };
  37893. return BaseBarSeriesModel;
  37894. }(SeriesModel);
  37895. SeriesModel.registerClass(BaseBarSeriesModel);
  37896. var BarSeriesModel =
  37897. /** @class */
  37898. function (_super) {
  37899. __extends(BarSeriesModel, _super);
  37900. function BarSeriesModel() {
  37901. var _this = _super !== null && _super.apply(this, arguments) || this;
  37902. _this.type = BarSeriesModel.type;
  37903. return _this;
  37904. }
  37905. BarSeriesModel.prototype.getInitialData = function () {
  37906. return createSeriesData(null, this, {
  37907. useEncodeDefaulter: true,
  37908. createInvertedIndices: !!this.get('realtimeSort', true) || null
  37909. });
  37910. };
  37911. /**
  37912. * @override
  37913. */
  37914. BarSeriesModel.prototype.getProgressive = function () {
  37915. // Do not support progressive in normal mode.
  37916. return this.get('large') ? this.get('progressive') : false;
  37917. };
  37918. /**
  37919. * @override
  37920. */
  37921. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  37922. // Do not support progressive in normal mode.
  37923. var progressiveThreshold = this.get('progressiveThreshold');
  37924. var largeThreshold = this.get('largeThreshold');
  37925. if (largeThreshold > progressiveThreshold) {
  37926. progressiveThreshold = largeThreshold;
  37927. }
  37928. return progressiveThreshold;
  37929. };
  37930. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  37931. return selectors.rect(data.getItemLayout(dataIndex));
  37932. };
  37933. BarSeriesModel.type = 'series.bar';
  37934. BarSeriesModel.dependencies = ['grid', 'polar'];
  37935. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  37936. // If clipped
  37937. // Only available on cartesian2d
  37938. clip: true,
  37939. roundCap: false,
  37940. showBackground: false,
  37941. backgroundStyle: {
  37942. color: 'rgba(180, 180, 180, 0.2)',
  37943. borderColor: null,
  37944. borderWidth: 0,
  37945. borderType: 'solid',
  37946. borderRadius: 0,
  37947. shadowBlur: 0,
  37948. shadowColor: null,
  37949. shadowOffsetX: 0,
  37950. shadowOffsetY: 0,
  37951. opacity: 1
  37952. },
  37953. select: {
  37954. itemStyle: {
  37955. borderColor: '#212121'
  37956. }
  37957. },
  37958. realtimeSort: false
  37959. });
  37960. return BarSeriesModel;
  37961. }(BaseBarSeriesModel);
  37962. /**
  37963. * Sausage: similar to sector, but have half circle on both sides
  37964. */
  37965. var SausageShape =
  37966. /** @class */
  37967. function () {
  37968. function SausageShape() {
  37969. this.cx = 0;
  37970. this.cy = 0;
  37971. this.r0 = 0;
  37972. this.r = 0;
  37973. this.startAngle = 0;
  37974. this.endAngle = Math.PI * 2;
  37975. this.clockwise = true;
  37976. }
  37977. return SausageShape;
  37978. }();
  37979. var SausagePath =
  37980. /** @class */
  37981. function (_super) {
  37982. __extends(SausagePath, _super);
  37983. function SausagePath(opts) {
  37984. var _this = _super.call(this, opts) || this;
  37985. _this.type = 'sausage';
  37986. return _this;
  37987. }
  37988. SausagePath.prototype.getDefaultShape = function () {
  37989. return new SausageShape();
  37990. };
  37991. SausagePath.prototype.buildPath = function (ctx, shape) {
  37992. var cx = shape.cx;
  37993. var cy = shape.cy;
  37994. var r0 = Math.max(shape.r0 || 0, 0);
  37995. var r = Math.max(shape.r, 0);
  37996. var dr = (r - r0) * 0.5;
  37997. var rCenter = r0 + dr;
  37998. var startAngle = shape.startAngle;
  37999. var endAngle = shape.endAngle;
  38000. var clockwise = shape.clockwise;
  38001. var PI2 = Math.PI * 2;
  38002. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  38003. if (!lessThanCircle) {
  38004. // Normalize angles
  38005. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  38006. }
  38007. var unitStartX = Math.cos(startAngle);
  38008. var unitStartY = Math.sin(startAngle);
  38009. var unitEndX = Math.cos(endAngle);
  38010. var unitEndY = Math.sin(endAngle);
  38011. if (lessThanCircle) {
  38012. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  38013. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  38014. } else {
  38015. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  38016. }
  38017. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  38018. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  38019. if (r0 !== 0) {
  38020. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  38021. } // ctx.closePath();
  38022. };
  38023. return SausagePath;
  38024. }(Path);
  38025. function createSectorCalculateTextPosition(positionMapping, opts) {
  38026. opts = opts || {};
  38027. var isRoundCap = opts.isRoundCap;
  38028. return function (out, opts, boundingRect) {
  38029. var textPosition = opts.position;
  38030. if (!textPosition || textPosition instanceof Array) {
  38031. return calculateTextPosition(out, opts, boundingRect);
  38032. }
  38033. var mappedSectorPosition = positionMapping(textPosition);
  38034. var distance = opts.distance != null ? opts.distance : 5;
  38035. var sector = this.shape;
  38036. var cx = sector.cx;
  38037. var cy = sector.cy;
  38038. var r = sector.r;
  38039. var r0 = sector.r0;
  38040. var middleR = (r + r0) / 2;
  38041. var startAngle = sector.startAngle;
  38042. var endAngle = sector.endAngle;
  38043. var middleAngle = (startAngle + endAngle) / 2;
  38044. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  38045. var mathCos = Math.cos;
  38046. var mathSin = Math.sin; // base position: top-left
  38047. var x = cx + r * mathCos(startAngle);
  38048. var y = cy + r * mathSin(startAngle);
  38049. var textAlign = 'left';
  38050. var textVerticalAlign = 'top';
  38051. switch (mappedSectorPosition) {
  38052. case 'startArc':
  38053. x = cx + (r0 - distance) * mathCos(middleAngle);
  38054. y = cy + (r0 - distance) * mathSin(middleAngle);
  38055. textAlign = 'center';
  38056. textVerticalAlign = 'top';
  38057. break;
  38058. case 'insideStartArc':
  38059. x = cx + (r0 + distance) * mathCos(middleAngle);
  38060. y = cy + (r0 + distance) * mathSin(middleAngle);
  38061. textAlign = 'center';
  38062. textVerticalAlign = 'bottom';
  38063. break;
  38064. case 'startAngle':
  38065. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  38066. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  38067. textAlign = 'right';
  38068. textVerticalAlign = 'middle';
  38069. break;
  38070. case 'insideStartAngle':
  38071. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  38072. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  38073. textAlign = 'left';
  38074. textVerticalAlign = 'middle';
  38075. break;
  38076. case 'middle':
  38077. x = cx + middleR * mathCos(middleAngle);
  38078. y = cy + middleR * mathSin(middleAngle);
  38079. textAlign = 'center';
  38080. textVerticalAlign = 'middle';
  38081. break;
  38082. case 'endArc':
  38083. x = cx + (r + distance) * mathCos(middleAngle);
  38084. y = cy + (r + distance) * mathSin(middleAngle);
  38085. textAlign = 'center';
  38086. textVerticalAlign = 'bottom';
  38087. break;
  38088. case 'insideEndArc':
  38089. x = cx + (r - distance) * mathCos(middleAngle);
  38090. y = cy + (r - distance) * mathSin(middleAngle);
  38091. textAlign = 'center';
  38092. textVerticalAlign = 'top';
  38093. break;
  38094. case 'endAngle':
  38095. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  38096. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  38097. textAlign = 'left';
  38098. textVerticalAlign = 'middle';
  38099. break;
  38100. case 'insideEndAngle':
  38101. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  38102. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  38103. textAlign = 'right';
  38104. textVerticalAlign = 'middle';
  38105. break;
  38106. default:
  38107. return calculateTextPosition(out, opts, boundingRect);
  38108. }
  38109. out = out || {};
  38110. out.x = x;
  38111. out.y = y;
  38112. out.align = textAlign;
  38113. out.verticalAlign = textVerticalAlign;
  38114. return out;
  38115. };
  38116. }
  38117. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  38118. if (isNumber(rotateType)) {
  38119. // user-set rotation
  38120. sector.setTextConfig({
  38121. rotation: rotateType
  38122. });
  38123. return;
  38124. } else if (isArray(textPosition)) {
  38125. // user-set position, use 0 as auto rotation
  38126. sector.setTextConfig({
  38127. rotation: 0
  38128. });
  38129. return;
  38130. }
  38131. var shape = sector.shape;
  38132. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  38133. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  38134. var middleAngle = (startAngle + endAngle) / 2;
  38135. var anchorAngle;
  38136. var mappedSectorPosition = positionMapping(textPosition);
  38137. switch (mappedSectorPosition) {
  38138. case 'startArc':
  38139. case 'insideStartArc':
  38140. case 'middle':
  38141. case 'insideEndArc':
  38142. case 'endArc':
  38143. anchorAngle = middleAngle;
  38144. break;
  38145. case 'startAngle':
  38146. case 'insideStartAngle':
  38147. anchorAngle = startAngle;
  38148. break;
  38149. case 'endAngle':
  38150. case 'insideEndAngle':
  38151. anchorAngle = endAngle;
  38152. break;
  38153. default:
  38154. sector.setTextConfig({
  38155. rotation: 0
  38156. });
  38157. return;
  38158. }
  38159. var rotate = Math.PI * 1.5 - anchorAngle;
  38160. /**
  38161. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  38162. * half round flipped to increase readability. However, only middle
  38163. * position supports this for now, because in other positions, the
  38164. * anchor point is not at the center of the text, so the positions
  38165. * after rotating is not as expected.
  38166. */
  38167. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  38168. rotate -= Math.PI;
  38169. }
  38170. sector.setTextConfig({
  38171. rotation: rotate
  38172. });
  38173. }
  38174. function adjustAngleDistanceX(angle, distance, isEnd) {
  38175. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  38176. }
  38177. function adjustAngleDistanceY(angle, distance, isEnd) {
  38178. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  38179. }
  38180. function getSectorCornerRadius(model, shape, zeroIfNull) {
  38181. var cornerRadius = model.get('borderRadius');
  38182. if (cornerRadius == null) {
  38183. return zeroIfNull ? {
  38184. cornerRadius: 0
  38185. } : null;
  38186. }
  38187. if (!isArray(cornerRadius)) {
  38188. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  38189. }
  38190. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  38191. return {
  38192. cornerRadius: map(cornerRadius, function (cr) {
  38193. return parsePercent(cr, dr);
  38194. })
  38195. };
  38196. }
  38197. var mathMax$6 = Math.max;
  38198. var mathMin$6 = Math.min;
  38199. function getClipArea(coord, data) {
  38200. var coordSysClipArea = coord.getArea && coord.getArea();
  38201. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  38202. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  38203. // We should not clip this part.
  38204. // See test/bar2.html
  38205. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  38206. var expandWidth = data.getLayout('bandWidth');
  38207. if (baseAxis.isHorizontal()) {
  38208. coordSysClipArea.x -= expandWidth;
  38209. coordSysClipArea.width += expandWidth * 2;
  38210. } else {
  38211. coordSysClipArea.y -= expandWidth;
  38212. coordSysClipArea.height += expandWidth * 2;
  38213. }
  38214. }
  38215. }
  38216. return coordSysClipArea;
  38217. }
  38218. var BarView =
  38219. /** @class */
  38220. function (_super) {
  38221. __extends(BarView, _super);
  38222. function BarView() {
  38223. var _this = _super.call(this) || this;
  38224. _this.type = BarView.type;
  38225. _this._isFirstFrame = true;
  38226. return _this;
  38227. }
  38228. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  38229. this._model = seriesModel;
  38230. this._removeOnRenderedListener(api);
  38231. this._updateDrawMode(seriesModel);
  38232. var coordinateSystemType = seriesModel.get('coordinateSystem');
  38233. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  38234. // Clear previously rendered progressive elements.
  38235. this._progressiveEls = null;
  38236. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  38237. } else if ("development" !== 'production') {
  38238. warn('Only cartesian2d and polar supported for bar.');
  38239. }
  38240. };
  38241. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  38242. this._clear();
  38243. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  38244. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  38245. this._updateLargeClip(seriesModel);
  38246. };
  38247. BarView.prototype.incrementalRender = function (params, seriesModel) {
  38248. // Reset
  38249. this._progressiveEls = []; // Do not support progressive in normal mode.
  38250. this._incrementalRenderLarge(params, seriesModel);
  38251. };
  38252. BarView.prototype.eachRendered = function (cb) {
  38253. traverseElements(this._progressiveEls || this.group, cb);
  38254. };
  38255. BarView.prototype._updateDrawMode = function (seriesModel) {
  38256. var isLargeDraw = seriesModel.pipelineContext.large;
  38257. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  38258. this._isLargeDraw = isLargeDraw;
  38259. this._clear();
  38260. }
  38261. };
  38262. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  38263. var group = this.group;
  38264. var data = seriesModel.getData();
  38265. var oldData = this._data;
  38266. var coord = seriesModel.coordinateSystem;
  38267. var baseAxis = coord.getBaseAxis();
  38268. var isHorizontalOrRadial;
  38269. if (coord.type === 'cartesian2d') {
  38270. isHorizontalOrRadial = baseAxis.isHorizontal();
  38271. } else if (coord.type === 'polar') {
  38272. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38273. }
  38274. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  38275. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  38276. if (realtimeSortCfg) {
  38277. this._enableRealtimeSort(realtimeSortCfg, data, api);
  38278. }
  38279. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  38280. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  38281. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  38282. // And don't want the label are clipped.
  38283. var roundCap = seriesModel.get('roundCap', true);
  38284. var drawBackground = seriesModel.get('showBackground', true);
  38285. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38286. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  38287. var bgEls = [];
  38288. var oldBgEls = this._backgroundEls;
  38289. var isInitSort = payload && payload.isInitSort;
  38290. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  38291. function createBackground(dataIndex) {
  38292. var bgLayout = getLayout[coord.type](data, dataIndex);
  38293. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  38294. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  38295. if (coord.type === 'cartesian2d') {
  38296. bgEl.setShape('r', barBorderRadius);
  38297. } else {
  38298. bgEl.setShape('cornerRadius', barBorderRadius);
  38299. }
  38300. bgEls[dataIndex] = bgEl;
  38301. return bgEl;
  38302. }
  38303. data.diff(oldData).add(function (dataIndex) {
  38304. var itemModel = data.getItemModel(dataIndex);
  38305. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  38306. if (drawBackground) {
  38307. createBackground(dataIndex);
  38308. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  38309. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  38310. return;
  38311. }
  38312. var isClipped = false;
  38313. if (needsClip) {
  38314. // Clip will modify the layout params.
  38315. // And return a boolean to determine if the shape are fully clipped.
  38316. isClipped = clip[coord.type](coordSysClipArea, layout);
  38317. }
  38318. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  38319. if (realtimeSortCfg) {
  38320. /**
  38321. * Force label animation because even if the element is
  38322. * ignored because it's clipped, it may not be clipped after
  38323. * changing order. Then, if not using forceLabelAnimation,
  38324. * the label animation was never started, in which case,
  38325. * the label will be the final value and doesn't have label
  38326. * animation.
  38327. */
  38328. el.forceLabelAnimation = true;
  38329. }
  38330. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  38331. if (isInitSort) {
  38332. el.attr({
  38333. shape: layout
  38334. });
  38335. } else if (realtimeSortCfg) {
  38336. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  38337. } else {
  38338. initProps(el, {
  38339. shape: layout
  38340. }, seriesModel, dataIndex);
  38341. }
  38342. data.setItemGraphicEl(dataIndex, el);
  38343. group.add(el);
  38344. el.ignore = isClipped;
  38345. }).update(function (newIndex, oldIndex) {
  38346. var itemModel = data.getItemModel(newIndex);
  38347. var layout = getLayout[coord.type](data, newIndex, itemModel);
  38348. if (drawBackground) {
  38349. var bgEl = void 0;
  38350. if (oldBgEls.length === 0) {
  38351. bgEl = createBackground(oldIndex);
  38352. } else {
  38353. bgEl = oldBgEls[oldIndex];
  38354. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  38355. if (coord.type === 'cartesian2d') {
  38356. bgEl.setShape('r', barBorderRadius);
  38357. } else {
  38358. bgEl.setShape('cornerRadius', barBorderRadius);
  38359. }
  38360. bgEls[newIndex] = bgEl;
  38361. }
  38362. var bgLayout = getLayout[coord.type](data, newIndex);
  38363. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  38364. updateProps(bgEl, {
  38365. shape: shape
  38366. }, animationModel, newIndex);
  38367. }
  38368. var el = oldData.getItemGraphicEl(oldIndex);
  38369. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  38370. group.remove(el);
  38371. return;
  38372. }
  38373. var isClipped = false;
  38374. if (needsClip) {
  38375. isClipped = clip[coord.type](coordSysClipArea, layout);
  38376. if (isClipped) {
  38377. group.remove(el);
  38378. }
  38379. }
  38380. if (!el) {
  38381. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  38382. } else {
  38383. saveOldStyle(el);
  38384. }
  38385. if (realtimeSortCfg) {
  38386. el.forceLabelAnimation = true;
  38387. }
  38388. if (isChangeOrder) {
  38389. var textEl = el.getTextContent();
  38390. if (textEl) {
  38391. var labelInnerStore = labelInner(textEl);
  38392. if (labelInnerStore.prevValue != null) {
  38393. /**
  38394. * Set preValue to be value so that no new label
  38395. * should be started, otherwise, it will take a full
  38396. * `animationDurationUpdate` time to finish the
  38397. * animation, which is not expected.
  38398. */
  38399. labelInnerStore.prevValue = labelInnerStore.value;
  38400. }
  38401. }
  38402. } // Not change anything if only order changed.
  38403. // Especially not change label.
  38404. else {
  38405. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  38406. }
  38407. if (isInitSort) {
  38408. el.attr({
  38409. shape: layout
  38410. });
  38411. } else if (realtimeSortCfg) {
  38412. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  38413. } else {
  38414. updateProps(el, {
  38415. shape: layout
  38416. }, seriesModel, newIndex, null);
  38417. }
  38418. data.setItemGraphicEl(newIndex, el);
  38419. el.ignore = isClipped;
  38420. group.add(el);
  38421. }).remove(function (dataIndex) {
  38422. var el = oldData.getItemGraphicEl(dataIndex);
  38423. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  38424. }).execute();
  38425. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  38426. bgGroup.removeAll();
  38427. for (var i = 0; i < bgEls.length; ++i) {
  38428. bgGroup.add(bgEls[i]);
  38429. }
  38430. group.add(bgGroup);
  38431. this._backgroundEls = bgEls;
  38432. this._data = data;
  38433. };
  38434. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  38435. this._clear();
  38436. createLarge(seriesModel, this.group);
  38437. this._updateLargeClip(seriesModel);
  38438. };
  38439. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  38440. this._removeBackground();
  38441. createLarge(seriesModel, this.group, this._progressiveEls, true);
  38442. };
  38443. BarView.prototype._updateLargeClip = function (seriesModel) {
  38444. // Use clipPath in large mode.
  38445. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  38446. var group = this.group;
  38447. if (clipPath) {
  38448. group.setClipPath(clipPath);
  38449. } else {
  38450. group.removeClipPath();
  38451. }
  38452. };
  38453. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  38454. var _this = this; // If no data in the first frame, wait for data to initSort
  38455. if (!data.count()) {
  38456. return;
  38457. }
  38458. var baseAxis = realtimeSortCfg.baseAxis;
  38459. if (this._isFirstFrame) {
  38460. this._dispatchInitSort(data, realtimeSortCfg, api);
  38461. this._isFirstFrame = false;
  38462. } else {
  38463. var orderMapping_1 = function (idx) {
  38464. var el = data.getItemGraphicEl(idx);
  38465. var shape = el && el.shape;
  38466. return shape && // The result should be consistent with the initial sort by data value.
  38467. // Do not support the case that both positive and negative exist.
  38468. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  38469. || 0;
  38470. };
  38471. this._onRendered = function () {
  38472. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  38473. };
  38474. api.getZr().on('rendered', this._onRendered);
  38475. }
  38476. };
  38477. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  38478. var info = [];
  38479. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  38480. var mappedValue = orderMapping(dataIdx);
  38481. mappedValue = mappedValue == null ? NaN : mappedValue;
  38482. info.push({
  38483. dataIndex: dataIdx,
  38484. mappedValue: mappedValue,
  38485. ordinalNumber: ordinalNumber
  38486. });
  38487. });
  38488. info.sort(function (a, b) {
  38489. // If NaN, it will be treated as min val.
  38490. return b.mappedValue - a.mappedValue;
  38491. });
  38492. return {
  38493. ordinalNumbers: map(info, function (item) {
  38494. return item.ordinalNumber;
  38495. })
  38496. };
  38497. };
  38498. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  38499. var scale = baseAxis.scale;
  38500. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  38501. var lastValue = Number.MAX_VALUE;
  38502. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  38503. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  38504. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  38505. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  38506. : orderMapping(data.indexOfRawIndex(rawIdx));
  38507. if (value > lastValue) {
  38508. return true;
  38509. }
  38510. lastValue = value;
  38511. }
  38512. return false;
  38513. };
  38514. /*
  38515. * Consider the case when A and B changed order, whose representing
  38516. * bars are both out of sight, we don't wish to trigger reorder action
  38517. * as long as the order in the view doesn't change.
  38518. */
  38519. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  38520. var scale = baseAxis.scale;
  38521. var extent = scale.getExtent();
  38522. var tickNum = Math.max(0, extent[0]);
  38523. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  38524. for (; tickNum <= tickMax; ++tickNum) {
  38525. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  38526. return true;
  38527. }
  38528. }
  38529. };
  38530. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  38531. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  38532. return;
  38533. }
  38534. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  38535. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  38536. this._removeOnRenderedListener(api);
  38537. api.dispatchAction({
  38538. type: 'changeAxisOrder',
  38539. componentType: baseAxis.dim + 'Axis',
  38540. axisId: baseAxis.index,
  38541. sortInfo: sortInfo
  38542. });
  38543. }
  38544. };
  38545. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  38546. var baseAxis = realtimeSortCfg.baseAxis;
  38547. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  38548. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  38549. });
  38550. api.dispatchAction({
  38551. type: 'changeAxisOrder',
  38552. componentType: baseAxis.dim + 'Axis',
  38553. isInitSort: true,
  38554. axisId: baseAxis.index,
  38555. sortInfo: sortResult
  38556. });
  38557. };
  38558. BarView.prototype.remove = function (ecModel, api) {
  38559. this._clear(this._model);
  38560. this._removeOnRenderedListener(api);
  38561. };
  38562. BarView.prototype.dispose = function (ecModel, api) {
  38563. this._removeOnRenderedListener(api);
  38564. };
  38565. BarView.prototype._removeOnRenderedListener = function (api) {
  38566. if (this._onRendered) {
  38567. api.getZr().off('rendered', this._onRendered);
  38568. this._onRendered = null;
  38569. }
  38570. };
  38571. BarView.prototype._clear = function (model) {
  38572. var group = this.group;
  38573. var data = this._data;
  38574. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  38575. this._removeBackground();
  38576. this._backgroundEls = [];
  38577. data.eachItemGraphicEl(function (el) {
  38578. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  38579. });
  38580. } else {
  38581. group.removeAll();
  38582. }
  38583. this._data = null;
  38584. this._isFirstFrame = true;
  38585. };
  38586. BarView.prototype._removeBackground = function () {
  38587. this.group.remove(this._backgroundGroup);
  38588. this._backgroundGroup = null;
  38589. };
  38590. BarView.type = 'bar';
  38591. return BarView;
  38592. }(ChartView);
  38593. var clip = {
  38594. cartesian2d: function (coordSysBoundingRect, layout) {
  38595. var signWidth = layout.width < 0 ? -1 : 1;
  38596. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  38597. if (signWidth < 0) {
  38598. layout.x += layout.width;
  38599. layout.width = -layout.width;
  38600. }
  38601. if (signHeight < 0) {
  38602. layout.y += layout.height;
  38603. layout.height = -layout.height;
  38604. }
  38605. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  38606. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  38607. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  38608. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  38609. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  38610. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  38611. var xClipped = x2 < x;
  38612. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  38613. // But we should also place the element at the edge of the coord sys bounding rect.
  38614. // Because if data changed and the bar shows again, its transition animation
  38615. // will begin at this place.
  38616. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  38617. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  38618. layout.width = xClipped ? 0 : x2 - x;
  38619. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  38620. if (signWidth < 0) {
  38621. layout.x += layout.width;
  38622. layout.width = -layout.width;
  38623. }
  38624. if (signHeight < 0) {
  38625. layout.y += layout.height;
  38626. layout.height = -layout.height;
  38627. }
  38628. return xClipped || yClipped;
  38629. },
  38630. polar: function (coordSysClipArea, layout) {
  38631. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  38632. if (signR < 0) {
  38633. var tmp = layout.r;
  38634. layout.r = layout.r0;
  38635. layout.r0 = tmp;
  38636. }
  38637. var r = mathMin$6(layout.r, coordSysClipArea.r);
  38638. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  38639. layout.r = r;
  38640. layout.r0 = r0;
  38641. var clipped = r - r0 < 0; // Reverse back
  38642. if (signR < 0) {
  38643. var tmp = layout.r;
  38644. layout.r = layout.r0;
  38645. layout.r0 = tmp;
  38646. }
  38647. return clipped;
  38648. }
  38649. };
  38650. var elementCreator = {
  38651. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  38652. var rect = new Rect({
  38653. shape: extend({}, layout),
  38654. z2: 1
  38655. });
  38656. rect.__dataIndex = newIndex;
  38657. rect.name = 'item';
  38658. if (animationModel) {
  38659. var rectShape = rect.shape;
  38660. var animateProperty = isHorizontal ? 'height' : 'width';
  38661. rectShape[animateProperty] = 0;
  38662. }
  38663. return rect;
  38664. },
  38665. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  38666. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  38667. var sector = new ShapeClass({
  38668. shape: layout,
  38669. z2: 1
  38670. });
  38671. sector.name = 'item';
  38672. var positionMap = createPolarPositionMapping(isRadial);
  38673. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  38674. isRoundCap: ShapeClass === SausagePath
  38675. }); // Animation
  38676. if (animationModel) {
  38677. var sectorShape = sector.shape;
  38678. var animateProperty = isRadial ? 'r' : 'endAngle';
  38679. var animateTarget = {};
  38680. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  38681. animateTarget[animateProperty] = layout[animateProperty];
  38682. (isUpdate ? updateProps : initProps)(sector, {
  38683. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  38684. }, animationModel);
  38685. }
  38686. return sector;
  38687. }
  38688. };
  38689. function shouldRealtimeSort(seriesModel, coordSys) {
  38690. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  38691. var baseAxis = coordSys.getBaseAxis();
  38692. if ("development" !== 'production') {
  38693. if (realtimeSortOption) {
  38694. if (baseAxis.type !== 'category') {
  38695. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  38696. }
  38697. if (coordSys.type !== 'cartesian2d') {
  38698. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  38699. }
  38700. }
  38701. }
  38702. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  38703. return {
  38704. baseAxis: baseAxis,
  38705. otherAxis: coordSys.getOtherAxis(baseAxis)
  38706. };
  38707. }
  38708. }
  38709. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  38710. var seriesTarget;
  38711. var axisTarget;
  38712. if (isHorizontal) {
  38713. axisTarget = {
  38714. x: layout.x,
  38715. width: layout.width
  38716. };
  38717. seriesTarget = {
  38718. y: layout.y,
  38719. height: layout.height
  38720. };
  38721. } else {
  38722. axisTarget = {
  38723. y: layout.y,
  38724. height: layout.height
  38725. };
  38726. seriesTarget = {
  38727. x: layout.x,
  38728. width: layout.width
  38729. };
  38730. }
  38731. if (!isChangeOrder) {
  38732. // Keep the original growth animation if only axis order changed.
  38733. // Not start a new animation.
  38734. (isUpdate ? updateProps : initProps)(el, {
  38735. shape: seriesTarget
  38736. }, seriesAnimationModel, newIndex, null);
  38737. }
  38738. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  38739. (isUpdate ? updateProps : initProps)(el, {
  38740. shape: axisTarget
  38741. }, axisAnimationModel, newIndex);
  38742. }
  38743. function checkPropertiesNotValid(obj, props) {
  38744. for (var i = 0; i < props.length; i++) {
  38745. if (!isFinite(obj[props[i]])) {
  38746. return true;
  38747. }
  38748. }
  38749. return false;
  38750. }
  38751. var rectPropties = ['x', 'y', 'width', 'height'];
  38752. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  38753. var isValidLayout = {
  38754. cartesian2d: function (layout) {
  38755. return !checkPropertiesNotValid(layout, rectPropties);
  38756. },
  38757. polar: function (layout) {
  38758. return !checkPropertiesNotValid(layout, polarPropties);
  38759. }
  38760. };
  38761. var getLayout = {
  38762. // itemModel is only used to get borderWidth, which is not needed
  38763. // when calculating bar background layout.
  38764. cartesian2d: function (data, dataIndex, itemModel) {
  38765. var layout = data.getItemLayout(dataIndex);
  38766. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  38767. var signX = layout.width > 0 ? 1 : -1;
  38768. var signY = layout.height > 0 ? 1 : -1;
  38769. return {
  38770. x: layout.x + signX * fixedLineWidth / 2,
  38771. y: layout.y + signY * fixedLineWidth / 2,
  38772. width: layout.width - signX * fixedLineWidth,
  38773. height: layout.height - signY * fixedLineWidth
  38774. };
  38775. },
  38776. polar: function (data, dataIndex, itemModel) {
  38777. var layout = data.getItemLayout(dataIndex);
  38778. return {
  38779. cx: layout.cx,
  38780. cy: layout.cy,
  38781. r0: layout.r0,
  38782. r: layout.r,
  38783. startAngle: layout.startAngle,
  38784. endAngle: layout.endAngle,
  38785. clockwise: layout.clockwise
  38786. };
  38787. }
  38788. };
  38789. function isZeroOnPolar(layout) {
  38790. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  38791. }
  38792. function createPolarPositionMapping(isRadial) {
  38793. return function (isRadial) {
  38794. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  38795. return function (position) {
  38796. switch (position) {
  38797. case 'start':
  38798. case 'insideStart':
  38799. case 'end':
  38800. case 'insideEnd':
  38801. return position + arcOrAngle;
  38802. default:
  38803. return position;
  38804. }
  38805. };
  38806. }(isRadial);
  38807. }
  38808. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  38809. var style = data.getItemVisual(dataIndex, 'style');
  38810. if (!isPolar) {
  38811. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  38812. el.setShape('r', borderRadius);
  38813. } else if (!seriesModel.get('roundCap')) {
  38814. var sectorShape = el.shape;
  38815. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  38816. extend(sectorShape, cornerRadius);
  38817. el.setShape(sectorShape);
  38818. }
  38819. el.useStyle(style);
  38820. var cursorStyle = itemModel.getShallow('cursor');
  38821. cursorStyle && el.attr('cursor', cursorStyle);
  38822. 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';
  38823. var labelStatesModels = getLabelStatesModels(itemModel);
  38824. setLabelStyle(el, labelStatesModels, {
  38825. labelFetcher: seriesModel,
  38826. labelDataIndex: dataIndex,
  38827. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  38828. inheritColor: style.fill,
  38829. defaultOpacity: style.opacity,
  38830. defaultOutsidePosition: labelPositionOutside
  38831. });
  38832. var label = el.getTextContent();
  38833. if (isPolar && label) {
  38834. var position = itemModel.get(['label', 'position']);
  38835. el.textConfig.inside = position === 'middle' ? true : null;
  38836. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  38837. }
  38838. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  38839. return getDefaultInterpolatedLabel(data, value);
  38840. });
  38841. var emphasisModel = itemModel.getModel(['emphasis']);
  38842. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  38843. setStatesStylesFromModel(el, itemModel);
  38844. if (isZeroOnPolar(layout)) {
  38845. el.style.fill = 'none';
  38846. el.style.stroke = 'none';
  38847. each(el.states, function (state) {
  38848. if (state.style) {
  38849. state.style.fill = state.style.stroke = 'none';
  38850. }
  38851. });
  38852. }
  38853. } // In case width or height are too small.
  38854. function getLineWidth(itemModel, rawLayout) {
  38855. // Has no border.
  38856. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  38857. if (!borderColor || borderColor === 'none') {
  38858. return 0;
  38859. }
  38860. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  38861. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  38862. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  38863. return Math.min(lineWidth, width, height);
  38864. }
  38865. var LagePathShape =
  38866. /** @class */
  38867. function () {
  38868. function LagePathShape() {}
  38869. return LagePathShape;
  38870. }();
  38871. var LargePath =
  38872. /** @class */
  38873. function (_super) {
  38874. __extends(LargePath, _super);
  38875. function LargePath(opts) {
  38876. var _this = _super.call(this, opts) || this;
  38877. _this.type = 'largeBar';
  38878. return _this;
  38879. }
  38880. LargePath.prototype.getDefaultShape = function () {
  38881. return new LagePathShape();
  38882. };
  38883. LargePath.prototype.buildPath = function (ctx, shape) {
  38884. // Drawing lines is more efficient than drawing
  38885. // a whole line or drawing rects.
  38886. var points = shape.points;
  38887. var baseDimIdx = this.baseDimIdx;
  38888. var valueDimIdx = 1 - this.baseDimIdx;
  38889. var startPoint = [];
  38890. var size = [];
  38891. var barWidth = this.barWidth;
  38892. for (var i = 0; i < points.length; i += 3) {
  38893. size[baseDimIdx] = barWidth;
  38894. size[valueDimIdx] = points[i + 2];
  38895. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38896. startPoint[valueDimIdx] = points[i + valueDimIdx];
  38897. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  38898. }
  38899. };
  38900. return LargePath;
  38901. }(Path);
  38902. function createLarge(seriesModel, group, progressiveEls, incremental) {
  38903. // TODO support polar
  38904. var data = seriesModel.getData();
  38905. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38906. var largeDataIndices = data.getLayout('largeDataIndices');
  38907. var barWidth = data.getLayout('size');
  38908. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38909. var bgPoints = data.getLayout('largeBackgroundPoints');
  38910. if (bgPoints) {
  38911. var bgEl = new LargePath({
  38912. shape: {
  38913. points: bgPoints
  38914. },
  38915. incremental: !!incremental,
  38916. silent: true,
  38917. z2: 0
  38918. });
  38919. bgEl.baseDimIdx = baseDimIdx;
  38920. bgEl.largeDataIndices = largeDataIndices;
  38921. bgEl.barWidth = barWidth;
  38922. bgEl.useStyle(backgroundModel.getItemStyle());
  38923. group.add(bgEl);
  38924. progressiveEls && progressiveEls.push(bgEl);
  38925. }
  38926. var el = new LargePath({
  38927. shape: {
  38928. points: data.getLayout('largePoints')
  38929. },
  38930. incremental: !!incremental,
  38931. ignoreCoarsePointer: true,
  38932. z2: 1
  38933. });
  38934. el.baseDimIdx = baseDimIdx;
  38935. el.largeDataIndices = largeDataIndices;
  38936. el.barWidth = barWidth;
  38937. group.add(el);
  38938. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  38939. getECData(el).seriesIndex = seriesModel.seriesIndex;
  38940. if (!seriesModel.get('silent')) {
  38941. el.on('mousedown', largePathUpdateDataIndex);
  38942. el.on('mousemove', largePathUpdateDataIndex);
  38943. }
  38944. progressiveEls && progressiveEls.push(el);
  38945. } // Use throttle to avoid frequently traverse to find dataIndex.
  38946. var largePathUpdateDataIndex = throttle(function (event) {
  38947. var largePath = this;
  38948. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38949. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  38950. }, 30, false);
  38951. function largePathFindDataIndex(largePath, x, y) {
  38952. var baseDimIdx = largePath.baseDimIdx;
  38953. var valueDimIdx = 1 - baseDimIdx;
  38954. var points = largePath.shape.points;
  38955. var largeDataIndices = largePath.largeDataIndices;
  38956. var startPoint = [];
  38957. var size = [];
  38958. var barWidth = largePath.barWidth;
  38959. for (var i = 0, len = points.length / 3; i < len; i++) {
  38960. var ii = i * 3;
  38961. size[baseDimIdx] = barWidth;
  38962. size[valueDimIdx] = points[ii + 2];
  38963. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  38964. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  38965. if (size[valueDimIdx] < 0) {
  38966. startPoint[valueDimIdx] += size[valueDimIdx];
  38967. size[valueDimIdx] = -size[valueDimIdx];
  38968. }
  38969. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  38970. return largeDataIndices[i];
  38971. }
  38972. }
  38973. return -1;
  38974. }
  38975. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  38976. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  38977. var rectShape = layout;
  38978. var coordLayout = coord.getArea();
  38979. return {
  38980. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  38981. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  38982. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  38983. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  38984. };
  38985. } else {
  38986. var coordLayout = coord.getArea();
  38987. var sectorShape = layout;
  38988. return {
  38989. cx: coordLayout.cx,
  38990. cy: coordLayout.cy,
  38991. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  38992. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  38993. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  38994. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  38995. };
  38996. }
  38997. }
  38998. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  38999. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  39000. return new ElementClz({
  39001. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  39002. silent: true,
  39003. z2: 0
  39004. });
  39005. }
  39006. function install$3(registers) {
  39007. registers.registerChartView(BarView);
  39008. registers.registerSeriesModel(BarSeriesModel);
  39009. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can prepare some information.
  39010. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  39011. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  39012. /**
  39013. * @payload
  39014. * @property {string} [componentType=series]
  39015. * @property {number} [dx]
  39016. * @property {number} [dy]
  39017. * @property {number} [zoom]
  39018. * @property {number} [originX]
  39019. * @property {number} [originY]
  39020. */
  39021. registers.registerAction({
  39022. type: 'changeAxisOrder',
  39023. event: 'changeAxisOrder',
  39024. update: 'update'
  39025. }, function (payload, ecModel) {
  39026. var componentType = payload.componentType || 'series';
  39027. ecModel.eachComponent({
  39028. mainType: componentType,
  39029. query: payload
  39030. }, function (componentModel) {
  39031. if (payload.sortInfo) {
  39032. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  39033. }
  39034. });
  39035. });
  39036. }
  39037. var PI2$7 = Math.PI * 2;
  39038. var RADIAN = Math.PI / 180;
  39039. function getViewRect(seriesModel, api) {
  39040. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  39041. width: api.getWidth(),
  39042. height: api.getHeight()
  39043. });
  39044. }
  39045. function getBasicPieLayout(seriesModel, api) {
  39046. var viewRect = getViewRect(seriesModel, api); // center can be string or number when coordinateSystem is specified
  39047. var center = seriesModel.get('center');
  39048. var radius = seriesModel.get('radius');
  39049. if (!isArray(radius)) {
  39050. radius = [0, radius];
  39051. }
  39052. var width = parsePercent$1(viewRect.width, api.getWidth());
  39053. var height = parsePercent$1(viewRect.height, api.getHeight());
  39054. var size = Math.min(width, height);
  39055. var r0 = parsePercent$1(radius[0], size / 2);
  39056. var r = parsePercent$1(radius[1], size / 2);
  39057. var cx;
  39058. var cy;
  39059. var coordSys = seriesModel.coordinateSystem;
  39060. if (coordSys) {
  39061. // percentage is not allowed when coordinate system is specified
  39062. var point = coordSys.dataToPoint(center);
  39063. cx = point[0] || 0;
  39064. cy = point[1] || 0;
  39065. } else {
  39066. if (!isArray(center)) {
  39067. center = [center, center];
  39068. }
  39069. cx = parsePercent$1(center[0], width) + viewRect.x;
  39070. cy = parsePercent$1(center[1], height) + viewRect.y;
  39071. }
  39072. return {
  39073. cx: cx,
  39074. cy: cy,
  39075. r0: r0,
  39076. r: r
  39077. };
  39078. }
  39079. function pieLayout(seriesType, ecModel, api) {
  39080. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39081. var data = seriesModel.getData();
  39082. var valueDim = data.mapDimension('value');
  39083. var viewRect = getViewRect(seriesModel, api);
  39084. var _a = getBasicPieLayout(seriesModel, api),
  39085. cx = _a.cx,
  39086. cy = _a.cy,
  39087. r = _a.r,
  39088. r0 = _a.r0;
  39089. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39090. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39091. var validDataCount = 0;
  39092. data.each(valueDim, function (value) {
  39093. !isNaN(value) && validDataCount++;
  39094. });
  39095. var sum = data.getSum(valueDim); // Sum may be 0
  39096. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39097. var clockwise = seriesModel.get('clockwise');
  39098. var roseType = seriesModel.get('roseType');
  39099. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  39100. var extent = data.getDataExtent(valueDim);
  39101. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  39102. var restAngle = PI2$7;
  39103. var valueSumLargerThanMinAngle = 0;
  39104. var currentAngle = startAngle;
  39105. var dir = clockwise ? 1 : -1;
  39106. data.setLayout({
  39107. viewRect: viewRect,
  39108. r: r
  39109. });
  39110. data.each(valueDim, function (value, idx) {
  39111. var angle;
  39112. if (isNaN(value)) {
  39113. data.setItemLayout(idx, {
  39114. angle: NaN,
  39115. startAngle: NaN,
  39116. endAngle: NaN,
  39117. clockwise: clockwise,
  39118. cx: cx,
  39119. cy: cy,
  39120. r0: r0,
  39121. r: roseType ? NaN : r
  39122. });
  39123. return;
  39124. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39125. if (roseType !== 'area') {
  39126. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  39127. } else {
  39128. angle = PI2$7 / validDataCount;
  39129. }
  39130. if (angle < minAngle) {
  39131. angle = minAngle;
  39132. restAngle -= minAngle;
  39133. } else {
  39134. valueSumLargerThanMinAngle += value;
  39135. }
  39136. var endAngle = currentAngle + dir * angle;
  39137. data.setItemLayout(idx, {
  39138. angle: angle,
  39139. startAngle: currentAngle,
  39140. endAngle: endAngle,
  39141. clockwise: clockwise,
  39142. cx: cx,
  39143. cy: cy,
  39144. r0: r0,
  39145. r: roseType ? linearMap(value, extent, [r0, r]) : r
  39146. });
  39147. currentAngle = endAngle;
  39148. }); // Some sector is constrained by minAngle
  39149. // Rest sectors needs recalculate angle
  39150. if (restAngle < PI2$7 && validDataCount) {
  39151. // Average the angle if rest angle is not enough after all angles is
  39152. // Constrained by minAngle
  39153. if (restAngle <= 1e-3) {
  39154. var angle_1 = PI2$7 / validDataCount;
  39155. data.each(valueDim, function (value, idx) {
  39156. if (!isNaN(value)) {
  39157. var layout_1 = data.getItemLayout(idx);
  39158. layout_1.angle = angle_1;
  39159. layout_1.startAngle = startAngle + dir * idx * angle_1;
  39160. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  39161. }
  39162. });
  39163. } else {
  39164. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39165. currentAngle = startAngle;
  39166. data.each(valueDim, function (value, idx) {
  39167. if (!isNaN(value)) {
  39168. var layout_2 = data.getItemLayout(idx);
  39169. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  39170. layout_2.startAngle = currentAngle;
  39171. layout_2.endAngle = currentAngle + dir * angle;
  39172. currentAngle += dir * angle;
  39173. }
  39174. });
  39175. }
  39176. }
  39177. });
  39178. }
  39179. /*
  39180. * Licensed to the Apache Software Foundation (ASF) under one
  39181. * or more contributor license agreements. See the NOTICE file
  39182. * distributed with this work for additional information
  39183. * regarding copyright ownership. The ASF licenses this file
  39184. * to you under the Apache License, Version 2.0 (the
  39185. * "License"); you may not use this file except in compliance
  39186. * with the License. You may obtain a copy of the License at
  39187. *
  39188. * http://www.apache.org/licenses/LICENSE-2.0
  39189. *
  39190. * Unless required by applicable law or agreed to in writing,
  39191. * software distributed under the License is distributed on an
  39192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39193. * KIND, either express or implied. See the License for the
  39194. * specific language governing permissions and limitations
  39195. * under the License.
  39196. */
  39197. /**
  39198. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39199. */
  39200. /*
  39201. * Licensed to the Apache Software Foundation (ASF) under one
  39202. * or more contributor license agreements. See the NOTICE file
  39203. * distributed with this work for additional information
  39204. * regarding copyright ownership. The ASF licenses this file
  39205. * to you under the Apache License, Version 2.0 (the
  39206. * "License"); you may not use this file except in compliance
  39207. * with the License. You may obtain a copy of the License at
  39208. *
  39209. * http://www.apache.org/licenses/LICENSE-2.0
  39210. *
  39211. * Unless required by applicable law or agreed to in writing,
  39212. * software distributed under the License is distributed on an
  39213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39214. * KIND, either express or implied. See the License for the
  39215. * specific language governing permissions and limitations
  39216. * under the License.
  39217. */
  39218. function dataFilter(seriesType) {
  39219. return {
  39220. seriesType: seriesType,
  39221. reset: function (seriesModel, ecModel) {
  39222. var legendModels = ecModel.findComponents({
  39223. mainType: 'legend'
  39224. });
  39225. if (!legendModels || !legendModels.length) {
  39226. return;
  39227. }
  39228. var data = seriesModel.getData();
  39229. data.filterSelf(function (idx) {
  39230. var name = data.getName(idx); // If in any legend component the status is not selected.
  39231. for (var i = 0; i < legendModels.length; i++) {
  39232. // @ts-ignore FIXME: LegendModel
  39233. if (!legendModels[i].isSelected(name)) {
  39234. return false;
  39235. }
  39236. }
  39237. return true;
  39238. });
  39239. }
  39240. };
  39241. }
  39242. var RADIAN$1 = Math.PI / 180;
  39243. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  39244. if (list.length < 2) {
  39245. return;
  39246. }
  39247. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  39248. var rB = semi.rB;
  39249. var rB2 = rB * rB;
  39250. for (var i = 0; i < semi.list.length; i++) {
  39251. var item = semi.list[i];
  39252. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  39253. var rA = r + item.len;
  39254. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  39255. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  39256. var newX = cx + (dx + item.len2) * dir;
  39257. var deltaX = newX - item.label.x;
  39258. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  39259. constrainTextWidth(item, newTargetWidth, true);
  39260. item.label.x = newX;
  39261. }
  39262. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  39263. function recalculateX(items) {
  39264. // Extremes of
  39265. var topSemi = {
  39266. list: [],
  39267. maxY: 0
  39268. };
  39269. var bottomSemi = {
  39270. list: [],
  39271. maxY: 0
  39272. };
  39273. for (var i = 0; i < items.length; i++) {
  39274. if (items[i].labelAlignTo !== 'none') {
  39275. continue;
  39276. }
  39277. var item = items[i];
  39278. var semi = item.label.y > cy ? bottomSemi : topSemi;
  39279. var dy = Math.abs(item.label.y - cy);
  39280. if (dy >= semi.maxY) {
  39281. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  39282. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  39283. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  39284. semi.rB = rB;
  39285. semi.maxY = dy;
  39286. }
  39287. semi.list.push(item);
  39288. }
  39289. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  39290. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  39291. }
  39292. var len = list.length;
  39293. for (var i = 0; i < len; i++) {
  39294. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39295. var dx = list[i].label.x - farthestX;
  39296. list[i].linePoints[1][0] += dx;
  39297. list[i].label.x = farthestX;
  39298. }
  39299. }
  39300. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  39301. recalculateX(list);
  39302. }
  39303. }
  39304. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39305. var leftList = [];
  39306. var rightList = [];
  39307. var leftmostX = Number.MAX_VALUE;
  39308. var rightmostX = -Number.MAX_VALUE;
  39309. for (var i = 0; i < labelLayoutList.length; i++) {
  39310. var label = labelLayoutList[i].label;
  39311. if (isPositionCenter(labelLayoutList[i])) {
  39312. continue;
  39313. }
  39314. if (label.x < cx) {
  39315. leftmostX = Math.min(leftmostX, label.x);
  39316. leftList.push(labelLayoutList[i]);
  39317. } else {
  39318. rightmostX = Math.max(rightmostX, label.x);
  39319. rightList.push(labelLayoutList[i]);
  39320. }
  39321. }
  39322. for (var i = 0; i < labelLayoutList.length; i++) {
  39323. var layout = labelLayoutList[i];
  39324. if (!isPositionCenter(layout) && layout.linePoints) {
  39325. if (layout.labelStyleWidth != null) {
  39326. continue;
  39327. }
  39328. var label = layout.label;
  39329. var linePoints = layout.linePoints;
  39330. var targetTextWidth = void 0;
  39331. if (layout.labelAlignTo === 'edge') {
  39332. if (label.x < cx) {
  39333. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  39334. } else {
  39335. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  39336. }
  39337. } else if (layout.labelAlignTo === 'labelLine') {
  39338. if (label.x < cx) {
  39339. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  39340. } else {
  39341. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  39342. }
  39343. } else {
  39344. if (label.x < cx) {
  39345. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  39346. } else {
  39347. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  39348. }
  39349. }
  39350. layout.targetTextWidth = targetTextWidth;
  39351. constrainTextWidth(layout, targetTextWidth);
  39352. }
  39353. }
  39354. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39355. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39356. for (var i = 0; i < labelLayoutList.length; i++) {
  39357. var layout = labelLayoutList[i];
  39358. if (!isPositionCenter(layout) && layout.linePoints) {
  39359. var label = layout.label;
  39360. var linePoints = layout.linePoints;
  39361. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39362. var padding = label.style.padding;
  39363. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  39364. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  39365. var realTextWidth = layout.rect.width + extraPaddingH;
  39366. var dist = linePoints[1][0] - linePoints[2][0];
  39367. if (isAlignToEdge) {
  39368. if (label.x < cx) {
  39369. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  39370. } else {
  39371. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  39372. }
  39373. } else {
  39374. if (label.x < cx) {
  39375. linePoints[2][0] = label.x + layout.labelDistance;
  39376. } else {
  39377. linePoints[2][0] = label.x - layout.labelDistance;
  39378. }
  39379. linePoints[1][0] = linePoints[2][0] + dist;
  39380. }
  39381. linePoints[1][1] = linePoints[2][1] = label.y;
  39382. }
  39383. }
  39384. }
  39385. /**
  39386. * Set max width of each label, and then wrap each label to the max width.
  39387. *
  39388. * @param layout label layout
  39389. * @param availableWidth max width for the label to display
  39390. * @param forceRecalculate recaculate the text layout even if the current width
  39391. * is smaller than `availableWidth`. This is useful when the text was previously
  39392. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  39393. * which case, previous wrapping should be redo.
  39394. */
  39395. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  39396. if (forceRecalculate === void 0) {
  39397. forceRecalculate = false;
  39398. }
  39399. if (layout.labelStyleWidth != null) {
  39400. // User-defined style.width has the highest priority.
  39401. return;
  39402. }
  39403. var label = layout.label;
  39404. var style = label.style;
  39405. var textRect = layout.rect;
  39406. var bgColor = style.backgroundColor;
  39407. var padding = style.padding;
  39408. var paddingH = padding ? padding[1] + padding[3] : 0;
  39409. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  39410. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  39411. if (availableWidth < oldOuterWidth || forceRecalculate) {
  39412. var oldHeight = textRect.height;
  39413. if (overflow && overflow.match('break')) {
  39414. // Temporarily set background to be null to calculate
  39415. // the bounding box without background.
  39416. label.setStyle('backgroundColor', null); // Set constraining width
  39417. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding.
  39418. var innerRect = label.getBoundingRect();
  39419. label.setStyle('width', Math.ceil(innerRect.width));
  39420. label.setStyle('backgroundColor', bgColor);
  39421. } else {
  39422. var availableInnerWidth = availableWidth - paddingH;
  39423. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  39424. ? availableInnerWidth : // Current available width is enough, but the text may have
  39425. // already been wrapped with a smaller available width.
  39426. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  39427. // so don't constrain width (otherwise it may have
  39428. // empty space in the background).
  39429. ? null // Current available is smaller than text width, so
  39430. // use the current available width as constraining
  39431. // width.
  39432. : availableInnerWidth : // Current available width is enough, so no need to
  39433. // constrain.
  39434. null;
  39435. label.setStyle('width', newWidth);
  39436. }
  39437. var newRect = label.getBoundingRect();
  39438. textRect.width = newRect.width;
  39439. var margin = (label.style.margin || 0) + 2.1;
  39440. textRect.height = newRect.height + margin;
  39441. textRect.y -= (textRect.height - oldHeight) / 2;
  39442. }
  39443. }
  39444. function isPositionCenter(sectorShape) {
  39445. // Not change x for center label
  39446. return sectorShape.position === 'center';
  39447. }
  39448. function pieLabelLayout(seriesModel) {
  39449. var data = seriesModel.getData();
  39450. var labelLayoutList = [];
  39451. var cx;
  39452. var cy;
  39453. var hasLabelRotate = false;
  39454. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39455. var viewRect = data.getLayout('viewRect');
  39456. var r = data.getLayout('r');
  39457. var viewWidth = viewRect.width;
  39458. var viewLeft = viewRect.x;
  39459. var viewTop = viewRect.y;
  39460. var viewHeight = viewRect.height;
  39461. function setNotShow(el) {
  39462. el.ignore = true;
  39463. }
  39464. function isLabelShown(label) {
  39465. if (!label.ignore) {
  39466. return true;
  39467. }
  39468. for (var key in label.states) {
  39469. if (label.states[key].ignore === false) {
  39470. return true;
  39471. }
  39472. }
  39473. return false;
  39474. }
  39475. data.each(function (idx) {
  39476. var sector = data.getItemGraphicEl(idx);
  39477. var sectorShape = sector.shape;
  39478. var label = sector.getTextContent();
  39479. var labelLine = sector.getTextGuideLine();
  39480. var itemModel = data.getItemModel(idx);
  39481. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  39482. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  39483. var labelDistance = labelModel.get('distanceToLabelLine');
  39484. var labelAlignTo = labelModel.get('alignTo');
  39485. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  39486. var bleedMargin = labelModel.get('bleedMargin');
  39487. var labelLineModel = itemModel.getModel('labelLine');
  39488. var labelLineLen = labelLineModel.get('length');
  39489. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39490. var labelLineLen2 = labelLineModel.get('length2');
  39491. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39492. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  39493. each(label.states, setNotShow);
  39494. label.ignore = true;
  39495. if (labelLine) {
  39496. each(labelLine.states, setNotShow);
  39497. labelLine.ignore = true;
  39498. }
  39499. return;
  39500. }
  39501. if (!isLabelShown(label)) {
  39502. return;
  39503. }
  39504. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  39505. var nx = Math.cos(midAngle);
  39506. var ny = Math.sin(midAngle);
  39507. var textX;
  39508. var textY;
  39509. var linePoints;
  39510. var textAlign;
  39511. cx = sectorShape.cx;
  39512. cy = sectorShape.cy;
  39513. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39514. if (labelPosition === 'center') {
  39515. textX = sectorShape.cx;
  39516. textY = sectorShape.cy;
  39517. textAlign = 'center';
  39518. } else {
  39519. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  39520. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  39521. textX = x1 + nx * 3;
  39522. textY = y1 + ny * 3;
  39523. if (!isLabelInside) {
  39524. // For roseType
  39525. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  39526. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  39527. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  39528. var y3 = y2;
  39529. if (labelAlignTo === 'edge') {
  39530. // Adjust textX because text align of edge is opposite
  39531. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  39532. } else {
  39533. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  39534. }
  39535. textY = y3;
  39536. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39537. }
  39538. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  39539. }
  39540. var PI = Math.PI;
  39541. var labelRotate = 0;
  39542. var rotate = labelModel.get('rotate');
  39543. if (isNumber(rotate)) {
  39544. labelRotate = rotate * (PI / 180);
  39545. } else if (labelPosition === 'center') {
  39546. labelRotate = 0;
  39547. } else if (rotate === 'radial' || rotate === true) {
  39548. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  39549. labelRotate = radialAngle;
  39550. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  39551. var rad = Math.atan2(nx, ny);
  39552. if (rad < 0) {
  39553. rad = PI * 2 + rad;
  39554. }
  39555. var isDown = ny > 0;
  39556. if (isDown) {
  39557. rad = PI + rad;
  39558. }
  39559. labelRotate = rad - PI;
  39560. }
  39561. hasLabelRotate = !!labelRotate;
  39562. label.x = textX;
  39563. label.y = textY;
  39564. label.rotation = labelRotate;
  39565. label.setStyle({
  39566. verticalAlign: 'middle'
  39567. }); // Not sectorShape the inside label
  39568. if (!isLabelInside) {
  39569. var textRect = label.getBoundingRect().clone();
  39570. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  39571. var margin = (label.style.margin || 0) + 2.1;
  39572. textRect.y -= margin / 2;
  39573. textRect.height += margin;
  39574. labelLayoutList.push({
  39575. label: label,
  39576. labelLine: labelLine,
  39577. position: labelPosition,
  39578. len: labelLineLen,
  39579. len2: labelLineLen2,
  39580. minTurnAngle: labelLineModel.get('minTurnAngle'),
  39581. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  39582. surfaceNormal: new Point(nx, ny),
  39583. linePoints: linePoints,
  39584. textAlign: textAlign,
  39585. labelDistance: labelDistance,
  39586. labelAlignTo: labelAlignTo,
  39587. edgeDistance: edgeDistance,
  39588. bleedMargin: bleedMargin,
  39589. rect: textRect,
  39590. unconstrainedWidth: textRect.width,
  39591. labelStyleWidth: label.style.width
  39592. });
  39593. } else {
  39594. label.setStyle({
  39595. align: textAlign
  39596. });
  39597. var selectState = label.states.select;
  39598. if (selectState) {
  39599. selectState.x += label.x;
  39600. selectState.y += label.y;
  39601. }
  39602. }
  39603. sector.setTextConfig({
  39604. inside: isLabelInside
  39605. });
  39606. });
  39607. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39608. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39609. }
  39610. for (var i = 0; i < labelLayoutList.length; i++) {
  39611. var layout = labelLayoutList[i];
  39612. var label = layout.label;
  39613. var labelLine = layout.labelLine;
  39614. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  39615. if (label) {
  39616. label.setStyle({
  39617. align: layout.textAlign
  39618. });
  39619. if (notShowLabel) {
  39620. each(label.states, setNotShow);
  39621. label.ignore = true;
  39622. }
  39623. var selectState = label.states.select;
  39624. if (selectState) {
  39625. selectState.x += label.x;
  39626. selectState.y += label.y;
  39627. }
  39628. }
  39629. if (labelLine) {
  39630. var linePoints = layout.linePoints;
  39631. if (notShowLabel || !linePoints) {
  39632. each(labelLine.states, setNotShow);
  39633. labelLine.ignore = true;
  39634. } else {
  39635. limitTurnAngle(linePoints, layout.minTurnAngle);
  39636. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  39637. labelLine.setShape({
  39638. points: linePoints
  39639. }); // Set the anchor to the midpoint of sector
  39640. label.__hostTarget.textGuideLineConfig = {
  39641. anchor: new Point(linePoints[0][0], linePoints[0][1])
  39642. };
  39643. }
  39644. }
  39645. }
  39646. }
  39647. /**
  39648. * Piece of pie including Sector, Label, LabelLine
  39649. */
  39650. var PiePiece =
  39651. /** @class */
  39652. function (_super) {
  39653. __extends(PiePiece, _super);
  39654. function PiePiece(data, idx, startAngle) {
  39655. var _this = _super.call(this) || this;
  39656. _this.z2 = 2;
  39657. var text = new ZRText();
  39658. _this.setTextContent(text);
  39659. _this.updateData(data, idx, startAngle, true);
  39660. return _this;
  39661. }
  39662. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  39663. var sector = this;
  39664. var seriesModel = data.hostModel;
  39665. var itemModel = data.getItemModel(idx);
  39666. var emphasisModel = itemModel.getModel('emphasis');
  39667. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  39668. // see `setItemLayout` in `pieLayout.ts`.
  39669. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  39670. if (isNaN(sectorShape.startAngle)) {
  39671. // Use NaN shape to avoid drawing shape.
  39672. sector.setShape(sectorShape);
  39673. return;
  39674. }
  39675. if (firstCreate) {
  39676. sector.setShape(sectorShape);
  39677. var animationType = seriesModel.getShallow('animationType');
  39678. if (seriesModel.ecModel.ssr) {
  39679. // Use scale animation in SSR mode(opacity?)
  39680. // Because CSS SVG animation doesn't support very customized shape animation.
  39681. initProps(sector, {
  39682. scaleX: 0,
  39683. scaleY: 0
  39684. }, seriesModel, {
  39685. dataIndex: idx,
  39686. isFrom: true
  39687. });
  39688. sector.originX = sectorShape.cx;
  39689. sector.originY = sectorShape.cy;
  39690. } else if (animationType === 'scale') {
  39691. sector.shape.r = layout.r0;
  39692. initProps(sector, {
  39693. shape: {
  39694. r: layout.r
  39695. }
  39696. }, seriesModel, idx);
  39697. } // Expansion
  39698. else {
  39699. if (startAngle != null) {
  39700. sector.setShape({
  39701. startAngle: startAngle,
  39702. endAngle: startAngle
  39703. });
  39704. initProps(sector, {
  39705. shape: {
  39706. startAngle: layout.startAngle,
  39707. endAngle: layout.endAngle
  39708. }
  39709. }, seriesModel, idx);
  39710. } else {
  39711. sector.shape.endAngle = layout.startAngle;
  39712. updateProps(sector, {
  39713. shape: {
  39714. endAngle: layout.endAngle
  39715. }
  39716. }, seriesModel, idx);
  39717. }
  39718. }
  39719. } else {
  39720. saveOldStyle(sector); // Transition animation from the old shape
  39721. updateProps(sector, {
  39722. shape: sectorShape
  39723. }, seriesModel, idx);
  39724. }
  39725. sector.useStyle(data.getItemVisual(idx, 'style'));
  39726. setStatesStylesFromModel(sector, itemModel);
  39727. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39728. var offset = seriesModel.get('selectedOffset');
  39729. var dx = Math.cos(midAngle) * offset;
  39730. var dy = Math.sin(midAngle) * offset;
  39731. var cursorStyle = itemModel.getShallow('cursor');
  39732. cursorStyle && sector.attr('cursor', cursorStyle);
  39733. this._updateLabel(seriesModel, data, idx);
  39734. sector.ensureState('emphasis').shape = extend({
  39735. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  39736. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  39737. extend(sector.ensureState('select'), {
  39738. x: dx,
  39739. y: dy,
  39740. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  39741. });
  39742. extend(sector.ensureState('blur'), {
  39743. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  39744. });
  39745. var labelLine = sector.getTextGuideLine();
  39746. var labelText = sector.getTextContent();
  39747. labelLine && extend(labelLine.ensureState('select'), {
  39748. x: dx,
  39749. y: dy
  39750. }); // TODO: needs dx, dy in zrender?
  39751. extend(labelText.ensureState('select'), {
  39752. x: dx,
  39753. y: dy
  39754. });
  39755. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39756. };
  39757. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  39758. var sector = this;
  39759. var itemModel = data.getItemModel(idx);
  39760. var labelLineModel = itemModel.getModel('labelLine');
  39761. var style = data.getItemVisual(idx, 'style');
  39762. var visualColor = style && style.fill;
  39763. var visualOpacity = style && style.opacity;
  39764. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  39765. labelFetcher: data.hostModel,
  39766. labelDataIndex: idx,
  39767. inheritColor: visualColor,
  39768. defaultOpacity: visualOpacity,
  39769. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  39770. });
  39771. var labelText = sector.getTextContent(); // Set textConfig on sector.
  39772. sector.setTextConfig({
  39773. // reset position, rotation
  39774. position: null,
  39775. rotation: null
  39776. }); // Make sure update style on labelText after setLabelStyle.
  39777. // Because setLabelStyle will replace a new style on it.
  39778. labelText.attr({
  39779. z2: 10
  39780. });
  39781. var labelPosition = seriesModel.get(['label', 'position']);
  39782. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  39783. sector.removeTextGuideLine();
  39784. } else {
  39785. var polyline = this.getTextGuideLine();
  39786. if (!polyline) {
  39787. polyline = new Polyline();
  39788. this.setTextGuideLine(polyline);
  39789. } // Default use item visual color
  39790. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  39791. stroke: visualColor,
  39792. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  39793. });
  39794. }
  39795. };
  39796. return PiePiece;
  39797. }(Sector); // Pie view
  39798. var PieView =
  39799. /** @class */
  39800. function (_super) {
  39801. __extends(PieView, _super);
  39802. function PieView() {
  39803. var _this = _super !== null && _super.apply(this, arguments) || this;
  39804. _this.ignoreLabelLineUpdate = true;
  39805. return _this;
  39806. }
  39807. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39808. var data = seriesModel.getData();
  39809. var oldData = this._data;
  39810. var group = this.group;
  39811. var startAngle; // First render
  39812. if (!oldData && data.count() > 0) {
  39813. var shape = data.getItemLayout(0);
  39814. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  39815. shape = data.getItemLayout(s);
  39816. }
  39817. if (shape) {
  39818. startAngle = shape.startAngle;
  39819. }
  39820. } // remove empty-circle if it exists
  39821. if (this._emptyCircleSector) {
  39822. group.remove(this._emptyCircleSector);
  39823. } // when all data are filtered, show lightgray empty circle
  39824. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  39825. var sector = new Sector({
  39826. shape: getBasicPieLayout(seriesModel, api)
  39827. });
  39828. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  39829. this._emptyCircleSector = sector;
  39830. group.add(sector);
  39831. }
  39832. data.diff(oldData).add(function (idx) {
  39833. var piePiece = new PiePiece(data, idx, startAngle);
  39834. data.setItemGraphicEl(idx, piePiece);
  39835. group.add(piePiece);
  39836. }).update(function (newIdx, oldIdx) {
  39837. var piePiece = oldData.getItemGraphicEl(oldIdx);
  39838. piePiece.updateData(data, newIdx, startAngle);
  39839. piePiece.off('click');
  39840. group.add(piePiece);
  39841. data.setItemGraphicEl(newIdx, piePiece);
  39842. }).remove(function (idx) {
  39843. var piePiece = oldData.getItemGraphicEl(idx);
  39844. removeElementWithFadeOut(piePiece, seriesModel, idx);
  39845. }).execute();
  39846. pieLabelLayout(seriesModel); // Always use initial animation.
  39847. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  39848. this._data = data;
  39849. }
  39850. };
  39851. PieView.prototype.dispose = function () {};
  39852. PieView.prototype.containPoint = function (point, seriesModel) {
  39853. var data = seriesModel.getData();
  39854. var itemLayout = data.getItemLayout(0);
  39855. if (itemLayout) {
  39856. var dx = point[0] - itemLayout.cx;
  39857. var dy = point[1] - itemLayout.cy;
  39858. var radius = Math.sqrt(dx * dx + dy * dy);
  39859. return radius <= itemLayout.r && radius >= itemLayout.r0;
  39860. }
  39861. };
  39862. PieView.type = 'pie';
  39863. return PieView;
  39864. }(ChartView);
  39865. /**
  39866. * [Usage]:
  39867. * (1)
  39868. * createListSimply(seriesModel, ['value']);
  39869. * (2)
  39870. * createListSimply(seriesModel, {
  39871. * coordDimensions: ['value'],
  39872. * dimensionsCount: 5
  39873. * });
  39874. */
  39875. function createSeriesDataSimply(seriesModel, opt, nameList) {
  39876. opt = isArray(opt) && {
  39877. coordDimensions: opt
  39878. } || extend({
  39879. encodeDefine: seriesModel.getEncode()
  39880. }, opt);
  39881. var source = seriesModel.getSource();
  39882. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  39883. var list = new SeriesData(dimensions, seriesModel);
  39884. list.initData(source, nameList);
  39885. return list;
  39886. }
  39887. /*
  39888. * Licensed to the Apache Software Foundation (ASF) under one
  39889. * or more contributor license agreements. See the NOTICE file
  39890. * distributed with this work for additional information
  39891. * regarding copyright ownership. The ASF licenses this file
  39892. * to you under the Apache License, Version 2.0 (the
  39893. * "License"); you may not use this file except in compliance
  39894. * with the License. You may obtain a copy of the License at
  39895. *
  39896. * http://www.apache.org/licenses/LICENSE-2.0
  39897. *
  39898. * Unless required by applicable law or agreed to in writing,
  39899. * software distributed under the License is distributed on an
  39900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39901. * KIND, either express or implied. See the License for the
  39902. * specific language governing permissions and limitations
  39903. * under the License.
  39904. */
  39905. /**
  39906. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39907. */
  39908. /*
  39909. * Licensed to the Apache Software Foundation (ASF) under one
  39910. * or more contributor license agreements. See the NOTICE file
  39911. * distributed with this work for additional information
  39912. * regarding copyright ownership. The ASF licenses this file
  39913. * to you under the Apache License, Version 2.0 (the
  39914. * "License"); you may not use this file except in compliance
  39915. * with the License. You may obtain a copy of the License at
  39916. *
  39917. * http://www.apache.org/licenses/LICENSE-2.0
  39918. *
  39919. * Unless required by applicable law or agreed to in writing,
  39920. * software distributed under the License is distributed on an
  39921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39922. * KIND, either express or implied. See the License for the
  39923. * specific language governing permissions and limitations
  39924. * under the License.
  39925. */
  39926. /**
  39927. * LegendVisualProvider is an bridge that pick encoded color from data and
  39928. * provide to the legend component.
  39929. */
  39930. var LegendVisualProvider =
  39931. /** @class */
  39932. function () {
  39933. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  39934. getDataWithEncodedVisual, // Function to get raw data before filtered.
  39935. getRawData) {
  39936. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  39937. this._getRawData = getRawData;
  39938. }
  39939. LegendVisualProvider.prototype.getAllNames = function () {
  39940. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  39941. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  39942. return rawData.mapArray(rawData.getName);
  39943. };
  39944. LegendVisualProvider.prototype.containName = function (name) {
  39945. var rawData = this._getRawData();
  39946. return rawData.indexOfName(name) >= 0;
  39947. };
  39948. LegendVisualProvider.prototype.indexOfName = function (name) {
  39949. // Only get data when necessary.
  39950. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  39951. // Invoking Series#getData immediately will throw an error.
  39952. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  39953. return dataWithEncodedVisual.indexOfName(name);
  39954. };
  39955. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  39956. // Get encoded visual properties from final filtered data.
  39957. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  39958. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  39959. };
  39960. return LegendVisualProvider;
  39961. }();
  39962. var innerData = makeInner();
  39963. var PieSeriesModel =
  39964. /** @class */
  39965. function (_super) {
  39966. __extends(PieSeriesModel, _super);
  39967. function PieSeriesModel() {
  39968. return _super !== null && _super.apply(this, arguments) || this;
  39969. }
  39970. /**
  39971. * @overwrite
  39972. */
  39973. PieSeriesModel.prototype.init = function (option) {
  39974. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  39975. // Use a function instead of direct access because data reference may changed
  39976. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  39977. this._defaultLabelLine(option);
  39978. };
  39979. /**
  39980. * @overwrite
  39981. */
  39982. PieSeriesModel.prototype.mergeOption = function () {
  39983. _super.prototype.mergeOption.apply(this, arguments);
  39984. };
  39985. /**
  39986. * @overwrite
  39987. */
  39988. PieSeriesModel.prototype.getInitialData = function () {
  39989. return createSeriesDataSimply(this, {
  39990. coordDimensions: ['value'],
  39991. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  39992. });
  39993. };
  39994. /**
  39995. * @overwrite
  39996. */
  39997. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  39998. var data = this.getData(); // update seats when data is changed
  39999. var dataInner = innerData(data);
  40000. var seats = dataInner.seats;
  40001. if (!seats) {
  40002. var valueList_1 = [];
  40003. data.each(data.mapDimension('value'), function (value) {
  40004. valueList_1.push(value);
  40005. });
  40006. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  40007. }
  40008. var params = _super.prototype.getDataParams.call(this, dataIndex); // seats may be empty when sum is 0
  40009. params.percent = seats[dataIndex] || 0;
  40010. params.$vars.push('percent');
  40011. return params;
  40012. };
  40013. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  40014. // Extend labelLine emphasis
  40015. defaultEmphasis(option, 'labelLine', ['show']);
  40016. var labelLineNormalOpt = option.labelLine;
  40017. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  40018. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  40019. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  40020. };
  40021. PieSeriesModel.type = 'series.pie';
  40022. PieSeriesModel.defaultOption = {
  40023. // zlevel: 0,
  40024. z: 2,
  40025. legendHoverLink: true,
  40026. colorBy: 'data',
  40027. // 默认全局居中
  40028. center: ['50%', '50%'],
  40029. radius: [0, '75%'],
  40030. // 默认顺时针
  40031. clockwise: true,
  40032. startAngle: 90,
  40033. // 最小角度改为0
  40034. minAngle: 0,
  40035. // If the angle of a sector less than `minShowLabelAngle`,
  40036. // the label will not be displayed.
  40037. minShowLabelAngle: 0,
  40038. // 选中时扇区偏移量
  40039. selectedOffset: 10,
  40040. // 选择模式,默认关闭,可选single,multiple
  40041. // selectedMode: false,
  40042. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  40043. // roseType: null,
  40044. percentPrecision: 2,
  40045. // If still show when all data zero.
  40046. stillShowZeroSum: true,
  40047. // cursor: null,
  40048. left: 0,
  40049. top: 0,
  40050. right: 0,
  40051. bottom: 0,
  40052. width: null,
  40053. height: null,
  40054. label: {
  40055. // color: 'inherit',
  40056. // If rotate around circle
  40057. rotate: 0,
  40058. show: true,
  40059. overflow: 'truncate',
  40060. // 'outer', 'inside', 'center'
  40061. position: 'outer',
  40062. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  40063. alignTo: 'none',
  40064. // Closest distance between label and chart edge.
  40065. // Works only position is 'outer' and alignTo is 'edge'.
  40066. edgeDistance: '25%',
  40067. // Works only position is 'outer' and alignTo is not 'edge'.
  40068. bleedMargin: 10,
  40069. // Distance between text and label line.
  40070. distanceToLabelLine: 5 // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  40071. // 默认使用全局文本样式,详见 textStyle
  40072. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  40073. },
  40074. // Enabled when label.normal.position is 'outer'
  40075. labelLine: {
  40076. show: true,
  40077. // 引导线两段中的第一段长度
  40078. length: 15,
  40079. // 引导线两段中的第二段长度
  40080. length2: 15,
  40081. smooth: false,
  40082. minTurnAngle: 90,
  40083. maxSurfaceAngle: 90,
  40084. lineStyle: {
  40085. // color: 各异,
  40086. width: 1,
  40087. type: 'solid'
  40088. }
  40089. },
  40090. itemStyle: {
  40091. borderWidth: 1,
  40092. borderJoin: 'round'
  40093. },
  40094. showEmptyCircle: true,
  40095. emptyCircleStyle: {
  40096. color: 'lightgray',
  40097. opacity: 1
  40098. },
  40099. labelLayout: {
  40100. // Hide the overlapped label.
  40101. hideOverlap: true
  40102. },
  40103. emphasis: {
  40104. scale: true,
  40105. scaleSize: 5
  40106. },
  40107. // If use strategy to avoid label overlapping
  40108. avoidLabelOverlap: true,
  40109. // Animation type. Valid values: expansion, scale
  40110. animationType: 'expansion',
  40111. animationDuration: 1000,
  40112. // Animation type when update. Valid values: transition, expansion
  40113. animationTypeUpdate: 'transition',
  40114. animationEasingUpdate: 'cubicInOut',
  40115. animationDurationUpdate: 500,
  40116. animationEasing: 'cubicInOut'
  40117. };
  40118. return PieSeriesModel;
  40119. }(SeriesModel);
  40120. function negativeDataFilter(seriesType) {
  40121. return {
  40122. seriesType: seriesType,
  40123. reset: function (seriesModel, ecModel) {
  40124. var data = seriesModel.getData();
  40125. data.filterSelf(function (idx) {
  40126. // handle negative value condition
  40127. var valueDim = data.mapDimension('value');
  40128. var curValue = data.get(valueDim, idx);
  40129. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  40130. return false;
  40131. }
  40132. return true;
  40133. });
  40134. }
  40135. };
  40136. }
  40137. function install$4(registers) {
  40138. registers.registerChartView(PieView);
  40139. registers.registerSeriesModel(PieSeriesModel);
  40140. createLegacyDataSelectAction('pie', registers.registerAction);
  40141. registers.registerLayout(curry(pieLayout, 'pie'));
  40142. registers.registerProcessor(dataFilter('pie'));
  40143. registers.registerProcessor(negativeDataFilter('pie'));
  40144. }
  40145. var ScatterSeriesModel =
  40146. /** @class */
  40147. function (_super) {
  40148. __extends(ScatterSeriesModel, _super);
  40149. function ScatterSeriesModel() {
  40150. var _this = _super !== null && _super.apply(this, arguments) || this;
  40151. _this.type = ScatterSeriesModel.type;
  40152. _this.hasSymbolVisual = true;
  40153. return _this;
  40154. }
  40155. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  40156. return createSeriesData(null, this, {
  40157. useEncodeDefaulter: true
  40158. });
  40159. };
  40160. ScatterSeriesModel.prototype.getProgressive = function () {
  40161. var progressive = this.option.progressive;
  40162. if (progressive == null) {
  40163. // PENDING
  40164. return this.option.large ? 5e3 : this.get('progressive');
  40165. }
  40166. return progressive;
  40167. };
  40168. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  40169. var progressiveThreshold = this.option.progressiveThreshold;
  40170. if (progressiveThreshold == null) {
  40171. // PENDING
  40172. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  40173. }
  40174. return progressiveThreshold;
  40175. };
  40176. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  40177. return selectors.point(data.getItemLayout(dataIndex));
  40178. };
  40179. ScatterSeriesModel.prototype.getZLevelKey = function () {
  40180. // Each progressive series has individual key.
  40181. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  40182. };
  40183. ScatterSeriesModel.type = 'series.scatter';
  40184. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  40185. ScatterSeriesModel.defaultOption = {
  40186. coordinateSystem: 'cartesian2d',
  40187. // zlevel: 0,
  40188. z: 2,
  40189. legendHoverLink: true,
  40190. symbolSize: 10,
  40191. // symbolRotate: null, // 图形旋转控制
  40192. large: false,
  40193. // Available when large is true
  40194. largeThreshold: 2000,
  40195. // cursor: null,
  40196. itemStyle: {
  40197. opacity: 0.8 // color: 各异
  40198. },
  40199. emphasis: {
  40200. scale: true
  40201. },
  40202. // If clip the overflow graphics
  40203. // Works on cartesian / polar series
  40204. clip: true,
  40205. select: {
  40206. itemStyle: {
  40207. borderColor: '#212121'
  40208. }
  40209. },
  40210. universalTransition: {
  40211. divideShape: 'clone'
  40212. } // progressive: null
  40213. };
  40214. return ScatterSeriesModel;
  40215. }(SeriesModel);
  40216. var BOOST_SIZE_THRESHOLD = 4;
  40217. var LargeSymbolPathShape =
  40218. /** @class */
  40219. function () {
  40220. function LargeSymbolPathShape() {}
  40221. return LargeSymbolPathShape;
  40222. }();
  40223. var LargeSymbolPath =
  40224. /** @class */
  40225. function (_super) {
  40226. __extends(LargeSymbolPath, _super);
  40227. function LargeSymbolPath(opts) {
  40228. var _this = _super.call(this, opts) || this;
  40229. _this._off = 0;
  40230. _this.hoverDataIdx = -1;
  40231. return _this;
  40232. }
  40233. LargeSymbolPath.prototype.getDefaultShape = function () {
  40234. return new LargeSymbolPathShape();
  40235. };
  40236. LargeSymbolPath.prototype.reset = function () {
  40237. this.notClear = false;
  40238. this._off = 0;
  40239. };
  40240. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  40241. var points = shape.points;
  40242. var size = shape.size;
  40243. var symbolProxy = this.symbolProxy;
  40244. var symbolProxyShape = symbolProxy.shape;
  40245. var ctx = path.getContext ? path.getContext() : path;
  40246. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  40247. var softClipShape = this.softClipShape;
  40248. var i; // Do draw in afterBrush.
  40249. if (canBoost) {
  40250. this._ctx = ctx;
  40251. return;
  40252. }
  40253. this._ctx = null;
  40254. for (i = this._off; i < points.length;) {
  40255. var x = points[i++];
  40256. var y = points[i++];
  40257. if (isNaN(x) || isNaN(y)) {
  40258. continue;
  40259. }
  40260. if (softClipShape && !softClipShape.contain(x, y)) {
  40261. continue;
  40262. }
  40263. symbolProxyShape.x = x - size[0] / 2;
  40264. symbolProxyShape.y = y - size[1] / 2;
  40265. symbolProxyShape.width = size[0];
  40266. symbolProxyShape.height = size[1];
  40267. symbolProxy.buildPath(path, symbolProxyShape, true);
  40268. }
  40269. if (this.incremental) {
  40270. this._off = i;
  40271. this.notClear = true;
  40272. }
  40273. };
  40274. LargeSymbolPath.prototype.afterBrush = function () {
  40275. var shape = this.shape;
  40276. var points = shape.points;
  40277. var size = shape.size;
  40278. var ctx = this._ctx;
  40279. var softClipShape = this.softClipShape;
  40280. var i;
  40281. if (!ctx) {
  40282. return;
  40283. } // PENDING If style or other canvas status changed?
  40284. for (i = this._off; i < points.length;) {
  40285. var x = points[i++];
  40286. var y = points[i++];
  40287. if (isNaN(x) || isNaN(y)) {
  40288. continue;
  40289. }
  40290. if (softClipShape && !softClipShape.contain(x, y)) {
  40291. continue;
  40292. } // fillRect is faster than building a rect path and draw.
  40293. // And it support light globalCompositeOperation.
  40294. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  40295. }
  40296. if (this.incremental) {
  40297. this._off = i;
  40298. this.notClear = true;
  40299. }
  40300. };
  40301. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  40302. // TODO ???
  40303. // Consider transform
  40304. var shape = this.shape;
  40305. var points = shape.points;
  40306. var size = shape.size;
  40307. var w = Math.max(size[0], 4);
  40308. var h = Math.max(size[1], 4); // Not consider transform
  40309. // Treat each element as a rect
  40310. // top down traverse
  40311. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  40312. var i = idx * 2;
  40313. var x0 = points[i] - w / 2;
  40314. var y0 = points[i + 1] - h / 2;
  40315. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  40316. return idx;
  40317. }
  40318. }
  40319. return -1;
  40320. };
  40321. LargeSymbolPath.prototype.contain = function (x, y) {
  40322. var localPos = this.transformCoordToLocal(x, y);
  40323. var rect = this.getBoundingRect();
  40324. x = localPos[0];
  40325. y = localPos[1];
  40326. if (rect.contain(x, y)) {
  40327. // Cache found data index.
  40328. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  40329. return dataIdx >= 0;
  40330. }
  40331. this.hoverDataIdx = -1;
  40332. return false;
  40333. };
  40334. LargeSymbolPath.prototype.getBoundingRect = function () {
  40335. // Ignore stroke for large symbol draw.
  40336. var rect = this._rect;
  40337. if (!rect) {
  40338. var shape = this.shape;
  40339. var points = shape.points;
  40340. var size = shape.size;
  40341. var w = size[0];
  40342. var h = size[1];
  40343. var minX = Infinity;
  40344. var minY = Infinity;
  40345. var maxX = -Infinity;
  40346. var maxY = -Infinity;
  40347. for (var i = 0; i < points.length;) {
  40348. var x = points[i++];
  40349. var y = points[i++];
  40350. minX = Math.min(x, minX);
  40351. maxX = Math.max(x, maxX);
  40352. minY = Math.min(y, minY);
  40353. maxY = Math.max(y, maxY);
  40354. }
  40355. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  40356. }
  40357. return rect;
  40358. };
  40359. return LargeSymbolPath;
  40360. }(Path);
  40361. var LargeSymbolDraw =
  40362. /** @class */
  40363. function () {
  40364. function LargeSymbolDraw() {
  40365. this.group = new Group();
  40366. }
  40367. /**
  40368. * Update symbols draw by new data
  40369. */
  40370. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  40371. this._clear();
  40372. var symbolEl = this._create();
  40373. symbolEl.setShape({
  40374. points: data.getLayout('points')
  40375. });
  40376. this._setCommon(symbolEl, data, opt);
  40377. };
  40378. LargeSymbolDraw.prototype.updateLayout = function (data) {
  40379. var points = data.getLayout('points');
  40380. this.group.eachChild(function (child) {
  40381. if (child.startIndex != null) {
  40382. var len = (child.endIndex - child.startIndex) * 2;
  40383. var byteOffset = child.startIndex * 4 * 2;
  40384. points = new Float32Array(points.buffer, byteOffset, len);
  40385. }
  40386. child.setShape('points', points); // Reset draw cursor.
  40387. child.reset();
  40388. });
  40389. };
  40390. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  40391. this._clear();
  40392. };
  40393. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  40394. var lastAdded = this._newAdded[0];
  40395. var points = data.getLayout('points');
  40396. var oldPoints = lastAdded && lastAdded.shape.points; // Merging the exists. Each element has 1e4 points.
  40397. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  40398. if (oldPoints && oldPoints.length < 2e4) {
  40399. var oldLen = oldPoints.length;
  40400. var newPoints = new Float32Array(oldLen + points.length); // Concat two array
  40401. newPoints.set(oldPoints);
  40402. newPoints.set(points, oldLen); // Update endIndex
  40403. lastAdded.endIndex = taskParams.end;
  40404. lastAdded.setShape({
  40405. points: newPoints
  40406. });
  40407. } else {
  40408. // Clear
  40409. this._newAdded = [];
  40410. var symbolEl = this._create();
  40411. symbolEl.startIndex = taskParams.start;
  40412. symbolEl.endIndex = taskParams.end;
  40413. symbolEl.incremental = true;
  40414. symbolEl.setShape({
  40415. points: points
  40416. });
  40417. this._setCommon(symbolEl, data, opt);
  40418. }
  40419. };
  40420. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  40421. this._newAdded[0] && cb(this._newAdded[0]);
  40422. };
  40423. LargeSymbolDraw.prototype._create = function () {
  40424. var symbolEl = new LargeSymbolPath({
  40425. cursor: 'default'
  40426. });
  40427. symbolEl.ignoreCoarsePointer = true;
  40428. this.group.add(symbolEl);
  40429. this._newAdded.push(symbolEl);
  40430. return symbolEl;
  40431. };
  40432. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  40433. var hostModel = data.hostModel;
  40434. opt = opt || {};
  40435. var size = data.getVisual('symbolSize');
  40436. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  40437. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  40438. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  40439. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  40440. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  40441. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  40442. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  40443. var globalStyle = data.getVisual('style');
  40444. var visualColor = globalStyle && globalStyle.fill;
  40445. if (visualColor) {
  40446. symbolEl.setColor(visualColor);
  40447. }
  40448. var ecData = getECData(symbolEl); // Enable tooltip
  40449. // PENDING May have performance issue when path is extremely large
  40450. ecData.seriesIndex = hostModel.seriesIndex;
  40451. symbolEl.on('mousemove', function (e) {
  40452. ecData.dataIndex = null;
  40453. var dataIndex = symbolEl.hoverDataIdx;
  40454. if (dataIndex >= 0) {
  40455. // Provide dataIndex for tooltip
  40456. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  40457. }
  40458. });
  40459. };
  40460. LargeSymbolDraw.prototype.remove = function () {
  40461. this._clear();
  40462. };
  40463. LargeSymbolDraw.prototype._clear = function () {
  40464. this._newAdded = [];
  40465. this.group.removeAll();
  40466. };
  40467. return LargeSymbolDraw;
  40468. }();
  40469. var ScatterView =
  40470. /** @class */
  40471. function (_super) {
  40472. __extends(ScatterView, _super);
  40473. function ScatterView() {
  40474. var _this = _super !== null && _super.apply(this, arguments) || this;
  40475. _this.type = ScatterView.type;
  40476. return _this;
  40477. }
  40478. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  40479. var data = seriesModel.getData();
  40480. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40481. symbolDraw.updateData(data, {
  40482. // TODO
  40483. // If this parameter should be a shape or a bounding volume
  40484. // shape will be more general.
  40485. // But bounding volume like bounding rect will be much faster in the contain calculation
  40486. clipShape: this._getClipShape(seriesModel)
  40487. });
  40488. this._finished = true;
  40489. };
  40490. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  40491. var data = seriesModel.getData();
  40492. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40493. symbolDraw.incrementalPrepareUpdate(data);
  40494. this._finished = false;
  40495. };
  40496. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  40497. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  40498. clipShape: this._getClipShape(seriesModel)
  40499. });
  40500. this._finished = taskParams.end === seriesModel.getData().count();
  40501. };
  40502. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  40503. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  40504. // PENDING
  40505. this.group.dirty();
  40506. if (!this._finished || data.count() > 1e4) {
  40507. return {
  40508. update: true
  40509. };
  40510. } else {
  40511. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  40512. if (res.progress) {
  40513. res.progress({
  40514. start: 0,
  40515. end: data.count(),
  40516. count: data.count()
  40517. }, data);
  40518. }
  40519. this._symbolDraw.updateLayout(data);
  40520. }
  40521. };
  40522. ScatterView.prototype.eachRendered = function (cb) {
  40523. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  40524. };
  40525. ScatterView.prototype._getClipShape = function (seriesModel) {
  40526. var coordSys = seriesModel.coordinateSystem;
  40527. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  40528. return seriesModel.get('clip', true) ? clipArea : null;
  40529. };
  40530. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  40531. var symbolDraw = this._symbolDraw;
  40532. var pipelineContext = seriesModel.pipelineContext;
  40533. var isLargeDraw = pipelineContext.large;
  40534. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  40535. symbolDraw && symbolDraw.remove();
  40536. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  40537. this._isLargeDraw = isLargeDraw;
  40538. this.group.removeAll();
  40539. }
  40540. this.group.add(symbolDraw.group);
  40541. return symbolDraw;
  40542. };
  40543. ScatterView.prototype.remove = function (ecModel, api) {
  40544. this._symbolDraw && this._symbolDraw.remove(true);
  40545. this._symbolDraw = null;
  40546. };
  40547. ScatterView.prototype.dispose = function () {};
  40548. ScatterView.type = 'scatter';
  40549. return ScatterView;
  40550. }(ChartView);
  40551. var GridModel =
  40552. /** @class */
  40553. function (_super) {
  40554. __extends(GridModel, _super);
  40555. function GridModel() {
  40556. return _super !== null && _super.apply(this, arguments) || this;
  40557. }
  40558. GridModel.type = 'grid';
  40559. GridModel.dependencies = ['xAxis', 'yAxis'];
  40560. GridModel.layoutMode = 'box';
  40561. GridModel.defaultOption = {
  40562. show: false,
  40563. // zlevel: 0,
  40564. z: 0,
  40565. left: '10%',
  40566. top: 60,
  40567. right: '10%',
  40568. bottom: 70,
  40569. // If grid size contain label
  40570. containLabel: false,
  40571. // width: {totalWidth} - left - right,
  40572. // height: {totalHeight} - top - bottom,
  40573. backgroundColor: 'rgba(0,0,0,0)',
  40574. borderWidth: 1,
  40575. borderColor: '#ccc'
  40576. };
  40577. return GridModel;
  40578. }(ComponentModel);
  40579. var CartesianAxisModel =
  40580. /** @class */
  40581. function (_super) {
  40582. __extends(CartesianAxisModel, _super);
  40583. function CartesianAxisModel() {
  40584. return _super !== null && _super.apply(this, arguments) || this;
  40585. }
  40586. CartesianAxisModel.prototype.getCoordSysModel = function () {
  40587. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  40588. };
  40589. CartesianAxisModel.type = 'cartesian2dAxis';
  40590. return CartesianAxisModel;
  40591. }(ComponentModel);
  40592. mixin(CartesianAxisModel, AxisModelCommonMixin);
  40593. var defaultOption = {
  40594. show: true,
  40595. // zlevel: 0,
  40596. z: 0,
  40597. // Inverse the axis.
  40598. inverse: false,
  40599. // Axis name displayed.
  40600. name: '',
  40601. // 'start' | 'middle' | 'end'
  40602. nameLocation: 'end',
  40603. // By degree. By default auto rotate by nameLocation.
  40604. nameRotate: null,
  40605. nameTruncate: {
  40606. maxWidth: null,
  40607. ellipsis: '...',
  40608. placeholder: '.'
  40609. },
  40610. // Use global text style by default.
  40611. nameTextStyle: {},
  40612. // The gap between axisName and axisLine.
  40613. nameGap: 15,
  40614. // Default `false` to support tooltip.
  40615. silent: false,
  40616. // Default `false` to avoid legacy user event listener fail.
  40617. triggerEvent: false,
  40618. tooltip: {
  40619. show: false
  40620. },
  40621. axisPointer: {},
  40622. axisLine: {
  40623. show: true,
  40624. onZero: true,
  40625. onZeroAxisIndex: null,
  40626. lineStyle: {
  40627. color: '#6E7079',
  40628. width: 1,
  40629. type: 'solid'
  40630. },
  40631. // The arrow at both ends the the axis.
  40632. symbol: ['none', 'none'],
  40633. symbolSize: [10, 15]
  40634. },
  40635. axisTick: {
  40636. show: true,
  40637. // Whether axisTick is inside the grid or outside the grid.
  40638. inside: false,
  40639. // The length of axisTick.
  40640. length: 5,
  40641. lineStyle: {
  40642. width: 1
  40643. }
  40644. },
  40645. axisLabel: {
  40646. show: true,
  40647. // Whether axisLabel is inside the grid or outside the grid.
  40648. inside: false,
  40649. rotate: 0,
  40650. // true | false | null/undefined (auto)
  40651. showMinLabel: null,
  40652. // true | false | null/undefined (auto)
  40653. showMaxLabel: null,
  40654. margin: 8,
  40655. // formatter: null,
  40656. fontSize: 12
  40657. },
  40658. splitLine: {
  40659. show: true,
  40660. lineStyle: {
  40661. color: ['#E0E6F1'],
  40662. width: 1,
  40663. type: 'solid'
  40664. }
  40665. },
  40666. splitArea: {
  40667. show: false,
  40668. areaStyle: {
  40669. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  40670. }
  40671. }
  40672. };
  40673. var categoryAxis = merge({
  40674. // The gap at both ends of the axis. For categoryAxis, boolean.
  40675. boundaryGap: true,
  40676. // Set false to faster category collection.
  40677. deduplication: null,
  40678. // splitArea: {
  40679. // show: false
  40680. // },
  40681. splitLine: {
  40682. show: false
  40683. },
  40684. axisTick: {
  40685. // If tick is align with label when boundaryGap is true
  40686. alignWithLabel: false,
  40687. interval: 'auto'
  40688. },
  40689. axisLabel: {
  40690. interval: 'auto'
  40691. }
  40692. }, defaultOption);
  40693. var valueAxis = merge({
  40694. boundaryGap: [0, 0],
  40695. axisLine: {
  40696. // Not shown when other axis is categoryAxis in cartesian
  40697. show: 'auto'
  40698. },
  40699. axisTick: {
  40700. // Not shown when other axis is categoryAxis in cartesian
  40701. show: 'auto'
  40702. },
  40703. // TODO
  40704. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  40705. splitNumber: 5,
  40706. minorTick: {
  40707. // Minor tick, not available for cateogry axis.
  40708. show: false,
  40709. // Split number of minor ticks. The value should be in range of (0, 100)
  40710. splitNumber: 5,
  40711. // Length of minor tick
  40712. length: 3,
  40713. // Line style
  40714. lineStyle: {// Default to be same with axisTick
  40715. }
  40716. },
  40717. minorSplitLine: {
  40718. show: false,
  40719. lineStyle: {
  40720. color: '#F4F7FD',
  40721. width: 1
  40722. }
  40723. }
  40724. }, defaultOption);
  40725. var timeAxis = merge({
  40726. splitNumber: 6,
  40727. axisLabel: {
  40728. // To eliminate labels that are not nice
  40729. showMinLabel: false,
  40730. showMaxLabel: false,
  40731. rich: {
  40732. primary: {
  40733. fontWeight: 'bold'
  40734. }
  40735. }
  40736. },
  40737. splitLine: {
  40738. show: false
  40739. }
  40740. }, valueAxis);
  40741. var logAxis = defaults({
  40742. logBase: 10
  40743. }, valueAxis);
  40744. var axisDefault = {
  40745. category: categoryAxis,
  40746. value: valueAxis,
  40747. time: timeAxis,
  40748. log: logAxis
  40749. };
  40750. /*
  40751. * Licensed to the Apache Software Foundation (ASF) under one
  40752. * or more contributor license agreements. See the NOTICE file
  40753. * distributed with this work for additional information
  40754. * regarding copyright ownership. The ASF licenses this file
  40755. * to you under the Apache License, Version 2.0 (the
  40756. * "License"); you may not use this file except in compliance
  40757. * with the License. You may obtain a copy of the License at
  40758. *
  40759. * http://www.apache.org/licenses/LICENSE-2.0
  40760. *
  40761. * Unless required by applicable law or agreed to in writing,
  40762. * software distributed under the License is distributed on an
  40763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40764. * KIND, either express or implied. See the License for the
  40765. * specific language governing permissions and limitations
  40766. * under the License.
  40767. */
  40768. /**
  40769. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40770. */
  40771. /*
  40772. * Licensed to the Apache Software Foundation (ASF) under one
  40773. * or more contributor license agreements. See the NOTICE file
  40774. * distributed with this work for additional information
  40775. * regarding copyright ownership. The ASF licenses this file
  40776. * to you under the Apache License, Version 2.0 (the
  40777. * "License"); you may not use this file except in compliance
  40778. * with the License. You may obtain a copy of the License at
  40779. *
  40780. * http://www.apache.org/licenses/LICENSE-2.0
  40781. *
  40782. * Unless required by applicable law or agreed to in writing,
  40783. * software distributed under the License is distributed on an
  40784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40785. * KIND, either express or implied. See the License for the
  40786. * specific language governing permissions and limitations
  40787. * under the License.
  40788. */
  40789. var AXIS_TYPES = {
  40790. value: 1,
  40791. category: 1,
  40792. time: 1,
  40793. log: 1
  40794. };
  40795. /**
  40796. * Generate sub axis model class
  40797. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  40798. */
  40799. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  40800. each(AXIS_TYPES, function (v, axisType) {
  40801. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  40802. var AxisModel =
  40803. /** @class */
  40804. function (_super) {
  40805. __extends(AxisModel, _super);
  40806. function AxisModel() {
  40807. var _this = _super !== null && _super.apply(this, arguments) || this;
  40808. _this.type = axisName + 'Axis.' + axisType;
  40809. return _this;
  40810. }
  40811. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  40812. var layoutMode = fetchLayoutMode(this);
  40813. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  40814. var themeModel = ecModel.getTheme();
  40815. merge(option, themeModel.get(axisType + 'Axis'));
  40816. merge(option, this.getDefaultOption());
  40817. option.type = getAxisType(option);
  40818. if (layoutMode) {
  40819. mergeLayoutParam(option, inputPositionParams, layoutMode);
  40820. }
  40821. };
  40822. AxisModel.prototype.optionUpdated = function () {
  40823. var thisOption = this.option;
  40824. if (thisOption.type === 'category') {
  40825. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  40826. }
  40827. };
  40828. /**
  40829. * Should not be called before all of 'getInitailData' finished.
  40830. * Because categories are collected during initializing data.
  40831. */
  40832. AxisModel.prototype.getCategories = function (rawData) {
  40833. var option = this.option; // FIXME
  40834. // warning if called before all of 'getInitailData' finished.
  40835. if (option.type === 'category') {
  40836. if (rawData) {
  40837. return option.data;
  40838. }
  40839. return this.__ordinalMeta.categories;
  40840. }
  40841. };
  40842. AxisModel.prototype.getOrdinalMeta = function () {
  40843. return this.__ordinalMeta;
  40844. };
  40845. AxisModel.type = axisName + 'Axis.' + axisType;
  40846. AxisModel.defaultOption = defaultOption;
  40847. return AxisModel;
  40848. }(BaseAxisModelClass);
  40849. registers.registerComponentModel(AxisModel);
  40850. });
  40851. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  40852. }
  40853. function getAxisType(option) {
  40854. // Default axis with data is category axis
  40855. return option.type || (option.data ? 'category' : 'value');
  40856. }
  40857. var Cartesian =
  40858. /** @class */
  40859. function () {
  40860. function Cartesian(name) {
  40861. this.type = 'cartesian';
  40862. this._dimList = [];
  40863. this._axes = {};
  40864. this.name = name || '';
  40865. }
  40866. Cartesian.prototype.getAxis = function (dim) {
  40867. return this._axes[dim];
  40868. };
  40869. Cartesian.prototype.getAxes = function () {
  40870. return map(this._dimList, function (dim) {
  40871. return this._axes[dim];
  40872. }, this);
  40873. };
  40874. Cartesian.prototype.getAxesByScale = function (scaleType) {
  40875. scaleType = scaleType.toLowerCase();
  40876. return filter(this.getAxes(), function (axis) {
  40877. return axis.scale.type === scaleType;
  40878. });
  40879. };
  40880. Cartesian.prototype.addAxis = function (axis) {
  40881. var dim = axis.dim;
  40882. this._axes[dim] = axis;
  40883. this._dimList.push(dim);
  40884. };
  40885. return Cartesian;
  40886. }();
  40887. var cartesian2DDimensions = ['x', 'y'];
  40888. function canCalculateAffineTransform(scale) {
  40889. return scale.type === 'interval' || scale.type === 'time';
  40890. }
  40891. var Cartesian2D =
  40892. /** @class */
  40893. function (_super) {
  40894. __extends(Cartesian2D, _super);
  40895. function Cartesian2D() {
  40896. var _this = _super !== null && _super.apply(this, arguments) || this;
  40897. _this.type = 'cartesian2d';
  40898. _this.dimensions = cartesian2DDimensions;
  40899. return _this;
  40900. }
  40901. /**
  40902. * Calculate an affine transform matrix if two axes are time or value.
  40903. * It's mainly for accelartion on the large time series data.
  40904. */
  40905. Cartesian2D.prototype.calcAffineTransform = function () {
  40906. this._transform = this._invTransform = null;
  40907. var xAxisScale = this.getAxis('x').scale;
  40908. var yAxisScale = this.getAxis('y').scale;
  40909. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  40910. return;
  40911. }
  40912. var xScaleExtent = xAxisScale.getExtent();
  40913. var yScaleExtent = yAxisScale.getExtent();
  40914. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  40915. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  40916. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  40917. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  40918. if (!xScaleSpan || !yScaleSpan) {
  40919. return;
  40920. } // Accelerate data to point calculation on the special large time series data.
  40921. var scaleX = (end[0] - start[0]) / xScaleSpan;
  40922. var scaleY = (end[1] - start[1]) / yScaleSpan;
  40923. var translateX = start[0] - xScaleExtent[0] * scaleX;
  40924. var translateY = start[1] - yScaleExtent[0] * scaleY;
  40925. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  40926. this._invTransform = invert([], m);
  40927. };
  40928. /**
  40929. * Base axis will be used on stacking.
  40930. */
  40931. Cartesian2D.prototype.getBaseAxis = function () {
  40932. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  40933. };
  40934. Cartesian2D.prototype.containPoint = function (point) {
  40935. var axisX = this.getAxis('x');
  40936. var axisY = this.getAxis('y');
  40937. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  40938. };
  40939. Cartesian2D.prototype.containData = function (data) {
  40940. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  40941. };
  40942. Cartesian2D.prototype.containZone = function (data1, data2) {
  40943. var zoneDiag1 = this.dataToPoint(data1);
  40944. var zoneDiag2 = this.dataToPoint(data2);
  40945. var area = this.getArea();
  40946. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  40947. return area.intersect(zone);
  40948. };
  40949. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  40950. out = out || [];
  40951. var xVal = data[0];
  40952. var yVal = data[1]; // Fast path
  40953. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  40954. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  40955. return applyTransform(out, data, this._transform);
  40956. }
  40957. var xAxis = this.getAxis('x');
  40958. var yAxis = this.getAxis('y');
  40959. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  40960. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  40961. return out;
  40962. };
  40963. Cartesian2D.prototype.clampData = function (data, out) {
  40964. var xScale = this.getAxis('x').scale;
  40965. var yScale = this.getAxis('y').scale;
  40966. var xAxisExtent = xScale.getExtent();
  40967. var yAxisExtent = yScale.getExtent();
  40968. var x = xScale.parse(data[0]);
  40969. var y = yScale.parse(data[1]);
  40970. out = out || [];
  40971. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  40972. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  40973. return out;
  40974. };
  40975. Cartesian2D.prototype.pointToData = function (point, clamp) {
  40976. var out = [];
  40977. if (this._invTransform) {
  40978. return applyTransform(out, point, this._invTransform);
  40979. }
  40980. var xAxis = this.getAxis('x');
  40981. var yAxis = this.getAxis('y');
  40982. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  40983. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  40984. return out;
  40985. };
  40986. Cartesian2D.prototype.getOtherAxis = function (axis) {
  40987. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  40988. };
  40989. /**
  40990. * Get rect area of cartesian.
  40991. * Area will have a contain function to determine if a point is in the coordinate system.
  40992. */
  40993. Cartesian2D.prototype.getArea = function () {
  40994. var xExtent = this.getAxis('x').getGlobalExtent();
  40995. var yExtent = this.getAxis('y').getGlobalExtent();
  40996. var x = Math.min(xExtent[0], xExtent[1]);
  40997. var y = Math.min(yExtent[0], yExtent[1]);
  40998. var width = Math.max(xExtent[0], xExtent[1]) - x;
  40999. var height = Math.max(yExtent[0], yExtent[1]) - y;
  41000. return new BoundingRect(x, y, width, height);
  41001. };
  41002. return Cartesian2D;
  41003. }(Cartesian);
  41004. var Axis2D =
  41005. /** @class */
  41006. function (_super) {
  41007. __extends(Axis2D, _super);
  41008. function Axis2D(dim, scale, coordExtent, axisType, position) {
  41009. var _this = _super.call(this, dim, scale, coordExtent) || this;
  41010. /**
  41011. * Index of axis, can be used as key
  41012. * Injected outside.
  41013. */
  41014. _this.index = 0;
  41015. _this.type = axisType || 'value';
  41016. _this.position = position || 'bottom';
  41017. return _this;
  41018. }
  41019. Axis2D.prototype.isHorizontal = function () {
  41020. var position = this.position;
  41021. return position === 'top' || position === 'bottom';
  41022. };
  41023. /**
  41024. * Each item cooresponds to this.getExtent(), which
  41025. * means globalExtent[0] may greater than globalExtent[1],
  41026. * unless `asc` is input.
  41027. *
  41028. * @param {boolean} [asc]
  41029. * @return {Array.<number>}
  41030. */
  41031. Axis2D.prototype.getGlobalExtent = function (asc) {
  41032. var ret = this.getExtent();
  41033. ret[0] = this.toGlobalCoord(ret[0]);
  41034. ret[1] = this.toGlobalCoord(ret[1]);
  41035. asc && ret[0] > ret[1] && ret.reverse();
  41036. return ret;
  41037. };
  41038. Axis2D.prototype.pointToData = function (point, clamp) {
  41039. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  41040. };
  41041. /**
  41042. * Set ordinalSortInfo
  41043. * @param info new OrdinalSortInfo
  41044. */
  41045. Axis2D.prototype.setCategorySortInfo = function (info) {
  41046. if (this.type !== 'category') {
  41047. return false;
  41048. }
  41049. this.model.option.categorySortInfo = info;
  41050. this.scale.setSortInfo(info);
  41051. };
  41052. return Axis2D;
  41053. }(Axis);
  41054. /**
  41055. * Can only be called after coordinate system creation stage.
  41056. * (Can be called before coordinate system update stage).
  41057. */
  41058. function layout$1(gridModel, axisModel, opt) {
  41059. opt = opt || {};
  41060. var grid = gridModel.coordinateSystem;
  41061. var axis = axisModel.axis;
  41062. var layout = {};
  41063. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  41064. var rawAxisPosition = axis.position;
  41065. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  41066. var axisDim = axis.dim;
  41067. var rect = grid.getRect();
  41068. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  41069. var idx = {
  41070. left: 0,
  41071. right: 1,
  41072. top: 0,
  41073. bottom: 1,
  41074. onZero: 2
  41075. };
  41076. var axisOffset = axisModel.get('offset') || 0;
  41077. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  41078. if (otherAxisOnZeroOf) {
  41079. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  41080. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  41081. } // Axis position
  41082. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  41083. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  41084. var dirMap = {
  41085. top: -1,
  41086. bottom: 1,
  41087. left: -1,
  41088. right: 1
  41089. };
  41090. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  41091. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  41092. if (axisModel.get(['axisTick', 'inside'])) {
  41093. layout.tickDirection = -layout.tickDirection;
  41094. }
  41095. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  41096. layout.labelDirection = -layout.labelDirection;
  41097. } // Special label rotation
  41098. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  41099. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  41100. layout.z2 = 1;
  41101. return layout;
  41102. }
  41103. function isCartesian2DSeries(seriesModel) {
  41104. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  41105. }
  41106. function findAxisModels(seriesModel) {
  41107. var axisModelMap = {
  41108. xAxisModel: null,
  41109. yAxisModel: null
  41110. };
  41111. each(axisModelMap, function (v, key) {
  41112. var axisType = key.replace(/Model$/, '');
  41113. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  41114. if ("development" !== 'production') {
  41115. if (!axisModel) {
  41116. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  41117. }
  41118. }
  41119. axisModelMap[key] = axisModel;
  41120. });
  41121. return axisModelMap;
  41122. }
  41123. var mathLog$1 = Math.log;
  41124. function alignScaleTicks(scale, axisModel, alignToScale) {
  41125. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  41126. // In log scale we store _interval and _extent of exponent value.
  41127. // So if we use the method of InternalScale to set/get these data.
  41128. // It process the exponent value, which is linear and what we want here.
  41129. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  41130. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  41131. var alignToSplitNumber = alignToTicks.length - 1;
  41132. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  41133. var scaleExtent = getScaleExtent(scale, axisModel);
  41134. var rawExtent = scaleExtent.extent;
  41135. var isMinFixed = scaleExtent.fixMin;
  41136. var isMaxFixed = scaleExtent.fixMax;
  41137. if (scale.type === 'log') {
  41138. var logBase = mathLog$1(scale.base);
  41139. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  41140. }
  41141. scale.setExtent(rawExtent[0], rawExtent[1]);
  41142. scale.calcNiceExtent({
  41143. splitNumber: alignToSplitNumber,
  41144. fixMin: isMinFixed,
  41145. fixMax: isMaxFixed
  41146. });
  41147. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  41148. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  41149. if (isMinFixed) {
  41150. rawExtent[0] = extent[0];
  41151. }
  41152. if (isMaxFixed) {
  41153. rawExtent[1] = extent[1];
  41154. }
  41155. var interval = intervalScaleProto.getInterval.call(scale);
  41156. var min = rawExtent[0];
  41157. var max = rawExtent[1];
  41158. if (isMinFixed && isMaxFixed) {
  41159. // User set min, max, divide to get new interval
  41160. interval = (max - min) / alignToSplitNumber;
  41161. } else if (isMinFixed) {
  41162. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  41163. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  41164. interval = increaseInterval(interval);
  41165. max = rawExtent[0] + interval * alignToSplitNumber;
  41166. }
  41167. } else if (isMaxFixed) {
  41168. // User set max, expand extent on the other side
  41169. min = rawExtent[1] - interval * alignToSplitNumber;
  41170. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  41171. interval = increaseInterval(interval);
  41172. min = rawExtent[1] - interval * alignToSplitNumber;
  41173. }
  41174. } else {
  41175. var nicedSplitNumber = scale.getTicks().length - 1;
  41176. if (nicedSplitNumber > alignToSplitNumber) {
  41177. interval = increaseInterval(interval);
  41178. }
  41179. var range = interval * alignToSplitNumber;
  41180. max = Math.ceil(rawExtent[1] / interval) * interval;
  41181. min = round(max - range); // Not change the result that crossing zero.
  41182. if (min < 0 && rawExtent[0] >= 0) {
  41183. min = 0;
  41184. max = round(range);
  41185. } else if (max > 0 && rawExtent[1] <= 0) {
  41186. max = 0;
  41187. min = -round(range);
  41188. }
  41189. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  41190. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  41191. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  41192. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  41193. intervalScaleProto.setInterval.call(scale, interval);
  41194. if (t0 || t1) {
  41195. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  41196. }
  41197. if ("development" !== 'production') {
  41198. var ticks = intervalScaleProto.getTicks.call(scale);
  41199. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  41200. warn( // eslint-disable-next-line
  41201. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  41202. }
  41203. }
  41204. }
  41205. var Grid =
  41206. /** @class */
  41207. function () {
  41208. function Grid(gridModel, ecModel, api) {
  41209. // FIXME:TS where used (different from registered type 'cartesian2d')?
  41210. this.type = 'grid';
  41211. this._coordsMap = {};
  41212. this._coordsList = [];
  41213. this._axesMap = {};
  41214. this._axesList = [];
  41215. this.axisPointerEnabled = true;
  41216. this.dimensions = cartesian2DDimensions;
  41217. this._initCartesian(gridModel, ecModel, api);
  41218. this.model = gridModel;
  41219. }
  41220. Grid.prototype.getRect = function () {
  41221. return this._rect;
  41222. };
  41223. Grid.prototype.update = function (ecModel, api) {
  41224. var axesMap = this._axesMap;
  41225. this._updateScale(ecModel, this.model);
  41226. function updateAxisTicks(axes) {
  41227. var alignTo; // Axis is added in order of axisIndex.
  41228. var axesIndices = keys(axes);
  41229. var len = axesIndices.length;
  41230. if (!len) {
  41231. return;
  41232. }
  41233. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  41234. for (var i = len - 1; i >= 0; i--) {
  41235. var idx = +axesIndices[i]; // Convert to number.
  41236. var axis = axes[idx];
  41237. var model = axis.model;
  41238. var scale = axis.scale;
  41239. if ( // Only value and log axis without interval support alignTicks.
  41240. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  41241. axisNeedsAlign.push(axis);
  41242. } else {
  41243. niceScaleExtent(scale, model);
  41244. if (isIntervalOrLogScale(scale)) {
  41245. // Can only align to interval or log axis.
  41246. alignTo = axis;
  41247. }
  41248. }
  41249. }
  41250. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  41251. if (axisNeedsAlign.length) {
  41252. if (!alignTo) {
  41253. alignTo = axisNeedsAlign.pop();
  41254. niceScaleExtent(alignTo.scale, alignTo.model);
  41255. }
  41256. each(axisNeedsAlign, function (axis) {
  41257. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  41258. });
  41259. }
  41260. }
  41261. updateAxisTicks(axesMap.x);
  41262. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  41263. var onZeroRecords = {};
  41264. each(axesMap.x, function (xAxis) {
  41265. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  41266. });
  41267. each(axesMap.y, function (yAxis) {
  41268. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  41269. }); // Resize again if containLabel is enabled
  41270. // FIXME It may cause getting wrong grid size in data processing stage
  41271. this.resize(this.model, api);
  41272. };
  41273. /**
  41274. * Resize the grid
  41275. */
  41276. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  41277. var boxLayoutParams = gridModel.getBoxLayoutParams();
  41278. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  41279. var gridRect = getLayoutRect(boxLayoutParams, {
  41280. width: api.getWidth(),
  41281. height: api.getHeight()
  41282. });
  41283. this._rect = gridRect;
  41284. var axesList = this._axesList;
  41285. adjustAxes(); // Minus label size
  41286. if (isContainLabel) {
  41287. each(axesList, function (axis) {
  41288. if (!axis.model.get(['axisLabel', 'inside'])) {
  41289. var labelUnionRect = estimateLabelUnionRect(axis);
  41290. if (labelUnionRect) {
  41291. var dim = axis.isHorizontal() ? 'height' : 'width';
  41292. var margin = axis.model.get(['axisLabel', 'margin']);
  41293. gridRect[dim] -= labelUnionRect[dim] + margin;
  41294. if (axis.position === 'top') {
  41295. gridRect.y += labelUnionRect.height + margin;
  41296. } else if (axis.position === 'left') {
  41297. gridRect.x += labelUnionRect.width + margin;
  41298. }
  41299. }
  41300. }
  41301. });
  41302. adjustAxes();
  41303. }
  41304. each(this._coordsList, function (coord) {
  41305. // Calculate affine matrix to accelerate the data to point transform.
  41306. // If all the axes scales are time or value.
  41307. coord.calcAffineTransform();
  41308. });
  41309. function adjustAxes() {
  41310. each(axesList, function (axis) {
  41311. var isHorizontal = axis.isHorizontal();
  41312. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  41313. var idx = axis.inverse ? 1 : 0;
  41314. axis.setExtent(extent[idx], extent[1 - idx]);
  41315. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  41316. });
  41317. }
  41318. };
  41319. Grid.prototype.getAxis = function (dim, axisIndex) {
  41320. var axesMapOnDim = this._axesMap[dim];
  41321. if (axesMapOnDim != null) {
  41322. return axesMapOnDim[axisIndex || 0];
  41323. }
  41324. };
  41325. Grid.prototype.getAxes = function () {
  41326. return this._axesList.slice();
  41327. };
  41328. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  41329. if (xAxisIndex != null && yAxisIndex != null) {
  41330. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  41331. return this._coordsMap[key];
  41332. }
  41333. if (isObject(xAxisIndex)) {
  41334. yAxisIndex = xAxisIndex.yAxisIndex;
  41335. xAxisIndex = xAxisIndex.xAxisIndex;
  41336. }
  41337. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  41338. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  41339. return coordList[i];
  41340. }
  41341. }
  41342. };
  41343. Grid.prototype.getCartesians = function () {
  41344. return this._coordsList.slice();
  41345. };
  41346. /**
  41347. * @implements
  41348. */
  41349. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  41350. var target = this._findConvertTarget(finder);
  41351. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  41352. };
  41353. /**
  41354. * @implements
  41355. */
  41356. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  41357. var target = this._findConvertTarget(finder);
  41358. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  41359. };
  41360. Grid.prototype._findConvertTarget = function (finder) {
  41361. var seriesModel = finder.seriesModel;
  41362. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  41363. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  41364. var gridModel = finder.gridModel;
  41365. var coordsList = this._coordsList;
  41366. var cartesian;
  41367. var axis;
  41368. if (seriesModel) {
  41369. cartesian = seriesModel.coordinateSystem;
  41370. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  41371. } else if (xAxisModel && yAxisModel) {
  41372. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41373. } else if (xAxisModel) {
  41374. axis = this.getAxis('x', xAxisModel.componentIndex);
  41375. } else if (yAxisModel) {
  41376. axis = this.getAxis('y', yAxisModel.componentIndex);
  41377. } // Lowest priority.
  41378. else if (gridModel) {
  41379. var grid = gridModel.coordinateSystem;
  41380. if (grid === this) {
  41381. cartesian = this._coordsList[0];
  41382. }
  41383. }
  41384. return {
  41385. cartesian: cartesian,
  41386. axis: axis
  41387. };
  41388. };
  41389. /**
  41390. * @implements
  41391. */
  41392. Grid.prototype.containPoint = function (point) {
  41393. var coord = this._coordsList[0];
  41394. if (coord) {
  41395. return coord.containPoint(point);
  41396. }
  41397. };
  41398. /**
  41399. * Initialize cartesian coordinate systems
  41400. */
  41401. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  41402. var _this = this;
  41403. var grid = this;
  41404. var axisPositionUsed = {
  41405. left: false,
  41406. right: false,
  41407. top: false,
  41408. bottom: false
  41409. };
  41410. var axesMap = {
  41411. x: {},
  41412. y: {}
  41413. };
  41414. var axesCount = {
  41415. x: 0,
  41416. y: 0
  41417. }; // Create axis
  41418. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  41419. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  41420. if (!axesCount.x || !axesCount.y) {
  41421. // Roll back when there no either x or y axis
  41422. this._axesMap = {};
  41423. this._axesList = [];
  41424. return;
  41425. }
  41426. this._axesMap = axesMap; // Create cartesian2d
  41427. each(axesMap.x, function (xAxis, xAxisIndex) {
  41428. each(axesMap.y, function (yAxis, yAxisIndex) {
  41429. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  41430. var cartesian = new Cartesian2D(key);
  41431. cartesian.master = _this;
  41432. cartesian.model = gridModel;
  41433. _this._coordsMap[key] = cartesian;
  41434. _this._coordsList.push(cartesian);
  41435. cartesian.addAxis(xAxis);
  41436. cartesian.addAxis(yAxis);
  41437. });
  41438. });
  41439. function createAxisCreator(dimName) {
  41440. return function (axisModel, idx) {
  41441. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  41442. return;
  41443. }
  41444. var axisPosition = axisModel.get('position');
  41445. if (dimName === 'x') {
  41446. // Fix position
  41447. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  41448. // Default bottom of X
  41449. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  41450. }
  41451. } else {
  41452. // Fix position
  41453. if (axisPosition !== 'left' && axisPosition !== 'right') {
  41454. // Default left of Y
  41455. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  41456. }
  41457. }
  41458. axisPositionUsed[axisPosition] = true;
  41459. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  41460. var isCategory = axis.type === 'category';
  41461. axis.onBand = isCategory && axisModel.get('boundaryGap');
  41462. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  41463. axisModel.axis = axis; // Inject axisModel into axis
  41464. axis.model = axisModel; // Inject grid info axis
  41465. axis.grid = grid; // Index of axis, can be used as key
  41466. axis.index = idx;
  41467. grid._axesList.push(axis);
  41468. axesMap[dimName][idx] = axis;
  41469. axesCount[dimName]++;
  41470. };
  41471. }
  41472. };
  41473. /**
  41474. * Update cartesian properties from series.
  41475. */
  41476. Grid.prototype._updateScale = function (ecModel, gridModel) {
  41477. // Reset scale
  41478. each(this._axesList, function (axis) {
  41479. axis.scale.setExtent(Infinity, -Infinity);
  41480. if (axis.type === 'category') {
  41481. var categorySortInfo = axis.model.get('categorySortInfo');
  41482. axis.scale.setSortInfo(categorySortInfo);
  41483. }
  41484. });
  41485. ecModel.eachSeries(function (seriesModel) {
  41486. if (isCartesian2DSeries(seriesModel)) {
  41487. var axesModelMap = findAxisModels(seriesModel);
  41488. var xAxisModel = axesModelMap.xAxisModel;
  41489. var yAxisModel = axesModelMap.yAxisModel;
  41490. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  41491. return;
  41492. }
  41493. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41494. var data = seriesModel.getData();
  41495. var xAxis = cartesian.getAxis('x');
  41496. var yAxis = cartesian.getAxis('y');
  41497. unionExtent(data, xAxis);
  41498. unionExtent(data, yAxis);
  41499. }
  41500. }, this);
  41501. function unionExtent(data, axis) {
  41502. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  41503. axis.scale.unionExtentFromData(data, dim);
  41504. });
  41505. }
  41506. };
  41507. /**
  41508. * @param dim 'x' or 'y' or 'auto' or null/undefined
  41509. */
  41510. Grid.prototype.getTooltipAxes = function (dim) {
  41511. var baseAxes = [];
  41512. var otherAxes = [];
  41513. each(this.getCartesians(), function (cartesian) {
  41514. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  41515. var otherAxis = cartesian.getOtherAxis(baseAxis);
  41516. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  41517. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  41518. });
  41519. return {
  41520. baseAxes: baseAxes,
  41521. otherAxes: otherAxes
  41522. };
  41523. };
  41524. Grid.create = function (ecModel, api) {
  41525. var grids = [];
  41526. ecModel.eachComponent('grid', function (gridModel, idx) {
  41527. var grid = new Grid(gridModel, ecModel, api);
  41528. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  41529. // should be performed in create stage.
  41530. grid.resize(gridModel, api, true);
  41531. gridModel.coordinateSystem = grid;
  41532. grids.push(grid);
  41533. }); // Inject the coordinateSystems into seriesModel
  41534. ecModel.eachSeries(function (seriesModel) {
  41535. if (!isCartesian2DSeries(seriesModel)) {
  41536. return;
  41537. }
  41538. var axesModelMap = findAxisModels(seriesModel);
  41539. var xAxisModel = axesModelMap.xAxisModel;
  41540. var yAxisModel = axesModelMap.yAxisModel;
  41541. var gridModel = xAxisModel.getCoordSysModel();
  41542. if ("development" !== 'production') {
  41543. if (!gridModel) {
  41544. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  41545. }
  41546. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  41547. throw new Error('xAxis and yAxis must use the same grid');
  41548. }
  41549. }
  41550. var grid = gridModel.coordinateSystem;
  41551. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41552. });
  41553. return grids;
  41554. }; // For deciding which dimensions to use when creating list data
  41555. Grid.dimensions = cartesian2DDimensions;
  41556. return Grid;
  41557. }();
  41558. /**
  41559. * Check if the axis is used in the specified grid.
  41560. */
  41561. function isAxisUsedInTheGrid(axisModel, gridModel) {
  41562. return axisModel.getCoordSysModel() === gridModel;
  41563. }
  41564. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  41565. onZeroRecords) {
  41566. axis.getAxesOnZeroOf = function () {
  41567. // TODO: onZero of multiple axes.
  41568. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  41569. }; // onZero can not be enabled in these two situations:
  41570. // 1. When any other axis is a category axis.
  41571. // 2. When no axis is cross 0 point.
  41572. var otherAxes = axesMap[otherAxisDim];
  41573. var otherAxisOnZeroOf;
  41574. var axisModel = axis.model;
  41575. var onZero = axisModel.get(['axisLine', 'onZero']);
  41576. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  41577. if (!onZero) {
  41578. return;
  41579. } // If target axis is specified.
  41580. if (onZeroAxisIndex != null) {
  41581. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  41582. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  41583. }
  41584. } else {
  41585. // Find the first available other axis.
  41586. for (var idx in otherAxes) {
  41587. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  41588. // if both onZero, the two Y axes overlap.
  41589. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  41590. otherAxisOnZeroOf = otherAxes[idx];
  41591. break;
  41592. }
  41593. }
  41594. }
  41595. if (otherAxisOnZeroOf) {
  41596. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  41597. }
  41598. function getOnZeroRecordKey(axis) {
  41599. return axis.dim + '_' + axis.index;
  41600. }
  41601. }
  41602. function canOnZeroToAxis(axis) {
  41603. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  41604. }
  41605. function updateAxisTransform(axis, coordBase) {
  41606. var axisExtent = axis.getExtent();
  41607. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  41608. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  41609. return coord + coordBase;
  41610. } : function (coord) {
  41611. return axisExtentSum - coord + coordBase;
  41612. };
  41613. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  41614. return coord - coordBase;
  41615. } : function (coord) {
  41616. return axisExtentSum - coord + coordBase;
  41617. };
  41618. }
  41619. var PI$5 = Math.PI;
  41620. /**
  41621. * A final axis is translated and rotated from a "standard axis".
  41622. * So opt.position and opt.rotation is required.
  41623. *
  41624. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  41625. * for example: (0, 0) ------------> (0, 50)
  41626. *
  41627. * nameDirection or tickDirection or labelDirection is 1 means tick
  41628. * or label is below the standard axis, whereas is -1 means above
  41629. * the standard axis. labelOffset means offset between label and axis,
  41630. * which is useful when 'onZero', where axisLabel is in the grid and
  41631. * label in outside grid.
  41632. *
  41633. * Tips: like always,
  41634. * positive rotation represents anticlockwise, and negative rotation
  41635. * represents clockwise.
  41636. * The direction of position coordinate is the same as the direction
  41637. * of screen coordinate.
  41638. *
  41639. * Do not need to consider axis 'inverse', which is auto processed by
  41640. * axis extent.
  41641. */
  41642. var AxisBuilder =
  41643. /** @class */
  41644. function () {
  41645. function AxisBuilder(axisModel, opt) {
  41646. this.group = new Group();
  41647. this.opt = opt;
  41648. this.axisModel = axisModel; // Default value
  41649. defaults(opt, {
  41650. labelOffset: 0,
  41651. nameDirection: 1,
  41652. tickDirection: 1,
  41653. labelDirection: 1,
  41654. silent: true,
  41655. handleAutoShown: function () {
  41656. return true;
  41657. }
  41658. }); // FIXME Not use a separate text group?
  41659. var transformGroup = new Group({
  41660. x: opt.position[0],
  41661. y: opt.position[1],
  41662. rotation: opt.rotation
  41663. }); // this.group.add(transformGroup);
  41664. // this._transformGroup = transformGroup;
  41665. transformGroup.updateTransform();
  41666. this._transformGroup = transformGroup;
  41667. }
  41668. AxisBuilder.prototype.hasBuilder = function (name) {
  41669. return !!builders[name];
  41670. };
  41671. AxisBuilder.prototype.add = function (name) {
  41672. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  41673. };
  41674. AxisBuilder.prototype.getGroup = function () {
  41675. return this.group;
  41676. };
  41677. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  41678. var rotationDiff = remRadian(textRotation - axisRotation);
  41679. var textAlign;
  41680. var textVerticalAlign;
  41681. if (isRadianAroundZero(rotationDiff)) {
  41682. // Label is parallel with axis line.
  41683. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  41684. textAlign = 'center';
  41685. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  41686. // Label is inverse parallel with axis line.
  41687. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  41688. textAlign = 'center';
  41689. } else {
  41690. textVerticalAlign = 'middle';
  41691. if (rotationDiff > 0 && rotationDiff < PI$5) {
  41692. textAlign = direction > 0 ? 'right' : 'left';
  41693. } else {
  41694. textAlign = direction > 0 ? 'left' : 'right';
  41695. }
  41696. }
  41697. return {
  41698. rotation: rotationDiff,
  41699. textAlign: textAlign,
  41700. textVerticalAlign: textVerticalAlign
  41701. };
  41702. };
  41703. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  41704. var eventData = {
  41705. componentType: axisModel.mainType,
  41706. componentIndex: axisModel.componentIndex
  41707. };
  41708. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  41709. return eventData;
  41710. };
  41711. AxisBuilder.isLabelSilent = function (axisModel) {
  41712. var tooltipOpt = axisModel.get('tooltip');
  41713. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  41714. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  41715. };
  41716. return AxisBuilder;
  41717. }();
  41718. var builders = {
  41719. axisLine: function (opt, axisModel, group, transformGroup) {
  41720. var shown = axisModel.get(['axisLine', 'show']);
  41721. if (shown === 'auto' && opt.handleAutoShown) {
  41722. shown = opt.handleAutoShown('axisLine');
  41723. }
  41724. if (!shown) {
  41725. return;
  41726. }
  41727. var extent = axisModel.axis.getExtent();
  41728. var matrix = transformGroup.transform;
  41729. var pt1 = [extent[0], 0];
  41730. var pt2 = [extent[1], 0];
  41731. var inverse = pt1[0] > pt2[0];
  41732. if (matrix) {
  41733. applyTransform(pt1, pt1, matrix);
  41734. applyTransform(pt2, pt2, matrix);
  41735. }
  41736. var lineStyle = extend({
  41737. lineCap: 'round'
  41738. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  41739. var line = new Line({
  41740. shape: {
  41741. x1: pt1[0],
  41742. y1: pt1[1],
  41743. x2: pt2[0],
  41744. y2: pt2[1]
  41745. },
  41746. style: lineStyle,
  41747. strokeContainThreshold: opt.strokeContainThreshold || 5,
  41748. silent: true,
  41749. z2: 1
  41750. });
  41751. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  41752. line.anid = 'line';
  41753. group.add(line);
  41754. var arrows = axisModel.get(['axisLine', 'symbol']);
  41755. if (arrows != null) {
  41756. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  41757. if (isString(arrows)) {
  41758. // Use the same arrow for start and end point
  41759. arrows = [arrows, arrows];
  41760. }
  41761. if (isString(arrowSize) || isNumber(arrowSize)) {
  41762. // Use the same size for width and height
  41763. arrowSize = [arrowSize, arrowSize];
  41764. }
  41765. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  41766. var symbolWidth_1 = arrowSize[0];
  41767. var symbolHeight_1 = arrowSize[1];
  41768. each([{
  41769. rotate: opt.rotation + Math.PI / 2,
  41770. offset: arrowOffset[0],
  41771. r: 0
  41772. }, {
  41773. rotate: opt.rotation - Math.PI / 2,
  41774. offset: arrowOffset[1],
  41775. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  41776. }], function (point, index) {
  41777. if (arrows[index] !== 'none' && arrows[index] != null) {
  41778. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  41779. var r = point.r + point.offset;
  41780. var pt = inverse ? pt2 : pt1;
  41781. symbol.attr({
  41782. rotation: point.rotate,
  41783. x: pt[0] + r * Math.cos(opt.rotation),
  41784. y: pt[1] - r * Math.sin(opt.rotation),
  41785. silent: true,
  41786. z2: 11
  41787. });
  41788. group.add(symbol);
  41789. }
  41790. });
  41791. }
  41792. },
  41793. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  41794. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  41795. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  41796. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  41797. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  41798. // See https://github.com/apache/echarts/issues/14266 for more.
  41799. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  41800. var labelList = prepareLayoutList(map(labelEls, function (label) {
  41801. return {
  41802. label: label,
  41803. priority: label.z2,
  41804. defaultAttr: {
  41805. ignore: label.ignore
  41806. }
  41807. };
  41808. }));
  41809. hideOverlap(labelList);
  41810. }
  41811. },
  41812. axisName: function (opt, axisModel, group, transformGroup) {
  41813. var name = retrieve(opt.axisName, axisModel.get('name'));
  41814. if (!name) {
  41815. return;
  41816. }
  41817. var nameLocation = axisModel.get('nameLocation');
  41818. var nameDirection = opt.nameDirection;
  41819. var textStyleModel = axisModel.getModel('nameTextStyle');
  41820. var gap = axisModel.get('nameGap') || 0;
  41821. var extent = axisModel.axis.getExtent();
  41822. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  41823. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  41824. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  41825. var labelLayout;
  41826. var nameRotation = axisModel.get('nameRotate');
  41827. if (nameRotation != null) {
  41828. nameRotation = nameRotation * PI$5 / 180; // To radian.
  41829. }
  41830. var axisNameAvailableWidth;
  41831. if (isNameLocationCenter(nameLocation)) {
  41832. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  41833. nameDirection);
  41834. } else {
  41835. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  41836. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  41837. if (axisNameAvailableWidth != null) {
  41838. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  41839. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  41840. }
  41841. }
  41842. var textFont = textStyleModel.getFont();
  41843. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  41844. var ellipsis = truncateOpt.ellipsis;
  41845. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  41846. var textEl = new ZRText({
  41847. x: pos[0],
  41848. y: pos[1],
  41849. rotation: labelLayout.rotation,
  41850. silent: AxisBuilder.isLabelSilent(axisModel),
  41851. style: createTextStyle(textStyleModel, {
  41852. text: name,
  41853. font: textFont,
  41854. overflow: 'truncate',
  41855. width: maxWidth,
  41856. ellipsis: ellipsis,
  41857. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  41858. align: textStyleModel.get('align') || labelLayout.textAlign,
  41859. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  41860. }),
  41861. z2: 1
  41862. });
  41863. setTooltipConfig({
  41864. el: textEl,
  41865. componentModel: axisModel,
  41866. itemName: name
  41867. });
  41868. textEl.__fullText = name; // Id for animation
  41869. textEl.anid = 'name';
  41870. if (axisModel.get('triggerEvent')) {
  41871. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  41872. eventData.targetType = 'axisName';
  41873. eventData.name = name;
  41874. getECData(textEl).eventData = eventData;
  41875. } // FIXME
  41876. transformGroup.add(textEl);
  41877. textEl.updateTransform();
  41878. group.add(textEl);
  41879. textEl.decomposeTransform();
  41880. }
  41881. };
  41882. function endTextLayout(rotation, textPosition, textRotate, extent) {
  41883. var rotationDiff = remRadian(textRotate - rotation);
  41884. var textAlign;
  41885. var textVerticalAlign;
  41886. var inverse = extent[0] > extent[1];
  41887. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  41888. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  41889. textVerticalAlign = onLeft ? 'bottom' : 'top';
  41890. textAlign = 'center';
  41891. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  41892. textVerticalAlign = onLeft ? 'top' : 'bottom';
  41893. textAlign = 'center';
  41894. } else {
  41895. textVerticalAlign = 'middle';
  41896. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  41897. textAlign = onLeft ? 'left' : 'right';
  41898. } else {
  41899. textAlign = onLeft ? 'right' : 'left';
  41900. }
  41901. }
  41902. return {
  41903. rotation: rotationDiff,
  41904. textAlign: textAlign,
  41905. textVerticalAlign: textVerticalAlign
  41906. };
  41907. }
  41908. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  41909. if (shouldShowAllLabels(axisModel.axis)) {
  41910. return;
  41911. } // If min or max are user set, we need to check
  41912. // If the tick on min(max) are overlap on their neighbour tick
  41913. // If they are overlapped, we need to hide the min(max) tick label
  41914. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  41915. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  41916. // Have not consider onBand yet, where tick els is more than label els.
  41917. labelEls = labelEls || [];
  41918. tickEls = tickEls || [];
  41919. var firstLabel = labelEls[0];
  41920. var nextLabel = labelEls[1];
  41921. var lastLabel = labelEls[labelEls.length - 1];
  41922. var prevLabel = labelEls[labelEls.length - 2];
  41923. var firstTick = tickEls[0];
  41924. var nextTick = tickEls[1];
  41925. var lastTick = tickEls[tickEls.length - 1];
  41926. var prevTick = tickEls[tickEls.length - 2];
  41927. if (showMinLabel === false) {
  41928. ignoreEl(firstLabel);
  41929. ignoreEl(firstTick);
  41930. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  41931. if (showMinLabel) {
  41932. ignoreEl(nextLabel);
  41933. ignoreEl(nextTick);
  41934. } else {
  41935. ignoreEl(firstLabel);
  41936. ignoreEl(firstTick);
  41937. }
  41938. }
  41939. if (showMaxLabel === false) {
  41940. ignoreEl(lastLabel);
  41941. ignoreEl(lastTick);
  41942. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  41943. if (showMaxLabel) {
  41944. ignoreEl(prevLabel);
  41945. ignoreEl(prevTick);
  41946. } else {
  41947. ignoreEl(lastLabel);
  41948. ignoreEl(lastTick);
  41949. }
  41950. }
  41951. }
  41952. function ignoreEl(el) {
  41953. el && (el.ignore = true);
  41954. }
  41955. function isTwoLabelOverlapped(current, next) {
  41956. // current and next has the same rotation.
  41957. var firstRect = current && current.getBoundingRect().clone();
  41958. var nextRect = next && next.getBoundingRect().clone();
  41959. if (!firstRect || !nextRect) {
  41960. return;
  41961. } // When checking intersect of two rotated labels, we use mRotationBack
  41962. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  41963. var mRotationBack = identity([]);
  41964. rotate(mRotationBack, mRotationBack, -current.rotation);
  41965. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  41966. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  41967. return firstRect.intersect(nextRect);
  41968. }
  41969. function isNameLocationCenter(nameLocation) {
  41970. return nameLocation === 'middle' || nameLocation === 'center';
  41971. }
  41972. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  41973. var tickEls = [];
  41974. var pt1 = [];
  41975. var pt2 = [];
  41976. for (var i = 0; i < ticksCoords.length; i++) {
  41977. var tickCoord = ticksCoords[i].coord;
  41978. pt1[0] = tickCoord;
  41979. pt1[1] = 0;
  41980. pt2[0] = tickCoord;
  41981. pt2[1] = tickEndCoord;
  41982. if (tickTransform) {
  41983. applyTransform(pt1, pt1, tickTransform);
  41984. applyTransform(pt2, pt2, tickTransform);
  41985. } // Tick line, Not use group transform to have better line draw
  41986. var tickEl = new Line({
  41987. shape: {
  41988. x1: pt1[0],
  41989. y1: pt1[1],
  41990. x2: pt2[0],
  41991. y2: pt2[1]
  41992. },
  41993. style: tickLineStyle,
  41994. z2: 2,
  41995. autoBatch: true,
  41996. silent: true
  41997. });
  41998. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  41999. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  42000. tickEls.push(tickEl);
  42001. }
  42002. return tickEls;
  42003. }
  42004. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  42005. var axis = axisModel.axis;
  42006. var tickModel = axisModel.getModel('axisTick');
  42007. var shown = tickModel.get('show');
  42008. if (shown === 'auto' && opt.handleAutoShown) {
  42009. shown = opt.handleAutoShown('axisTick');
  42010. }
  42011. if (!shown || axis.scale.isBlank()) {
  42012. return;
  42013. }
  42014. var lineStyleModel = tickModel.getModel('lineStyle');
  42015. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  42016. var ticksCoords = axis.getTicksCoords();
  42017. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  42018. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  42019. }), 'ticks');
  42020. for (var i = 0; i < ticksEls.length; i++) {
  42021. group.add(ticksEls[i]);
  42022. }
  42023. return ticksEls;
  42024. }
  42025. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  42026. var axis = axisModel.axis;
  42027. var minorTickModel = axisModel.getModel('minorTick');
  42028. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  42029. return;
  42030. }
  42031. var minorTicksCoords = axis.getMinorTicksCoords();
  42032. if (!minorTicksCoords.length) {
  42033. return;
  42034. }
  42035. var lineStyleModel = minorTickModel.getModel('lineStyle');
  42036. var tickEndCoord = tickDirection * minorTickModel.get('length');
  42037. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  42038. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  42039. }));
  42040. for (var i = 0; i < minorTicksCoords.length; i++) {
  42041. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  42042. for (var k = 0; k < minorTicksEls.length; k++) {
  42043. group.add(minorTicksEls[k]);
  42044. }
  42045. }
  42046. }
  42047. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  42048. var axis = axisModel.axis;
  42049. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  42050. if (!show || axis.scale.isBlank()) {
  42051. return;
  42052. }
  42053. var labelModel = axisModel.getModel('axisLabel');
  42054. var labelMargin = labelModel.get('margin');
  42055. var labels = axis.getViewLabels(); // Special label rotate.
  42056. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  42057. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  42058. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  42059. var labelEls = [];
  42060. var silent = AxisBuilder.isLabelSilent(axisModel);
  42061. var triggerEvent = axisModel.get('triggerEvent');
  42062. each(labels, function (labelItem, index) {
  42063. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  42064. var formattedLabel = labelItem.formattedLabel;
  42065. var rawLabel = labelItem.rawLabel;
  42066. var itemLabelModel = labelModel;
  42067. if (rawCategoryData && rawCategoryData[tickValue]) {
  42068. var rawCategoryItem = rawCategoryData[tickValue];
  42069. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  42070. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  42071. }
  42072. }
  42073. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  42074. var tickCoord = axis.dataToCoord(tickValue);
  42075. var textEl = new ZRText({
  42076. x: tickCoord,
  42077. y: opt.labelOffset + opt.labelDirection * labelMargin,
  42078. rotation: labelLayout.rotation,
  42079. silent: silent,
  42080. z2: 10 + (labelItem.level || 0),
  42081. style: createTextStyle(itemLabelModel, {
  42082. text: formattedLabel,
  42083. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  42084. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  42085. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  42086. // index of axis.data. So tick should not be exposed to user
  42087. // in category axis.
  42088. // (2) Compatible with previous version, which always use formatted label as
  42089. // input. But in interval scale the formatted label is like '223,445', which
  42090. // maked user replace ','. So we modify it to return original val but remain
  42091. // it as 'string' to avoid error in replacing.
  42092. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  42093. })
  42094. });
  42095. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  42096. if (triggerEvent) {
  42097. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  42098. eventData.targetType = 'axisLabel';
  42099. eventData.value = rawLabel;
  42100. eventData.tickIndex = index;
  42101. if (axis.type === 'category') {
  42102. eventData.dataIndex = tickValue;
  42103. }
  42104. getECData(textEl).eventData = eventData;
  42105. } // FIXME
  42106. transformGroup.add(textEl);
  42107. textEl.updateTransform();
  42108. labelEls.push(textEl);
  42109. group.add(textEl);
  42110. textEl.decomposeTransform();
  42111. });
  42112. return labelEls;
  42113. }
  42114. // allAxesInfo should be updated when setOption performed.
  42115. function collect(ecModel, api) {
  42116. var result = {
  42117. /**
  42118. * key: makeKey(axis.model)
  42119. * value: {
  42120. * axis,
  42121. * coordSys,
  42122. * axisPointerModel,
  42123. * triggerTooltip,
  42124. * involveSeries,
  42125. * snap,
  42126. * seriesModels,
  42127. * seriesDataCount
  42128. * }
  42129. */
  42130. axesInfo: {},
  42131. seriesInvolved: false,
  42132. /**
  42133. * key: makeKey(coordSys.model)
  42134. * value: Object: key makeKey(axis.model), value: axisInfo
  42135. */
  42136. coordSysAxesInfo: {},
  42137. coordSysMap: {}
  42138. };
  42139. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  42140. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  42141. return result;
  42142. }
  42143. function collectAxesInfo(result, ecModel, api) {
  42144. var globalTooltipModel = ecModel.getComponent('tooltip');
  42145. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  42146. var linksOption = globalAxisPointerModel.get('link', true) || [];
  42147. var linkGroups = []; // Collect axes info.
  42148. each(api.getCoordinateSystems(), function (coordSys) {
  42149. // Some coordinate system do not support axes, like geo.
  42150. if (!coordSys.axisPointerEnabled) {
  42151. return;
  42152. }
  42153. var coordSysKey = makeKey(coordSys.model);
  42154. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  42155. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convenient way to show axisPointer
  42156. // for user. So we enable setting tooltip on coordSys model.
  42157. var coordSysModel = coordSys.model;
  42158. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  42159. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  42160. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  42161. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  42162. // show but axisPointer will show as normal.
  42163. && baseTooltipModel.get('show')) {
  42164. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  42165. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  42166. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  42167. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  42168. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  42169. if (triggerAxis || cross) {
  42170. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  42171. }
  42172. if (cross) {
  42173. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  42174. }
  42175. } // fromTooltip: true | false | 'cross'
  42176. // triggerTooltip: true | false | null
  42177. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  42178. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  42179. var axisPointerShow = axisPointerModel.get('show');
  42180. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  42181. return;
  42182. }
  42183. if (triggerTooltip == null) {
  42184. triggerTooltip = axisPointerModel.get('triggerTooltip');
  42185. }
  42186. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  42187. var snap = axisPointerModel.get('snap');
  42188. var axisKey = makeKey(axis.model);
  42189. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  42190. var axisInfo = result.axesInfo[axisKey] = {
  42191. key: axisKey,
  42192. axis: axis,
  42193. coordSys: coordSys,
  42194. axisPointerModel: axisPointerModel,
  42195. triggerTooltip: triggerTooltip,
  42196. involveSeries: involveSeries,
  42197. snap: snap,
  42198. useHandle: isHandleTrigger(axisPointerModel),
  42199. seriesModels: [],
  42200. linkGroup: null
  42201. };
  42202. axesInfoInCoordSys[axisKey] = axisInfo;
  42203. result.seriesInvolved = result.seriesInvolved || involveSeries;
  42204. var groupIndex = getLinkGroupIndex(linksOption, axis);
  42205. if (groupIndex != null) {
  42206. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  42207. axesInfo: {}
  42208. });
  42209. linkGroup.axesInfo[axisKey] = axisInfo;
  42210. linkGroup.mapper = linksOption[groupIndex].mapper;
  42211. axisInfo.linkGroup = linkGroup;
  42212. }
  42213. }
  42214. });
  42215. }
  42216. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  42217. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  42218. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  42219. var volatileOption = {};
  42220. each(fields, function (field) {
  42221. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  42222. }); // category axis do not auto snap, otherwise some tick that do not
  42223. // has value can not be hovered. value/time/log axis default snap if
  42224. // triggered from tooltip and trigger tooltip.
  42225. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatible with previous behavior, tooltip axis does not show label by default.
  42226. // Only these properties can be overridden from tooltip to axisPointer.
  42227. if (tooltipAxisPointerModel.get('type') === 'cross') {
  42228. volatileOption.type = 'line';
  42229. }
  42230. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  42231. labelOption.show == null && (labelOption.show = false);
  42232. if (fromTooltip === 'cross') {
  42233. // When 'cross', both axes show labels.
  42234. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  42235. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  42236. // (cross style is dashed by default)
  42237. if (!triggerTooltip) {
  42238. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  42239. crossStyle && defaults(labelOption, crossStyle.textStyle);
  42240. }
  42241. }
  42242. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  42243. }
  42244. function collectSeriesInfo(result, ecModel) {
  42245. // Prepare data for axis trigger
  42246. ecModel.eachSeries(function (seriesModel) {
  42247. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  42248. var coordSys = seriesModel.coordinateSystem;
  42249. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  42250. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  42251. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  42252. return;
  42253. }
  42254. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  42255. var axis = axisInfo.axis;
  42256. if (coordSys.getAxis(axis.dim) === axis) {
  42257. axisInfo.seriesModels.push(seriesModel);
  42258. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  42259. axisInfo.seriesDataCount += seriesModel.getData().count();
  42260. }
  42261. });
  42262. });
  42263. }
  42264. /**
  42265. * For example:
  42266. * {
  42267. * axisPointer: {
  42268. * links: [{
  42269. * xAxisIndex: [2, 4],
  42270. * yAxisIndex: 'all'
  42271. * }, {
  42272. * xAxisId: ['a5', 'a7'],
  42273. * xAxisName: 'xxx'
  42274. * }]
  42275. * }
  42276. * }
  42277. */
  42278. function getLinkGroupIndex(linksOption, axis) {
  42279. var axisModel = axis.model;
  42280. var dim = axis.dim;
  42281. for (var i = 0; i < linksOption.length; i++) {
  42282. var linkOption = linksOption[i] || {};
  42283. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  42284. return i;
  42285. }
  42286. }
  42287. }
  42288. function checkPropInLink(linkPropValue, axisPropValue) {
  42289. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  42290. }
  42291. function fixValue(axisModel) {
  42292. var axisInfo = getAxisInfo(axisModel);
  42293. if (!axisInfo) {
  42294. return;
  42295. }
  42296. var axisPointerModel = axisInfo.axisPointerModel;
  42297. var scale = axisInfo.axis.scale;
  42298. var option = axisPointerModel.option;
  42299. var status = axisPointerModel.get('status');
  42300. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  42301. if (value != null) {
  42302. value = scale.parse(value);
  42303. }
  42304. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  42305. // and status should be initialized.
  42306. if (status == null) {
  42307. option.status = useHandle ? 'show' : 'hide';
  42308. }
  42309. var extent = scale.getExtent().slice();
  42310. extent[0] > extent[1] && extent.reverse();
  42311. if ( // Pick a value on axis when initializing.
  42312. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  42313. // where we should re-pick a value to keep `handle` displaying normally.
  42314. || value > extent[1]) {
  42315. // Make handle displayed on the end of the axis when init, which looks better.
  42316. value = extent[1];
  42317. }
  42318. if (value < extent[0]) {
  42319. value = extent[0];
  42320. }
  42321. option.value = value;
  42322. if (useHandle) {
  42323. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  42324. }
  42325. }
  42326. function getAxisInfo(axisModel) {
  42327. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  42328. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  42329. }
  42330. function getAxisPointerModel(axisModel) {
  42331. var axisInfo = getAxisInfo(axisModel);
  42332. return axisInfo && axisInfo.axisPointerModel;
  42333. }
  42334. function isHandleTrigger(axisPointerModel) {
  42335. return !!axisPointerModel.get(['handle', 'show']);
  42336. }
  42337. /**
  42338. * @param {module:echarts/model/Model} model
  42339. * @return {string} unique key
  42340. */
  42341. function makeKey(model) {
  42342. return model.type + '||' + model.id;
  42343. }
  42344. var axisPointerClazz = {};
  42345. /**
  42346. * Base class of AxisView.
  42347. */
  42348. var AxisView =
  42349. /** @class */
  42350. function (_super) {
  42351. __extends(AxisView, _super);
  42352. function AxisView() {
  42353. var _this = _super !== null && _super.apply(this, arguments) || this;
  42354. _this.type = AxisView.type;
  42355. return _this;
  42356. }
  42357. /**
  42358. * @override
  42359. */
  42360. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  42361. // FIXME
  42362. // This process should proformed after coordinate systems updated
  42363. // (axis scale updated), and should be performed each time update.
  42364. // So put it here temporarily, although it is not appropriate to
  42365. // put a model-writing procedure in `view`.
  42366. this.axisPointerClass && fixValue(axisModel);
  42367. _super.prototype.render.apply(this, arguments);
  42368. this._doUpdateAxisPointerClass(axisModel, api, true);
  42369. };
  42370. /**
  42371. * Action handler.
  42372. */
  42373. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  42374. this._doUpdateAxisPointerClass(axisModel, api, false);
  42375. };
  42376. /**
  42377. * @override
  42378. */
  42379. AxisView.prototype.remove = function (ecModel, api) {
  42380. var axisPointer = this._axisPointer;
  42381. axisPointer && axisPointer.remove(api);
  42382. };
  42383. /**
  42384. * @override
  42385. */
  42386. AxisView.prototype.dispose = function (ecModel, api) {
  42387. this._disposeAxisPointer(api);
  42388. _super.prototype.dispose.apply(this, arguments);
  42389. };
  42390. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  42391. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  42392. if (!Clazz) {
  42393. return;
  42394. }
  42395. var axisPointerModel = getAxisPointerModel(axisModel);
  42396. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  42397. };
  42398. AxisView.prototype._disposeAxisPointer = function (api) {
  42399. this._axisPointer && this._axisPointer.dispose(api);
  42400. this._axisPointer = null;
  42401. };
  42402. AxisView.registerAxisPointerClass = function (type, clazz) {
  42403. if ("development" !== 'production') {
  42404. if (axisPointerClazz[type]) {
  42405. throw new Error('axisPointer ' + type + ' exists');
  42406. }
  42407. }
  42408. axisPointerClazz[type] = clazz;
  42409. };
  42410. AxisView.getAxisPointerClass = function (type) {
  42411. return type && axisPointerClazz[type];
  42412. };
  42413. AxisView.type = 'axis';
  42414. return AxisView;
  42415. }(ComponentView);
  42416. var inner$6 = makeInner();
  42417. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  42418. var axis = axisModel.axis;
  42419. if (axis.scale.isBlank()) {
  42420. return;
  42421. } // TODO: TYPE
  42422. var splitAreaModel = axisModel.getModel('splitArea');
  42423. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  42424. var areaColors = areaStyleModel.get('color');
  42425. var gridRect = gridModel.coordinateSystem.getRect();
  42426. var ticksCoords = axis.getTicksCoords({
  42427. tickModel: splitAreaModel,
  42428. clamp: true
  42429. });
  42430. if (!ticksCoords.length) {
  42431. return;
  42432. } // For Making appropriate splitArea animation, the color and anid
  42433. // should be corresponding to previous one if possible.
  42434. var areaColorsLen = areaColors.length;
  42435. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  42436. var newSplitAreaColors = createHashMap();
  42437. var colorIndex = 0;
  42438. if (lastSplitAreaColors) {
  42439. for (var i = 0; i < ticksCoords.length; i++) {
  42440. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  42441. if (cIndex != null) {
  42442. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  42443. break;
  42444. }
  42445. }
  42446. }
  42447. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  42448. var areaStyle = areaStyleModel.getAreaStyle();
  42449. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  42450. for (var i = 1; i < ticksCoords.length; i++) {
  42451. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  42452. var x = void 0;
  42453. var y = void 0;
  42454. var width = void 0;
  42455. var height = void 0;
  42456. if (axis.isHorizontal()) {
  42457. x = prev;
  42458. y = gridRect.y;
  42459. width = tickCoord - x;
  42460. height = gridRect.height;
  42461. prev = x + width;
  42462. } else {
  42463. x = gridRect.x;
  42464. y = prev;
  42465. width = gridRect.width;
  42466. height = tickCoord - y;
  42467. prev = y + height;
  42468. }
  42469. var tickValue = ticksCoords[i - 1].tickValue;
  42470. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  42471. axisGroup.add(new Rect({
  42472. anid: tickValue != null ? 'area_' + tickValue : null,
  42473. shape: {
  42474. x: x,
  42475. y: y,
  42476. width: width,
  42477. height: height
  42478. },
  42479. style: defaults({
  42480. fill: areaColors[colorIndex]
  42481. }, areaStyle),
  42482. autoBatch: true,
  42483. silent: true
  42484. }));
  42485. colorIndex = (colorIndex + 1) % areaColorsLen;
  42486. }
  42487. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  42488. }
  42489. function rectCoordAxisHandleRemove(axisView) {
  42490. inner$6(axisView).splitAreaColors = null;
  42491. }
  42492. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  42493. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  42494. var CartesianAxisView =
  42495. /** @class */
  42496. function (_super) {
  42497. __extends(CartesianAxisView, _super);
  42498. function CartesianAxisView() {
  42499. var _this = _super !== null && _super.apply(this, arguments) || this;
  42500. _this.type = CartesianAxisView.type;
  42501. _this.axisPointerClass = 'CartesianAxisPointer';
  42502. return _this;
  42503. }
  42504. /**
  42505. * @override
  42506. */
  42507. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  42508. this.group.removeAll();
  42509. var oldAxisGroup = this._axisGroup;
  42510. this._axisGroup = new Group();
  42511. this.group.add(this._axisGroup);
  42512. if (!axisModel.get('show')) {
  42513. return;
  42514. }
  42515. var gridModel = axisModel.getCoordSysModel();
  42516. var layout = layout$1(gridModel, axisModel);
  42517. var axisBuilder = new AxisBuilder(axisModel, extend({
  42518. handleAutoShown: function (elementType) {
  42519. var cartesians = gridModel.coordinateSystem.getCartesians();
  42520. for (var i = 0; i < cartesians.length; i++) {
  42521. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  42522. // Still show axis tick or axisLine if other axis is value / log
  42523. return true;
  42524. }
  42525. } // Not show axisTick or axisLine if other axis is category / time
  42526. return false;
  42527. }
  42528. }, layout));
  42529. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  42530. this._axisGroup.add(axisBuilder.getGroup());
  42531. each(selfBuilderAttrs, function (name) {
  42532. if (axisModel.get([name, 'show'])) {
  42533. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  42534. }
  42535. }, this); // THIS is a special case for bar racing chart.
  42536. // Update the axis label from the natural initial layout to
  42537. // sorted layout should has no animation.
  42538. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  42539. if (!isInitialSortFromBarRacing) {
  42540. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  42541. }
  42542. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  42543. };
  42544. CartesianAxisView.prototype.remove = function () {
  42545. rectCoordAxisHandleRemove(this);
  42546. };
  42547. CartesianAxisView.type = 'cartesianAxis';
  42548. return CartesianAxisView;
  42549. }(AxisView);
  42550. var axisElementBuilders = {
  42551. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  42552. var axis = axisModel.axis;
  42553. if (axis.scale.isBlank()) {
  42554. return;
  42555. }
  42556. var splitLineModel = axisModel.getModel('splitLine');
  42557. var lineStyleModel = splitLineModel.getModel('lineStyle');
  42558. var lineColors = lineStyleModel.get('color');
  42559. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  42560. var gridRect = gridModel.coordinateSystem.getRect();
  42561. var isHorizontal = axis.isHorizontal();
  42562. var lineCount = 0;
  42563. var ticksCoords = axis.getTicksCoords({
  42564. tickModel: splitLineModel
  42565. });
  42566. var p1 = [];
  42567. var p2 = [];
  42568. var lineStyle = lineStyleModel.getLineStyle();
  42569. for (var i = 0; i < ticksCoords.length; i++) {
  42570. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  42571. if (isHorizontal) {
  42572. p1[0] = tickCoord;
  42573. p1[1] = gridRect.y;
  42574. p2[0] = tickCoord;
  42575. p2[1] = gridRect.y + gridRect.height;
  42576. } else {
  42577. p1[0] = gridRect.x;
  42578. p1[1] = tickCoord;
  42579. p2[0] = gridRect.x + gridRect.width;
  42580. p2[1] = tickCoord;
  42581. }
  42582. var colorIndex = lineCount++ % lineColors.length;
  42583. var tickValue = ticksCoords[i].tickValue;
  42584. var line = new Line({
  42585. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  42586. autoBatch: true,
  42587. shape: {
  42588. x1: p1[0],
  42589. y1: p1[1],
  42590. x2: p2[0],
  42591. y2: p2[1]
  42592. },
  42593. style: defaults({
  42594. stroke: lineColors[colorIndex]
  42595. }, lineStyle),
  42596. silent: true
  42597. });
  42598. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  42599. axisGroup.add(line);
  42600. }
  42601. },
  42602. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  42603. var axis = axisModel.axis;
  42604. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  42605. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  42606. var gridRect = gridModel.coordinateSystem.getRect();
  42607. var isHorizontal = axis.isHorizontal();
  42608. var minorTicksCoords = axis.getMinorTicksCoords();
  42609. if (!minorTicksCoords.length) {
  42610. return;
  42611. }
  42612. var p1 = [];
  42613. var p2 = [];
  42614. var lineStyle = lineStyleModel.getLineStyle();
  42615. for (var i = 0; i < minorTicksCoords.length; i++) {
  42616. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  42617. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  42618. if (isHorizontal) {
  42619. p1[0] = tickCoord;
  42620. p1[1] = gridRect.y;
  42621. p2[0] = tickCoord;
  42622. p2[1] = gridRect.y + gridRect.height;
  42623. } else {
  42624. p1[0] = gridRect.x;
  42625. p1[1] = tickCoord;
  42626. p2[0] = gridRect.x + gridRect.width;
  42627. p2[1] = tickCoord;
  42628. }
  42629. var line = new Line({
  42630. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  42631. autoBatch: true,
  42632. shape: {
  42633. x1: p1[0],
  42634. y1: p1[1],
  42635. x2: p2[0],
  42636. y2: p2[1]
  42637. },
  42638. style: lineStyle,
  42639. silent: true
  42640. });
  42641. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  42642. axisGroup.add(line);
  42643. }
  42644. }
  42645. },
  42646. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  42647. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  42648. }
  42649. };
  42650. var CartesianXAxisView =
  42651. /** @class */
  42652. function (_super) {
  42653. __extends(CartesianXAxisView, _super);
  42654. function CartesianXAxisView() {
  42655. var _this = _super !== null && _super.apply(this, arguments) || this;
  42656. _this.type = CartesianXAxisView.type;
  42657. return _this;
  42658. }
  42659. CartesianXAxisView.type = 'xAxis';
  42660. return CartesianXAxisView;
  42661. }(CartesianAxisView);
  42662. var CartesianYAxisView =
  42663. /** @class */
  42664. function (_super) {
  42665. __extends(CartesianYAxisView, _super);
  42666. function CartesianYAxisView() {
  42667. var _this = _super !== null && _super.apply(this, arguments) || this;
  42668. _this.type = CartesianXAxisView.type;
  42669. return _this;
  42670. }
  42671. CartesianYAxisView.type = 'yAxis';
  42672. return CartesianYAxisView;
  42673. }(CartesianAxisView);
  42674. var GridView =
  42675. /** @class */
  42676. function (_super) {
  42677. __extends(GridView, _super);
  42678. function GridView() {
  42679. var _this = _super !== null && _super.apply(this, arguments) || this;
  42680. _this.type = 'grid';
  42681. return _this;
  42682. }
  42683. GridView.prototype.render = function (gridModel, ecModel) {
  42684. this.group.removeAll();
  42685. if (gridModel.get('show')) {
  42686. this.group.add(new Rect({
  42687. shape: gridModel.coordinateSystem.getRect(),
  42688. style: defaults({
  42689. fill: gridModel.get('backgroundColor')
  42690. }, gridModel.getItemStyle()),
  42691. silent: true,
  42692. z2: -1
  42693. }));
  42694. }
  42695. };
  42696. GridView.type = 'grid';
  42697. return GridView;
  42698. }(ComponentView);
  42699. var extraOption = {
  42700. // gridIndex: 0,
  42701. // gridId: '',
  42702. offset: 0
  42703. };
  42704. function install$5(registers) {
  42705. registers.registerComponentView(GridView);
  42706. registers.registerComponentModel(GridModel);
  42707. registers.registerCoordinateSystem('cartesian2d', Grid);
  42708. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  42709. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  42710. registers.registerComponentView(CartesianXAxisView);
  42711. registers.registerComponentView(CartesianYAxisView);
  42712. registers.registerPreprocessor(function (option) {
  42713. // Only create grid when need
  42714. if (option.xAxis && option.yAxis && !option.grid) {
  42715. option.grid = {};
  42716. }
  42717. });
  42718. }
  42719. function install$6(registers) {
  42720. // In case developer forget to include grid component
  42721. use(install$5);
  42722. registers.registerSeriesModel(ScatterSeriesModel);
  42723. registers.registerChartView(ScatterView);
  42724. registers.registerLayout(pointsLayout('scatter'));
  42725. }
  42726. var inner$7 = makeInner();
  42727. var clone$3 = clone;
  42728. var bind$1 = bind;
  42729. /**
  42730. * Base axis pointer class in 2D.
  42731. */
  42732. var BaseAxisPointer =
  42733. /** @class */
  42734. function () {
  42735. function BaseAxisPointer() {
  42736. this._dragging = false;
  42737. /**
  42738. * In px, arbitrary value. Do not set too small,
  42739. * no animation is ok for most cases.
  42740. */
  42741. this.animationThreshold = 15;
  42742. }
  42743. /**
  42744. * @implement
  42745. */
  42746. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  42747. var value = axisPointerModel.get('value');
  42748. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  42749. // be replaced when user calling setOption in not merge mode.
  42750. this._axisModel = axisModel;
  42751. this._axisPointerModel = axisPointerModel;
  42752. this._api = api; // Optimize: `render` will be called repeatedly during mouse move.
  42753. // So it is power consuming if performing `render` each time,
  42754. // especially on mobile device.
  42755. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  42756. return;
  42757. }
  42758. this._lastValue = value;
  42759. this._lastStatus = status;
  42760. var group = this._group;
  42761. var handle = this._handle;
  42762. if (!status || status === 'hide') {
  42763. // Do not clear here, for animation better.
  42764. group && group.hide();
  42765. handle && handle.hide();
  42766. return;
  42767. }
  42768. group && group.show();
  42769. handle && handle.show(); // Otherwise status is 'show'
  42770. var elOption = {};
  42771. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  42772. var graphicKey = elOption.graphicKey;
  42773. if (graphicKey !== this._lastGraphicKey) {
  42774. this.clear(api);
  42775. }
  42776. this._lastGraphicKey = graphicKey;
  42777. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  42778. if (!group) {
  42779. group = this._group = new Group();
  42780. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  42781. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  42782. api.getZr().add(group);
  42783. } else {
  42784. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  42785. this.updatePointerEl(group, elOption, doUpdateProps);
  42786. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  42787. }
  42788. updateMandatoryProps(group, axisPointerModel, true);
  42789. this._renderHandle(value);
  42790. };
  42791. /**
  42792. * @implement
  42793. */
  42794. BaseAxisPointer.prototype.remove = function (api) {
  42795. this.clear(api);
  42796. };
  42797. /**
  42798. * @implement
  42799. */
  42800. BaseAxisPointer.prototype.dispose = function (api) {
  42801. this.clear(api);
  42802. };
  42803. /**
  42804. * @protected
  42805. */
  42806. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  42807. var animation = axisPointerModel.get('animation');
  42808. var axis = axisModel.axis;
  42809. var isCategoryAxis = axis.type === 'category';
  42810. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  42811. if (!useSnap && !isCategoryAxis) {
  42812. return false;
  42813. }
  42814. if (animation === 'auto' || animation == null) {
  42815. var animationThreshold = this.animationThreshold;
  42816. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  42817. return true;
  42818. } // It is important to auto animation when snap used. Consider if there is
  42819. // a dataZoom, animation will be disabled when too many points exist, while
  42820. // it will be enabled for better visual effect when little points exist.
  42821. if (useSnap) {
  42822. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  42823. var axisExtent = axis.getExtent(); // Approximate band width
  42824. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  42825. }
  42826. return false;
  42827. }
  42828. return animation === true;
  42829. };
  42830. /**
  42831. * add {pointer, label, graphicKey} to elOption
  42832. * @protected
  42833. */
  42834. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Should be implemenented by sub-class.
  42835. };
  42836. /**
  42837. * @protected
  42838. */
  42839. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  42840. var pointerOption = elOption.pointer;
  42841. if (pointerOption) {
  42842. var pointerEl = inner$7(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  42843. group.add(pointerEl);
  42844. }
  42845. };
  42846. /**
  42847. * @protected
  42848. */
  42849. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  42850. if (elOption.label) {
  42851. var labelEl = inner$7(group).labelEl = new ZRText(clone$3(elOption.label));
  42852. group.add(labelEl);
  42853. updateLabelShowHide(labelEl, axisPointerModel);
  42854. }
  42855. };
  42856. /**
  42857. * @protected
  42858. */
  42859. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  42860. var pointerEl = inner$7(group).pointerEl;
  42861. if (pointerEl && elOption.pointer) {
  42862. pointerEl.setStyle(elOption.pointer.style);
  42863. updateProps(pointerEl, {
  42864. shape: elOption.pointer.shape
  42865. });
  42866. }
  42867. };
  42868. /**
  42869. * @protected
  42870. */
  42871. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  42872. var labelEl = inner$7(group).labelEl;
  42873. if (labelEl) {
  42874. labelEl.setStyle(elOption.label.style);
  42875. updateProps(labelEl, {
  42876. // Consider text length change in vertical axis, animation should
  42877. // be used on shape, otherwise the effect will be weird.
  42878. // TODOTODO
  42879. // shape: elOption.label.shape,
  42880. x: elOption.label.x,
  42881. y: elOption.label.y
  42882. });
  42883. updateLabelShowHide(labelEl, axisPointerModel);
  42884. }
  42885. };
  42886. /**
  42887. * @private
  42888. */
  42889. BaseAxisPointer.prototype._renderHandle = function (value) {
  42890. if (this._dragging || !this.updateHandleTransform) {
  42891. return;
  42892. }
  42893. var axisPointerModel = this._axisPointerModel;
  42894. var zr = this._api.getZr();
  42895. var handle = this._handle;
  42896. var handleModel = axisPointerModel.getModel('handle');
  42897. var status = axisPointerModel.get('status');
  42898. if (!handleModel.get('show') || !status || status === 'hide') {
  42899. handle && zr.remove(handle);
  42900. this._handle = null;
  42901. return;
  42902. }
  42903. var isInit;
  42904. if (!this._handle) {
  42905. isInit = true;
  42906. handle = this._handle = createIcon(handleModel.get('icon'), {
  42907. cursor: 'move',
  42908. draggable: true,
  42909. onmousemove: function (e) {
  42910. // For mobile device, prevent screen slider on the button.
  42911. stop(e.event);
  42912. },
  42913. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  42914. drift: bind$1(this._onHandleDragMove, this),
  42915. ondragend: bind$1(this._onHandleDragEnd, this)
  42916. });
  42917. zr.add(handle);
  42918. }
  42919. updateMandatoryProps(handle, axisPointerModel, false); // update style
  42920. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  42921. var handleSize = handleModel.get('size');
  42922. if (!isArray(handleSize)) {
  42923. handleSize = [handleSize, handleSize];
  42924. }
  42925. handle.scaleX = handleSize[0] / 2;
  42926. handle.scaleY = handleSize[1] / 2;
  42927. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  42928. this._moveHandleToValue(value, isInit);
  42929. };
  42930. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  42931. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  42932. };
  42933. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  42934. var handle = this._handle;
  42935. if (!handle) {
  42936. return;
  42937. }
  42938. this._dragging = true; // Persistent for throttle.
  42939. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  42940. this._payloadInfo = trans;
  42941. handle.stopAnimation();
  42942. handle.attr(getHandleTransProps(trans));
  42943. inner$7(handle).lastProp = null;
  42944. this._doDispatchAxisPointer();
  42945. };
  42946. /**
  42947. * Throttled method.
  42948. */
  42949. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  42950. var handle = this._handle;
  42951. if (!handle) {
  42952. return;
  42953. }
  42954. var payloadInfo = this._payloadInfo;
  42955. var axisModel = this._axisModel;
  42956. this._api.dispatchAction({
  42957. type: 'updateAxisPointer',
  42958. x: payloadInfo.cursorPoint[0],
  42959. y: payloadInfo.cursorPoint[1],
  42960. tooltipOption: payloadInfo.tooltipOption,
  42961. axesInfo: [{
  42962. axisDim: axisModel.axis.dim,
  42963. axisIndex: axisModel.componentIndex
  42964. }]
  42965. });
  42966. };
  42967. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  42968. this._dragging = false;
  42969. var handle = this._handle;
  42970. if (!handle) {
  42971. return;
  42972. }
  42973. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  42974. // axisPointer. So move handle to align the exact value position when
  42975. // drag ended.
  42976. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  42977. // button, and will be hidden after finger left handle button.
  42978. this._api.dispatchAction({
  42979. type: 'hideTip'
  42980. });
  42981. };
  42982. /**
  42983. * @private
  42984. */
  42985. BaseAxisPointer.prototype.clear = function (api) {
  42986. this._lastValue = null;
  42987. this._lastStatus = null;
  42988. var zr = api.getZr();
  42989. var group = this._group;
  42990. var handle = this._handle;
  42991. if (zr && group) {
  42992. this._lastGraphicKey = null;
  42993. group && zr.remove(group);
  42994. handle && zr.remove(handle);
  42995. this._group = null;
  42996. this._handle = null;
  42997. this._payloadInfo = null;
  42998. }
  42999. clear(this, '_doDispatchAxisPointer');
  43000. };
  43001. /**
  43002. * @protected
  43003. */
  43004. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  43005. };
  43006. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  43007. xDimIndex = xDimIndex || 0;
  43008. return {
  43009. x: xy[xDimIndex],
  43010. y: xy[1 - xDimIndex],
  43011. width: wh[xDimIndex],
  43012. height: wh[1 - xDimIndex]
  43013. };
  43014. };
  43015. return BaseAxisPointer;
  43016. }();
  43017. function updateProps$1(animationModel, moveAnimation, el, props) {
  43018. // Animation optimize.
  43019. if (!propsEqual(inner$7(el).lastProp, props)) {
  43020. inner$7(el).lastProp = props;
  43021. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  43022. }
  43023. }
  43024. function propsEqual(lastProps, newProps) {
  43025. if (isObject(lastProps) && isObject(newProps)) {
  43026. var equals_1 = true;
  43027. each(newProps, function (item, key) {
  43028. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  43029. });
  43030. return !!equals_1;
  43031. } else {
  43032. return lastProps === newProps;
  43033. }
  43034. }
  43035. function updateLabelShowHide(labelEl, axisPointerModel) {
  43036. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  43037. }
  43038. function getHandleTransProps(trans) {
  43039. return {
  43040. x: trans.x || 0,
  43041. y: trans.y || 0,
  43042. rotation: trans.rotation || 0
  43043. };
  43044. }
  43045. function updateMandatoryProps(group, axisPointerModel, silent) {
  43046. var z = axisPointerModel.get('z');
  43047. var zlevel = axisPointerModel.get('zlevel');
  43048. group && group.traverse(function (el) {
  43049. if (el.type !== 'group') {
  43050. z != null && (el.z = z);
  43051. zlevel != null && (el.zlevel = zlevel);
  43052. el.silent = silent;
  43053. }
  43054. });
  43055. }
  43056. function buildElStyle(axisPointerModel) {
  43057. var axisPointerType = axisPointerModel.get('type');
  43058. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  43059. var style;
  43060. if (axisPointerType === 'line') {
  43061. style = styleModel.getLineStyle();
  43062. style.fill = null;
  43063. } else if (axisPointerType === 'shadow') {
  43064. style = styleModel.getAreaStyle();
  43065. style.stroke = null;
  43066. }
  43067. return style;
  43068. }
  43069. /**
  43070. * @param {Function} labelPos {align, verticalAlign, position}
  43071. */
  43072. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  43073. var value = axisPointerModel.get('value');
  43074. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  43075. precision: axisPointerModel.get(['label', 'precision']),
  43076. formatter: axisPointerModel.get(['label', 'formatter'])
  43077. });
  43078. var labelModel = axisPointerModel.getModel('label');
  43079. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  43080. var font = labelModel.getFont();
  43081. var textRect = getBoundingRect(text, font);
  43082. var position = labelPos.position;
  43083. var width = textRect.width + paddings[1] + paddings[3];
  43084. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  43085. var align = labelPos.align;
  43086. align === 'right' && (position[0] -= width);
  43087. align === 'center' && (position[0] -= width / 2);
  43088. var verticalAlign = labelPos.verticalAlign;
  43089. verticalAlign === 'bottom' && (position[1] -= height);
  43090. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  43091. confineInContainer(position, width, height, api);
  43092. var bgColor = labelModel.get('backgroundColor');
  43093. if (!bgColor || bgColor === 'auto') {
  43094. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  43095. }
  43096. elOption.label = {
  43097. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  43098. x: position[0],
  43099. y: position[1],
  43100. style: createTextStyle(labelModel, {
  43101. text: text,
  43102. font: font,
  43103. fill: labelModel.getTextColor(),
  43104. padding: paddings,
  43105. backgroundColor: bgColor
  43106. }),
  43107. // Label should be over axisPointer.
  43108. z2: 10
  43109. };
  43110. } // Do not overflow ec container
  43111. function confineInContainer(position, width, height, api) {
  43112. var viewWidth = api.getWidth();
  43113. var viewHeight = api.getHeight();
  43114. position[0] = Math.min(position[0] + width, viewWidth) - width;
  43115. position[1] = Math.min(position[1] + height, viewHeight) - height;
  43116. position[0] = Math.max(position[0], 0);
  43117. position[1] = Math.max(position[1], 0);
  43118. }
  43119. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  43120. value = axis.scale.parse(value);
  43121. var text = axis.scale.getLabel({
  43122. value: value
  43123. }, {
  43124. // If `precision` is set, width can be fixed (like '12.00500'), which
  43125. // helps to debounce when when moving label.
  43126. precision: opt.precision
  43127. });
  43128. var formatter = opt.formatter;
  43129. if (formatter) {
  43130. var params_1 = {
  43131. value: getAxisRawValue(axis, {
  43132. value: value
  43133. }),
  43134. axisDimension: axis.dim,
  43135. axisIndex: axis.index,
  43136. seriesData: []
  43137. };
  43138. each(seriesDataIndices, function (idxItem) {
  43139. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  43140. var dataIndex = idxItem.dataIndexInside;
  43141. var dataParams = series && series.getDataParams(dataIndex);
  43142. dataParams && params_1.seriesData.push(dataParams);
  43143. });
  43144. if (isString(formatter)) {
  43145. text = formatter.replace('{value}', text);
  43146. } else if (isFunction(formatter)) {
  43147. text = formatter(params_1);
  43148. }
  43149. }
  43150. return text;
  43151. }
  43152. function getTransformedPosition(axis, value, layoutInfo) {
  43153. var transform = create$1();
  43154. rotate(transform, transform, layoutInfo.rotation);
  43155. translate(transform, transform, layoutInfo.position);
  43156. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  43157. }
  43158. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  43159. // @ts-ignore
  43160. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  43161. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  43162. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  43163. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  43164. align: textLayout.textAlign,
  43165. verticalAlign: textLayout.textVerticalAlign
  43166. });
  43167. }
  43168. function makeLineShape(p1, p2, xDimIndex) {
  43169. xDimIndex = xDimIndex || 0;
  43170. return {
  43171. x1: p1[xDimIndex],
  43172. y1: p1[1 - xDimIndex],
  43173. x2: p2[xDimIndex],
  43174. y2: p2[1 - xDimIndex]
  43175. };
  43176. }
  43177. function makeRectShape(xy, wh, xDimIndex) {
  43178. xDimIndex = xDimIndex || 0;
  43179. return {
  43180. x: xy[xDimIndex],
  43181. y: xy[1 - xDimIndex],
  43182. width: wh[xDimIndex],
  43183. height: wh[1 - xDimIndex]
  43184. };
  43185. }
  43186. var CartesianAxisPointer =
  43187. /** @class */
  43188. function (_super) {
  43189. __extends(CartesianAxisPointer, _super);
  43190. function CartesianAxisPointer() {
  43191. return _super !== null && _super.apply(this, arguments) || this;
  43192. }
  43193. /**
  43194. * @override
  43195. */
  43196. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  43197. var axis = axisModel.axis;
  43198. var grid = axis.grid;
  43199. var axisPointerType = axisPointerModel.get('type');
  43200. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  43201. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  43202. if (axisPointerType && axisPointerType !== 'none') {
  43203. var elStyle = buildElStyle(axisPointerModel);
  43204. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  43205. pointerOption.style = elStyle;
  43206. elOption.graphicKey = pointerOption.type;
  43207. elOption.pointer = pointerOption;
  43208. }
  43209. var layoutInfo = layout$1(grid.model, axisModel);
  43210. buildCartesianSingleLabelElOption( // @ts-ignore
  43211. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  43212. };
  43213. /**
  43214. * @override
  43215. */
  43216. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  43217. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  43218. labelInside: false
  43219. }); // @ts-ignore
  43220. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  43221. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  43222. return {
  43223. x: pos[0],
  43224. y: pos[1],
  43225. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  43226. };
  43227. };
  43228. /**
  43229. * @override
  43230. */
  43231. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  43232. var axis = axisModel.axis;
  43233. var grid = axis.grid;
  43234. var axisExtent = axis.getGlobalExtent(true);
  43235. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  43236. var dimIndex = axis.dim === 'x' ? 0 : 1;
  43237. var currPosition = [transform.x, transform.y];
  43238. currPosition[dimIndex] += delta[dimIndex];
  43239. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  43240. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  43241. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  43242. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  43243. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  43244. var tooltipOptions = [{
  43245. verticalAlign: 'middle'
  43246. }, {
  43247. align: 'center'
  43248. }];
  43249. return {
  43250. x: currPosition[0],
  43251. y: currPosition[1],
  43252. rotation: transform.rotation,
  43253. cursorPoint: cursorPoint,
  43254. tooltipOption: tooltipOptions[dimIndex]
  43255. };
  43256. };
  43257. return CartesianAxisPointer;
  43258. }(BaseAxisPointer);
  43259. function getCartesian(grid, axis) {
  43260. var opt = {};
  43261. opt[axis.dim + 'AxisIndex'] = axis.index;
  43262. return grid.getCartesian(opt);
  43263. }
  43264. var pointerShapeBuilder = {
  43265. line: function (axis, pixelValue, otherExtent) {
  43266. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  43267. return {
  43268. type: 'Line',
  43269. subPixelOptimize: true,
  43270. shape: targetShape
  43271. };
  43272. },
  43273. shadow: function (axis, pixelValue, otherExtent) {
  43274. var bandWidth = Math.max(1, axis.getBandWidth());
  43275. var span = otherExtent[1] - otherExtent[0];
  43276. return {
  43277. type: 'Rect',
  43278. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  43279. };
  43280. }
  43281. };
  43282. function getAxisDimIndex(axis) {
  43283. return axis.dim === 'x' ? 0 : 1;
  43284. }
  43285. var AxisPointerModel =
  43286. /** @class */
  43287. function (_super) {
  43288. __extends(AxisPointerModel, _super);
  43289. function AxisPointerModel() {
  43290. var _this = _super !== null && _super.apply(this, arguments) || this;
  43291. _this.type = AxisPointerModel.type;
  43292. return _this;
  43293. }
  43294. AxisPointerModel.type = 'axisPointer';
  43295. AxisPointerModel.defaultOption = {
  43296. // 'auto' means that show when triggered by tooltip or handle.
  43297. show: 'auto',
  43298. // zlevel: 0,
  43299. z: 50,
  43300. type: 'line',
  43301. // axispointer triggered by tootip determine snap automatically,
  43302. // see `modelHelper`.
  43303. snap: false,
  43304. triggerTooltip: true,
  43305. value: null,
  43306. status: null,
  43307. link: [],
  43308. // Do not set 'auto' here, otherwise global animation: false
  43309. // will not effect at this axispointer.
  43310. animation: null,
  43311. animationDurationUpdate: 200,
  43312. lineStyle: {
  43313. color: '#B9BEC9',
  43314. width: 1,
  43315. type: 'dashed'
  43316. },
  43317. shadowStyle: {
  43318. color: 'rgba(210,219,238,0.2)'
  43319. },
  43320. label: {
  43321. show: true,
  43322. formatter: null,
  43323. precision: 'auto',
  43324. margin: 3,
  43325. color: '#fff',
  43326. padding: [5, 7, 5, 7],
  43327. backgroundColor: 'auto',
  43328. borderColor: null,
  43329. borderWidth: 0,
  43330. borderRadius: 3
  43331. },
  43332. handle: {
  43333. show: false,
  43334. // eslint-disable-next-line
  43335. 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',
  43336. size: 45,
  43337. // handle margin is from symbol center to axis, which is stable when circular move.
  43338. margin: 50,
  43339. // color: '#1b8bbd'
  43340. // color: '#2f4554'
  43341. color: '#333',
  43342. shadowBlur: 3,
  43343. shadowColor: '#aaa',
  43344. shadowOffsetX: 0,
  43345. shadowOffsetY: 2,
  43346. // For mobile performance
  43347. throttle: 40
  43348. }
  43349. };
  43350. return AxisPointerModel;
  43351. }(ComponentModel);
  43352. var inner$8 = makeInner();
  43353. var each$3 = each;
  43354. /**
  43355. * @param {string} key
  43356. * @param {module:echarts/ExtensionAPI} api
  43357. * @param {Function} handler
  43358. * param: {string} currTrigger
  43359. * param: {Array.<number>} point
  43360. */
  43361. function register(key, api, handler) {
  43362. if (env.node) {
  43363. return;
  43364. }
  43365. var zr = api.getZr();
  43366. inner$8(zr).records || (inner$8(zr).records = {});
  43367. initGlobalListeners(zr, api);
  43368. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  43369. record.handler = handler;
  43370. }
  43371. function initGlobalListeners(zr, api) {
  43372. if (inner$8(zr).initialized) {
  43373. return;
  43374. }
  43375. inner$8(zr).initialized = true;
  43376. useHandler('click', curry(doEnter, 'click'));
  43377. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  43378. useHandler('globalout', onLeave);
  43379. function useHandler(eventType, cb) {
  43380. zr.on(eventType, function (e) {
  43381. var dis = makeDispatchAction(api);
  43382. each$3(inner$8(zr).records, function (record) {
  43383. record && cb(record, e, dis.dispatchAction);
  43384. });
  43385. dispatchTooltipFinally(dis.pendings, api);
  43386. });
  43387. }
  43388. }
  43389. function dispatchTooltipFinally(pendings, api) {
  43390. var showLen = pendings.showTip.length;
  43391. var hideLen = pendings.hideTip.length;
  43392. var actuallyPayload;
  43393. if (showLen) {
  43394. actuallyPayload = pendings.showTip[showLen - 1];
  43395. } else if (hideLen) {
  43396. actuallyPayload = pendings.hideTip[hideLen - 1];
  43397. }
  43398. if (actuallyPayload) {
  43399. actuallyPayload.dispatchAction = null;
  43400. api.dispatchAction(actuallyPayload);
  43401. }
  43402. }
  43403. function onLeave(record, e, dispatchAction) {
  43404. record.handler('leave', null, dispatchAction);
  43405. }
  43406. function doEnter(currTrigger, record, e, dispatchAction) {
  43407. record.handler(currTrigger, e, dispatchAction);
  43408. }
  43409. function makeDispatchAction(api) {
  43410. var pendings = {
  43411. showTip: [],
  43412. hideTip: []
  43413. }; // FIXME
  43414. // better approach?
  43415. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  43416. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  43417. // So we have to add "final stage" to merge those dispatched actions.
  43418. var dispatchAction = function (payload) {
  43419. var pendingList = pendings[payload.type];
  43420. if (pendingList) {
  43421. pendingList.push(payload);
  43422. } else {
  43423. payload.dispatchAction = dispatchAction;
  43424. api.dispatchAction(payload);
  43425. }
  43426. };
  43427. return {
  43428. dispatchAction: dispatchAction,
  43429. pendings: pendings
  43430. };
  43431. }
  43432. function unregister(key, api) {
  43433. if (env.node) {
  43434. return;
  43435. }
  43436. var zr = api.getZr();
  43437. var record = (inner$8(zr).records || {})[key];
  43438. if (record) {
  43439. inner$8(zr).records[key] = null;
  43440. }
  43441. }
  43442. var AxisPointerView =
  43443. /** @class */
  43444. function (_super) {
  43445. __extends(AxisPointerView, _super);
  43446. function AxisPointerView() {
  43447. var _this = _super !== null && _super.apply(this, arguments) || this;
  43448. _this.type = AxisPointerView.type;
  43449. return _this;
  43450. }
  43451. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  43452. var globalTooltipModel = ecModel.getComponent('tooltip');
  43453. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  43454. // AxisPointerView to be independent to Tooltip.
  43455. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  43456. // If 'none', it is not controlled by mouse totally.
  43457. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  43458. dispatchAction({
  43459. type: 'updateAxisPointer',
  43460. currTrigger: currTrigger,
  43461. x: e && e.offsetX,
  43462. y: e && e.offsetY
  43463. });
  43464. }
  43465. });
  43466. };
  43467. AxisPointerView.prototype.remove = function (ecModel, api) {
  43468. unregister('axisPointer', api);
  43469. };
  43470. AxisPointerView.prototype.dispose = function (ecModel, api) {
  43471. unregister('axisPointer', api);
  43472. };
  43473. AxisPointerView.type = 'axisPointer';
  43474. return AxisPointerView;
  43475. }(ComponentView);
  43476. /**
  43477. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  43478. * @param ecModel
  43479. * @return {point: [x, y], el: ...} point Will not be null.
  43480. */
  43481. function findPointFromSeries(finder, ecModel) {
  43482. var point = [];
  43483. var seriesIndex = finder.seriesIndex;
  43484. var seriesModel;
  43485. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  43486. return {
  43487. point: []
  43488. };
  43489. }
  43490. var data = seriesModel.getData();
  43491. var dataIndex = queryDataIndex(data, finder);
  43492. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  43493. return {
  43494. point: []
  43495. };
  43496. }
  43497. var el = data.getItemGraphicEl(dataIndex);
  43498. var coordSys = seriesModel.coordinateSystem;
  43499. if (seriesModel.getTooltipPosition) {
  43500. point = seriesModel.getTooltipPosition(dataIndex) || [];
  43501. } else if (coordSys && coordSys.dataToPoint) {
  43502. if (finder.isStacked) {
  43503. var baseAxis = coordSys.getBaseAxis();
  43504. var valueAxis = coordSys.getOtherAxis(baseAxis);
  43505. var valueAxisDim = valueAxis.dim;
  43506. var baseAxisDim = baseAxis.dim;
  43507. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  43508. var baseDim = data.mapDimension(baseAxisDim);
  43509. var stackedData = [];
  43510. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  43511. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  43512. point = coordSys.dataToPoint(stackedData) || [];
  43513. } else {
  43514. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  43515. return data.mapDimension(dim);
  43516. }), dataIndex)) || [];
  43517. }
  43518. } else if (el) {
  43519. // Use graphic bounding rect
  43520. var rect = el.getBoundingRect().clone();
  43521. rect.applyTransform(el.transform);
  43522. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  43523. }
  43524. return {
  43525. point: point,
  43526. el: el
  43527. };
  43528. }
  43529. var inner$9 = makeInner();
  43530. /**
  43531. * Basic logic: check all axis, if they do not demand show/highlight,
  43532. * then hide/downplay them.
  43533. *
  43534. * @return content of event obj for echarts.connect.
  43535. */
  43536. function axisTrigger(payload, ecModel, api) {
  43537. var currTrigger = payload.currTrigger;
  43538. var point = [payload.x, payload.y];
  43539. var finder = payload;
  43540. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  43541. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  43542. // See #6121. But we are not able to reproduce it yet.
  43543. if (!coordSysAxesInfo) {
  43544. return;
  43545. }
  43546. if (illegalPoint(point)) {
  43547. // Used in the default behavior of `connection`: use the sample seriesIndex
  43548. // and dataIndex. And also used in the tooltipView trigger.
  43549. point = findPointFromSeries({
  43550. seriesIndex: finder.seriesIndex,
  43551. // Do not use dataIndexInside from other ec instance.
  43552. // FIXME: auto detect it?
  43553. dataIndex: finder.dataIndex
  43554. }, ecModel).point;
  43555. }
  43556. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  43557. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  43558. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  43559. // and dataIndex.
  43560. var inputAxesInfo = finder.axesInfo;
  43561. var axesInfo = coordSysAxesInfo.axesInfo;
  43562. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  43563. var outputPayload = {};
  43564. var showValueMap = {};
  43565. var dataByCoordSys = {
  43566. list: [],
  43567. map: {}
  43568. };
  43569. var updaters = {
  43570. showPointer: curry(showPointer, showValueMap),
  43571. showTooltip: curry(showTooltip, dataByCoordSys)
  43572. }; // Process for triggered axes.
  43573. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  43574. // If a point given, it must be contained by the coordinate system.
  43575. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  43576. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  43577. var axis = axisInfo.axis;
  43578. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  43579. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  43580. var val = inputAxisInfo && inputAxisInfo.value;
  43581. if (val == null && !isIllegalPoint) {
  43582. val = axis.pointToData(point);
  43583. }
  43584. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  43585. }
  43586. });
  43587. }); // Process for linked axes.
  43588. var linkTriggers = {};
  43589. each(axesInfo, function (tarAxisInfo, tarKey) {
  43590. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  43591. if (linkGroup && !showValueMap[tarKey]) {
  43592. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  43593. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  43594. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  43595. var val = srcValItem.value;
  43596. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  43597. linkTriggers[tarAxisInfo.key] = val;
  43598. }
  43599. });
  43600. }
  43601. });
  43602. each(linkTriggers, function (val, tarKey) {
  43603. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  43604. });
  43605. updateModelActually(showValueMap, axesInfo, outputPayload);
  43606. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  43607. dispatchHighDownActually(axesInfo, dispatchAction, api);
  43608. return outputPayload;
  43609. }
  43610. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  43611. var axis = axisInfo.axis;
  43612. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  43613. return;
  43614. }
  43615. if (!axisInfo.involveSeries) {
  43616. updaters.showPointer(axisInfo, newValue);
  43617. return;
  43618. } // Heavy calculation. So put it after axis.containData checking.
  43619. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  43620. var payloadBatch = payloadInfo.payloadBatch;
  43621. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  43622. // By default use the first involved series data as a sample to connect.
  43623. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  43624. extend(outputFinder, payloadBatch[0]);
  43625. } // If no linkSource input, this process is for collecting link
  43626. // target, where snap should not be accepted.
  43627. if (!noSnap && axisInfo.snap) {
  43628. if (axis.containData(snapToValue) && snapToValue != null) {
  43629. newValue = snapToValue;
  43630. }
  43631. }
  43632. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  43633. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  43634. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  43635. }
  43636. function buildPayloadsBySeries(value, axisInfo) {
  43637. var axis = axisInfo.axis;
  43638. var dim = axis.dim;
  43639. var snapToValue = value;
  43640. var payloadBatch = [];
  43641. var minDist = Number.MAX_VALUE;
  43642. var minDiff = -1;
  43643. each(axisInfo.seriesModels, function (series, idx) {
  43644. var dataDim = series.getData().mapDimensionsAll(dim);
  43645. var seriesNestestValue;
  43646. var dataIndices;
  43647. if (series.getAxisTooltipData) {
  43648. var result = series.getAxisTooltipData(dataDim, value, axis);
  43649. dataIndices = result.dataIndices;
  43650. seriesNestestValue = result.nestestValue;
  43651. } else {
  43652. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  43653. // when data length is not same.
  43654. // false,
  43655. axis.type === 'category' ? 0.5 : null);
  43656. if (!dataIndices.length) {
  43657. return;
  43658. }
  43659. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  43660. }
  43661. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  43662. return;
  43663. }
  43664. var diff = value - seriesNestestValue;
  43665. var dist = Math.abs(diff); // Consider category case
  43666. if (dist <= minDist) {
  43667. if (dist < minDist || diff >= 0 && minDiff < 0) {
  43668. minDist = dist;
  43669. minDiff = diff;
  43670. snapToValue = seriesNestestValue;
  43671. payloadBatch.length = 0;
  43672. }
  43673. each(dataIndices, function (dataIndex) {
  43674. payloadBatch.push({
  43675. seriesIndex: series.seriesIndex,
  43676. dataIndexInside: dataIndex,
  43677. dataIndex: series.getData().getRawIndex(dataIndex)
  43678. });
  43679. });
  43680. }
  43681. });
  43682. return {
  43683. payloadBatch: payloadBatch,
  43684. snapToValue: snapToValue
  43685. };
  43686. }
  43687. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  43688. showValueMap[axisInfo.key] = {
  43689. value: value,
  43690. payloadBatch: payloadBatch
  43691. };
  43692. }
  43693. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  43694. var payloadBatch = payloadInfo.payloadBatch;
  43695. var axis = axisInfo.axis;
  43696. var axisModel = axis.model;
  43697. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  43698. // whose length will be used to judge whether dispatch action.
  43699. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  43700. return;
  43701. }
  43702. var coordSysModel = axisInfo.coordSys.model;
  43703. var coordSysKey = makeKey(coordSysModel);
  43704. var coordSysItem = dataByCoordSys.map[coordSysKey];
  43705. if (!coordSysItem) {
  43706. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  43707. coordSysId: coordSysModel.id,
  43708. coordSysIndex: coordSysModel.componentIndex,
  43709. coordSysType: coordSysModel.type,
  43710. coordSysMainType: coordSysModel.mainType,
  43711. dataByAxis: []
  43712. };
  43713. dataByCoordSys.list.push(coordSysItem);
  43714. }
  43715. coordSysItem.dataByAxis.push({
  43716. axisDim: axis.dim,
  43717. axisIndex: axisModel.componentIndex,
  43718. axisType: axisModel.type,
  43719. axisId: axisModel.id,
  43720. value: value,
  43721. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  43722. // depends that all models have been updated. So it should not be performed
  43723. // here. Considering axisPointerModel used here is volatile, which is hard
  43724. // to be retrieve in TooltipView, we prepare parameters here.
  43725. valueLabelOpt: {
  43726. precision: axisPointerModel.get(['label', 'precision']),
  43727. formatter: axisPointerModel.get(['label', 'formatter'])
  43728. },
  43729. seriesDataIndices: payloadBatch.slice()
  43730. });
  43731. }
  43732. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  43733. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  43734. each(axesInfo, function (axisInfo, key) {
  43735. var option = axisInfo.axisPointerModel.option;
  43736. var valItem = showValueMap[key];
  43737. if (valItem) {
  43738. !axisInfo.useHandle && (option.status = 'show');
  43739. option.value = valItem.value; // For label formatter param and highlight.
  43740. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  43741. } // When always show (e.g., handle used), remain
  43742. // original value and status.
  43743. else {
  43744. // If hide, value still need to be set, consider
  43745. // click legend to toggle axis blank.
  43746. !axisInfo.useHandle && (option.status = 'hide');
  43747. } // If status is 'hide', should be no info in payload.
  43748. option.status === 'show' && outputAxesInfo.push({
  43749. axisDim: axisInfo.axis.dim,
  43750. axisIndex: axisInfo.axis.model.componentIndex,
  43751. value: option.value
  43752. });
  43753. });
  43754. }
  43755. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  43756. // Basic logic: If no showTip required, hideTip will be dispatched.
  43757. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  43758. dispatchAction({
  43759. type: 'hideTip'
  43760. });
  43761. return;
  43762. } // In most case only one axis (or event one series is used). It is
  43763. // convenient to fetch payload.seriesIndex and payload.dataIndex
  43764. // directly. So put the first seriesIndex and dataIndex of the first
  43765. // axis on the payload.
  43766. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  43767. dispatchAction({
  43768. type: 'showTip',
  43769. escapeConnect: true,
  43770. x: point[0],
  43771. y: point[1],
  43772. tooltipOption: payload.tooltipOption,
  43773. position: payload.position,
  43774. dataIndexInside: sampleItem.dataIndexInside,
  43775. dataIndex: sampleItem.dataIndex,
  43776. seriesIndex: sampleItem.seriesIndex,
  43777. dataByCoordSys: dataByCoordSys.list
  43778. });
  43779. }
  43780. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  43781. // FIXME
  43782. // highlight status modification should be a stage of main process?
  43783. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  43784. var zr = api.getZr();
  43785. var highDownKey = 'axisPointerLastHighlights';
  43786. var lastHighlights = inner$9(zr)[highDownKey] || {};
  43787. var newHighlights = inner$9(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  43788. // Build hash map and remove duplicate incidentally.
  43789. each(axesInfo, function (axisInfo, key) {
  43790. var option = axisInfo.axisPointerModel.option;
  43791. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  43792. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  43793. newHighlights[key] = batchItem;
  43794. });
  43795. }); // Diff.
  43796. var toHighlight = [];
  43797. var toDownplay = [];
  43798. each(lastHighlights, function (batchItem, key) {
  43799. !newHighlights[key] && toDownplay.push(batchItem);
  43800. });
  43801. each(newHighlights, function (batchItem, key) {
  43802. !lastHighlights[key] && toHighlight.push(batchItem);
  43803. });
  43804. toDownplay.length && api.dispatchAction({
  43805. type: 'downplay',
  43806. escapeConnect: true,
  43807. // Not blur others when highlight in axisPointer.
  43808. notBlur: true,
  43809. batch: toDownplay
  43810. });
  43811. toHighlight.length && api.dispatchAction({
  43812. type: 'highlight',
  43813. escapeConnect: true,
  43814. // Not blur others when highlight in axisPointer.
  43815. notBlur: true,
  43816. batch: toHighlight
  43817. });
  43818. }
  43819. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  43820. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  43821. var inputAxisInfo = inputAxesInfo[i];
  43822. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  43823. return inputAxisInfo;
  43824. }
  43825. }
  43826. }
  43827. function makeMapperParam(axisInfo) {
  43828. var axisModel = axisInfo.axis.model;
  43829. var item = {};
  43830. var dim = item.axisDim = axisInfo.axis.dim;
  43831. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  43832. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  43833. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  43834. return item;
  43835. }
  43836. function illegalPoint(point) {
  43837. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  43838. }
  43839. function install$7(registers) {
  43840. // CartesianAxisPointer is not supposed to be required here. But consider
  43841. // echarts.simple.js and online build tooltip, which only require gridSimple,
  43842. // CartesianAxisPointer should be able to required somewhere.
  43843. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  43844. registers.registerComponentModel(AxisPointerModel);
  43845. registers.registerComponentView(AxisPointerView);
  43846. registers.registerPreprocessor(function (option) {
  43847. // Always has a global axisPointerModel for default setting.
  43848. if (option) {
  43849. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  43850. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  43851. // is not set, remain null/undefined, otherwise it will
  43852. // override existent link setting.
  43853. if (link && !isArray(link)) {
  43854. option.axisPointer.link = [link];
  43855. }
  43856. }
  43857. }); // This process should proformed after coordinate systems created
  43858. // and series data processed. So put it on statistic processing stage.
  43859. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  43860. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  43861. // allAxesInfo should be updated when setOption performed.
  43862. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  43863. }); // Broadcast to all views.
  43864. registers.registerAction({
  43865. type: 'updateAxisPointer',
  43866. event: 'updateAxisPointer',
  43867. update: ':updateAxisPointer'
  43868. }, axisTrigger);
  43869. }
  43870. function install$8(registers) {
  43871. use(install$5);
  43872. use(install$7);
  43873. }
  43874. function setKeyInfoToNewElOption(resultItem, newElOption) {
  43875. var existElOption = resultItem.existing; // Set id and type after id assigned.
  43876. newElOption.id = resultItem.keyInfo.id;
  43877. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  43878. if (newElOption.parentId == null) {
  43879. var newElParentOption = newElOption.parentOption;
  43880. if (newElParentOption) {
  43881. newElOption.parentId = newElParentOption.id;
  43882. } else if (existElOption) {
  43883. newElOption.parentId = existElOption.parentId;
  43884. }
  43885. } // Clear
  43886. newElOption.parentOption = null;
  43887. }
  43888. function isSetLoc(obj, props) {
  43889. var isSet;
  43890. each(props, function (prop) {
  43891. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  43892. });
  43893. return isSet;
  43894. }
  43895. function mergeNewElOptionToExist(existList, index, newElOption) {
  43896. // Update existing options, for `getOption` feature.
  43897. var newElOptCopy = extend({}, newElOption);
  43898. var existElOption = existList[index];
  43899. var $action = newElOption.$action || 'merge';
  43900. if ($action === 'merge') {
  43901. if (existElOption) {
  43902. if ("development" !== 'production') {
  43903. var newType = newElOption.type;
  43904. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  43905. } // We can ensure that newElOptCopy and existElOption are not
  43906. // the same object, so `merge` will not change newElOptCopy.
  43907. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  43908. mergeLayoutParam(existElOption, newElOptCopy, {
  43909. ignoreSize: true
  43910. }); // Will be used in render.
  43911. copyLayoutParams(newElOption, existElOption); // Copy transition info to new option so it can be used in the transition.
  43912. // DO IT AFTER merge
  43913. copyTransitionInfo(newElOption, existElOption);
  43914. copyTransitionInfo(newElOption, existElOption, 'shape');
  43915. copyTransitionInfo(newElOption, existElOption, 'style');
  43916. copyTransitionInfo(newElOption, existElOption, 'extra'); // Copy clipPath
  43917. newElOption.clipPath = existElOption.clipPath;
  43918. } else {
  43919. existList[index] = newElOptCopy;
  43920. }
  43921. } else if ($action === 'replace') {
  43922. existList[index] = newElOptCopy;
  43923. } else if ($action === 'remove') {
  43924. // null will be cleaned later.
  43925. existElOption && (existList[index] = null);
  43926. }
  43927. }
  43928. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  43929. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  43930. function copyTransitionInfo(target, source, targetProp) {
  43931. if (targetProp) {
  43932. if (!target[targetProp] && source[targetProp]) {
  43933. // TODO avoid creating this empty object when there is no transition configuration.
  43934. target[targetProp] = {};
  43935. }
  43936. target = target[targetProp];
  43937. source = source[targetProp];
  43938. }
  43939. if (!target || !source) {
  43940. return;
  43941. }
  43942. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  43943. for (var i = 0; i < props.length; i++) {
  43944. var prop = props[i];
  43945. if (target[prop] == null && source[prop] != null) {
  43946. target[prop] = source[prop];
  43947. }
  43948. }
  43949. }
  43950. function setLayoutInfoToExist(existItem, newElOption) {
  43951. if (!existItem) {
  43952. return;
  43953. }
  43954. existItem.hv = newElOption.hv = [// Rigid body, don't care about `width`.
  43955. isSetLoc(newElOption, ['left', 'right']), // Rigid body, don't care about `height`.
  43956. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  43957. if (existItem.type === 'group') {
  43958. var existingGroupOpt = existItem;
  43959. var newGroupOpt = newElOption;
  43960. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  43961. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  43962. }
  43963. }
  43964. var GraphicComponentModel =
  43965. /** @class */
  43966. function (_super) {
  43967. __extends(GraphicComponentModel, _super);
  43968. function GraphicComponentModel() {
  43969. var _this = _super !== null && _super.apply(this, arguments) || this;
  43970. _this.type = GraphicComponentModel.type;
  43971. _this.preventAutoZ = true;
  43972. return _this;
  43973. }
  43974. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  43975. // Prevent default merge to elements
  43976. var elements = this.option.elements;
  43977. this.option.elements = null;
  43978. _super.prototype.mergeOption.call(this, option, ecModel);
  43979. this.option.elements = elements;
  43980. };
  43981. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  43982. var thisOption = this.option;
  43983. var newList = (isInit ? thisOption : newOption).elements;
  43984. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  43985. var flattenedList = [];
  43986. this._flatten(newList, flattenedList, null);
  43987. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  43988. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  43989. each(mappingResult, function (resultItem, index) {
  43990. var newElOption = resultItem.newOption;
  43991. if ("development" !== 'production') {
  43992. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  43993. }
  43994. if (!newElOption) {
  43995. return;
  43996. }
  43997. elOptionsToUpdate.push(newElOption);
  43998. setKeyInfoToNewElOption(resultItem, newElOption);
  43999. mergeNewElOptionToExist(existList, index, newElOption);
  44000. setLayoutInfoToExist(existList[index], newElOption);
  44001. }, this); // Clean
  44002. thisOption.elements = filter(existList, function (item) {
  44003. // $action should be volatile, otherwise option gotten from
  44004. // `getOption` will contain unexpected $action.
  44005. item && delete item.$action;
  44006. return item != null;
  44007. });
  44008. };
  44009. /**
  44010. * Convert
  44011. * [{
  44012. * type: 'group',
  44013. * id: 'xx',
  44014. * children: [{type: 'circle'}, {type: 'polygon'}]
  44015. * }]
  44016. * to
  44017. * [
  44018. * {type: 'group', id: 'xx'},
  44019. * {type: 'circle', parentId: 'xx'},
  44020. * {type: 'polygon', parentId: 'xx'}
  44021. * ]
  44022. */
  44023. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  44024. each(optionList, function (option) {
  44025. if (!option) {
  44026. return;
  44027. }
  44028. if (parentOption) {
  44029. option.parentOption = parentOption;
  44030. }
  44031. result.push(option);
  44032. var children = option.children; // here we don't judge if option.type is `group`
  44033. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  44034. if (children && children.length) {
  44035. this._flatten(children, result, option);
  44036. } // Deleting for JSON output, and for not affecting group creation.
  44037. delete option.children;
  44038. }, this);
  44039. }; // FIXME
  44040. // Pass to view using payload? setOption has a payload?
  44041. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  44042. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  44043. this._elOptionsToUpdate = null;
  44044. return els;
  44045. };
  44046. GraphicComponentModel.type = 'graphic';
  44047. GraphicComponentModel.defaultOption = {
  44048. elements: [] // parentId: null
  44049. };
  44050. return GraphicComponentModel;
  44051. }(ComponentModel);
  44052. /**
  44053. * Whether need to call `convertEC4CompatibleStyle`.
  44054. */
  44055. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  44056. // Since echarts5, `RectText` is separated from its host element and style.text
  44057. // does not exist any more. The compat work brings some extra burden on performance.
  44058. // So we provide:
  44059. // `legacy: true` force make compat.
  44060. // `legacy: false`, force do not compat.
  44061. // `legacy` not set: auto detect whether legacy.
  44062. // But in this case we do not compat (difficult to detect and rare case):
  44063. // Becuse custom series and graphic component support "merge", users may firstly
  44064. // only set `textStrokeWidth` style or secondly only set `text`.
  44065. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  44066. && (elType === 'text' || hasOwn(style, 'text')));
  44067. }
  44068. /**
  44069. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  44070. * @param hostStyle The properties might be modified.
  44071. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  44072. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  44073. * retried from the `hostStyle`.
  44074. */
  44075. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  44076. var srcStyle = hostStyle;
  44077. var textConfig;
  44078. var textContent;
  44079. var textContentStyle;
  44080. if (elType === 'text') {
  44081. textContentStyle = srcStyle;
  44082. } else {
  44083. textContentStyle = {};
  44084. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  44085. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  44086. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  44087. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  44088. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  44089. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  44090. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  44091. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  44092. textContent = {
  44093. type: 'text',
  44094. style: textContentStyle,
  44095. // ec4 does not support rectText trigger.
  44096. // And when text position is different in normal and emphasis
  44097. // => hover text trigger emphasis;
  44098. // => text position changed, leave mouse pointer immediately;
  44099. // That might cause incorrect state.
  44100. silent: true
  44101. };
  44102. textConfig = {};
  44103. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  44104. if (isNormal) {
  44105. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  44106. } else {
  44107. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  44108. }
  44109. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  44110. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  44111. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  44112. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  44113. }
  44114. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  44115. each(textContentStyle.rich, function (richItem) {
  44116. convertEC4CompatibleRichItem(richItem, richItem);
  44117. });
  44118. return {
  44119. textConfig: textConfig,
  44120. textContent: textContent
  44121. };
  44122. }
  44123. /**
  44124. * The result will be set to `out`.
  44125. */
  44126. function convertEC4CompatibleRichItem(out, richItem) {
  44127. if (!richItem) {
  44128. return;
  44129. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  44130. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  44131. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  44132. // richText in ec5.
  44133. // (2) `out === richItem` if and only if `out` is text el or rich item.
  44134. // So we can overwrite existing props in `out` since textXXX has higher priority.
  44135. richItem.font = richItem.textFont || richItem.font;
  44136. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  44137. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  44138. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  44139. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  44140. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  44141. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  44142. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  44143. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  44144. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  44145. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  44146. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  44147. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  44148. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  44149. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  44150. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  44151. }
  44152. var LEGACY_TRANSFORM_PROPS_MAP = {
  44153. position: ['x', 'y'],
  44154. scale: ['scaleX', 'scaleY'],
  44155. origin: ['originX', 'originY']
  44156. };
  44157. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  44158. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  44159. obj[key] = 1;
  44160. return obj;
  44161. }, {});
  44162. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', '); // '' means root
  44163. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  44164. var transitionInnerStore = makeInner();
  44165. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  44166. var animationProp = animationType + "Animation";
  44167. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  44168. var userDuring = transitionInnerStore(el).userDuring; // Only set when duration is > 0 and it's need to be animated.
  44169. if (config.duration > 0) {
  44170. // For simplicity, if during not specified, the previous during will not work any more.
  44171. config.during = userDuring ? bind(duringCall, {
  44172. el: el,
  44173. userDuring: userDuring
  44174. }) : null;
  44175. config.setToFinal = true;
  44176. config.scope = animationType;
  44177. }
  44178. extend(config, elOption[animationProp]);
  44179. return config;
  44180. }
  44181. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  44182. opts = opts || {};
  44183. var dataIndex = opts.dataIndex,
  44184. isInit = opts.isInit,
  44185. clearStyle = opts.clearStyle;
  44186. var hasAnimation = animatableModel.isAnimationEnabled(); // Save the meta info for further morphing. Like apply on the sub morphing elements.
  44187. var store = transitionInnerStore(el);
  44188. var styleOpt = elOption.style;
  44189. store.userDuring = elOption.during;
  44190. var transFromProps = {};
  44191. var propsToSet = {};
  44192. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  44193. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  44194. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  44195. if (!isInit && hasAnimation) {
  44196. prepareTransformTransitionFrom(el, elOption, transFromProps);
  44197. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  44198. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  44199. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  44200. }
  44201. propsToSet.style = styleOpt;
  44202. applyPropsDirectly(el, propsToSet, clearStyle);
  44203. applyMiscProps(el, elOption);
  44204. if (hasAnimation) {
  44205. if (isInit) {
  44206. var enterFromProps_1 = {};
  44207. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  44208. var prop = propName ? elOption[propName] : elOption;
  44209. if (prop && prop.enterFrom) {
  44210. if (propName) {
  44211. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  44212. }
  44213. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  44214. }
  44215. });
  44216. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  44217. if (config.duration > 0) {
  44218. el.animateFrom(enterFromProps_1, config);
  44219. }
  44220. } else {
  44221. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  44222. }
  44223. } // Store leave to be used in leave transition.
  44224. updateLeaveTo(el, elOption);
  44225. styleOpt ? el.dirty() : el.markRedraw();
  44226. }
  44227. function updateLeaveTo(el, elOption) {
  44228. // Try merge to previous set leaveTo
  44229. var leaveToProps = transitionInnerStore(el).leaveToProps;
  44230. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  44231. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  44232. var prop = propName ? elOption[propName] : elOption;
  44233. if (prop && prop.leaveTo) {
  44234. if (!leaveToProps) {
  44235. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  44236. }
  44237. if (propName) {
  44238. leaveToProps[propName] = leaveToProps[propName] || {};
  44239. }
  44240. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  44241. }
  44242. }
  44243. }
  44244. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  44245. if (el) {
  44246. var parent_1 = el.parent;
  44247. var leaveToProps = transitionInnerStore(el).leaveToProps;
  44248. if (leaveToProps) {
  44249. // TODO TODO use leave after leaveAnimation in series is introduced
  44250. // TODO Data index?
  44251. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  44252. config.done = function () {
  44253. parent_1.remove(el);
  44254. onRemove && onRemove();
  44255. };
  44256. el.animateTo(leaveToProps, config);
  44257. } else {
  44258. parent_1.remove(el);
  44259. onRemove && onRemove();
  44260. }
  44261. }
  44262. }
  44263. function isTransitionAll(transition) {
  44264. return transition === 'all';
  44265. }
  44266. function applyPropsDirectly(el, // Can be null/undefined
  44267. allPropsFinal, clearStyle) {
  44268. var styleOpt = allPropsFinal.style;
  44269. if (!el.isGroup && styleOpt) {
  44270. if (clearStyle) {
  44271. el.useStyle({}); // When style object changed, how to trade the existing animation?
  44272. // It is probably complicated and not needed to cover all the cases.
  44273. // But still need consider the case:
  44274. // (1) When using init animation on `style.opacity`, and before the animation
  44275. // ended users triggers an update by mousewhel. At that time the init
  44276. // animation should better be continued rather than terminated.
  44277. // So after `useStyle` called, we should change the animation target manually
  44278. // to continue the effect of the init animation.
  44279. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  44280. // to update the value to `val2` and no animation declared, should be terminate
  44281. // the previous animation or just modify the target of the animation?
  44282. // Therotically That will happen not only on `style` but also on `shape` and
  44283. // `transfrom` props. But we haven't handle this case at present yet.
  44284. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  44285. var animators = el.animators;
  44286. for (var i = 0; i < animators.length; i++) {
  44287. var animator = animators[i]; // targetName is the "topKey".
  44288. if (animator.targetName === 'style') {
  44289. animator.changeTarget(el.style);
  44290. }
  44291. }
  44292. }
  44293. el.setStyle(styleOpt);
  44294. }
  44295. if (allPropsFinal) {
  44296. // Not set style here.
  44297. allPropsFinal.style = null; // Set el to the final state firstly.
  44298. allPropsFinal && el.attr(allPropsFinal);
  44299. allPropsFinal.style = styleOpt;
  44300. }
  44301. }
  44302. function applyPropsTransition(el, elOption, dataIndex, model, // Can be null/undefined
  44303. transFromProps) {
  44304. if (transFromProps) {
  44305. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  44306. if (config.duration > 0) {
  44307. el.animateFrom(transFromProps, config);
  44308. }
  44309. }
  44310. }
  44311. function applyMiscProps(el, elOption) {
  44312. // Merge by default.
  44313. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  44314. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  44315. if (el instanceof Displayable) {
  44316. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  44317. }
  44318. if (el instanceof Path) {
  44319. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  44320. }
  44321. } // Use it to avoid it be exposed to user.
  44322. var tmpDuringScope = {};
  44323. var transitionDuringAPI = {
  44324. // Usually other props do not need to be changed in animation during.
  44325. setTransform: function (key, val) {
  44326. if ("development" !== 'production') {
  44327. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  44328. }
  44329. tmpDuringScope.el[key] = val;
  44330. return this;
  44331. },
  44332. getTransform: function (key) {
  44333. if ("development" !== 'production') {
  44334. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  44335. }
  44336. return tmpDuringScope.el[key];
  44337. },
  44338. setShape: function (key, val) {
  44339. if ("development" !== 'production') {
  44340. assertNotReserved(key);
  44341. }
  44342. var el = tmpDuringScope.el;
  44343. var shape = el.shape || (el.shape = {});
  44344. shape[key] = val;
  44345. el.dirtyShape && el.dirtyShape();
  44346. return this;
  44347. },
  44348. getShape: function (key) {
  44349. if ("development" !== 'production') {
  44350. assertNotReserved(key);
  44351. }
  44352. var shape = tmpDuringScope.el.shape;
  44353. if (shape) {
  44354. return shape[key];
  44355. }
  44356. },
  44357. setStyle: function (key, val) {
  44358. if ("development" !== 'production') {
  44359. assertNotReserved(key);
  44360. }
  44361. var el = tmpDuringScope.el;
  44362. var style = el.style;
  44363. if (style) {
  44364. if ("development" !== 'production') {
  44365. if (eqNaN(val)) {
  44366. warn('style.' + key + ' must not be assigned with NaN.');
  44367. }
  44368. }
  44369. style[key] = val;
  44370. el.dirtyStyle && el.dirtyStyle();
  44371. }
  44372. return this;
  44373. },
  44374. getStyle: function (key) {
  44375. if ("development" !== 'production') {
  44376. assertNotReserved(key);
  44377. }
  44378. var style = tmpDuringScope.el.style;
  44379. if (style) {
  44380. return style[key];
  44381. }
  44382. },
  44383. setExtra: function (key, val) {
  44384. if ("development" !== 'production') {
  44385. assertNotReserved(key);
  44386. }
  44387. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  44388. extra[key] = val;
  44389. return this;
  44390. },
  44391. getExtra: function (key) {
  44392. if ("development" !== 'production') {
  44393. assertNotReserved(key);
  44394. }
  44395. var extra = tmpDuringScope.el.extra;
  44396. if (extra) {
  44397. return extra[key];
  44398. }
  44399. }
  44400. };
  44401. function assertNotReserved(key) {
  44402. if ("development" !== 'production') {
  44403. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  44404. throw new Error('key must not be "' + key + '"');
  44405. }
  44406. }
  44407. }
  44408. function duringCall() {
  44409. // Do not provide "percent" until some requirements come.
  44410. // Because consider thies case:
  44411. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  44412. // And enter duration is different from update duration.
  44413. // Thus it might be confused about the meaning of "percent" in during callback.
  44414. var scope = this;
  44415. var el = scope.el;
  44416. if (!el) {
  44417. return;
  44418. } // If el is remove from zr by reason like legend, during still need to called,
  44419. // because el will be added back to zr and the prop value should not be incorrect.
  44420. var latestUserDuring = transitionInnerStore(el).userDuring;
  44421. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  44422. // If a during is called multiple times in one frame, maybe some users' calculation logic
  44423. // might be wrong (not sure whether this usage exists).
  44424. // The case of a during might be called twice can be: by default there is a animator for
  44425. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  44426. // another animators for 'style'/'shape'/'extra'.
  44427. if (latestUserDuring !== scopeUserDuring) {
  44428. // release
  44429. scope.el = scope.userDuring = null;
  44430. return;
  44431. }
  44432. tmpDuringScope.el = el; // Give no `this` to user in "during" calling.
  44433. scopeUserDuring(transitionDuringAPI); // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  44434. // consider the issue that the prop might be incorrect when return to "normal" state.
  44435. }
  44436. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  44437. var attrOpt = elOption[mainAttr];
  44438. if (!attrOpt) {
  44439. return;
  44440. }
  44441. var elPropsInAttr = fromEl[mainAttr];
  44442. var transFromPropsInAttr;
  44443. if (elPropsInAttr) {
  44444. var transition = elOption.transition;
  44445. var attrTransition = attrOpt.transition;
  44446. if (attrTransition) {
  44447. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  44448. if (isTransitionAll(attrTransition)) {
  44449. extend(transFromPropsInAttr, elPropsInAttr);
  44450. } else {
  44451. var transitionKeys = normalizeToArray(attrTransition);
  44452. for (var i = 0; i < transitionKeys.length; i++) {
  44453. var key = transitionKeys[i];
  44454. var elVal = elPropsInAttr[key];
  44455. transFromPropsInAttr[key] = elVal;
  44456. }
  44457. }
  44458. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  44459. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  44460. var elPropsInAttrKeys = keys(elPropsInAttr);
  44461. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  44462. var key = elPropsInAttrKeys[i];
  44463. var elVal = elPropsInAttr[key];
  44464. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  44465. transFromPropsInAttr[key] = elVal;
  44466. }
  44467. }
  44468. }
  44469. }
  44470. }
  44471. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  44472. var attrOpt = elOption[mainAttr];
  44473. if (!attrOpt) {
  44474. return;
  44475. }
  44476. var allPropsInAttr = allProps[mainAttr] = {};
  44477. var keysInAttr = keys(attrOpt);
  44478. for (var i = 0; i < keysInAttr.length; i++) {
  44479. var key = keysInAttr[i]; // To avoid share one object with different element, and
  44480. // to avoid user modify the object inexpectedly, have to clone.
  44481. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  44482. }
  44483. }
  44484. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  44485. var transition = elOption.transition;
  44486. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  44487. for (var i = 0; i < transitionKeys.length; i++) {
  44488. var key = transitionKeys[i];
  44489. if (key === 'style' || key === 'shape' || key === 'extra') {
  44490. continue;
  44491. }
  44492. var elVal = el[key];
  44493. if ("development" !== 'production') {
  44494. checkTransformPropRefer(key, 'el.transition');
  44495. } // Do not clone, animator will perform that clone.
  44496. transFromProps[key] = elVal;
  44497. }
  44498. }
  44499. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  44500. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  44501. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  44502. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  44503. var legacyArr = elOption[legacyName];
  44504. if (legacyArr) {
  44505. allProps[xyName[0]] = legacyArr[0];
  44506. allProps[xyName[1]] = legacyArr[1];
  44507. }
  44508. }
  44509. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  44510. var key = TRANSFORMABLE_PROPS[i];
  44511. if (elOption[key] != null) {
  44512. allProps[key] = elOption[key];
  44513. }
  44514. }
  44515. }
  44516. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  44517. if (!styleOpt) {
  44518. return;
  44519. }
  44520. var fromElStyle = fromEl.style;
  44521. var transFromStyleProps;
  44522. if (fromElStyle) {
  44523. var styleTransition = styleOpt.transition;
  44524. var elTransition = elOption.transition;
  44525. if (styleTransition && !isTransitionAll(styleTransition)) {
  44526. var transitionKeys = normalizeToArray(styleTransition);
  44527. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  44528. for (var i = 0; i < transitionKeys.length; i++) {
  44529. var key = transitionKeys[i];
  44530. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  44531. transFromStyleProps[key] = elVal;
  44532. }
  44533. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  44534. var animationProps = fromEl.getAnimationStyleProps();
  44535. var animationStyleProps = animationProps ? animationProps.style : null;
  44536. if (animationStyleProps) {
  44537. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  44538. var styleKeys = keys(styleOpt);
  44539. for (var i = 0; i < styleKeys.length; i++) {
  44540. var key = styleKeys[i];
  44541. if (animationStyleProps[key]) {
  44542. var elVal = fromElStyle[key];
  44543. transFromStyleProps[key] = elVal;
  44544. }
  44545. }
  44546. }
  44547. }
  44548. }
  44549. }
  44550. function isNonStyleTransitionEnabled(optVal, elVal) {
  44551. // The same as `checkNonStyleTansitionRefer`.
  44552. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  44553. }
  44554. var checkTransformPropRefer;
  44555. if ("development" !== 'production') {
  44556. checkTransformPropRefer = function (key, usedIn) {
  44557. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  44558. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  44559. }
  44560. };
  44561. }
  44562. var getStateToRestore = makeInner();
  44563. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  44564. /**
  44565. * Stop previous keyframe animation and restore the attributes.
  44566. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  44567. */
  44568. function stopPreviousKeyframeAnimationAndRestore(el) {
  44569. // Stop previous keyframe animation.
  44570. el.stopAnimation('keyframe'); // Restore
  44571. el.attr(getStateToRestore(el));
  44572. }
  44573. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  44574. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  44575. return;
  44576. }
  44577. if (isArray(animationOpts)) {
  44578. each(animationOpts, function (singleAnimationOpts) {
  44579. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  44580. });
  44581. return;
  44582. }
  44583. var keyframes = animationOpts.keyframes;
  44584. var duration = animationOpts.duration;
  44585. if (animatableModel && duration == null) {
  44586. // Default to use duration of config.
  44587. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  44588. var config = getAnimationConfig('enter', animatableModel, 0);
  44589. duration = config && config.duration;
  44590. }
  44591. if (!keyframes || !duration) {
  44592. return;
  44593. }
  44594. var stateToRestore = getStateToRestore(el);
  44595. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  44596. if (targetPropName && !el[targetPropName]) {
  44597. return;
  44598. }
  44599. var animator;
  44600. var endFrameIsSet = false; // Sort keyframes by percent.
  44601. keyframes.sort(function (a, b) {
  44602. return a.percent - b.percent;
  44603. });
  44604. each(keyframes, function (kf) {
  44605. // Stop current animation.
  44606. var animators = el.animators;
  44607. var kfValues = targetPropName ? kf[targetPropName] : kf;
  44608. if ("development" !== 'production') {
  44609. if (kf.percent >= 1) {
  44610. endFrameIsSet = true;
  44611. }
  44612. }
  44613. if (!kfValues) {
  44614. return;
  44615. }
  44616. var propKeys = keys(kfValues);
  44617. if (!targetPropName) {
  44618. // PENDING performance?
  44619. propKeys = filter(propKeys, function (key) {
  44620. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  44621. });
  44622. }
  44623. if (!propKeys.length) {
  44624. return;
  44625. }
  44626. if (!animator) {
  44627. animator = el.animate(targetPropName, animationOpts.loop, true);
  44628. animator.scope = 'keyframe';
  44629. }
  44630. for (var i = 0; i < animators.length; i++) {
  44631. // Stop all other animation that is not keyframe.
  44632. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  44633. animators[i].stopTracks(propKeys);
  44634. }
  44635. }
  44636. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  44637. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  44638. each(propKeys, function (key) {
  44639. // Save original value.
  44640. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  44641. });
  44642. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  44643. });
  44644. if (!animator) {
  44645. return;
  44646. }
  44647. if ("development" !== 'production') {
  44648. if (!endFrameIsSet) {
  44649. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  44650. }
  44651. }
  44652. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  44653. });
  44654. }
  44655. var nonShapeGraphicElements = {
  44656. // Reserved but not supported in graphic component.
  44657. path: null,
  44658. compoundPath: null,
  44659. // Supported in graphic component.
  44660. group: Group,
  44661. image: ZRImage,
  44662. text: ZRText
  44663. };
  44664. var inner$a = makeInner(); // ------------------------
  44665. // View
  44666. // ------------------------
  44667. var GraphicComponentView =
  44668. /** @class */
  44669. function (_super) {
  44670. __extends(GraphicComponentView, _super);
  44671. function GraphicComponentView() {
  44672. var _this = _super !== null && _super.apply(this, arguments) || this;
  44673. _this.type = GraphicComponentView.type;
  44674. return _this;
  44675. }
  44676. GraphicComponentView.prototype.init = function () {
  44677. this._elMap = createHashMap();
  44678. };
  44679. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  44680. // Having leveraged between use cases and algorithm complexity, a very
  44681. // simple layout mechanism is used:
  44682. // The size(width/height) can be determined by itself or its parent (not
  44683. // implemented yet), but can not by its children. (Top-down travel)
  44684. // The location(x/y) can be determined by the bounding rect of itself
  44685. // (can including its descendants or not) and the size of its parent.
  44686. // (Bottom-up travel)
  44687. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  44688. // view will be reused.
  44689. if (graphicModel !== this._lastGraphicModel) {
  44690. this._clear();
  44691. }
  44692. this._lastGraphicModel = graphicModel;
  44693. this._updateElements(graphicModel);
  44694. this._relocate(graphicModel, api);
  44695. };
  44696. /**
  44697. * Update graphic elements.
  44698. */
  44699. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  44700. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  44701. if (!elOptionsToUpdate) {
  44702. return;
  44703. }
  44704. var elMap = this._elMap;
  44705. var rootGroup = this.group;
  44706. var globalZ = graphicModel.get('z');
  44707. var globalZLevel = graphicModel.get('zlevel'); // Top-down tranverse to assign graphic settings to each elements.
  44708. each(elOptionsToUpdate, function (elOption) {
  44709. var id = convertOptionIdName(elOption.id, null);
  44710. var elExisting = id != null ? elMap.get(id) : null;
  44711. var parentId = convertOptionIdName(elOption.parentId, null);
  44712. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  44713. var elType = elOption.type;
  44714. var elOptionStyle = elOption.style;
  44715. if (elType === 'text' && elOptionStyle) {
  44716. // In top/bottom mode, textVerticalAlign should not be used, which cause
  44717. // inaccurately locating.
  44718. if (elOption.hv && elOption.hv[1]) {
  44719. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  44720. }
  44721. }
  44722. var textContentOption = elOption.textContent;
  44723. var textConfig = elOption.textConfig;
  44724. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  44725. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  44726. if (!textConfig && convertResult.textConfig) {
  44727. textConfig = elOption.textConfig = convertResult.textConfig;
  44728. }
  44729. if (!textContentOption && convertResult.textContent) {
  44730. textContentOption = convertResult.textContent;
  44731. }
  44732. } // Remove unnecessary props to avoid potential problems.
  44733. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  44734. if ("development" !== 'production') {
  44735. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  44736. }
  44737. var $action = elOption.$action || 'merge';
  44738. var isMerge = $action === 'merge';
  44739. var isReplace = $action === 'replace';
  44740. if (isMerge) {
  44741. var isInit = !elExisting;
  44742. var el_1 = elExisting;
  44743. if (isInit) {
  44744. el_1 = createEl(id, targetElParent, elOption.type, elMap);
  44745. } else {
  44746. el_1 && (inner$a(el_1).isNew = false); // Stop and restore before update any other attributes.
  44747. stopPreviousKeyframeAnimationAndRestore(el_1);
  44748. }
  44749. if (el_1) {
  44750. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  44751. isInit: isInit
  44752. });
  44753. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  44754. }
  44755. } else if (isReplace) {
  44756. removeEl(elExisting, elOption, elMap, graphicModel);
  44757. var el_2 = createEl(id, targetElParent, elOption.type, elMap);
  44758. if (el_2) {
  44759. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  44760. isInit: true
  44761. });
  44762. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  44763. }
  44764. } else if ($action === 'remove') {
  44765. updateLeaveTo(elExisting, elOption);
  44766. removeEl(elExisting, elOption, elMap, graphicModel);
  44767. }
  44768. var el = elMap.get(id);
  44769. if (el && textContentOption) {
  44770. if (isMerge) {
  44771. var textContentExisting = el.getTextContent();
  44772. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  44773. } else if (isReplace) {
  44774. el.setTextContent(new ZRText(textContentOption));
  44775. }
  44776. }
  44777. if (el) {
  44778. var clipPathOption = elOption.clipPath;
  44779. if (clipPathOption) {
  44780. var clipPathType = clipPathOption.type;
  44781. var clipPath = void 0;
  44782. var isInit = false;
  44783. if (isMerge) {
  44784. var oldClipPath = el.getClipPath();
  44785. isInit = !oldClipPath || inner$a(oldClipPath).type !== clipPathType;
  44786. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  44787. } else if (isReplace) {
  44788. isInit = true;
  44789. clipPath = newEl(clipPathType);
  44790. }
  44791. el.setClipPath(clipPath);
  44792. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  44793. isInit: isInit
  44794. });
  44795. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  44796. }
  44797. var elInner = inner$a(el);
  44798. el.setTextConfig(textConfig);
  44799. elInner.option = elOption;
  44800. setEventData(el, graphicModel, elOption);
  44801. setTooltipConfig({
  44802. el: el,
  44803. componentModel: graphicModel,
  44804. itemName: el.name,
  44805. itemTooltipOption: elOption.tooltip
  44806. });
  44807. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  44808. }
  44809. });
  44810. };
  44811. /**
  44812. * Locate graphic elements.
  44813. */
  44814. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  44815. var elOptions = graphicModel.option.elements;
  44816. var rootGroup = this.group;
  44817. var elMap = this._elMap;
  44818. var apiWidth = api.getWidth();
  44819. var apiHeight = api.getHeight();
  44820. var xy = ['x', 'y']; // Top-down to calculate percentage width/height of group
  44821. for (var i = 0; i < elOptions.length; i++) {
  44822. var elOption = elOptions[i];
  44823. var id = convertOptionIdName(elOption.id, null);
  44824. var el = id != null ? elMap.get(id) : null;
  44825. if (!el || !el.isGroup) {
  44826. continue;
  44827. }
  44828. var parentEl = el.parent;
  44829. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  44830. var elInner = inner$a(el);
  44831. var parentElInner = inner$a(parentEl);
  44832. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  44833. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  44834. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  44835. for (var i = elOptions.length - 1; i >= 0; i--) {
  44836. var elOption = elOptions[i];
  44837. var id = convertOptionIdName(elOption.id, null);
  44838. var el = id != null ? elMap.get(id) : null;
  44839. if (!el) {
  44840. continue;
  44841. }
  44842. var parentEl = el.parent;
  44843. var parentElInner = inner$a(parentEl);
  44844. var containerInfo = parentEl === rootGroup ? {
  44845. width: apiWidth,
  44846. height: apiHeight
  44847. } : {
  44848. width: parentElInner.width,
  44849. height: parentElInner.height
  44850. }; // PENDING
  44851. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  44852. // does not include the rect of [0, 0, group.width, group.height], which
  44853. // is probably weird for users. Should we make a break change for it?
  44854. var layoutPos = {};
  44855. var layouted = positionElement(el, elOption, containerInfo, null, {
  44856. hv: elOption.hv,
  44857. boundingMode: elOption.bounding
  44858. }, layoutPos);
  44859. if (!inner$a(el).isNew && layouted) {
  44860. var transition = elOption.transition;
  44861. var animatePos = {};
  44862. for (var k = 0; k < xy.length; k++) {
  44863. var key = xy[k];
  44864. var val = layoutPos[key];
  44865. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  44866. animatePos[key] = val;
  44867. } else {
  44868. el[key] = val;
  44869. }
  44870. }
  44871. updateProps(el, animatePos, graphicModel, 0);
  44872. } else {
  44873. el.attr(layoutPos);
  44874. }
  44875. }
  44876. };
  44877. /**
  44878. * Clear all elements.
  44879. */
  44880. GraphicComponentView.prototype._clear = function () {
  44881. var _this = this;
  44882. var elMap = this._elMap;
  44883. elMap.each(function (el) {
  44884. removeEl(el, inner$a(el).option, elMap, _this._lastGraphicModel);
  44885. });
  44886. this._elMap = createHashMap();
  44887. };
  44888. GraphicComponentView.prototype.dispose = function () {
  44889. this._clear();
  44890. };
  44891. GraphicComponentView.type = 'graphic';
  44892. return GraphicComponentView;
  44893. }(ComponentView);
  44894. function newEl(graphicType) {
  44895. if ("development" !== 'production') {
  44896. assert(graphicType, 'graphic type MUST be set');
  44897. }
  44898. var Clz = hasOwn(nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  44899. // overwritten by users, so do them first.
  44900. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  44901. if ("development" !== 'production') {
  44902. assert(Clz, "graphic type " + graphicType + " can not be found");
  44903. }
  44904. var el = new Clz({});
  44905. inner$a(el).type = graphicType;
  44906. return el;
  44907. }
  44908. function createEl(id, targetElParent, graphicType, elMap) {
  44909. var el = newEl(graphicType);
  44910. targetElParent.add(el);
  44911. elMap.set(id, el);
  44912. inner$a(el).id = id;
  44913. inner$a(el).isNew = true;
  44914. return el;
  44915. }
  44916. function removeEl(elExisting, elOption, elMap, graphicModel) {
  44917. var existElParent = elExisting && elExisting.parent;
  44918. if (existElParent) {
  44919. elExisting.type === 'group' && elExisting.traverse(function (el) {
  44920. removeEl(el, elOption, elMap, graphicModel);
  44921. });
  44922. applyLeaveTransition(elExisting, elOption, graphicModel);
  44923. elMap.removeKey(inner$a(elExisting).id);
  44924. }
  44925. }
  44926. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  44927. if (!el.isGroup) {
  44928. each([['cursor', Displayable.prototype.cursor], // We should not support configure z and zlevel in the element level.
  44929. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  44930. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0], // z2 must not be null/undefined, otherwise sort error may occur.
  44931. ['z2', 0]], function (item) {
  44932. var prop = item[0];
  44933. if (hasOwn(elOption, prop)) {
  44934. el[prop] = retrieve2(elOption[prop], item[1]);
  44935. } else if (el[prop] == null) {
  44936. el[prop] = item[1];
  44937. }
  44938. });
  44939. }
  44940. each(keys(elOption), function (key) {
  44941. // Assign event handlers.
  44942. // PENDING: should enumerate all event names or use pattern matching?
  44943. if (key.indexOf('on') === 0) {
  44944. var val = elOption[key];
  44945. el[key] = isFunction(val) ? val : null;
  44946. }
  44947. });
  44948. if (hasOwn(elOption, 'draggable')) {
  44949. el.draggable = elOption.draggable;
  44950. } // Other attributes
  44951. elOption.name != null && (el.name = elOption.name);
  44952. elOption.id != null && (el.id = elOption.id);
  44953. } // Remove unnecessary props to avoid potential problems.
  44954. function getCleanedElOption(elOption) {
  44955. elOption = extend({}, elOption);
  44956. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  44957. delete elOption[name];
  44958. });
  44959. return elOption;
  44960. }
  44961. function setEventData(el, graphicModel, elOption) {
  44962. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  44963. if (!el.silent && !el.ignore && !eventData) {
  44964. eventData = getECData(el).eventData = {
  44965. componentType: 'graphic',
  44966. componentIndex: graphicModel.componentIndex,
  44967. name: el.name
  44968. };
  44969. } // `elOption.info` enables user to mount some info on
  44970. // elements and use them in event handlers.
  44971. if (eventData) {
  44972. eventData.info = elOption.info;
  44973. }
  44974. }
  44975. function install$9(registers) {
  44976. registers.registerComponentModel(GraphicComponentModel);
  44977. registers.registerComponentView(GraphicComponentView);
  44978. registers.registerPreprocessor(function (option) {
  44979. var graphicOption = option.graphic; // Convert
  44980. // {graphic: [{left: 10, type: 'circle'}, ...]}
  44981. // or
  44982. // {graphic: {left: 10, type: 'circle'}}
  44983. // to
  44984. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  44985. if (isArray(graphicOption)) {
  44986. if (!graphicOption[0] || !graphicOption[0].elements) {
  44987. option.graphic = [{
  44988. elements: graphicOption
  44989. }];
  44990. } else {
  44991. // Only one graphic instance can be instantiated. (We don't
  44992. // want that too many views are created in echarts._viewMap.)
  44993. option.graphic = [option.graphic[0]];
  44994. }
  44995. } else if (graphicOption && !graphicOption.elements) {
  44996. option.graphic = [{
  44997. elements: [graphicOption]
  44998. }];
  44999. }
  45000. });
  45001. }
  45002. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  45003. // FIXME: polar has been broken (but rarely used).
  45004. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  45005. function isCoordSupported(seriesModel) {
  45006. var coordType = seriesModel.get('coordinateSystem');
  45007. return indexOf(SERIES_COORDS, coordType) >= 0;
  45008. }
  45009. function getAxisMainType(axisDim) {
  45010. if ("development" !== 'production') {
  45011. assert(axisDim);
  45012. }
  45013. return axisDim + 'Axis';
  45014. }
  45015. /**
  45016. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  45017. * This function finds all linked dataZoomModels start from the given payload.
  45018. */
  45019. function findEffectedDataZooms(ecModel, payload) {
  45020. // Key: `DataZoomAxisDimension`
  45021. var axisRecords = createHashMap();
  45022. var effectedModels = []; // Key: uid of dataZoomModel
  45023. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  45024. ecModel.eachComponent({
  45025. mainType: 'dataZoom',
  45026. query: payload
  45027. }, function (dataZoomModel) {
  45028. if (!effectedModelMap.get(dataZoomModel.uid)) {
  45029. addToEffected(dataZoomModel);
  45030. }
  45031. }); // Start from the given dataZoomModels, travel the graph to find
  45032. // all of the linked dataZoom models.
  45033. var foundNewLink;
  45034. do {
  45035. foundNewLink = false;
  45036. ecModel.eachComponent('dataZoom', processSingle);
  45037. } while (foundNewLink);
  45038. function processSingle(dataZoomModel) {
  45039. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  45040. addToEffected(dataZoomModel);
  45041. foundNewLink = true;
  45042. }
  45043. }
  45044. function addToEffected(dataZoom) {
  45045. effectedModelMap.set(dataZoom.uid, true);
  45046. effectedModels.push(dataZoom);
  45047. markAxisControlled(dataZoom);
  45048. }
  45049. function isLinked(dataZoomModel) {
  45050. var isLink = false;
  45051. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45052. var axisIdxArr = axisRecords.get(axisDim);
  45053. if (axisIdxArr && axisIdxArr[axisIndex]) {
  45054. isLink = true;
  45055. }
  45056. });
  45057. return isLink;
  45058. }
  45059. function markAxisControlled(dataZoomModel) {
  45060. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45061. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  45062. });
  45063. }
  45064. return effectedModels;
  45065. }
  45066. /**
  45067. * Find the first target coordinate system.
  45068. * Available after model built.
  45069. *
  45070. * @return Like {
  45071. * grid: [
  45072. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  45073. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  45074. * ...
  45075. * ], // cartesians must not be null/undefined.
  45076. * polar: [
  45077. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  45078. * ...
  45079. * ], // polars must not be null/undefined.
  45080. * singleAxis: [
  45081. * {model: coord0, axisModels: [], coordIndex: 0}
  45082. * ]
  45083. * }
  45084. */
  45085. function collectReferCoordSysModelInfo(dataZoomModel) {
  45086. var ecModel = dataZoomModel.ecModel;
  45087. var coordSysInfoWrap = {
  45088. infoList: [],
  45089. infoMap: createHashMap()
  45090. };
  45091. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45092. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45093. if (!axisModel) {
  45094. return;
  45095. }
  45096. var coordSysModel = axisModel.getCoordSysModel();
  45097. if (!coordSysModel) {
  45098. return;
  45099. }
  45100. var coordSysUid = coordSysModel.uid;
  45101. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  45102. if (!coordSysInfo) {
  45103. coordSysInfo = {
  45104. model: coordSysModel,
  45105. axisModels: []
  45106. };
  45107. coordSysInfoWrap.infoList.push(coordSysInfo);
  45108. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  45109. }
  45110. coordSysInfo.axisModels.push(axisModel);
  45111. });
  45112. return coordSysInfoWrap;
  45113. }
  45114. var DataZoomAxisInfo =
  45115. /** @class */
  45116. function () {
  45117. function DataZoomAxisInfo() {
  45118. this.indexList = [];
  45119. this.indexMap = [];
  45120. }
  45121. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  45122. // Remove duplication.
  45123. if (!this.indexMap[axisCmptIdx]) {
  45124. this.indexList.push(axisCmptIdx);
  45125. this.indexMap[axisCmptIdx] = true;
  45126. }
  45127. };
  45128. return DataZoomAxisInfo;
  45129. }();
  45130. var DataZoomModel =
  45131. /** @class */
  45132. function (_super) {
  45133. __extends(DataZoomModel, _super);
  45134. function DataZoomModel() {
  45135. var _this = _super !== null && _super.apply(this, arguments) || this;
  45136. _this.type = DataZoomModel.type;
  45137. _this._autoThrottle = true;
  45138. _this._noTarget = true;
  45139. /**
  45140. * It is `[rangeModeForMin, rangeModeForMax]`.
  45141. * The optional values for `rangeMode`:
  45142. * + `'value'` mode: the axis extent will always be determined by
  45143. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  45144. * how data like and how `axis.min` and `axis.max` are.
  45145. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  45146. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  45147. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  45148. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  45149. *
  45150. * For example, when users are using dynamic data (update data periodically via `setOption`),
  45151. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  45152. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  45153. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  45154. */
  45155. _this._rangePropMode = ['percent', 'percent'];
  45156. return _this;
  45157. }
  45158. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  45159. var inputRawOption = retrieveRawOption(option);
  45160. /**
  45161. * Suppose a "main process" start at the point that model prepared (that is,
  45162. * model initialized or merged or method called in `action`).
  45163. * We should keep the `main process` idempotent, that is, given a set of values
  45164. * on `option`, we get the same result.
  45165. *
  45166. * But sometimes, values on `option` will be updated for providing users
  45167. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  45168. * should not be the base/input of the `main process`.
  45169. *
  45170. * So in that case we should save and keep the input of the `main process`
  45171. * separately, called `settledOption`.
  45172. *
  45173. * For example, consider the case:
  45174. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  45175. * where the original input `option.startValue`, `option.endValue` are earsed by
  45176. * calculated value.
  45177. * (Step)2) click the legend to hide and show a series,
  45178. * where the new range is calculated by the earsed `startValue` and `endValue`,
  45179. * which brings incorrect result.
  45180. */
  45181. this.settledOption = inputRawOption;
  45182. this.mergeDefaultAndTheme(option, ecModel);
  45183. this._doInit(inputRawOption);
  45184. };
  45185. DataZoomModel.prototype.mergeOption = function (newOption) {
  45186. var inputRawOption = retrieveRawOption(newOption); // FIX #2591
  45187. merge(this.option, newOption, true);
  45188. merge(this.settledOption, inputRawOption, true);
  45189. this._doInit(inputRawOption);
  45190. };
  45191. DataZoomModel.prototype._doInit = function (inputRawOption) {
  45192. var thisOption = this.option;
  45193. this._setDefaultThrottle(inputRawOption);
  45194. this._updateRangeUse(inputRawOption);
  45195. var settledOption = this.settledOption;
  45196. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  45197. // start/end has higher priority over startValue/endValue if they
  45198. // both set, but we should make chart.setOption({endValue: 1000})
  45199. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  45200. if (this._rangePropMode[index] === 'value') {
  45201. thisOption[names[0]] = settledOption[names[0]] = null;
  45202. } // Otherwise do nothing and use the merge result.
  45203. }, this);
  45204. this._resetTarget();
  45205. };
  45206. DataZoomModel.prototype._resetTarget = function () {
  45207. var optionOrient = this.get('orient', true);
  45208. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  45209. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  45210. if (hasAxisSpecified) {
  45211. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  45212. } else {
  45213. this._orient = optionOrient || 'horizontal';
  45214. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  45215. }
  45216. this._noTarget = true;
  45217. targetAxisIndexMap.each(function (axisInfo) {
  45218. if (axisInfo.indexList.length) {
  45219. this._noTarget = false;
  45220. }
  45221. }, this);
  45222. };
  45223. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  45224. var hasAxisSpecified = false;
  45225. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  45226. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  45227. // but do not want use auto mode. Because empty array may be encountered when
  45228. // some error occurred.
  45229. if (!refering.specified) {
  45230. return;
  45231. }
  45232. hasAxisSpecified = true;
  45233. var axisInfo = new DataZoomAxisInfo();
  45234. each(refering.models, function (axisModel) {
  45235. axisInfo.add(axisModel.componentIndex);
  45236. });
  45237. targetAxisIndexMap.set(axisDim, axisInfo);
  45238. }, this);
  45239. return hasAxisSpecified;
  45240. };
  45241. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  45242. var ecModel = this.ecModel;
  45243. var needAuto = true; // Find axis that parallel to dataZoom as default.
  45244. if (needAuto) {
  45245. var axisDim = orient === 'vertical' ? 'y' : 'x';
  45246. var axisModels = ecModel.findComponents({
  45247. mainType: axisDim + 'Axis'
  45248. });
  45249. setParallelAxis(axisModels, axisDim);
  45250. } // Find axis that parallel to dataZoom as default.
  45251. if (needAuto) {
  45252. var axisModels = ecModel.findComponents({
  45253. mainType: 'singleAxis',
  45254. filter: function (axisModel) {
  45255. return axisModel.get('orient', true) === orient;
  45256. }
  45257. });
  45258. setParallelAxis(axisModels, 'single');
  45259. }
  45260. function setParallelAxis(axisModels, axisDim) {
  45261. // At least use the first parallel axis as the target axis.
  45262. var axisModel = axisModels[0];
  45263. if (!axisModel) {
  45264. return;
  45265. }
  45266. var axisInfo = new DataZoomAxisInfo();
  45267. axisInfo.add(axisModel.componentIndex);
  45268. targetAxisIndexMap.set(axisDim, axisInfo);
  45269. needAuto = false; // Find parallel axes in the same grid.
  45270. if (axisDim === 'x' || axisDim === 'y') {
  45271. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  45272. gridModel_1 && each(axisModels, function (axModel) {
  45273. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  45274. axisInfo.add(axModel.componentIndex);
  45275. }
  45276. });
  45277. }
  45278. }
  45279. if (needAuto) {
  45280. // If no parallel axis, find the first category axis as default. (Also consider polar).
  45281. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  45282. if (!needAuto) {
  45283. return;
  45284. }
  45285. var axisModels = ecModel.findComponents({
  45286. mainType: getAxisMainType(axisDim),
  45287. filter: function (axisModel) {
  45288. return axisModel.get('type', true) === 'category';
  45289. }
  45290. });
  45291. if (axisModels[0]) {
  45292. var axisInfo = new DataZoomAxisInfo();
  45293. axisInfo.add(axisModels[0].componentIndex);
  45294. targetAxisIndexMap.set(axisDim, axisInfo);
  45295. needAuto = false;
  45296. }
  45297. }, this);
  45298. }
  45299. };
  45300. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  45301. var dim; // Find the first axis
  45302. this.eachTargetAxis(function (axisDim) {
  45303. !dim && (dim = axisDim);
  45304. }, this);
  45305. return dim === 'y' ? 'vertical' : 'horizontal';
  45306. };
  45307. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  45308. // When first time user set throttle, auto throttle ends.
  45309. if (inputRawOption.hasOwnProperty('throttle')) {
  45310. this._autoThrottle = false;
  45311. }
  45312. if (this._autoThrottle) {
  45313. var globalOption = this.ecModel.option;
  45314. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  45315. }
  45316. };
  45317. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  45318. var rangePropMode = this._rangePropMode;
  45319. var rangeModeInOption = this.get('rangeMode');
  45320. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  45321. var percentSpecified = inputRawOption[names[0]] != null;
  45322. var valueSpecified = inputRawOption[names[1]] != null;
  45323. if (percentSpecified && !valueSpecified) {
  45324. rangePropMode[index] = 'percent';
  45325. } else if (!percentSpecified && valueSpecified) {
  45326. rangePropMode[index] = 'value';
  45327. } else if (rangeModeInOption) {
  45328. rangePropMode[index] = rangeModeInOption[index];
  45329. } else if (percentSpecified) {
  45330. // percentSpecified && valueSpecified
  45331. rangePropMode[index] = 'percent';
  45332. } // else remain its original setting.
  45333. });
  45334. };
  45335. DataZoomModel.prototype.noTarget = function () {
  45336. return this._noTarget;
  45337. };
  45338. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  45339. var firstAxisModel;
  45340. this.eachTargetAxis(function (axisDim, axisIndex) {
  45341. if (firstAxisModel == null) {
  45342. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45343. }
  45344. }, this);
  45345. return firstAxisModel;
  45346. };
  45347. /**
  45348. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  45349. */
  45350. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  45351. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  45352. each(axisInfo.indexList, function (axisIndex) {
  45353. callback.call(context, axisDim, axisIndex);
  45354. });
  45355. });
  45356. };
  45357. /**
  45358. * @return If not found, return null/undefined.
  45359. */
  45360. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  45361. var axisModel = this.getAxisModel(axisDim, axisIndex);
  45362. if (axisModel) {
  45363. return axisModel.__dzAxisProxy;
  45364. }
  45365. };
  45366. /**
  45367. * @return If not found, return null/undefined.
  45368. */
  45369. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  45370. if ("development" !== 'production') {
  45371. assert(axisDim && axisIndex != null);
  45372. }
  45373. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  45374. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  45375. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45376. }
  45377. };
  45378. /**
  45379. * If not specified, set to undefined.
  45380. */
  45381. DataZoomModel.prototype.setRawRange = function (opt) {
  45382. var thisOption = this.option;
  45383. var settledOption = this.settledOption;
  45384. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  45385. // Consider the pair <start, startValue>:
  45386. // If one has value and the other one is `null/undefined`, we both set them
  45387. // to `settledOption`. This strategy enables the feature to clear the original
  45388. // value in `settledOption` to `null/undefined`.
  45389. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  45390. // and keep `settledOption` with the original value. This strategy enables users to
  45391. // only set <end or endValue> but not set <start or startValue> when calling
  45392. // `dispatchAction`.
  45393. // The pair <end, endValue> is treated in the same way.
  45394. if (opt[names[0]] != null || opt[names[1]] != null) {
  45395. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  45396. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  45397. }
  45398. }, this);
  45399. this._updateRangeUse(opt);
  45400. };
  45401. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  45402. var option = this.option;
  45403. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  45404. option[name] = opt[name];
  45405. });
  45406. };
  45407. DataZoomModel.prototype.getPercentRange = function () {
  45408. var axisProxy = this.findRepresentativeAxisProxy();
  45409. if (axisProxy) {
  45410. return axisProxy.getDataPercentWindow();
  45411. }
  45412. };
  45413. /**
  45414. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  45415. *
  45416. * @return [startValue, endValue] value can only be '-' or finite number.
  45417. */
  45418. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  45419. if (axisDim == null && axisIndex == null) {
  45420. var axisProxy = this.findRepresentativeAxisProxy();
  45421. if (axisProxy) {
  45422. return axisProxy.getDataValueWindow();
  45423. }
  45424. } else {
  45425. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  45426. }
  45427. };
  45428. /**
  45429. * @param axisModel If axisModel given, find axisProxy
  45430. * corresponding to the axisModel
  45431. */
  45432. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  45433. if (axisModel) {
  45434. return axisModel.__dzAxisProxy;
  45435. } // Find the first hosted axisProxy
  45436. var firstProxy;
  45437. var axisDimList = this._targetAxisInfoMap.keys();
  45438. for (var i = 0; i < axisDimList.length; i++) {
  45439. var axisDim = axisDimList[i];
  45440. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  45441. for (var j = 0; j < axisInfo.indexList.length; j++) {
  45442. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  45443. if (proxy.hostedBy(this)) {
  45444. return proxy;
  45445. }
  45446. if (!firstProxy) {
  45447. firstProxy = proxy;
  45448. }
  45449. }
  45450. } // If no hosted proxy found, still need to return a proxy.
  45451. // This case always happens in toolbox dataZoom, where axes are all hosted by
  45452. // other dataZooms.
  45453. return firstProxy;
  45454. };
  45455. DataZoomModel.prototype.getRangePropMode = function () {
  45456. return this._rangePropMode.slice();
  45457. };
  45458. DataZoomModel.prototype.getOrient = function () {
  45459. if ("development" !== 'production') {
  45460. // Should not be called before initialized.
  45461. assert(this._orient);
  45462. }
  45463. return this._orient;
  45464. };
  45465. DataZoomModel.type = 'dataZoom';
  45466. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  45467. DataZoomModel.defaultOption = {
  45468. // zlevel: 0,
  45469. z: 4,
  45470. filterMode: 'filter',
  45471. start: 0,
  45472. end: 100
  45473. };
  45474. return DataZoomModel;
  45475. }(ComponentModel);
  45476. /**
  45477. * Retrieve those raw params from option, which will be cached separately,
  45478. * because they will be overwritten by normalized/calculated values in the main
  45479. * process.
  45480. */
  45481. function retrieveRawOption(option) {
  45482. var ret = {};
  45483. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  45484. option.hasOwnProperty(name) && (ret[name] = option[name]);
  45485. });
  45486. return ret;
  45487. }
  45488. var SelectDataZoomModel =
  45489. /** @class */
  45490. function (_super) {
  45491. __extends(SelectDataZoomModel, _super);
  45492. function SelectDataZoomModel() {
  45493. var _this = _super !== null && _super.apply(this, arguments) || this;
  45494. _this.type = SelectDataZoomModel.type;
  45495. return _this;
  45496. }
  45497. SelectDataZoomModel.type = 'dataZoom.select';
  45498. return SelectDataZoomModel;
  45499. }(DataZoomModel);
  45500. var DataZoomView =
  45501. /** @class */
  45502. function (_super) {
  45503. __extends(DataZoomView, _super);
  45504. function DataZoomView() {
  45505. var _this = _super !== null && _super.apply(this, arguments) || this;
  45506. _this.type = DataZoomView.type;
  45507. return _this;
  45508. }
  45509. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  45510. this.dataZoomModel = dataZoomModel;
  45511. this.ecModel = ecModel;
  45512. this.api = api;
  45513. };
  45514. DataZoomView.type = 'dataZoom';
  45515. return DataZoomView;
  45516. }(ComponentView);
  45517. var SelectDataZoomView =
  45518. /** @class */
  45519. function (_super) {
  45520. __extends(SelectDataZoomView, _super);
  45521. function SelectDataZoomView() {
  45522. var _this = _super !== null && _super.apply(this, arguments) || this;
  45523. _this.type = SelectDataZoomView.type;
  45524. return _this;
  45525. }
  45526. SelectDataZoomView.type = 'dataZoom.select';
  45527. return SelectDataZoomView;
  45528. }(DataZoomView);
  45529. /*
  45530. * Licensed to the Apache Software Foundation (ASF) under one
  45531. * or more contributor license agreements. See the NOTICE file
  45532. * distributed with this work for additional information
  45533. * regarding copyright ownership. The ASF licenses this file
  45534. * to you under the Apache License, Version 2.0 (the
  45535. * "License"); you may not use this file except in compliance
  45536. * with the License. You may obtain a copy of the License at
  45537. *
  45538. * http://www.apache.org/licenses/LICENSE-2.0
  45539. *
  45540. * Unless required by applicable law or agreed to in writing,
  45541. * software distributed under the License is distributed on an
  45542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45543. * KIND, either express or implied. See the License for the
  45544. * specific language governing permissions and limitations
  45545. * under the License.
  45546. */
  45547. /**
  45548. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45549. */
  45550. /*
  45551. * Licensed to the Apache Software Foundation (ASF) under one
  45552. * or more contributor license agreements. See the NOTICE file
  45553. * distributed with this work for additional information
  45554. * regarding copyright ownership. The ASF licenses this file
  45555. * to you under the Apache License, Version 2.0 (the
  45556. * "License"); you may not use this file except in compliance
  45557. * with the License. You may obtain a copy of the License at
  45558. *
  45559. * http://www.apache.org/licenses/LICENSE-2.0
  45560. *
  45561. * Unless required by applicable law or agreed to in writing,
  45562. * software distributed under the License is distributed on an
  45563. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45564. * KIND, either express or implied. See the License for the
  45565. * specific language governing permissions and limitations
  45566. * under the License.
  45567. */
  45568. /**
  45569. * Calculate slider move result.
  45570. * Usage:
  45571. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  45572. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  45573. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  45574. *
  45575. * @param delta Move length.
  45576. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  45577. * handleEnds will be modified in this method.
  45578. * @param extent handleEnds is restricted by extent.
  45579. * extent[0] should less or equals than extent[1].
  45580. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  45581. * @param minSpan The range of dataZoom can not be smaller than that.
  45582. * If not set, handle0 and cross handle1. If set as a non-negative
  45583. * number (including `0`), handles will push each other when reaching
  45584. * the minSpan.
  45585. * @param maxSpan The range of dataZoom can not be larger than that.
  45586. * @return The input handleEnds.
  45587. */
  45588. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  45589. delta = delta || 0;
  45590. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  45591. if (minSpan != null) {
  45592. minSpan = restrict(minSpan, [0, extentSpan]);
  45593. }
  45594. if (maxSpan != null) {
  45595. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  45596. }
  45597. if (handleIndex === 'all') {
  45598. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  45599. handleSpan = restrict(handleSpan, [0, extentSpan]);
  45600. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  45601. handleIndex = 0;
  45602. }
  45603. handleEnds[0] = restrict(handleEnds[0], extent);
  45604. handleEnds[1] = restrict(handleEnds[1], extent);
  45605. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  45606. handleEnds[handleIndex] += delta; // Restrict in extent.
  45607. var extentMinSpan = minSpan || 0;
  45608. var realExtent = extent.slice();
  45609. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  45610. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  45611. var currDistSign;
  45612. currDistSign = getSpanSign(handleEnds, handleIndex);
  45613. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  45614. // If minSpan exists, 'cross' is forbidden.
  45615. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  45616. } // Shrink span.
  45617. currDistSign = getSpanSign(handleEnds, handleIndex);
  45618. if (maxSpan != null && currDistSign.span > maxSpan) {
  45619. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  45620. }
  45621. return handleEnds;
  45622. }
  45623. function getSpanSign(handleEnds, handleIndex) {
  45624. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  45625. // is at left of handleEnds[1] for non-cross case.
  45626. return {
  45627. span: Math.abs(dist),
  45628. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  45629. };
  45630. }
  45631. function restrict(value, extend) {
  45632. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  45633. }
  45634. var each$4 = each;
  45635. var asc$1 = asc;
  45636. /**
  45637. * Operate single axis.
  45638. * One axis can only operated by one axis operator.
  45639. * Different dataZoomModels may be defined to operate the same axis.
  45640. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  45641. * So dataZoomModels share one axisProxy in that case.
  45642. */
  45643. var AxisProxy =
  45644. /** @class */
  45645. function () {
  45646. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  45647. this._dimName = dimName;
  45648. this._axisIndex = axisIndex;
  45649. this.ecModel = ecModel;
  45650. this._dataZoomModel = dataZoomModel; // /**
  45651. // * @readOnly
  45652. // * @private
  45653. // */
  45654. // this.hasSeriesStacked;
  45655. }
  45656. /**
  45657. * Whether the axisProxy is hosted by dataZoomModel.
  45658. */
  45659. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  45660. return this._dataZoomModel === dataZoomModel;
  45661. };
  45662. /**
  45663. * @return Value can only be NaN or finite value.
  45664. */
  45665. AxisProxy.prototype.getDataValueWindow = function () {
  45666. return this._valueWindow.slice();
  45667. };
  45668. /**
  45669. * @return {Array.<number>}
  45670. */
  45671. AxisProxy.prototype.getDataPercentWindow = function () {
  45672. return this._percentWindow.slice();
  45673. };
  45674. AxisProxy.prototype.getTargetSeriesModels = function () {
  45675. var seriesModels = [];
  45676. this.ecModel.eachSeries(function (seriesModel) {
  45677. if (isCoordSupported(seriesModel)) {
  45678. var axisMainType = getAxisMainType(this._dimName);
  45679. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  45680. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  45681. seriesModels.push(seriesModel);
  45682. }
  45683. }
  45684. }, this);
  45685. return seriesModels;
  45686. };
  45687. AxisProxy.prototype.getAxisModel = function () {
  45688. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  45689. };
  45690. AxisProxy.prototype.getMinMaxSpan = function () {
  45691. return clone(this._minMaxSpan);
  45692. };
  45693. /**
  45694. * Only calculate by given range and this._dataExtent, do not change anything.
  45695. */
  45696. AxisProxy.prototype.calculateDataWindow = function (opt) {
  45697. var dataExtent = this._dataExtent;
  45698. var axisModel = this.getAxisModel();
  45699. var scale = axisModel.axis.scale;
  45700. var rangePropMode = this._dataZoomModel.getRangePropMode();
  45701. var percentExtent = [0, 100];
  45702. var percentWindow = [];
  45703. var valueWindow = [];
  45704. var hasPropModeValue;
  45705. each$4(['start', 'end'], function (prop, idx) {
  45706. var boundPercent = opt[prop];
  45707. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  45708. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  45709. // but not min/max of axis, which will be calculated by data window then).
  45710. // The former one is suitable for cases that a dataZoom component controls multiple
  45711. // axes with different unit or extent, and the latter one is suitable for accurate
  45712. // zoom by pixel (e.g., in dataZoomSelect).
  45713. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  45714. // only when setOption or dispatchAction, otherwise it remains its original value.
  45715. // (Why not only record `percentProp` and always map to `valueProp`? Because
  45716. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  45717. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  45718. // data extent. All of values that are overflow the `dataExtent` will be calculated
  45719. // to percent '100%').
  45720. if (rangePropMode[idx] === 'percent') {
  45721. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  45722. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  45723. } else {
  45724. hasPropModeValue = true;
  45725. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  45726. // This calculation can not be inversed, because all of values that
  45727. // are overflow the `dataExtent` will be calculated to percent '100%'
  45728. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  45729. } // valueWindow[idx] = round(boundValue);
  45730. // percentWindow[idx] = round(boundPercent);
  45731. // fallback to extent start/end when parsed value or percent is invalid
  45732. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  45733. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  45734. });
  45735. asc$1(valueWindow);
  45736. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  45737. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  45738. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  45739. // where API is able to initialize/modify the window size even though `zoomLock`
  45740. // specified.
  45741. var spans = this._minMaxSpan;
  45742. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  45743. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  45744. var suffix = toValue ? 'Span' : 'ValueSpan';
  45745. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  45746. for (var i = 0; i < 2; i++) {
  45747. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  45748. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  45749. }
  45750. }
  45751. return {
  45752. valueWindow: valueWindow,
  45753. percentWindow: percentWindow
  45754. };
  45755. };
  45756. /**
  45757. * Notice: reset should not be called before series.restoreData() is called,
  45758. * so it is recommended to be called in "process stage" but not "model init
  45759. * stage".
  45760. */
  45761. AxisProxy.prototype.reset = function (dataZoomModel) {
  45762. if (dataZoomModel !== this._dataZoomModel) {
  45763. return;
  45764. }
  45765. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  45766. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  45767. this._updateMinMaxSpan();
  45768. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  45769. this._valueWindow = dataWindow.valueWindow;
  45770. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  45771. this._setAxisModel();
  45772. };
  45773. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  45774. if (dataZoomModel !== this._dataZoomModel) {
  45775. return;
  45776. }
  45777. var axisDim = this._dimName;
  45778. var seriesModels = this.getTargetSeriesModels();
  45779. var filterMode = dataZoomModel.get('filterMode');
  45780. var valueWindow = this._valueWindow;
  45781. if (filterMode === 'none') {
  45782. return;
  45783. } // FIXME
  45784. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  45785. // with NaN data, NaN will be filtered and stack will be wrong.
  45786. // So we need to force the mode to be set empty.
  45787. // In fect, it is not a big deal that do not support filterMode-'filter'
  45788. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  45789. // selection" some day, which might need "adapt to data extent on the
  45790. // otherAxis", which is disabled by filterMode-'empty'.
  45791. // But currently, stack has been fixed to based on value but not index,
  45792. // so this is not an issue any more.
  45793. // let otherAxisModel = this.getOtherAxisModel();
  45794. // if (dataZoomModel.get('$fromToolbox')
  45795. // && otherAxisModel
  45796. // && otherAxisModel.hasSeriesStacked
  45797. // ) {
  45798. // filterMode = 'empty';
  45799. // }
  45800. // TODO
  45801. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  45802. each$4(seriesModels, function (seriesModel) {
  45803. var seriesData = seriesModel.getData();
  45804. var dataDims = seriesData.mapDimensionsAll(axisDim);
  45805. if (!dataDims.length) {
  45806. return;
  45807. }
  45808. if (filterMode === 'weakFilter') {
  45809. var store_1 = seriesData.getStore();
  45810. var dataDimIndices_1 = map(dataDims, function (dim) {
  45811. return seriesData.getDimensionIndex(dim);
  45812. }, seriesData);
  45813. seriesData.filterSelf(function (dataIndex) {
  45814. var leftOut;
  45815. var rightOut;
  45816. var hasValue;
  45817. for (var i = 0; i < dataDims.length; i++) {
  45818. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  45819. var thisHasValue = !isNaN(value);
  45820. var thisLeftOut = value < valueWindow[0];
  45821. var thisRightOut = value > valueWindow[1];
  45822. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  45823. return true;
  45824. }
  45825. thisHasValue && (hasValue = true);
  45826. thisLeftOut && (leftOut = true);
  45827. thisRightOut && (rightOut = true);
  45828. } // If both left out and right out, do not filter.
  45829. return hasValue && leftOut && rightOut;
  45830. });
  45831. } else {
  45832. each$4(dataDims, function (dim) {
  45833. if (filterMode === 'empty') {
  45834. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  45835. return !isInWindow(value) ? NaN : value;
  45836. }));
  45837. } else {
  45838. var range = {};
  45839. range[dim] = valueWindow; // console.time('select');
  45840. seriesData.selectRange(range); // console.timeEnd('select');
  45841. }
  45842. });
  45843. }
  45844. each$4(dataDims, function (dim) {
  45845. seriesData.setApproximateExtent(valueWindow, dim);
  45846. });
  45847. });
  45848. function isInWindow(value) {
  45849. return value >= valueWindow[0] && value <= valueWindow[1];
  45850. }
  45851. };
  45852. AxisProxy.prototype._updateMinMaxSpan = function () {
  45853. var minMaxSpan = this._minMaxSpan = {};
  45854. var dataZoomModel = this._dataZoomModel;
  45855. var dataExtent = this._dataExtent;
  45856. each$4(['min', 'max'], function (minMax) {
  45857. var percentSpan = dataZoomModel.get(minMax + 'Span');
  45858. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  45859. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  45860. if (valueSpan != null) {
  45861. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  45862. } else if (percentSpan != null) {
  45863. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  45864. }
  45865. minMaxSpan[minMax + 'Span'] = percentSpan;
  45866. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  45867. }, this);
  45868. };
  45869. AxisProxy.prototype._setAxisModel = function () {
  45870. var axisModel = this.getAxisModel();
  45871. var percentWindow = this._percentWindow;
  45872. var valueWindow = this._valueWindow;
  45873. if (!percentWindow) {
  45874. return;
  45875. } // [0, 500]: arbitrary value, guess axis extent.
  45876. var precision = getPixelPrecision(valueWindow, [0, 500]);
  45877. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  45878. // by series data, which may be a little different from the extent calculated by
  45879. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  45880. // little when zooming. So it will not be fixed until some users require it strongly.
  45881. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  45882. if (percentWindow[0] !== 0) {
  45883. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  45884. }
  45885. if (percentWindow[1] !== 100) {
  45886. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  45887. }
  45888. rawExtentInfo.freeze();
  45889. };
  45890. return AxisProxy;
  45891. }();
  45892. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  45893. var dataExtent = [Infinity, -Infinity];
  45894. each$4(seriesModels, function (seriesModel) {
  45895. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  45896. }); // It is important to get "consistent" extent when more then one axes is
  45897. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  45898. // when zooming. But it is difficult to know what is "consistent", considering
  45899. // axes have different type or even different meanings (For example, two
  45900. // time axes are used to compare data of the same date in different years).
  45901. // So basically dataZoom just obtains extent by series.data (in category axis
  45902. // extent can be obtained from axis.data).
  45903. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  45904. // consistent.
  45905. var axisModel = axisProxy.getAxisModel();
  45906. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  45907. return [rawExtentResult.min, rawExtentResult.max];
  45908. }
  45909. var dataZoomProcessor = {
  45910. // `dataZoomProcessor` will only be performed in needed series. Consider if
  45911. // there is a line series and a pie series, it is better not to update the
  45912. // line series if only pie series is needed to be updated.
  45913. getTargetSeries: function (ecModel) {
  45914. function eachAxisModel(cb) {
  45915. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45916. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45917. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45918. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  45919. });
  45920. });
  45921. } // FIXME: it brings side-effect to `getTargetSeries`.
  45922. // Prepare axis proxies.
  45923. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  45924. // dispose all last axis proxy, in case that some axis are deleted.
  45925. axisModel.__dzAxisProxy = null;
  45926. });
  45927. var proxyList = [];
  45928. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  45929. // Different dataZooms may constrol the same axis. In that case,
  45930. // an axisProxy serves both of them.
  45931. if (!axisModel.__dzAxisProxy) {
  45932. // Use the first dataZoomModel as the main model of axisProxy.
  45933. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  45934. proxyList.push(axisModel.__dzAxisProxy);
  45935. }
  45936. });
  45937. var seriesModelMap = createHashMap();
  45938. each(proxyList, function (axisProxy) {
  45939. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  45940. seriesModelMap.set(seriesModel.uid, seriesModel);
  45941. });
  45942. });
  45943. return seriesModelMap;
  45944. },
  45945. // Consider appendData, where filter should be performed. Because data process is
  45946. // in block mode currently, it is not need to worry about that the overallProgress
  45947. // execute every frame.
  45948. overallReset: function (ecModel, api) {
  45949. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45950. // We calculate window and reset axis here but not in model
  45951. // init stage and not after action dispatch handler, because
  45952. // reset should be called after seriesData.restoreData.
  45953. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45954. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  45955. }); // Caution: data zoom filtering is order sensitive when using
  45956. // percent range and no min/max/scale set on axis.
  45957. // For example, we have dataZoom definition:
  45958. // [
  45959. // {xAxisIndex: 0, start: 30, end: 70},
  45960. // {yAxisIndex: 0, start: 20, end: 80}
  45961. // ]
  45962. // In this case, [20, 80] of y-dataZoom should be based on data
  45963. // that have filtered by x-dataZoom using range of [30, 70],
  45964. // but should not be based on full raw data. Thus sliding
  45965. // x-dataZoom will change both ranges of xAxis and yAxis,
  45966. // while sliding y-dataZoom will only change the range of yAxis.
  45967. // So we should filter x-axis after reset x-axis immediately,
  45968. // and then reset y-axis and filter y-axis.
  45969. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45970. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  45971. });
  45972. });
  45973. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45974. // Fullfill all of the range props so that user
  45975. // is able to get them from chart.getOption().
  45976. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  45977. if (axisProxy) {
  45978. var percentRange = axisProxy.getDataPercentWindow();
  45979. var valueRange = axisProxy.getDataValueWindow();
  45980. dataZoomModel.setCalculatedRange({
  45981. start: percentRange[0],
  45982. end: percentRange[1],
  45983. startValue: valueRange[0],
  45984. endValue: valueRange[1]
  45985. });
  45986. }
  45987. });
  45988. }
  45989. };
  45990. function installDataZoomAction(registers) {
  45991. registers.registerAction('dataZoom', function (payload, ecModel) {
  45992. var effectedModels = findEffectedDataZooms(ecModel, payload);
  45993. each(effectedModels, function (dataZoomModel) {
  45994. dataZoomModel.setRawRange({
  45995. start: payload.start,
  45996. end: payload.end,
  45997. startValue: payload.startValue,
  45998. endValue: payload.endValue
  45999. });
  46000. });
  46001. });
  46002. }
  46003. var installed = false;
  46004. function installCommon(registers) {
  46005. if (installed) {
  46006. return;
  46007. }
  46008. installed = true;
  46009. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  46010. installDataZoomAction(registers);
  46011. registers.registerSubTypeDefaulter('dataZoom', function () {
  46012. // Default 'slider' when no type specified.
  46013. return 'slider';
  46014. });
  46015. }
  46016. function install$a(registers) {
  46017. registers.registerComponentModel(SelectDataZoomModel);
  46018. registers.registerComponentView(SelectDataZoomView);
  46019. installCommon(registers);
  46020. }
  46021. /*
  46022. * Licensed to the Apache Software Foundation (ASF) under one
  46023. * or more contributor license agreements. See the NOTICE file
  46024. * distributed with this work for additional information
  46025. * regarding copyright ownership. The ASF licenses this file
  46026. * to you under the Apache License, Version 2.0 (the
  46027. * "License"); you may not use this file except in compliance
  46028. * with the License. You may obtain a copy of the License at
  46029. *
  46030. * http://www.apache.org/licenses/LICENSE-2.0
  46031. *
  46032. * Unless required by applicable law or agreed to in writing,
  46033. * software distributed under the License is distributed on an
  46034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46035. * KIND, either express or implied. See the License for the
  46036. * specific language governing permissions and limitations
  46037. * under the License.
  46038. */
  46039. /**
  46040. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46041. */
  46042. var ToolboxFeature =
  46043. /** @class */
  46044. function () {
  46045. function ToolboxFeature() {}
  46046. return ToolboxFeature;
  46047. }();
  46048. var features = {};
  46049. function registerFeature(name, ctor) {
  46050. features[name] = ctor;
  46051. }
  46052. function getFeature(name) {
  46053. return features[name];
  46054. }
  46055. var ToolboxModel =
  46056. /** @class */
  46057. function (_super) {
  46058. __extends(ToolboxModel, _super);
  46059. function ToolboxModel() {
  46060. var _this = _super !== null && _super.apply(this, arguments) || this;
  46061. _this.type = ToolboxModel.type;
  46062. return _this;
  46063. }
  46064. ToolboxModel.prototype.optionUpdated = function () {
  46065. _super.prototype.optionUpdated.apply(this, arguments);
  46066. var ecModel = this.ecModel;
  46067. each(this.option.feature, function (featureOpt, featureName) {
  46068. var Feature = getFeature(featureName);
  46069. if (Feature) {
  46070. if (Feature.getDefaultOption) {
  46071. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  46072. }
  46073. merge(featureOpt, Feature.defaultOption);
  46074. }
  46075. });
  46076. };
  46077. ToolboxModel.type = 'toolbox';
  46078. ToolboxModel.layoutMode = {
  46079. type: 'box',
  46080. ignoreSize: true
  46081. };
  46082. ToolboxModel.defaultOption = {
  46083. show: true,
  46084. z: 6,
  46085. // zlevel: 0,
  46086. orient: 'horizontal',
  46087. left: 'right',
  46088. top: 'top',
  46089. // right
  46090. // bottom
  46091. backgroundColor: 'transparent',
  46092. borderColor: '#ccc',
  46093. borderRadius: 0,
  46094. borderWidth: 0,
  46095. padding: 5,
  46096. itemSize: 15,
  46097. itemGap: 8,
  46098. showTitle: true,
  46099. iconStyle: {
  46100. borderColor: '#666',
  46101. color: 'none'
  46102. },
  46103. emphasis: {
  46104. iconStyle: {
  46105. borderColor: '#3E98C5'
  46106. }
  46107. },
  46108. // textStyle: {},
  46109. // feature
  46110. tooltip: {
  46111. show: false,
  46112. position: 'bottom'
  46113. }
  46114. };
  46115. return ToolboxModel;
  46116. }(ComponentModel);
  46117. /**
  46118. * Layout list like component.
  46119. * It will box layout each items in group of component and then position the whole group in the viewport
  46120. * @param {module:zrender/group/Group} group
  46121. * @param {module:echarts/model/Component} componentModel
  46122. * @param {module:echarts/ExtensionAPI}
  46123. */
  46124. function layout$2(group, componentModel, api) {
  46125. var boxLayoutParams = componentModel.getBoxLayoutParams();
  46126. var padding = componentModel.get('padding');
  46127. var viewportSize = {
  46128. width: api.getWidth(),
  46129. height: api.getHeight()
  46130. };
  46131. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  46132. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  46133. positionElement(group, boxLayoutParams, viewportSize, padding);
  46134. }
  46135. function makeBackground(rect, componentModel) {
  46136. var padding = normalizeCssArray$1(componentModel.get('padding'));
  46137. var style = componentModel.getItemStyle(['color', 'opacity']);
  46138. style.fill = componentModel.get('backgroundColor');
  46139. rect = new Rect({
  46140. shape: {
  46141. x: rect.x - padding[3],
  46142. y: rect.y - padding[0],
  46143. width: rect.width + padding[1] + padding[3],
  46144. height: rect.height + padding[0] + padding[2],
  46145. r: componentModel.get('borderRadius')
  46146. },
  46147. style: style,
  46148. silent: true,
  46149. z2: -1
  46150. }); // FIXME
  46151. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  46152. // and background rect when setting like `left: 0`, `top: 0`.
  46153. // graphic.subPixelOptimizeRect(rect);
  46154. return rect;
  46155. }
  46156. var ToolboxView =
  46157. /** @class */
  46158. function (_super) {
  46159. __extends(ToolboxView, _super);
  46160. function ToolboxView() {
  46161. return _super !== null && _super.apply(this, arguments) || this;
  46162. }
  46163. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  46164. var group = this.group;
  46165. group.removeAll();
  46166. if (!toolboxModel.get('show')) {
  46167. return;
  46168. }
  46169. var itemSize = +toolboxModel.get('itemSize');
  46170. var isVertical = toolboxModel.get('orient') === 'vertical';
  46171. var featureOpts = toolboxModel.get('feature') || {};
  46172. var features = this._features || (this._features = {});
  46173. var featureNames = [];
  46174. each(featureOpts, function (opt, name) {
  46175. featureNames.push(name);
  46176. });
  46177. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  46178. this._featureNames = featureNames;
  46179. function processFeature(newIndex, oldIndex) {
  46180. var featureName = featureNames[newIndex];
  46181. var oldName = featureNames[oldIndex];
  46182. var featureOpt = featureOpts[featureName];
  46183. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  46184. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  46185. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  46186. featureOpt.title = payload.newTitle;
  46187. }
  46188. if (featureName && !oldName) {
  46189. // Create
  46190. if (isUserFeatureName(featureName)) {
  46191. feature = {
  46192. onclick: featureModel.option.onclick,
  46193. featureName: featureName
  46194. };
  46195. } else {
  46196. var Feature = getFeature(featureName);
  46197. if (!Feature) {
  46198. return;
  46199. }
  46200. feature = new Feature();
  46201. }
  46202. features[featureName] = feature;
  46203. } else {
  46204. feature = features[oldName]; // If feature does not exist.
  46205. if (!feature) {
  46206. return;
  46207. }
  46208. }
  46209. feature.uid = getUID('toolbox-feature');
  46210. feature.model = featureModel;
  46211. feature.ecModel = ecModel;
  46212. feature.api = api;
  46213. var isToolboxFeature = feature instanceof ToolboxFeature;
  46214. if (!featureName && oldName) {
  46215. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  46216. return;
  46217. }
  46218. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  46219. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  46220. return;
  46221. }
  46222. createIconPaths(featureModel, feature, featureName);
  46223. featureModel.setIconStatus = function (iconName, status) {
  46224. var option = this.option;
  46225. var iconPaths = this.iconPaths;
  46226. option.iconStatus = option.iconStatus || {};
  46227. option.iconStatus[iconName] = status;
  46228. if (iconPaths[iconName]) {
  46229. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  46230. }
  46231. };
  46232. if (feature instanceof ToolboxFeature) {
  46233. if (feature.render) {
  46234. feature.render(featureModel, ecModel, api, payload);
  46235. }
  46236. }
  46237. }
  46238. function createIconPaths(featureModel, feature, featureName) {
  46239. var iconStyleModel = featureModel.getModel('iconStyle');
  46240. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has multiple icons, they are organized as
  46241. // {
  46242. // icon: {
  46243. // foo: '',
  46244. // bar: ''
  46245. // },
  46246. // title: {
  46247. // foo: '',
  46248. // bar: ''
  46249. // }
  46250. // }
  46251. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  46252. var titles = featureModel.get('title') || {};
  46253. var iconsMap;
  46254. var titlesMap;
  46255. if (isString(icons)) {
  46256. iconsMap = {};
  46257. iconsMap[featureName] = icons;
  46258. } else {
  46259. iconsMap = icons;
  46260. }
  46261. if (isString(titles)) {
  46262. titlesMap = {};
  46263. titlesMap[featureName] = titles;
  46264. } else {
  46265. titlesMap = titles;
  46266. }
  46267. var iconPaths = featureModel.iconPaths = {};
  46268. each(iconsMap, function (iconStr, iconName) {
  46269. var path = createIcon(iconStr, {}, {
  46270. x: -itemSize / 2,
  46271. y: -itemSize / 2,
  46272. width: itemSize,
  46273. height: itemSize
  46274. }); // TODO handling image
  46275. path.setStyle(iconStyleModel.getItemStyle());
  46276. var pathEmphasisState = path.ensureState('emphasis');
  46277. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  46278. var textContent = new ZRText({
  46279. style: {
  46280. text: titlesMap[iconName],
  46281. align: iconStyleEmphasisModel.get('textAlign'),
  46282. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  46283. padding: iconStyleEmphasisModel.get('textPadding'),
  46284. fill: null
  46285. },
  46286. ignore: true
  46287. });
  46288. path.setTextContent(textContent);
  46289. setTooltipConfig({
  46290. el: path,
  46291. componentModel: toolboxModel,
  46292. itemName: iconName,
  46293. formatterParamsExtra: {
  46294. title: titlesMap[iconName]
  46295. }
  46296. });
  46297. path.__title = titlesMap[iconName];
  46298. path.on('mouseover', function () {
  46299. // Should not reuse above hoverStyle, which might be modified.
  46300. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  46301. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  46302. textContent.setStyle({
  46303. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  46304. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  46305. });
  46306. path.setTextConfig({
  46307. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  46308. });
  46309. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  46310. // There are flags managed by the echarts.
  46311. api.enterEmphasis(this);
  46312. }).on('mouseout', function () {
  46313. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  46314. api.leaveEmphasis(this);
  46315. }
  46316. textContent.hide();
  46317. });
  46318. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  46319. group.add(path);
  46320. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  46321. iconPaths[iconName] = path;
  46322. });
  46323. }
  46324. layout$2(group, toolboxModel, api); // Render background after group is layout
  46325. // FIXME
  46326. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  46327. isVertical || group.eachChild(function (icon) {
  46328. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  46329. // TODO simplify code?
  46330. var emphasisState = icon.ensureState('emphasis');
  46331. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  46332. var textContent = icon.getTextContent();
  46333. var emphasisTextState = textContent && textContent.ensureState('emphasis'); // May be background element
  46334. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  46335. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  46336. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  46337. var offsetX = icon.x + group.x;
  46338. var offsetY = icon.y + group.y + itemSize;
  46339. var needPutOnTop = false;
  46340. if (offsetY + rect.height > api.getHeight()) {
  46341. emphasisTextConfig.position = 'top';
  46342. needPutOnTop = true;
  46343. }
  46344. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  46345. if (offsetX + rect.width / 2 > api.getWidth()) {
  46346. emphasisTextConfig.position = ['100%', topOffset];
  46347. emphasisTextStyle.align = 'right';
  46348. } else if (offsetX - rect.width / 2 < 0) {
  46349. emphasisTextConfig.position = [0, topOffset];
  46350. emphasisTextStyle.align = 'left';
  46351. }
  46352. }
  46353. });
  46354. };
  46355. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  46356. each(this._features, function (feature) {
  46357. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  46358. });
  46359. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  46360. // zrUtil.each(this._features, function (feature) {
  46361. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  46362. // });
  46363. // },
  46364. ToolboxView.prototype.remove = function (ecModel, api) {
  46365. each(this._features, function (feature) {
  46366. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  46367. });
  46368. this.group.removeAll();
  46369. };
  46370. ToolboxView.prototype.dispose = function (ecModel, api) {
  46371. each(this._features, function (feature) {
  46372. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  46373. });
  46374. };
  46375. ToolboxView.type = 'toolbox';
  46376. return ToolboxView;
  46377. }(ComponentView);
  46378. function isUserFeatureName(featureName) {
  46379. return featureName.indexOf('my') === 0;
  46380. }
  46381. /* global window, document */
  46382. var SaveAsImage =
  46383. /** @class */
  46384. function (_super) {
  46385. __extends(SaveAsImage, _super);
  46386. function SaveAsImage() {
  46387. return _super !== null && _super.apply(this, arguments) || this;
  46388. }
  46389. SaveAsImage.prototype.onclick = function (ecModel, api) {
  46390. var model = this.model;
  46391. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  46392. var isSvg = api.getZr().painter.getType() === 'svg';
  46393. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  46394. var url = api.getConnectedDataURL({
  46395. type: type,
  46396. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  46397. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  46398. excludeComponents: model.get('excludeComponents'),
  46399. pixelRatio: model.get('pixelRatio')
  46400. });
  46401. var browser = env.browser; // Chrome, Firefox, New Edge
  46402. if (isFunction(MouseEvent) && (browser.newEdge || !browser.ie && !browser.edge)) {
  46403. var $a = document.createElement('a');
  46404. $a.download = title + '.' + type;
  46405. $a.target = '_blank';
  46406. $a.href = url;
  46407. var evt = new MouseEvent('click', {
  46408. // some micro front-end framework, window maybe is a Proxy
  46409. view: document.defaultView,
  46410. bubbles: true,
  46411. cancelable: false
  46412. });
  46413. $a.dispatchEvent(evt);
  46414. } // IE or old Edge
  46415. else {
  46416. // @ts-ignore
  46417. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  46418. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  46419. var base64Encoded = parts[0].indexOf('base64') > -1;
  46420. var bstr = isSvg // should decode the svg data uri first
  46421. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  46422. // otherwise, like `svg` data uri exported by zrender,
  46423. // there will be an error, for it's not encoded with base64.
  46424. // (just a url-encoded string through `encodeURIComponent`)
  46425. base64Encoded && (bstr = window.atob(bstr));
  46426. var filename = title + '.' + type; // @ts-ignore
  46427. if (window.navigator.msSaveOrOpenBlob) {
  46428. var n = bstr.length;
  46429. var u8arr = new Uint8Array(n);
  46430. while (n--) {
  46431. u8arr[n] = bstr.charCodeAt(n);
  46432. }
  46433. var blob = new Blob([u8arr]); // @ts-ignore
  46434. window.navigator.msSaveOrOpenBlob(blob, filename);
  46435. } else {
  46436. var frame = document.createElement('iframe');
  46437. document.body.appendChild(frame);
  46438. var cw = frame.contentWindow;
  46439. var doc = cw.document;
  46440. doc.open('image/svg+xml', 'replace');
  46441. doc.write(bstr);
  46442. doc.close();
  46443. cw.focus();
  46444. doc.execCommand('SaveAs', true, filename);
  46445. document.body.removeChild(frame);
  46446. }
  46447. } else {
  46448. var lang = model.get('lang');
  46449. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  46450. var tab = window.open();
  46451. tab.document.write(html);
  46452. tab.document.title = title;
  46453. }
  46454. }
  46455. };
  46456. SaveAsImage.getDefaultOption = function (ecModel) {
  46457. var defaultOption = {
  46458. show: true,
  46459. 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',
  46460. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  46461. type: 'png',
  46462. // Default use option.backgroundColor
  46463. // backgroundColor: '#fff',
  46464. connectedBackgroundColor: '#fff',
  46465. name: '',
  46466. excludeComponents: ['toolbox'],
  46467. // use current pixel ratio of device by default
  46468. // pixelRatio: 1,
  46469. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  46470. };
  46471. return defaultOption;
  46472. };
  46473. return SaveAsImage;
  46474. }(ToolboxFeature);
  46475. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  46476. var radioTypes = [['line', 'bar'], ['stack']];
  46477. var MagicType =
  46478. /** @class */
  46479. function (_super) {
  46480. __extends(MagicType, _super);
  46481. function MagicType() {
  46482. return _super !== null && _super.apply(this, arguments) || this;
  46483. }
  46484. MagicType.prototype.getIcons = function () {
  46485. var model = this.model;
  46486. var availableIcons = model.get('icon');
  46487. var icons = {};
  46488. each(model.get('type'), function (type) {
  46489. if (availableIcons[type]) {
  46490. icons[type] = availableIcons[type];
  46491. }
  46492. });
  46493. return icons;
  46494. };
  46495. MagicType.getDefaultOption = function (ecModel) {
  46496. var defaultOption = {
  46497. show: true,
  46498. type: [],
  46499. // Icon group
  46500. icon: {
  46501. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  46502. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  46503. // eslint-disable-next-line
  46504. 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
  46505. },
  46506. // `line`, `bar`, `stack`, `tiled`
  46507. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  46508. option: {},
  46509. seriesIndex: {}
  46510. };
  46511. return defaultOption;
  46512. };
  46513. MagicType.prototype.onclick = function (ecModel, api, type) {
  46514. var model = this.model;
  46515. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  46516. if (!seriesOptGenreator[type]) {
  46517. return;
  46518. }
  46519. var newOption = {
  46520. series: []
  46521. };
  46522. var generateNewSeriesTypes = function (seriesModel) {
  46523. var seriesType = seriesModel.subType;
  46524. var seriesId = seriesModel.id;
  46525. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  46526. if (newSeriesOpt) {
  46527. // PENDING If merge original option?
  46528. defaults(newSeriesOpt, seriesModel.option);
  46529. newOption.series.push(newSeriesOpt);
  46530. } // Modify boundaryGap
  46531. var coordSys = seriesModel.coordinateSystem;
  46532. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  46533. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  46534. if (categoryAxis) {
  46535. var axisDim = categoryAxis.dim;
  46536. var axisType = axisDim + 'Axis';
  46537. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  46538. var axisIndex = axisModel.componentIndex;
  46539. newOption[axisType] = newOption[axisType] || [];
  46540. for (var i = 0; i <= axisIndex; i++) {
  46541. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  46542. }
  46543. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  46544. }
  46545. }
  46546. };
  46547. each(radioTypes, function (radio) {
  46548. if (indexOf(radio, type) >= 0) {
  46549. each(radio, function (item) {
  46550. model.setIconStatus(item, 'normal');
  46551. });
  46552. }
  46553. });
  46554. model.setIconStatus(type, 'emphasis');
  46555. ecModel.eachComponent({
  46556. mainType: 'series',
  46557. query: seriesIndex == null ? null : {
  46558. seriesIndex: seriesIndex
  46559. }
  46560. }, generateNewSeriesTypes);
  46561. var newTitle;
  46562. var currentType = type; // Change title of stack
  46563. if (type === 'stack') {
  46564. // use titles in model instead of ecModel
  46565. // as stack and tiled appears in pair, just flip them
  46566. // no need of checking stack state
  46567. newTitle = merge({
  46568. stack: model.option.title.tiled,
  46569. tiled: model.option.title.stack
  46570. }, model.option.title);
  46571. if (model.get(['iconStatus', type]) !== 'emphasis') {
  46572. currentType = 'tiled';
  46573. }
  46574. }
  46575. api.dispatchAction({
  46576. type: 'changeMagicType',
  46577. currentType: currentType,
  46578. newOption: newOption,
  46579. newTitle: newTitle,
  46580. featureName: 'magicType'
  46581. });
  46582. };
  46583. return MagicType;
  46584. }(ToolboxFeature);
  46585. var seriesOptGenreator = {
  46586. 'line': function (seriesType, seriesId, seriesModel, model) {
  46587. if (seriesType === 'bar') {
  46588. return merge({
  46589. id: seriesId,
  46590. type: 'line',
  46591. // Preserve data related option
  46592. data: seriesModel.get('data'),
  46593. stack: seriesModel.get('stack'),
  46594. markPoint: seriesModel.get('markPoint'),
  46595. markLine: seriesModel.get('markLine')
  46596. }, model.get(['option', 'line']) || {}, true);
  46597. }
  46598. },
  46599. 'bar': function (seriesType, seriesId, seriesModel, model) {
  46600. if (seriesType === 'line') {
  46601. return merge({
  46602. id: seriesId,
  46603. type: 'bar',
  46604. // Preserve data related option
  46605. data: seriesModel.get('data'),
  46606. stack: seriesModel.get('stack'),
  46607. markPoint: seriesModel.get('markPoint'),
  46608. markLine: seriesModel.get('markLine')
  46609. }, model.get(['option', 'bar']) || {}, true);
  46610. }
  46611. },
  46612. 'stack': function (seriesType, seriesId, seriesModel, model) {
  46613. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  46614. if (seriesType === 'line' || seriesType === 'bar') {
  46615. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  46616. return merge({
  46617. id: seriesId,
  46618. stack: isStack ? '' : INNER_STACK_KEYWORD
  46619. }, model.get(['option', 'stack']) || {}, true);
  46620. }
  46621. }
  46622. }; // TODO: SELF REGISTERED.
  46623. registerAction({
  46624. type: 'changeMagicType',
  46625. event: 'magicTypeChanged',
  46626. update: 'prepareAndUpdate'
  46627. }, function (payload, ecModel) {
  46628. ecModel.mergeOption(payload.newOption);
  46629. });
  46630. /* global document */
  46631. var BLOCK_SPLITER = new Array(60).join('-');
  46632. var ITEM_SPLITER = '\t';
  46633. /**
  46634. * Group series into two types
  46635. * 1. on category axis, like line, bar
  46636. * 2. others, like scatter, pie
  46637. */
  46638. function groupSeries(ecModel) {
  46639. var seriesGroupByCategoryAxis = {};
  46640. var otherSeries = [];
  46641. var meta = [];
  46642. ecModel.eachRawSeries(function (seriesModel) {
  46643. var coordSys = seriesModel.coordinateSystem;
  46644. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  46645. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  46646. var baseAxis = coordSys.getBaseAxis();
  46647. if (baseAxis.type === 'category') {
  46648. var key = baseAxis.dim + '_' + baseAxis.index;
  46649. if (!seriesGroupByCategoryAxis[key]) {
  46650. seriesGroupByCategoryAxis[key] = {
  46651. categoryAxis: baseAxis,
  46652. valueAxis: coordSys.getOtherAxis(baseAxis),
  46653. series: []
  46654. };
  46655. meta.push({
  46656. axisDim: baseAxis.dim,
  46657. axisIndex: baseAxis.index
  46658. });
  46659. }
  46660. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  46661. } else {
  46662. otherSeries.push(seriesModel);
  46663. }
  46664. } else {
  46665. otherSeries.push(seriesModel);
  46666. }
  46667. });
  46668. return {
  46669. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  46670. other: otherSeries,
  46671. meta: meta
  46672. };
  46673. }
  46674. /**
  46675. * Assemble content of series on cateogory axis
  46676. * @inner
  46677. */
  46678. function assembleSeriesWithCategoryAxis(groups) {
  46679. var tables = [];
  46680. each(groups, function (group, key) {
  46681. var categoryAxis = group.categoryAxis;
  46682. var valueAxis = group.valueAxis;
  46683. var valueAxisDim = valueAxis.dim;
  46684. var headers = [' '].concat(map(group.series, function (series) {
  46685. return series.name;
  46686. })); // @ts-ignore TODO Polar
  46687. var columns = [categoryAxis.model.getCategories()];
  46688. each(group.series, function (series) {
  46689. var rawData = series.getRawData();
  46690. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  46691. return val;
  46692. }));
  46693. }); // Assemble table content
  46694. var lines = [headers.join(ITEM_SPLITER)];
  46695. for (var i = 0; i < columns[0].length; i++) {
  46696. var items = [];
  46697. for (var j = 0; j < columns.length; j++) {
  46698. items.push(columns[j][i]);
  46699. }
  46700. lines.push(items.join(ITEM_SPLITER));
  46701. }
  46702. tables.push(lines.join('\n'));
  46703. });
  46704. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  46705. }
  46706. /**
  46707. * Assemble content of other series
  46708. */
  46709. function assembleOtherSeries(series) {
  46710. return map(series, function (series) {
  46711. var data = series.getRawData();
  46712. var lines = [series.name];
  46713. var vals = [];
  46714. data.each(data.dimensions, function () {
  46715. var argLen = arguments.length;
  46716. var dataIndex = arguments[argLen - 1];
  46717. var name = data.getName(dataIndex);
  46718. for (var i = 0; i < argLen - 1; i++) {
  46719. vals[i] = arguments[i];
  46720. }
  46721. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  46722. });
  46723. return lines.join('\n');
  46724. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  46725. }
  46726. function getContentFromModel(ecModel) {
  46727. var result = groupSeries(ecModel);
  46728. return {
  46729. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  46730. return !!str.replace(/[\n\t\s]/g, '');
  46731. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  46732. meta: result.meta
  46733. };
  46734. }
  46735. function trim$1(str) {
  46736. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  46737. }
  46738. /**
  46739. * If a block is tsv format
  46740. */
  46741. function isTSVFormat(block) {
  46742. // Simple method to find out if a block is tsv format
  46743. var firstLine = block.slice(0, block.indexOf('\n'));
  46744. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  46745. return true;
  46746. }
  46747. }
  46748. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  46749. /**
  46750. * @param {string} tsv
  46751. * @return {Object}
  46752. */
  46753. function parseTSVContents(tsv) {
  46754. var tsvLines = tsv.split(/\n+/g);
  46755. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  46756. var categories = [];
  46757. var series = map(headers, function (header) {
  46758. return {
  46759. name: header,
  46760. data: []
  46761. };
  46762. });
  46763. for (var i = 0; i < tsvLines.length; i++) {
  46764. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  46765. categories.push(items.shift());
  46766. for (var j = 0; j < items.length; j++) {
  46767. series[j] && (series[j].data[i] = items[j]);
  46768. }
  46769. }
  46770. return {
  46771. series: series,
  46772. categories: categories
  46773. };
  46774. }
  46775. function parseListContents(str) {
  46776. var lines = str.split(/\n+/g);
  46777. var seriesName = trim$1(lines.shift());
  46778. var data = [];
  46779. for (var i = 0; i < lines.length; i++) {
  46780. // if line is empty, ignore it.
  46781. // there is a case that a user forgot to delete `\n`.
  46782. var line = trim$1(lines[i]);
  46783. if (!line) {
  46784. continue;
  46785. }
  46786. var items = line.split(itemSplitRegex);
  46787. var name_1 = '';
  46788. var value = void 0;
  46789. var hasName = false;
  46790. if (isNaN(items[0])) {
  46791. // First item is name
  46792. hasName = true;
  46793. name_1 = items[0];
  46794. items = items.slice(1);
  46795. data[i] = {
  46796. name: name_1,
  46797. value: []
  46798. };
  46799. value = data[i].value;
  46800. } else {
  46801. value = data[i] = [];
  46802. }
  46803. for (var j = 0; j < items.length; j++) {
  46804. value.push(+items[j]);
  46805. }
  46806. if (value.length === 1) {
  46807. hasName ? data[i].value = value[0] : data[i] = value[0];
  46808. }
  46809. }
  46810. return {
  46811. name: seriesName,
  46812. data: data
  46813. };
  46814. }
  46815. function parseContents(str, blockMetaList) {
  46816. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  46817. var newOption = {
  46818. series: []
  46819. };
  46820. each(blocks, function (block, idx) {
  46821. if (isTSVFormat(block)) {
  46822. var result = parseTSVContents(block);
  46823. var blockMeta = blockMetaList[idx];
  46824. var axisKey = blockMeta.axisDim + 'Axis';
  46825. if (blockMeta) {
  46826. newOption[axisKey] = newOption[axisKey] || [];
  46827. newOption[axisKey][blockMeta.axisIndex] = {
  46828. data: result.categories
  46829. };
  46830. newOption.series = newOption.series.concat(result.series);
  46831. }
  46832. } else {
  46833. var result = parseListContents(block);
  46834. newOption.series.push(result);
  46835. }
  46836. });
  46837. return newOption;
  46838. }
  46839. var DataView =
  46840. /** @class */
  46841. function (_super) {
  46842. __extends(DataView, _super);
  46843. function DataView() {
  46844. return _super !== null && _super.apply(this, arguments) || this;
  46845. }
  46846. DataView.prototype.onclick = function (ecModel, api) {
  46847. // FIXME: better way?
  46848. setTimeout(function () {
  46849. api.dispatchAction({
  46850. type: 'hideTip'
  46851. });
  46852. });
  46853. var container = api.getDom();
  46854. var model = this.model;
  46855. if (this._dom) {
  46856. container.removeChild(this._dom);
  46857. }
  46858. var root = document.createElement('div'); // use padding to avoid 5px whitespace
  46859. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  46860. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  46861. var header = document.createElement('h4');
  46862. var lang = model.get('lang') || [];
  46863. header.innerHTML = lang[0] || model.get('title');
  46864. header.style.cssText = 'margin:10px 20px';
  46865. header.style.color = model.get('textColor');
  46866. var viewMain = document.createElement('div');
  46867. var textarea = document.createElement('textarea');
  46868. viewMain.style.cssText = 'overflow:auto';
  46869. var optionToContent = model.get('optionToContent');
  46870. var contentToOption = model.get('contentToOption');
  46871. var result = getContentFromModel(ecModel);
  46872. if (isFunction(optionToContent)) {
  46873. var htmlOrDom = optionToContent(api.getOption());
  46874. if (isString(htmlOrDom)) {
  46875. viewMain.innerHTML = htmlOrDom;
  46876. } else if (isDom(htmlOrDom)) {
  46877. viewMain.appendChild(htmlOrDom);
  46878. }
  46879. } else {
  46880. // Use default textarea
  46881. textarea.readOnly = model.get('readOnly');
  46882. var style = textarea.style; // eslint-disable-next-line max-len
  46883. 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';
  46884. style.color = model.get('textColor');
  46885. style.borderColor = model.get('textareaBorderColor');
  46886. style.backgroundColor = model.get('textareaColor');
  46887. textarea.value = result.value;
  46888. viewMain.appendChild(textarea);
  46889. }
  46890. var blockMetaList = result.meta;
  46891. var buttonContainer = document.createElement('div');
  46892. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0'; // eslint-disable-next-line max-len
  46893. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  46894. var closeButton = document.createElement('div');
  46895. var refreshButton = document.createElement('div');
  46896. buttonStyle += ';background-color:' + model.get('buttonColor');
  46897. buttonStyle += ';color:' + model.get('buttonTextColor');
  46898. var self = this;
  46899. function close() {
  46900. container.removeChild(root);
  46901. self._dom = null;
  46902. }
  46903. addEventListener(closeButton, 'click', close);
  46904. addEventListener(refreshButton, 'click', function () {
  46905. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  46906. if ("development" !== 'production') {
  46907. // eslint-disable-next-line
  46908. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  46909. }
  46910. close();
  46911. return;
  46912. }
  46913. var newOption;
  46914. try {
  46915. if (isFunction(contentToOption)) {
  46916. newOption = contentToOption(viewMain, api.getOption());
  46917. } else {
  46918. newOption = parseContents(textarea.value, blockMetaList);
  46919. }
  46920. } catch (e) {
  46921. close();
  46922. throw new Error('Data view format error ' + e);
  46923. }
  46924. if (newOption) {
  46925. api.dispatchAction({
  46926. type: 'changeDataView',
  46927. newOption: newOption
  46928. });
  46929. }
  46930. close();
  46931. });
  46932. closeButton.innerHTML = lang[1];
  46933. refreshButton.innerHTML = lang[2];
  46934. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  46935. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  46936. buttonContainer.appendChild(closeButton);
  46937. root.appendChild(header);
  46938. root.appendChild(viewMain);
  46939. root.appendChild(buttonContainer);
  46940. viewMain.style.height = container.clientHeight - 80 + 'px';
  46941. container.appendChild(root);
  46942. this._dom = root;
  46943. };
  46944. DataView.prototype.remove = function (ecModel, api) {
  46945. this._dom && api.getDom().removeChild(this._dom);
  46946. };
  46947. DataView.prototype.dispose = function (ecModel, api) {
  46948. this.remove(ecModel, api);
  46949. };
  46950. DataView.getDefaultOption = function (ecModel) {
  46951. var defaultOption = {
  46952. show: true,
  46953. readOnly: false,
  46954. optionToContent: null,
  46955. contentToOption: null,
  46956. // eslint-disable-next-line
  46957. 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',
  46958. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  46959. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  46960. backgroundColor: '#fff',
  46961. textColor: '#000',
  46962. textareaColor: '#fff',
  46963. textareaBorderColor: '#333',
  46964. buttonColor: '#c23531',
  46965. buttonTextColor: '#fff'
  46966. };
  46967. return defaultOption;
  46968. };
  46969. return DataView;
  46970. }(ToolboxFeature);
  46971. /**
  46972. * @inner
  46973. */
  46974. function tryMergeDataOption(newData, originalData) {
  46975. return map(newData, function (newVal, idx) {
  46976. var original = originalData && originalData[idx];
  46977. if (isObject(original) && !isArray(original)) {
  46978. var newValIsObject = isObject(newVal) && !isArray(newVal);
  46979. if (!newValIsObject) {
  46980. newVal = {
  46981. value: newVal
  46982. };
  46983. } // original data has name but new data has no name
  46984. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  46985. newVal = defaults(newVal, original);
  46986. shouldDeleteName && delete newVal.name;
  46987. return newVal;
  46988. } else {
  46989. return newVal;
  46990. }
  46991. });
  46992. } // TODO: SELF REGISTERED.
  46993. registerAction({
  46994. type: 'changeDataView',
  46995. event: 'dataViewChanged',
  46996. update: 'prepareAndUpdate'
  46997. }, function (payload, ecModel) {
  46998. var newSeriesOptList = [];
  46999. each(payload.newOption.series, function (seriesOpt) {
  47000. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  47001. if (!seriesModel) {
  47002. // New created series
  47003. // Geuss the series type
  47004. newSeriesOptList.push(extend({
  47005. // Default is scatter
  47006. type: 'scatter'
  47007. }, seriesOpt));
  47008. } else {
  47009. var originalData = seriesModel.get('data');
  47010. newSeriesOptList.push({
  47011. name: seriesOpt.name,
  47012. data: tryMergeDataOption(seriesOpt.data, originalData)
  47013. });
  47014. }
  47015. });
  47016. ecModel.mergeOption(defaults({
  47017. series: newSeriesOptList
  47018. }, payload.newOption));
  47019. });
  47020. var each$5 = each;
  47021. var inner$b = makeInner();
  47022. /**
  47023. * @param ecModel
  47024. * @param newSnapshot key is dataZoomId
  47025. */
  47026. function push(ecModel, newSnapshot) {
  47027. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  47028. // complete an range with current range.
  47029. each$5(newSnapshot, function (batchItem, dataZoomId) {
  47030. var i = storedSnapshots.length - 1;
  47031. for (; i >= 0; i--) {
  47032. var snapshot = storedSnapshots[i];
  47033. if (snapshot[dataZoomId]) {
  47034. break;
  47035. }
  47036. }
  47037. if (i < 0) {
  47038. // No origin range set, create one by current range.
  47039. var dataZoomModel = ecModel.queryComponents({
  47040. mainType: 'dataZoom',
  47041. subType: 'select',
  47042. id: dataZoomId
  47043. })[0];
  47044. if (dataZoomModel) {
  47045. var percentRange = dataZoomModel.getPercentRange();
  47046. storedSnapshots[0][dataZoomId] = {
  47047. dataZoomId: dataZoomId,
  47048. start: percentRange[0],
  47049. end: percentRange[1]
  47050. };
  47051. }
  47052. }
  47053. });
  47054. storedSnapshots.push(newSnapshot);
  47055. }
  47056. function pop(ecModel) {
  47057. var storedSnapshots = getStoreSnapshots(ecModel);
  47058. var head = storedSnapshots[storedSnapshots.length - 1];
  47059. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  47060. var snapshot = {};
  47061. each$5(head, function (batchItem, dataZoomId) {
  47062. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  47063. batchItem = storedSnapshots[i][dataZoomId];
  47064. if (batchItem) {
  47065. snapshot[dataZoomId] = batchItem;
  47066. break;
  47067. }
  47068. }
  47069. });
  47070. return snapshot;
  47071. }
  47072. function clear$1(ecModel) {
  47073. inner$b(ecModel).snapshots = null;
  47074. }
  47075. function count(ecModel) {
  47076. return getStoreSnapshots(ecModel).length;
  47077. }
  47078. /**
  47079. * History length of each dataZoom may be different.
  47080. * this._history[0] is used to store origin range.
  47081. */
  47082. function getStoreSnapshots(ecModel) {
  47083. var store = inner$b(ecModel);
  47084. if (!store.snapshots) {
  47085. store.snapshots = [{}];
  47086. }
  47087. return store.snapshots;
  47088. }
  47089. var RestoreOption =
  47090. /** @class */
  47091. function (_super) {
  47092. __extends(RestoreOption, _super);
  47093. function RestoreOption() {
  47094. return _super !== null && _super.apply(this, arguments) || this;
  47095. }
  47096. RestoreOption.prototype.onclick = function (ecModel, api) {
  47097. clear$1(ecModel);
  47098. api.dispatchAction({
  47099. type: 'restore',
  47100. from: this.uid
  47101. });
  47102. };
  47103. RestoreOption.getDefaultOption = function (ecModel) {
  47104. var defaultOption = {
  47105. show: true,
  47106. // eslint-disable-next-line
  47107. 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',
  47108. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  47109. };
  47110. return defaultOption;
  47111. };
  47112. return RestoreOption;
  47113. }(ToolboxFeature); // TODO: SELF REGISTERED.
  47114. registerAction({
  47115. type: 'restore',
  47116. event: 'restore',
  47117. update: 'prepareAndUpdate'
  47118. }, function (payload, ecModel) {
  47119. ecModel.resetOption('recreate');
  47120. });
  47121. var ATTR = '\0_ec_interaction_mutex';
  47122. function take(zr, resourceKey, userKey) {
  47123. var store = getStore(zr);
  47124. store[resourceKey] = userKey;
  47125. }
  47126. function release(zr, resourceKey, userKey) {
  47127. var store = getStore(zr);
  47128. var uKey = store[resourceKey];
  47129. if (uKey === userKey) {
  47130. store[resourceKey] = null;
  47131. }
  47132. }
  47133. function isTaken(zr, resourceKey) {
  47134. return !!getStore(zr)[resourceKey];
  47135. }
  47136. function getStore(zr) {
  47137. return zr[ATTR] || (zr[ATTR] = {});
  47138. }
  47139. /**
  47140. * payload: {
  47141. * type: 'takeGlobalCursor',
  47142. * key: 'dataZoomSelect', or 'brush', or ...,
  47143. * If no userKey, release global cursor.
  47144. * }
  47145. */
  47146. // TODO: SELF REGISTERED.
  47147. registerAction({
  47148. type: 'takeGlobalCursor',
  47149. event: 'globalCursorTaken',
  47150. update: 'update'
  47151. }, noop);
  47152. var BRUSH_PANEL_GLOBAL = true;
  47153. var mathMin$7 = Math.min;
  47154. var mathMax$7 = Math.max;
  47155. var mathPow$2 = Math.pow;
  47156. var COVER_Z = 10000;
  47157. var UNSELECT_THRESHOLD = 6;
  47158. var MIN_RESIZE_LINE_WIDTH = 6;
  47159. var MUTEX_RESOURCE_KEY = 'globalPan';
  47160. var DIRECTION_MAP = {
  47161. w: [0, 0],
  47162. e: [0, 1],
  47163. n: [1, 0],
  47164. s: [1, 1]
  47165. };
  47166. var CURSOR_MAP = {
  47167. w: 'ew',
  47168. e: 'ew',
  47169. n: 'ns',
  47170. s: 'ns',
  47171. ne: 'nesw',
  47172. sw: 'nesw',
  47173. nw: 'nwse',
  47174. se: 'nwse'
  47175. };
  47176. var DEFAULT_BRUSH_OPT = {
  47177. brushStyle: {
  47178. lineWidth: 2,
  47179. stroke: 'rgba(210,219,238,0.3)',
  47180. fill: '#D2DBEE'
  47181. },
  47182. transformable: true,
  47183. brushMode: 'single',
  47184. removeOnClick: false
  47185. };
  47186. var baseUID = 0;
  47187. /**
  47188. * params:
  47189. * areas: Array.<Array>, coord relates to container group,
  47190. * If no container specified, to global.
  47191. * opt {
  47192. * isEnd: boolean,
  47193. * removeOnClick: boolean
  47194. * }
  47195. */
  47196. var BrushController =
  47197. /** @class */
  47198. function (_super) {
  47199. __extends(BrushController, _super);
  47200. function BrushController(zr) {
  47201. var _this = _super.call(this) || this;
  47202. /**
  47203. * @internal
  47204. */
  47205. _this._track = [];
  47206. /**
  47207. * @internal
  47208. */
  47209. _this._covers = [];
  47210. _this._handlers = {};
  47211. if ("development" !== 'production') {
  47212. assert(zr);
  47213. }
  47214. _this._zr = zr;
  47215. _this.group = new Group();
  47216. _this._uid = 'brushController_' + baseUID++;
  47217. each(pointerHandlers, function (handler, eventName) {
  47218. this._handlers[eventName] = bind(handler, this);
  47219. }, _this);
  47220. return _this;
  47221. }
  47222. /**
  47223. * If set to `false`, select disabled.
  47224. */
  47225. BrushController.prototype.enableBrush = function (brushOption) {
  47226. if ("development" !== 'production') {
  47227. assert(this._mounted);
  47228. }
  47229. this._brushType && this._doDisableBrush();
  47230. brushOption.brushType && this._doEnableBrush(brushOption);
  47231. return this;
  47232. };
  47233. BrushController.prototype._doEnableBrush = function (brushOption) {
  47234. var zr = this._zr; // Consider roam, which takes globalPan too.
  47235. if (!this._enableGlobalPan) {
  47236. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  47237. }
  47238. each(this._handlers, function (handler, eventName) {
  47239. zr.on(eventName, handler);
  47240. });
  47241. this._brushType = brushOption.brushType;
  47242. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  47243. };
  47244. BrushController.prototype._doDisableBrush = function () {
  47245. var zr = this._zr;
  47246. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  47247. each(this._handlers, function (handler, eventName) {
  47248. zr.off(eventName, handler);
  47249. });
  47250. this._brushType = this._brushOption = null;
  47251. };
  47252. /**
  47253. * @param panelOpts If not pass, it is global brush.
  47254. */
  47255. BrushController.prototype.setPanels = function (panelOpts) {
  47256. if (panelOpts && panelOpts.length) {
  47257. var panels_1 = this._panels = {};
  47258. each(panelOpts, function (panelOpts) {
  47259. panels_1[panelOpts.panelId] = clone(panelOpts);
  47260. });
  47261. } else {
  47262. this._panels = null;
  47263. }
  47264. return this;
  47265. };
  47266. BrushController.prototype.mount = function (opt) {
  47267. opt = opt || {};
  47268. if ("development" !== 'production') {
  47269. this._mounted = true; // should be at first.
  47270. }
  47271. this._enableGlobalPan = opt.enableGlobalPan;
  47272. var thisGroup = this.group;
  47273. this._zr.add(thisGroup);
  47274. thisGroup.attr({
  47275. x: opt.x || 0,
  47276. y: opt.y || 0,
  47277. rotation: opt.rotation || 0,
  47278. scaleX: opt.scaleX || 1,
  47279. scaleY: opt.scaleY || 1
  47280. });
  47281. this._transform = thisGroup.getLocalTransform();
  47282. return this;
  47283. }; // eachCover(cb, context): void {
  47284. // each(this._covers, cb, context);
  47285. // }
  47286. /**
  47287. * Update covers.
  47288. * @param coverConfigList
  47289. * If coverConfigList is null/undefined, all covers removed.
  47290. */
  47291. BrushController.prototype.updateCovers = function (coverConfigList) {
  47292. if ("development" !== 'production') {
  47293. assert(this._mounted);
  47294. }
  47295. coverConfigList = map(coverConfigList, function (coverConfig) {
  47296. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  47297. });
  47298. var tmpIdPrefix = '\0-brush-index-';
  47299. var oldCovers = this._covers;
  47300. var newCovers = this._covers = [];
  47301. var controller = this;
  47302. var creatingCover = this._creatingCover;
  47303. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  47304. return this;
  47305. function getKey(brushOption, index) {
  47306. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  47307. }
  47308. function oldGetKey(cover, index) {
  47309. return getKey(cover.__brushOption, index);
  47310. }
  47311. function addOrUpdate(newIndex, oldIndex) {
  47312. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  47313. // where updating cover when creating should be forbidden.
  47314. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  47315. newCovers[newIndex] = oldCovers[oldIndex];
  47316. } else {
  47317. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  47318. updateCoverAfterCreation(controller, cover);
  47319. }
  47320. }
  47321. function remove(oldIndex) {
  47322. if (oldCovers[oldIndex] !== creatingCover) {
  47323. controller.group.remove(oldCovers[oldIndex]);
  47324. }
  47325. }
  47326. };
  47327. BrushController.prototype.unmount = function () {
  47328. if ("development" !== 'production') {
  47329. if (!this._mounted) {
  47330. return;
  47331. }
  47332. }
  47333. this.enableBrush(false); // container may 'removeAll' outside.
  47334. clearCovers(this);
  47335. this._zr.remove(this.group);
  47336. if ("development" !== 'production') {
  47337. this._mounted = false; // should be at last.
  47338. }
  47339. return this;
  47340. };
  47341. BrushController.prototype.dispose = function () {
  47342. this.unmount();
  47343. this.off();
  47344. };
  47345. return BrushController;
  47346. }(Eventful);
  47347. function createCover(controller, brushOption) {
  47348. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  47349. cover.__brushOption = brushOption;
  47350. updateZ(cover, brushOption);
  47351. controller.group.add(cover);
  47352. return cover;
  47353. }
  47354. function endCreating(controller, creatingCover) {
  47355. var coverRenderer = getCoverRenderer(creatingCover);
  47356. if (coverRenderer.endCreating) {
  47357. coverRenderer.endCreating(controller, creatingCover);
  47358. updateZ(creatingCover, creatingCover.__brushOption);
  47359. }
  47360. return creatingCover;
  47361. }
  47362. function updateCoverShape(controller, cover) {
  47363. var brushOption = cover.__brushOption;
  47364. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  47365. }
  47366. function updateZ(cover, brushOption) {
  47367. var z = brushOption.z;
  47368. z == null && (z = COVER_Z);
  47369. cover.traverse(function (el) {
  47370. el.z = z;
  47371. el.z2 = z; // Consider in given container.
  47372. });
  47373. }
  47374. function updateCoverAfterCreation(controller, cover) {
  47375. getCoverRenderer(cover).updateCommon(controller, cover);
  47376. updateCoverShape(controller, cover);
  47377. }
  47378. function getCoverRenderer(cover) {
  47379. return coverRenderers[cover.__brushOption.brushType];
  47380. } // return target panel or `true` (means global panel)
  47381. function getPanelByPoint(controller, e, localCursorPoint) {
  47382. var panels = controller._panels;
  47383. if (!panels) {
  47384. return BRUSH_PANEL_GLOBAL; // Global panel
  47385. }
  47386. var panel;
  47387. var transform = controller._transform;
  47388. each(panels, function (pn) {
  47389. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  47390. });
  47391. return panel;
  47392. } // Return a panel or true
  47393. function getPanelByCover(controller, cover) {
  47394. var panels = controller._panels;
  47395. if (!panels) {
  47396. return BRUSH_PANEL_GLOBAL; // Global panel
  47397. }
  47398. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  47399. // which is then treated as global panel.
  47400. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  47401. }
  47402. function clearCovers(controller) {
  47403. var covers = controller._covers;
  47404. var originalLength = covers.length;
  47405. each(covers, function (cover) {
  47406. controller.group.remove(cover);
  47407. }, controller);
  47408. covers.length = 0;
  47409. return !!originalLength;
  47410. }
  47411. function trigger(controller, opt) {
  47412. var areas = map(controller._covers, function (cover) {
  47413. var brushOption = cover.__brushOption;
  47414. var range = clone(brushOption.range);
  47415. return {
  47416. brushType: brushOption.brushType,
  47417. panelId: brushOption.panelId,
  47418. range: range
  47419. };
  47420. });
  47421. controller.trigger('brush', {
  47422. areas: areas,
  47423. isEnd: !!opt.isEnd,
  47424. removeOnClick: !!opt.removeOnClick
  47425. });
  47426. }
  47427. function shouldShowCover(controller) {
  47428. var track = controller._track;
  47429. if (!track.length) {
  47430. return false;
  47431. }
  47432. var p2 = track[track.length - 1];
  47433. var p1 = track[0];
  47434. var dx = p2[0] - p1[0];
  47435. var dy = p2[1] - p1[1];
  47436. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  47437. return dist > UNSELECT_THRESHOLD;
  47438. }
  47439. function getTrackEnds(track) {
  47440. var tail = track.length - 1;
  47441. tail < 0 && (tail = 0);
  47442. return [track[0], track[tail]];
  47443. }
  47444. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  47445. var cover = new Group();
  47446. cover.add(new Rect({
  47447. name: 'main',
  47448. style: makeStyle(brushOption),
  47449. silent: true,
  47450. draggable: true,
  47451. cursor: 'move',
  47452. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  47453. ondragend: curry(trigger, controller, {
  47454. isEnd: true
  47455. })
  47456. }));
  47457. each(edgeNameSequences, function (nameSequence) {
  47458. cover.add(new Rect({
  47459. name: nameSequence.join(''),
  47460. style: {
  47461. opacity: 0
  47462. },
  47463. draggable: true,
  47464. silent: true,
  47465. invisible: true,
  47466. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  47467. ondragend: curry(trigger, controller, {
  47468. isEnd: true
  47469. })
  47470. }));
  47471. });
  47472. return cover;
  47473. }
  47474. function updateBaseRect(controller, cover, localRange, brushOption) {
  47475. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  47476. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  47477. var x = localRange[0][0];
  47478. var y = localRange[1][0];
  47479. var xa = x - lineWidth / 2;
  47480. var ya = y - lineWidth / 2;
  47481. var x2 = localRange[0][1];
  47482. var y2 = localRange[1][1];
  47483. var x2a = x2 - handleSize + lineWidth / 2;
  47484. var y2a = y2 - handleSize + lineWidth / 2;
  47485. var width = x2 - x;
  47486. var height = y2 - y;
  47487. var widtha = width + lineWidth;
  47488. var heighta = height + lineWidth;
  47489. updateRectShape(controller, cover, 'main', x, y, width, height);
  47490. if (brushOption.transformable) {
  47491. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  47492. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  47493. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  47494. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  47495. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  47496. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  47497. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  47498. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  47499. }
  47500. }
  47501. function updateCommon(controller, cover) {
  47502. var brushOption = cover.__brushOption;
  47503. var transformable = brushOption.transformable;
  47504. var mainEl = cover.childAt(0);
  47505. mainEl.useStyle(makeStyle(brushOption));
  47506. mainEl.attr({
  47507. silent: !transformable,
  47508. cursor: transformable ? 'move' : 'default'
  47509. });
  47510. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  47511. var el = cover.childOfName(nameSequence.join(''));
  47512. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  47513. el && el.attr({
  47514. silent: !transformable,
  47515. invisible: !transformable,
  47516. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  47517. });
  47518. });
  47519. }
  47520. function updateRectShape(controller, cover, name, x, y, w, h) {
  47521. var el = cover.childOfName(name);
  47522. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  47523. }
  47524. function makeStyle(brushOption) {
  47525. return defaults({
  47526. strokeNoScale: true
  47527. }, brushOption.brushStyle);
  47528. }
  47529. function formatRectRange(x, y, x2, y2) {
  47530. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  47531. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  47532. return [[min[0], max[0]], [min[1], max[1]] // y range
  47533. ];
  47534. }
  47535. function getTransform$1(controller) {
  47536. return getTransform(controller.group);
  47537. }
  47538. function getGlobalDirection1(controller, localDirName) {
  47539. var map = {
  47540. w: 'left',
  47541. e: 'right',
  47542. n: 'top',
  47543. s: 'bottom'
  47544. };
  47545. var inverseMap = {
  47546. left: 'w',
  47547. right: 'e',
  47548. top: 'n',
  47549. bottom: 's'
  47550. };
  47551. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  47552. return inverseMap[dir];
  47553. }
  47554. function getGlobalDirection2(controller, localDirNameSeq) {
  47555. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  47556. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  47557. return globalDir.join('');
  47558. }
  47559. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  47560. var brushOption = cover.__brushOption;
  47561. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  47562. var localDelta = toLocalDelta(controller, dx, dy);
  47563. each(dirNameSequence, function (dirName) {
  47564. var ind = DIRECTION_MAP[dirName];
  47565. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  47566. });
  47567. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  47568. updateCoverAfterCreation(controller, cover);
  47569. trigger(controller, {
  47570. isEnd: false
  47571. });
  47572. }
  47573. function driftPolygon(controller, cover, dx, dy) {
  47574. var range = cover.__brushOption.range;
  47575. var localDelta = toLocalDelta(controller, dx, dy);
  47576. each(range, function (point) {
  47577. point[0] += localDelta[0];
  47578. point[1] += localDelta[1];
  47579. });
  47580. updateCoverAfterCreation(controller, cover);
  47581. trigger(controller, {
  47582. isEnd: false
  47583. });
  47584. }
  47585. function toLocalDelta(controller, dx, dy) {
  47586. var thisGroup = controller.group;
  47587. var localD = thisGroup.transformCoordToLocal(dx, dy);
  47588. var localZero = thisGroup.transformCoordToLocal(0, 0);
  47589. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  47590. }
  47591. function clipByPanel(controller, cover, data) {
  47592. var panel = getPanelByCover(controller, cover);
  47593. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  47594. }
  47595. function pointsToRect(points) {
  47596. var xmin = mathMin$7(points[0][0], points[1][0]);
  47597. var ymin = mathMin$7(points[0][1], points[1][1]);
  47598. var xmax = mathMax$7(points[0][0], points[1][0]);
  47599. var ymax = mathMax$7(points[0][1], points[1][1]);
  47600. return {
  47601. x: xmin,
  47602. y: ymin,
  47603. width: xmax - xmin,
  47604. height: ymax - ymin
  47605. };
  47606. }
  47607. function resetCursor(controller, e, localCursorPoint) {
  47608. if ( // Check active
  47609. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  47610. // but not called when mouse is out of zr area to avoid bad influence
  47611. // if `mousemove`, `mouseup` are triggered from `document` event.
  47612. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  47613. return;
  47614. }
  47615. var zr = controller._zr;
  47616. var covers = controller._covers;
  47617. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  47618. if (!controller._dragging) {
  47619. for (var i = 0; i < covers.length; i++) {
  47620. var brushOption = covers[i].__brushOption;
  47621. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  47622. // Use cursor style set on cover.
  47623. return;
  47624. }
  47625. }
  47626. }
  47627. currPanel && zr.setCursorStyle('crosshair');
  47628. }
  47629. function preventDefault(e) {
  47630. var rawE = e.event;
  47631. rawE.preventDefault && rawE.preventDefault();
  47632. }
  47633. function mainShapeContain(cover, x, y) {
  47634. return cover.childOfName('main').contain(x, y);
  47635. }
  47636. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  47637. var creatingCover = controller._creatingCover;
  47638. var panel = controller._creatingPanel;
  47639. var thisBrushOption = controller._brushOption;
  47640. var eventParams;
  47641. controller._track.push(localCursorPoint.slice());
  47642. if (shouldShowCover(controller) || creatingCover) {
  47643. if (panel && !creatingCover) {
  47644. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  47645. var brushOption = clone(thisBrushOption);
  47646. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  47647. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  47648. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  47649. controller._covers.push(creatingCover);
  47650. }
  47651. if (creatingCover) {
  47652. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  47653. var coverBrushOption = creatingCover.__brushOption;
  47654. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  47655. if (isEnd) {
  47656. endCreating(controller, creatingCover);
  47657. coverRenderer.updateCommon(controller, creatingCover);
  47658. }
  47659. updateCoverShape(controller, creatingCover);
  47660. eventParams = {
  47661. isEnd: isEnd
  47662. };
  47663. }
  47664. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  47665. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  47666. // But a single click do not clear covers, because user may have casual
  47667. // clicks (for example, click on other component and do not expect covers
  47668. // disappear).
  47669. // Only some cover removed, trigger action, but not every click trigger action.
  47670. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  47671. eventParams = {
  47672. isEnd: isEnd,
  47673. removeOnClick: true
  47674. };
  47675. }
  47676. }
  47677. return eventParams;
  47678. }
  47679. function determineBrushType(brushType, panel) {
  47680. if (brushType === 'auto') {
  47681. if ("development" !== 'production') {
  47682. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  47683. }
  47684. return panel.defaultBrushType;
  47685. }
  47686. return brushType;
  47687. }
  47688. var pointerHandlers = {
  47689. mousedown: function (e) {
  47690. if (this._dragging) {
  47691. // In case some browser do not support globalOut,
  47692. // and release mouse out side the browser.
  47693. handleDragEnd(this, e);
  47694. } else if (!e.target || !e.target.draggable) {
  47695. preventDefault(e);
  47696. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  47697. this._creatingCover = null;
  47698. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  47699. if (panel) {
  47700. this._dragging = true;
  47701. this._track = [localCursorPoint.slice()];
  47702. }
  47703. }
  47704. },
  47705. mousemove: function (e) {
  47706. var x = e.offsetX;
  47707. var y = e.offsetY;
  47708. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  47709. resetCursor(this, e, localCursorPoint);
  47710. if (this._dragging) {
  47711. preventDefault(e);
  47712. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  47713. eventParams && trigger(this, eventParams);
  47714. }
  47715. },
  47716. mouseup: function (e) {
  47717. handleDragEnd(this, e);
  47718. }
  47719. };
  47720. function handleDragEnd(controller, e) {
  47721. if (controller._dragging) {
  47722. preventDefault(e);
  47723. var x = e.offsetX;
  47724. var y = e.offsetY;
  47725. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  47726. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  47727. controller._dragging = false;
  47728. controller._track = [];
  47729. controller._creatingCover = null; // trigger event should be at final, after procedure will be nested.
  47730. eventParams && trigger(controller, eventParams);
  47731. }
  47732. }
  47733. function isOutsideZrArea(controller, x, y) {
  47734. var zr = controller._zr;
  47735. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  47736. }
  47737. /**
  47738. * key: brushType
  47739. */
  47740. var coverRenderers = {
  47741. lineX: getLineRenderer(0),
  47742. lineY: getLineRenderer(1),
  47743. rect: {
  47744. createCover: function (controller, brushOption) {
  47745. function returnInput(range) {
  47746. return range;
  47747. }
  47748. return createBaseRectCover({
  47749. toRectRange: returnInput,
  47750. fromRectRange: returnInput
  47751. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  47752. },
  47753. getCreatingRange: function (localTrack) {
  47754. var ends = getTrackEnds(localTrack);
  47755. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  47756. },
  47757. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47758. updateBaseRect(controller, cover, localRange, brushOption);
  47759. },
  47760. updateCommon: updateCommon,
  47761. contain: mainShapeContain
  47762. },
  47763. polygon: {
  47764. createCover: function (controller, brushOption) {
  47765. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  47766. // border of the shape when drawing, which is a better experience for user.
  47767. cover.add(new Polyline({
  47768. name: 'main',
  47769. style: makeStyle(brushOption),
  47770. silent: true
  47771. }));
  47772. return cover;
  47773. },
  47774. getCreatingRange: function (localTrack) {
  47775. return localTrack;
  47776. },
  47777. endCreating: function (controller, cover) {
  47778. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  47779. cover.add(new Polygon({
  47780. name: 'main',
  47781. draggable: true,
  47782. drift: curry(driftPolygon, controller, cover),
  47783. ondragend: curry(trigger, controller, {
  47784. isEnd: true
  47785. })
  47786. }));
  47787. },
  47788. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47789. cover.childAt(0).setShape({
  47790. points: clipByPanel(controller, cover, localRange)
  47791. });
  47792. },
  47793. updateCommon: updateCommon,
  47794. contain: mainShapeContain
  47795. }
  47796. };
  47797. function getLineRenderer(xyIndex) {
  47798. return {
  47799. createCover: function (controller, brushOption) {
  47800. return createBaseRectCover({
  47801. toRectRange: function (range) {
  47802. var rectRange = [range, [0, 100]];
  47803. xyIndex && rectRange.reverse();
  47804. return rectRange;
  47805. },
  47806. fromRectRange: function (rectRange) {
  47807. return rectRange[xyIndex];
  47808. }
  47809. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  47810. },
  47811. getCreatingRange: function (localTrack) {
  47812. var ends = getTrackEnds(localTrack);
  47813. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  47814. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  47815. return [min, max];
  47816. },
  47817. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47818. var otherExtent; // If brushWidth not specified, fit the panel.
  47819. var panel = getPanelByCover(controller, cover);
  47820. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  47821. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  47822. } else {
  47823. var zr = controller._zr;
  47824. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  47825. }
  47826. var rectRange = [localRange, otherExtent];
  47827. xyIndex && rectRange.reverse();
  47828. updateBaseRect(controller, cover, rectRange, brushOption);
  47829. },
  47830. updateCommon: updateCommon,
  47831. contain: mainShapeContain
  47832. };
  47833. }
  47834. /*
  47835. * Licensed to the Apache Software Foundation (ASF) under one
  47836. * or more contributor license agreements. See the NOTICE file
  47837. * distributed with this work for additional information
  47838. * regarding copyright ownership. The ASF licenses this file
  47839. * to you under the Apache License, Version 2.0 (the
  47840. * "License"); you may not use this file except in compliance
  47841. * with the License. You may obtain a copy of the License at
  47842. *
  47843. * http://www.apache.org/licenses/LICENSE-2.0
  47844. *
  47845. * Unless required by applicable law or agreed to in writing,
  47846. * software distributed under the License is distributed on an
  47847. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47848. * KIND, either express or implied. See the License for the
  47849. * specific language governing permissions and limitations
  47850. * under the License.
  47851. */
  47852. /**
  47853. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47854. */
  47855. /*
  47856. * Licensed to the Apache Software Foundation (ASF) under one
  47857. * or more contributor license agreements. See the NOTICE file
  47858. * distributed with this work for additional information
  47859. * regarding copyright ownership. The ASF licenses this file
  47860. * to you under the Apache License, Version 2.0 (the
  47861. * "License"); you may not use this file except in compliance
  47862. * with the License. You may obtain a copy of the License at
  47863. *
  47864. * http://www.apache.org/licenses/LICENSE-2.0
  47865. *
  47866. * Unless required by applicable law or agreed to in writing,
  47867. * software distributed under the License is distributed on an
  47868. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47869. * KIND, either express or implied. See the License for the
  47870. * specific language governing permissions and limitations
  47871. * under the License.
  47872. */
  47873. var IRRELEVANT_EXCLUDES = {
  47874. 'axisPointer': 1,
  47875. 'tooltip': 1,
  47876. 'brush': 1
  47877. };
  47878. /**
  47879. * Avoid that: mouse click on a elements that is over geo or graph,
  47880. * but roam is triggered.
  47881. */
  47882. function onIrrelevantElement(e, api, targetCoordSysModel) {
  47883. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  47884. var coordSys = model && model.coordinateSystem;
  47885. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  47886. }
  47887. function makeRectPanelClipPath(rect) {
  47888. rect = normalizeRect(rect);
  47889. return function (localPoints) {
  47890. return clipPointsByRect(localPoints, rect);
  47891. };
  47892. }
  47893. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  47894. rect = normalizeRect(rect);
  47895. return function (xyIndex) {
  47896. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  47897. var brushWidth = idx ? rect.width : rect.height;
  47898. var base = idx ? rect.x : rect.y;
  47899. return [base, base + (brushWidth || 0)];
  47900. };
  47901. }
  47902. function makeRectIsTargetByCursor(rect, api, targetModel) {
  47903. var boundingRect = normalizeRect(rect);
  47904. return function (e, localCursorPoint) {
  47905. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  47906. };
  47907. } // Consider width/height is negative.
  47908. function normalizeRect(rect) {
  47909. return BoundingRect.create(rect);
  47910. }
  47911. // how to genarialize to more coordinate systems.
  47912. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  47913. var BrushTargetManager =
  47914. /** @class */
  47915. function () {
  47916. /**
  47917. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  47918. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  47919. * @param opt.include include coordinate system types.
  47920. */
  47921. function BrushTargetManager(finder, ecModel, opt) {
  47922. var _this = this;
  47923. this._targetInfoList = [];
  47924. var foundCpts = parseFinder$1(ecModel, finder);
  47925. each(targetInfoBuilders, function (builder, type) {
  47926. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  47927. builder(foundCpts, _this._targetInfoList);
  47928. }
  47929. });
  47930. }
  47931. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  47932. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  47933. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  47934. if (!area.coordRange) {
  47935. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  47936. // rebuild range by coordRange accrately, which may bring trouble when
  47937. // brushing only one item. So we use __rangeOffset to rebuilding range
  47938. // by coordRange. And this it only used in brush component so it is no
  47939. // need to be adapted to coordRanges.
  47940. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  47941. area.__rangeOffset = {
  47942. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  47943. xyMinMax: result.xyMinMax
  47944. };
  47945. }
  47946. });
  47947. return areas;
  47948. };
  47949. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  47950. each(areas, function (area) {
  47951. var targetInfo = this.findTargetInfo(area, ecModel);
  47952. if (targetInfo && targetInfo !== true) {
  47953. each(targetInfo.coordSyses, function (coordSys) {
  47954. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  47955. cb(area, result.values, coordSys, ecModel);
  47956. });
  47957. }
  47958. }, this);
  47959. };
  47960. /**
  47961. * the `areas` is `BrushModel.areas`.
  47962. * Called in layout stage.
  47963. * convert `area.coordRange` to global range and set panelId to `area.range`.
  47964. */
  47965. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  47966. each(areas, function (area) {
  47967. var targetInfo = this.findTargetInfo(area, ecModel);
  47968. if ("development" !== 'production') {
  47969. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  47970. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  47971. }
  47972. area.range = area.range || []; // convert coordRange to global range and set panelId.
  47973. if (targetInfo && targetInfo !== true) {
  47974. area.panelId = targetInfo.panelId; // (1) area.range should always be calculate from coordRange but does
  47975. // not keep its original value, for the sake of the dataZoom scenario,
  47976. // where area.coordRange remains unchanged but area.range may be changed.
  47977. // (2) Only support converting one coordRange to pixel range in brush
  47978. // component. So do not consider `coordRanges`.
  47979. // (3) About __rangeOffset, see comment above.
  47980. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  47981. var rangeOffset = area.__rangeOffset;
  47982. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  47983. }
  47984. }, this);
  47985. };
  47986. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  47987. return map(this._targetInfoList, function (targetInfo) {
  47988. var rect = targetInfo.getPanelRect();
  47989. return {
  47990. panelId: targetInfo.panelId,
  47991. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  47992. clipPath: makeRectPanelClipPath(rect),
  47993. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  47994. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  47995. };
  47996. });
  47997. };
  47998. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  47999. // Check whether area is bound in coord, and series do not belong to that coord.
  48000. // If do not do this check, some brush (like lineX) will controll all axes.
  48001. var targetInfo = this.findTargetInfo(area, ecModel);
  48002. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  48003. };
  48004. /**
  48005. * If return Object, a coord found.
  48006. * If return true, global found.
  48007. * Otherwise nothing found.
  48008. */
  48009. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  48010. var targetInfoList = this._targetInfoList;
  48011. var foundCpts = parseFinder$1(ecModel, area);
  48012. for (var i = 0; i < targetInfoList.length; i++) {
  48013. var targetInfo = targetInfoList[i];
  48014. var areaPanelId = area.panelId;
  48015. if (areaPanelId) {
  48016. if (targetInfo.panelId === areaPanelId) {
  48017. return targetInfo;
  48018. }
  48019. } else {
  48020. for (var j = 0; j < targetInfoMatchers.length; j++) {
  48021. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  48022. return targetInfo;
  48023. }
  48024. }
  48025. }
  48026. }
  48027. return true;
  48028. };
  48029. return BrushTargetManager;
  48030. }();
  48031. function formatMinMax(minMax) {
  48032. minMax[0] > minMax[1] && minMax.reverse();
  48033. return minMax;
  48034. }
  48035. function parseFinder$1(ecModel, finder) {
  48036. return parseFinder(ecModel, finder, {
  48037. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  48038. });
  48039. }
  48040. var targetInfoBuilders = {
  48041. grid: function (foundCpts, targetInfoList) {
  48042. var xAxisModels = foundCpts.xAxisModels;
  48043. var yAxisModels = foundCpts.yAxisModels;
  48044. var gridModels = foundCpts.gridModels; // Remove duplicated.
  48045. var gridModelMap = createHashMap();
  48046. var xAxesHas = {};
  48047. var yAxesHas = {};
  48048. if (!xAxisModels && !yAxisModels && !gridModels) {
  48049. return;
  48050. }
  48051. each(xAxisModels, function (axisModel) {
  48052. var gridModel = axisModel.axis.grid.model;
  48053. gridModelMap.set(gridModel.id, gridModel);
  48054. xAxesHas[gridModel.id] = true;
  48055. });
  48056. each(yAxisModels, function (axisModel) {
  48057. var gridModel = axisModel.axis.grid.model;
  48058. gridModelMap.set(gridModel.id, gridModel);
  48059. yAxesHas[gridModel.id] = true;
  48060. });
  48061. each(gridModels, function (gridModel) {
  48062. gridModelMap.set(gridModel.id, gridModel);
  48063. xAxesHas[gridModel.id] = true;
  48064. yAxesHas[gridModel.id] = true;
  48065. });
  48066. gridModelMap.each(function (gridModel) {
  48067. var grid = gridModel.coordinateSystem;
  48068. var cartesians = [];
  48069. each(grid.getCartesians(), function (cartesian, index) {
  48070. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  48071. cartesians.push(cartesian);
  48072. }
  48073. });
  48074. targetInfoList.push({
  48075. panelId: 'grid--' + gridModel.id,
  48076. gridModel: gridModel,
  48077. coordSysModel: gridModel,
  48078. // Use the first one as the representitive coordSys.
  48079. coordSys: cartesians[0],
  48080. coordSyses: cartesians,
  48081. getPanelRect: panelRectBuilders.grid,
  48082. xAxisDeclared: xAxesHas[gridModel.id],
  48083. yAxisDeclared: yAxesHas[gridModel.id]
  48084. });
  48085. });
  48086. },
  48087. geo: function (foundCpts, targetInfoList) {
  48088. each(foundCpts.geoModels, function (geoModel) {
  48089. var coordSys = geoModel.coordinateSystem;
  48090. targetInfoList.push({
  48091. panelId: 'geo--' + geoModel.id,
  48092. geoModel: geoModel,
  48093. coordSysModel: geoModel,
  48094. coordSys: coordSys,
  48095. coordSyses: [coordSys],
  48096. getPanelRect: panelRectBuilders.geo
  48097. });
  48098. });
  48099. }
  48100. };
  48101. var targetInfoMatchers = [// grid
  48102. function (foundCpts, targetInfo) {
  48103. var xAxisModel = foundCpts.xAxisModel;
  48104. var yAxisModel = foundCpts.yAxisModel;
  48105. var gridModel = foundCpts.gridModel;
  48106. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  48107. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  48108. return gridModel && gridModel === targetInfo.gridModel;
  48109. }, // geo
  48110. function (foundCpts, targetInfo) {
  48111. var geoModel = foundCpts.geoModel;
  48112. return geoModel && geoModel === targetInfo.geoModel;
  48113. }];
  48114. var panelRectBuilders = {
  48115. grid: function () {
  48116. // grid is not Transformable.
  48117. return this.coordSys.master.getRect().clone();
  48118. },
  48119. geo: function () {
  48120. var coordSys = this.coordSys;
  48121. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  48122. rect.applyTransform(getTransform(coordSys));
  48123. return rect;
  48124. }
  48125. };
  48126. var coordConvert = {
  48127. lineX: curry(axisConvert, 0),
  48128. lineY: curry(axisConvert, 1),
  48129. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  48130. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  48131. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  48132. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  48133. return {
  48134. values: values,
  48135. xyMinMax: values
  48136. };
  48137. },
  48138. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  48139. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  48140. var values = map(rangeOrCoordRange, function (item) {
  48141. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  48142. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  48143. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  48144. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  48145. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  48146. return p;
  48147. });
  48148. return {
  48149. values: values,
  48150. xyMinMax: xyMinMax
  48151. };
  48152. }
  48153. };
  48154. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  48155. if ("development" !== 'production') {
  48156. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  48157. }
  48158. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  48159. var values = formatMinMax(map([0, 1], function (i) {
  48160. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  48161. }));
  48162. var xyMinMax = [];
  48163. xyMinMax[axisNameIndex] = values;
  48164. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  48165. return {
  48166. values: values,
  48167. xyMinMax: xyMinMax
  48168. };
  48169. }
  48170. var diffProcessor = {
  48171. lineX: curry(axisDiffProcessor, 0),
  48172. lineY: curry(axisDiffProcessor, 1),
  48173. rect: function (values, refer, scales) {
  48174. 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]]];
  48175. },
  48176. polygon: function (values, refer, scales) {
  48177. return map(values, function (item, idx) {
  48178. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  48179. });
  48180. }
  48181. };
  48182. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  48183. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  48184. } // We have to process scale caused by dataZoom manually,
  48185. // although it might be not accurate.
  48186. // Return [0~1, 0~1]
  48187. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  48188. var sizeCurr = getSize$1(xyMinMaxCurr);
  48189. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  48190. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  48191. isNaN(scales[0]) && (scales[0] = 1);
  48192. isNaN(scales[1]) && (scales[1] = 1);
  48193. return scales;
  48194. }
  48195. function getSize$1(xyMinMax) {
  48196. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  48197. }
  48198. var each$6 = each;
  48199. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  48200. var DataZoomFeature =
  48201. /** @class */
  48202. function (_super) {
  48203. __extends(DataZoomFeature, _super);
  48204. function DataZoomFeature() {
  48205. return _super !== null && _super.apply(this, arguments) || this;
  48206. }
  48207. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  48208. if (!this._brushController) {
  48209. this._brushController = new BrushController(api.getZr());
  48210. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  48211. }
  48212. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  48213. updateBackBtnStatus(featureModel, ecModel);
  48214. };
  48215. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  48216. handlers[type].call(this);
  48217. };
  48218. DataZoomFeature.prototype.remove = function (ecModel, api) {
  48219. this._brushController && this._brushController.unmount();
  48220. };
  48221. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  48222. this._brushController && this._brushController.dispose();
  48223. };
  48224. DataZoomFeature.prototype._onBrush = function (eventParam) {
  48225. var areas = eventParam.areas;
  48226. if (!eventParam.isEnd || !areas.length) {
  48227. return;
  48228. }
  48229. var snapshot = {};
  48230. var ecModel = this.ecModel;
  48231. this._brushController.updateCovers([]); // remove cover
  48232. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  48233. include: ['grid']
  48234. });
  48235. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  48236. if (coordSys.type !== 'cartesian2d') {
  48237. return;
  48238. }
  48239. var brushType = area.brushType;
  48240. if (brushType === 'rect') {
  48241. setBatch('x', coordSys, coordRange[0]);
  48242. setBatch('y', coordSys, coordRange[1]);
  48243. } else {
  48244. setBatch({
  48245. lineX: 'x',
  48246. lineY: 'y'
  48247. }[brushType], coordSys, coordRange);
  48248. }
  48249. });
  48250. push(ecModel, snapshot);
  48251. this._dispatchZoomAction(snapshot);
  48252. function setBatch(dimName, coordSys, minMax) {
  48253. var axis = coordSys.getAxis(dimName);
  48254. var axisModel = axis.model;
  48255. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  48256. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  48257. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  48258. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  48259. }
  48260. dataZoomModel && (snapshot[dataZoomModel.id] = {
  48261. dataZoomId: dataZoomModel.id,
  48262. startValue: minMax[0],
  48263. endValue: minMax[1]
  48264. });
  48265. }
  48266. function findDataZoom(dimName, axisModel, ecModel) {
  48267. var found;
  48268. ecModel.eachComponent({
  48269. mainType: 'dataZoom',
  48270. subType: 'select'
  48271. }, function (dzModel) {
  48272. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  48273. has && (found = dzModel);
  48274. });
  48275. return found;
  48276. }
  48277. };
  48278. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  48279. var batch = []; // Convert from hash map to array.
  48280. each$6(snapshot, function (batchItem, dataZoomId) {
  48281. batch.push(clone(batchItem));
  48282. });
  48283. batch.length && this.api.dispatchAction({
  48284. type: 'dataZoom',
  48285. from: this.uid,
  48286. batch: batch
  48287. });
  48288. };
  48289. DataZoomFeature.getDefaultOption = function (ecModel) {
  48290. var defaultOption = {
  48291. show: true,
  48292. filterMode: 'filter',
  48293. // Icon group
  48294. icon: {
  48295. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  48296. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  48297. },
  48298. // `zoom`, `back`
  48299. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  48300. brushStyle: {
  48301. borderWidth: 0,
  48302. color: 'rgba(210,219,238,0.2)'
  48303. }
  48304. };
  48305. return defaultOption;
  48306. };
  48307. return DataZoomFeature;
  48308. }(ToolboxFeature);
  48309. var handlers = {
  48310. zoom: function () {
  48311. var nextActive = !this._isZoomActive;
  48312. this.api.dispatchAction({
  48313. type: 'takeGlobalCursor',
  48314. key: 'dataZoomSelect',
  48315. dataZoomSelectActive: nextActive
  48316. });
  48317. },
  48318. back: function () {
  48319. this._dispatchZoomAction(pop(this.ecModel));
  48320. }
  48321. };
  48322. function makeAxisFinder(dzFeatureModel) {
  48323. var setting = {
  48324. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  48325. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  48326. xAxisId: dzFeatureModel.get('xAxisId', true),
  48327. yAxisId: dzFeatureModel.get('yAxisId', true)
  48328. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  48329. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  48330. // Some old cases set like this below to close yAxis control but leave xAxis control:
  48331. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  48332. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  48333. setting.xAxisIndex = 'all';
  48334. }
  48335. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  48336. setting.yAxisIndex = 'all';
  48337. }
  48338. return setting;
  48339. }
  48340. function updateBackBtnStatus(featureModel, ecModel) {
  48341. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  48342. }
  48343. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  48344. var zoomActive = view._isZoomActive;
  48345. if (payload && payload.type === 'takeGlobalCursor') {
  48346. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  48347. }
  48348. view._isZoomActive = zoomActive;
  48349. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  48350. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  48351. include: ['grid']
  48352. });
  48353. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  48354. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  48355. });
  48356. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  48357. brushType: 'auto',
  48358. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  48359. } : false);
  48360. }
  48361. registerInternalOptionCreator('dataZoom', function (ecModel) {
  48362. var toolboxModel = ecModel.getComponent('toolbox', 0);
  48363. var featureDataZoomPath = ['feature', 'dataZoom'];
  48364. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  48365. return;
  48366. }
  48367. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  48368. var dzOptions = [];
  48369. var finder = makeAxisFinder(dzFeatureModel);
  48370. var finderResult = parseFinder(ecModel, finder);
  48371. each$6(finderResult.xAxisModels, function (axisModel) {
  48372. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  48373. });
  48374. each$6(finderResult.yAxisModels, function (axisModel) {
  48375. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  48376. });
  48377. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  48378. var axisIndex = axisModel.componentIndex;
  48379. var newOpt = {
  48380. type: 'select',
  48381. $fromToolbox: true,
  48382. // Default to be filter
  48383. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  48384. // Id for merge mapping.
  48385. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  48386. };
  48387. newOpt[axisIndexPropName] = axisIndex;
  48388. dzOptions.push(newOpt);
  48389. }
  48390. return dzOptions;
  48391. });
  48392. function install$b(registers) {
  48393. registers.registerComponentModel(ToolboxModel);
  48394. registers.registerComponentView(ToolboxView);
  48395. registerFeature('saveAsImage', SaveAsImage);
  48396. registerFeature('magicType', MagicType);
  48397. registerFeature('dataView', DataView);
  48398. registerFeature('dataZoom', DataZoomFeature);
  48399. registerFeature('restore', RestoreOption);
  48400. use(install$a);
  48401. }
  48402. var TooltipModel =
  48403. /** @class */
  48404. function (_super) {
  48405. __extends(TooltipModel, _super);
  48406. function TooltipModel() {
  48407. var _this = _super !== null && _super.apply(this, arguments) || this;
  48408. _this.type = TooltipModel.type;
  48409. return _this;
  48410. }
  48411. TooltipModel.type = 'tooltip';
  48412. TooltipModel.dependencies = ['axisPointer'];
  48413. TooltipModel.defaultOption = {
  48414. // zlevel: 0,
  48415. z: 60,
  48416. show: true,
  48417. // tooltip main content
  48418. showContent: true,
  48419. // 'trigger' only works on coordinate system.
  48420. // 'item' | 'axis' | 'none'
  48421. trigger: 'item',
  48422. // 'click' | 'mousemove' | 'none'
  48423. triggerOn: 'mousemove|click',
  48424. alwaysShowContent: false,
  48425. displayMode: 'single',
  48426. renderMode: 'auto',
  48427. // whether restraint content inside viewRect.
  48428. // If renderMode: 'richText', default true.
  48429. // If renderMode: 'html', defaut false (for backward compat).
  48430. confine: null,
  48431. showDelay: 0,
  48432. hideDelay: 100,
  48433. // Animation transition time, unit is second
  48434. transitionDuration: 0.4,
  48435. enterable: false,
  48436. backgroundColor: '#fff',
  48437. // box shadow
  48438. shadowBlur: 10,
  48439. shadowColor: 'rgba(0, 0, 0, .2)',
  48440. shadowOffsetX: 1,
  48441. shadowOffsetY: 2,
  48442. // tooltip border radius, unit is px, default is 4
  48443. borderRadius: 4,
  48444. // tooltip border width, unit is px, default is 0 (no border)
  48445. borderWidth: 1,
  48446. // Tooltip inside padding, default is 5 for all direction
  48447. // Array is allowed to set up, right, bottom, left, same with css
  48448. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  48449. padding: null,
  48450. // Extra css text
  48451. extraCssText: '',
  48452. // axis indicator, trigger by axis
  48453. axisPointer: {
  48454. // default is line
  48455. // legal values: 'line' | 'shadow' | 'cross'
  48456. type: 'line',
  48457. // Valid when type is line, appoint tooltip line locate on which line. Optional
  48458. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  48459. // default is 'auto', chose the axis which type is category.
  48460. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  48461. axis: 'auto',
  48462. animation: 'auto',
  48463. animationDurationUpdate: 200,
  48464. animationEasingUpdate: 'exponentialOut',
  48465. crossStyle: {
  48466. color: '#999',
  48467. width: 1,
  48468. type: 'dashed',
  48469. // TODO formatter
  48470. textStyle: {}
  48471. } // lineStyle and shadowStyle should not be specified here,
  48472. // otherwise it will always override those styles on option.axisPointer.
  48473. },
  48474. textStyle: {
  48475. color: '#666',
  48476. fontSize: 14
  48477. }
  48478. };
  48479. return TooltipModel;
  48480. }(ComponentModel);
  48481. /* global document */
  48482. function shouldTooltipConfine(tooltipModel) {
  48483. var confineOption = tooltipModel.get('confine');
  48484. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  48485. : tooltipModel.get('renderMode') === 'richText';
  48486. }
  48487. function testStyle(styleProps) {
  48488. if (!env.domSupported) {
  48489. return;
  48490. }
  48491. var style = document.documentElement.style;
  48492. for (var i = 0, len = styleProps.length; i < len; i++) {
  48493. if (styleProps[i] in style) {
  48494. return styleProps[i];
  48495. }
  48496. }
  48497. }
  48498. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  48499. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  48500. function toCSSVendorPrefix(styleVendor, styleProp) {
  48501. if (!styleVendor) {
  48502. return styleProp;
  48503. }
  48504. styleProp = toCamelCase(styleProp, true);
  48505. var idx = styleVendor.indexOf(styleProp);
  48506. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  48507. return styleVendor.toLowerCase();
  48508. }
  48509. function getComputedStyle(el, style) {
  48510. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  48511. return stl ? style ? stl[style] : stl : null;
  48512. }
  48513. /* global document, window */
  48514. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  48515. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  48516. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  48517. function mirrorPos(pos) {
  48518. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  48519. return pos;
  48520. }
  48521. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  48522. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  48523. return '';
  48524. }
  48525. var backgroundColor = tooltipModel.get('backgroundColor');
  48526. var borderWidth = tooltipModel.get('borderWidth');
  48527. borderColor = convertToColorString(borderColor);
  48528. var arrowPos = mirrorPos(arrowPosition);
  48529. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  48530. var positionStyle = '';
  48531. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  48532. var rotateDeg;
  48533. if (indexOf(['left', 'right'], arrowPos) > -1) {
  48534. positionStyle += 'top:50%';
  48535. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  48536. } else {
  48537. positionStyle += 'left:50%';
  48538. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  48539. }
  48540. var rotateRadian = rotateDeg * Math.PI / 180;
  48541. var arrowWH = arrowSize + borderWidth;
  48542. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  48543. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  48544. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  48545. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  48546. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  48547. return "<div style=\"" + styleCss.join('') + "\"></div>";
  48548. }
  48549. function assembleTransition(duration, onlyFade) {
  48550. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  48551. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  48552. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  48553. if (!onlyFade) {
  48554. transitionOption = " " + duration + "s " + transitionCurve;
  48555. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  48556. }
  48557. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  48558. }
  48559. function assembleTransform(x, y, toString) {
  48560. // If using float on style, the final width of the dom might
  48561. // keep changing slightly while mouse move. So `toFixed(0)` them.
  48562. var x0 = x.toFixed(0) + 'px';
  48563. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  48564. if (!env.transformSupported) {
  48565. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  48566. } // support transform
  48567. var is3d = env.transform3dSupported;
  48568. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  48569. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  48570. }
  48571. /**
  48572. * @param {Object} textStyle
  48573. * @return {string}
  48574. * @inner
  48575. */
  48576. function assembleFont(textStyleModel) {
  48577. var cssText = [];
  48578. var fontSize = textStyleModel.get('fontSize');
  48579. var color = textStyleModel.getTextColor();
  48580. color && cssText.push('color:' + color);
  48581. cssText.push('font:' + textStyleModel.getFont());
  48582. fontSize // @ts-ignore, leave it to the tooltip refactor.
  48583. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  48584. var shadowColor = textStyleModel.get('textShadowColor');
  48585. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  48586. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  48587. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  48588. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  48589. each(['decoration', 'align'], function (name) {
  48590. var val = textStyleModel.get(name);
  48591. val && cssText.push('text-' + name + ':' + val);
  48592. });
  48593. return cssText.join(';');
  48594. }
  48595. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  48596. var cssText = [];
  48597. var transitionDuration = tooltipModel.get('transitionDuration');
  48598. var backgroundColor = tooltipModel.get('backgroundColor');
  48599. var shadowBlur = tooltipModel.get('shadowBlur');
  48600. var shadowColor = tooltipModel.get('shadowColor');
  48601. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  48602. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  48603. var textStyleModel = tooltipModel.getModel('textStyle');
  48604. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  48605. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  48606. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  48607. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  48608. if (backgroundColor) {
  48609. cssText.push('background-color:' + backgroundColor);
  48610. } // Border style
  48611. each(['width', 'color', 'radius'], function (name) {
  48612. var borderName = 'border-' + name;
  48613. var camelCase = toCamelCase(borderName);
  48614. var val = tooltipModel.get(camelCase);
  48615. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  48616. }); // Text style
  48617. cssText.push(assembleFont(textStyleModel)); // Padding
  48618. if (padding != null) {
  48619. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  48620. }
  48621. return cssText.join(';') + ';';
  48622. } // If not able to make, do not modify the input `out`.
  48623. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  48624. var zrPainter = zr && zr.painter;
  48625. if (appendToBody) {
  48626. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  48627. if (zrViewportRoot) {
  48628. // Some APPs might use scale on body, so we support CSS transform here.
  48629. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  48630. }
  48631. } else {
  48632. out[0] = zrX;
  48633. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  48634. // the sibling of canvas root. So padding of ec container
  48635. // should be considered here.
  48636. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  48637. if (viewportRootOffset) {
  48638. out[0] += viewportRootOffset.offsetLeft;
  48639. out[1] += viewportRootOffset.offsetTop;
  48640. }
  48641. }
  48642. out[2] = out[0] / zr.getWidth();
  48643. out[3] = out[1] / zr.getHeight();
  48644. }
  48645. var TooltipHTMLContent =
  48646. /** @class */
  48647. function () {
  48648. function TooltipHTMLContent(container, api, opt) {
  48649. this._show = false;
  48650. this._styleCoord = [0, 0, 0, 0];
  48651. this._enterable = true;
  48652. this._alwaysShowContent = false;
  48653. this._firstShow = true;
  48654. this._longHide = true;
  48655. if (env.wxa) {
  48656. return null;
  48657. }
  48658. var el = document.createElement('div'); // TODO: TYPE
  48659. el.domBelongToZr = true;
  48660. this.el = el;
  48661. var zr = this._zr = api.getZr();
  48662. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  48663. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  48664. if (appendToBody) {
  48665. document.body.appendChild(el);
  48666. } else {
  48667. container.appendChild(el);
  48668. }
  48669. this._container = container; // FIXME
  48670. // Is it needed to trigger zr event manually if
  48671. // the browser do not support `pointer-events: none`.
  48672. var self = this;
  48673. el.onmouseenter = function () {
  48674. // clear the timeout in hideLater and keep showing tooltip
  48675. if (self._enterable) {
  48676. clearTimeout(self._hideTimeout);
  48677. self._show = true;
  48678. }
  48679. self._inContent = true;
  48680. };
  48681. el.onmousemove = function (e) {
  48682. e = e || window.event;
  48683. if (!self._enterable) {
  48684. // `pointer-events: none` is set to tooltip content div
  48685. // if `enterable` is set as `false`, and `el.onmousemove`
  48686. // can not be triggered. But in browser that do not
  48687. // support `pointer-events`, we need to do this:
  48688. // Try trigger zrender event to avoid mouse
  48689. // in and out shape too frequently
  48690. var handler = zr.handler;
  48691. var zrViewportRoot = zr.painter.getViewportRoot();
  48692. normalizeEvent(zrViewportRoot, e, true);
  48693. handler.dispatch('mousemove', e);
  48694. }
  48695. };
  48696. el.onmouseleave = function () {
  48697. // set `_inContent` to `false` before `hideLater`
  48698. self._inContent = false;
  48699. if (self._enterable) {
  48700. if (self._show) {
  48701. self.hideLater(self._hideDelay);
  48702. }
  48703. }
  48704. };
  48705. }
  48706. /**
  48707. * Update when tooltip is rendered
  48708. */
  48709. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  48710. // FIXME
  48711. // Move this logic to ec main?
  48712. var container = this._container;
  48713. var position = getComputedStyle(container, 'position');
  48714. var domStyle = container.style;
  48715. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  48716. domStyle.position = 'relative';
  48717. } // move tooltip if chart resized
  48718. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  48719. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  48720. this._alwaysShowContent = alwaysShowContent; // update className
  48721. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  48722. // PENDING
  48723. // this.hide();
  48724. };
  48725. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  48726. clearTimeout(this._hideTimeout);
  48727. clearTimeout(this._longHideTimeout);
  48728. var el = this.el;
  48729. var style = el.style;
  48730. var styleCoord = this._styleCoord;
  48731. if (!el.innerHTML) {
  48732. style.display = 'none';
  48733. } else {
  48734. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  48735. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '') // If mouse occasionally move over the tooltip, a mouseout event will be
  48736. // triggered by canvas, and cause some unexpectable result like dragging
  48737. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  48738. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  48739. // scenario.
  48740. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  48741. }
  48742. this._show = true;
  48743. this._firstShow = false;
  48744. this._longHide = false;
  48745. };
  48746. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  48747. var el = this.el;
  48748. if (content == null) {
  48749. el.innerHTML = '';
  48750. return;
  48751. }
  48752. var arrow = '';
  48753. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  48754. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  48755. }
  48756. if (isString(content)) {
  48757. el.innerHTML = content + arrow;
  48758. } else if (content) {
  48759. // Clear previous
  48760. el.innerHTML = '';
  48761. if (!isArray(content)) {
  48762. content = [content];
  48763. }
  48764. for (var i = 0; i < content.length; i++) {
  48765. if (isDom(content[i]) && content[i].parentNode !== el) {
  48766. el.appendChild(content[i]);
  48767. }
  48768. } // no arrow if empty
  48769. if (arrow && el.childNodes.length) {
  48770. // no need to create a new parent element, but it's not supported by IE 10 and older.
  48771. // const arrowEl = document.createRange().createContextualFragment(arrow);
  48772. var arrowEl = document.createElement('div');
  48773. arrowEl.innerHTML = arrow;
  48774. el.appendChild(arrowEl);
  48775. }
  48776. }
  48777. };
  48778. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  48779. this._enterable = enterable;
  48780. };
  48781. TooltipHTMLContent.prototype.getSize = function () {
  48782. var el = this.el;
  48783. return [el.offsetWidth, el.offsetHeight];
  48784. };
  48785. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  48786. var styleCoord = this._styleCoord;
  48787. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  48788. if (styleCoord[0] != null && styleCoord[1] != null) {
  48789. var style_1 = this.el.style;
  48790. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  48791. each(transforms, function (transform) {
  48792. style_1[transform[0]] = transform[1];
  48793. });
  48794. }
  48795. };
  48796. /**
  48797. * when `alwaysShowContent` is true,
  48798. * move the tooltip after chart resized
  48799. */
  48800. TooltipHTMLContent.prototype._moveIfResized = function () {
  48801. // The ratio of left to width
  48802. var ratioX = this._styleCoord[2]; // The ratio of top to height
  48803. var ratioY = this._styleCoord[3];
  48804. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  48805. };
  48806. TooltipHTMLContent.prototype.hide = function () {
  48807. var _this = this;
  48808. var style = this.el.style;
  48809. style.visibility = 'hidden';
  48810. style.opacity = '0';
  48811. env.transform3dSupported && (style.willChange = '');
  48812. this._show = false;
  48813. this._longHideTimeout = setTimeout(function () {
  48814. return _this._longHide = true;
  48815. }, 500);
  48816. };
  48817. TooltipHTMLContent.prototype.hideLater = function (time) {
  48818. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  48819. if (time) {
  48820. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  48821. this._show = false;
  48822. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  48823. } else {
  48824. this.hide();
  48825. }
  48826. }
  48827. };
  48828. TooltipHTMLContent.prototype.isShow = function () {
  48829. return this._show;
  48830. };
  48831. TooltipHTMLContent.prototype.dispose = function () {
  48832. this.el.parentNode.removeChild(this.el);
  48833. };
  48834. return TooltipHTMLContent;
  48835. }();
  48836. var TooltipRichContent =
  48837. /** @class */
  48838. function () {
  48839. function TooltipRichContent(api) {
  48840. this._show = false;
  48841. this._styleCoord = [0, 0, 0, 0];
  48842. this._alwaysShowContent = false;
  48843. this._enterable = true;
  48844. this._zr = api.getZr();
  48845. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  48846. }
  48847. /**
  48848. * Update when tooltip is rendered
  48849. */
  48850. TooltipRichContent.prototype.update = function (tooltipModel) {
  48851. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  48852. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  48853. this._alwaysShowContent = alwaysShowContent;
  48854. };
  48855. TooltipRichContent.prototype.show = function () {
  48856. if (this._hideTimeout) {
  48857. clearTimeout(this._hideTimeout);
  48858. }
  48859. this.el.show();
  48860. this._show = true;
  48861. };
  48862. /**
  48863. * Set tooltip content
  48864. */
  48865. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  48866. var _this = this;
  48867. if (isObject(content)) {
  48868. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  48869. }
  48870. if (this.el) {
  48871. this._zr.remove(this.el);
  48872. }
  48873. var textStyleModel = tooltipModel.getModel('textStyle');
  48874. this.el = new ZRText({
  48875. style: {
  48876. rich: markupStyleCreator.richTextStyles,
  48877. text: content,
  48878. lineHeight: 22,
  48879. borderWidth: 1,
  48880. borderColor: borderColor,
  48881. textShadowColor: textStyleModel.get('textShadowColor'),
  48882. fill: tooltipModel.get(['textStyle', 'color']),
  48883. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  48884. verticalAlign: 'top',
  48885. align: 'left'
  48886. },
  48887. z: tooltipModel.get('z')
  48888. });
  48889. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  48890. _this.el.style[propName] = tooltipModel.get(propName);
  48891. });
  48892. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  48893. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  48894. });
  48895. this._zr.add(this.el);
  48896. var self = this;
  48897. this.el.on('mouseover', function () {
  48898. // clear the timeout in hideLater and keep showing tooltip
  48899. if (self._enterable) {
  48900. clearTimeout(self._hideTimeout);
  48901. self._show = true;
  48902. }
  48903. self._inContent = true;
  48904. });
  48905. this.el.on('mouseout', function () {
  48906. if (self._enterable) {
  48907. if (self._show) {
  48908. self.hideLater(self._hideDelay);
  48909. }
  48910. }
  48911. self._inContent = false;
  48912. });
  48913. };
  48914. TooltipRichContent.prototype.setEnterable = function (enterable) {
  48915. this._enterable = enterable;
  48916. };
  48917. TooltipRichContent.prototype.getSize = function () {
  48918. var el = this.el;
  48919. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  48920. // if overflow, it will be cut. So calculate them accurately.
  48921. var shadowOuterSize = calcShadowOuterSize(el.style);
  48922. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  48923. };
  48924. TooltipRichContent.prototype.moveTo = function (x, y) {
  48925. var el = this.el;
  48926. if (el) {
  48927. var styleCoord = this._styleCoord;
  48928. makeStyleCoord$1(styleCoord, this._zr, x, y);
  48929. x = styleCoord[0];
  48930. y = styleCoord[1];
  48931. var style = el.style;
  48932. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  48933. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  48934. el.x = x + borderWidth + shadowOuterSize.left;
  48935. el.y = y + borderWidth + shadowOuterSize.top;
  48936. el.markRedraw();
  48937. }
  48938. };
  48939. /**
  48940. * when `alwaysShowContent` is true,
  48941. * move the tooltip after chart resized
  48942. */
  48943. TooltipRichContent.prototype._moveIfResized = function () {
  48944. // The ratio of left to width
  48945. var ratioX = this._styleCoord[2]; // The ratio of top to height
  48946. var ratioY = this._styleCoord[3];
  48947. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  48948. };
  48949. TooltipRichContent.prototype.hide = function () {
  48950. if (this.el) {
  48951. this.el.hide();
  48952. }
  48953. this._show = false;
  48954. };
  48955. TooltipRichContent.prototype.hideLater = function (time) {
  48956. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  48957. if (time) {
  48958. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  48959. this._show = false;
  48960. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  48961. } else {
  48962. this.hide();
  48963. }
  48964. }
  48965. };
  48966. TooltipRichContent.prototype.isShow = function () {
  48967. return this._show;
  48968. };
  48969. TooltipRichContent.prototype.dispose = function () {
  48970. this._zr.remove(this.el);
  48971. };
  48972. return TooltipRichContent;
  48973. }();
  48974. function mathMaxWith0(val) {
  48975. return Math.max(0, val);
  48976. }
  48977. function calcShadowOuterSize(style) {
  48978. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  48979. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  48980. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  48981. return {
  48982. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  48983. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  48984. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  48985. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  48986. };
  48987. }
  48988. function makeStyleCoord$1(out, zr, zrX, zrY) {
  48989. out[0] = zrX;
  48990. out[1] = zrY;
  48991. out[2] = out[0] / zr.getWidth();
  48992. out[3] = out[1] / zr.getHeight();
  48993. }
  48994. var proxyRect = new Rect({
  48995. shape: {
  48996. x: -1,
  48997. y: -1,
  48998. width: 2,
  48999. height: 2
  49000. }
  49001. });
  49002. var TooltipView =
  49003. /** @class */
  49004. function (_super) {
  49005. __extends(TooltipView, _super);
  49006. function TooltipView() {
  49007. var _this = _super !== null && _super.apply(this, arguments) || this;
  49008. _this.type = TooltipView.type;
  49009. return _this;
  49010. }
  49011. TooltipView.prototype.init = function (ecModel, api) {
  49012. if (env.node || !api.getDom()) {
  49013. return;
  49014. }
  49015. var tooltipModel = ecModel.getComponent('tooltip');
  49016. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  49017. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  49018. appendToBody: tooltipModel.get('appendToBody', true)
  49019. });
  49020. };
  49021. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  49022. if (env.node || !api.getDom()) {
  49023. return;
  49024. } // Reset
  49025. this.group.removeAll();
  49026. this._tooltipModel = tooltipModel;
  49027. this._ecModel = ecModel;
  49028. this._api = api;
  49029. var tooltipContent = this._tooltipContent;
  49030. tooltipContent.update(tooltipModel);
  49031. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  49032. this._initGlobalListener();
  49033. this._keepShow(); // PENDING
  49034. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  49035. // which causes that the `updatePosition` function was also called frequently.
  49036. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  49037. // To avoid frequent triggering,
  49038. // consider throttling it in 50ms when transition is enabled
  49039. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  49040. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  49041. } else {
  49042. clear(this, '_updatePosition');
  49043. }
  49044. };
  49045. TooltipView.prototype._initGlobalListener = function () {
  49046. var tooltipModel = this._tooltipModel;
  49047. var triggerOn = tooltipModel.get('triggerOn');
  49048. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  49049. // If 'none', it is not controlled by mouse totally.
  49050. if (triggerOn !== 'none') {
  49051. if (triggerOn.indexOf(currTrigger) >= 0) {
  49052. this._tryShow(e, dispatchAction);
  49053. } else if (currTrigger === 'leave') {
  49054. this._hide(dispatchAction);
  49055. }
  49056. }
  49057. }, this));
  49058. };
  49059. TooltipView.prototype._keepShow = function () {
  49060. var tooltipModel = this._tooltipModel;
  49061. var ecModel = this._ecModel;
  49062. var api = this._api;
  49063. var triggerOn = tooltipModel.get('triggerOn'); // Try to keep the tooltip show when refreshing
  49064. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  49065. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  49066. // which is not expected.
  49067. && triggerOn !== 'none' && triggerOn !== 'click') {
  49068. var self_1 = this;
  49069. clearTimeout(this._refreshUpdateTimeout);
  49070. this._refreshUpdateTimeout = setTimeout(function () {
  49071. // Show tip next tick after other charts are rendered
  49072. // In case highlight action has wrong result
  49073. // FIXME
  49074. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  49075. x: self_1._lastX,
  49076. y: self_1._lastY,
  49077. dataByCoordSys: self_1._lastDataByCoordSys
  49078. });
  49079. });
  49080. }
  49081. };
  49082. /**
  49083. * Show tip manually by
  49084. * dispatchAction({
  49085. * type: 'showTip',
  49086. * x: 10,
  49087. * y: 10
  49088. * });
  49089. * Or
  49090. * dispatchAction({
  49091. * type: 'showTip',
  49092. * seriesIndex: 0,
  49093. * dataIndex or dataIndexInside or name
  49094. * });
  49095. *
  49096. * TODO Batch
  49097. */
  49098. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  49099. if (payload.from === this.uid || env.node || !api.getDom()) {
  49100. return;
  49101. }
  49102. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  49103. this._ticket = ''; // When triggered from axisPointer.
  49104. var dataByCoordSys = payload.dataByCoordSys;
  49105. var cmptRef = findComponentReference(payload, ecModel, api);
  49106. if (cmptRef) {
  49107. var rect = cmptRef.el.getBoundingRect().clone();
  49108. rect.applyTransform(cmptRef.el.transform);
  49109. this._tryShow({
  49110. offsetX: rect.x + rect.width / 2,
  49111. offsetY: rect.y + rect.height / 2,
  49112. target: cmptRef.el,
  49113. position: payload.position,
  49114. // When manully trigger, the mouse is not on the el, so we'd better to
  49115. // position tooltip on the bottom of the el and display arrow is possible.
  49116. positionDefault: 'bottom'
  49117. }, dispatchAction);
  49118. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  49119. var el = proxyRect;
  49120. el.x = payload.x;
  49121. el.y = payload.y;
  49122. el.update();
  49123. getECData(el).tooltipConfig = {
  49124. name: null,
  49125. option: payload.tooltip
  49126. }; // Manually show tooltip while view is not using zrender elements.
  49127. this._tryShow({
  49128. offsetX: payload.x,
  49129. offsetY: payload.y,
  49130. target: el
  49131. }, dispatchAction);
  49132. } else if (dataByCoordSys) {
  49133. this._tryShow({
  49134. offsetX: payload.x,
  49135. offsetY: payload.y,
  49136. position: payload.position,
  49137. dataByCoordSys: dataByCoordSys,
  49138. tooltipOption: payload.tooltipOption
  49139. }, dispatchAction);
  49140. } else if (payload.seriesIndex != null) {
  49141. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  49142. return;
  49143. }
  49144. var pointInfo = findPointFromSeries(payload, ecModel);
  49145. var cx = pointInfo.point[0];
  49146. var cy = pointInfo.point[1];
  49147. if (cx != null && cy != null) {
  49148. this._tryShow({
  49149. offsetX: cx,
  49150. offsetY: cy,
  49151. target: pointInfo.el,
  49152. position: payload.position,
  49153. // When manully trigger, the mouse is not on the el, so we'd better to
  49154. // position tooltip on the bottom of the el and display arrow is possible.
  49155. positionDefault: 'bottom'
  49156. }, dispatchAction);
  49157. }
  49158. } else if (payload.x != null && payload.y != null) {
  49159. // FIXME
  49160. // should wrap dispatchAction like `axisPointer/globalListener` ?
  49161. api.dispatchAction({
  49162. type: 'updateAxisPointer',
  49163. x: payload.x,
  49164. y: payload.y
  49165. });
  49166. this._tryShow({
  49167. offsetX: payload.x,
  49168. offsetY: payload.y,
  49169. position: payload.position,
  49170. target: api.getZr().findHover(payload.x, payload.y).target
  49171. }, dispatchAction);
  49172. }
  49173. };
  49174. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  49175. var tooltipContent = this._tooltipContent;
  49176. if (this._tooltipModel) {
  49177. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  49178. }
  49179. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  49180. if (payload.from !== this.uid) {
  49181. this._hide(makeDispatchAction$1(payload, api));
  49182. }
  49183. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  49184. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  49185. // and tooltip.
  49186. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  49187. var seriesIndex = payload.seriesIndex;
  49188. var dataIndex = payload.dataIndex; // @ts-ignore
  49189. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  49190. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  49191. return;
  49192. }
  49193. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  49194. if (!seriesModel) {
  49195. return;
  49196. }
  49197. var data = seriesModel.getData();
  49198. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  49199. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  49200. return;
  49201. }
  49202. api.dispatchAction({
  49203. type: 'updateAxisPointer',
  49204. seriesIndex: seriesIndex,
  49205. dataIndex: dataIndex,
  49206. position: payload.position
  49207. });
  49208. return true;
  49209. };
  49210. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  49211. var el = e.target;
  49212. var tooltipModel = this._tooltipModel;
  49213. if (!tooltipModel) {
  49214. return;
  49215. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  49216. this._lastX = e.offsetX;
  49217. this._lastY = e.offsetY;
  49218. var dataByCoordSys = e.dataByCoordSys;
  49219. if (dataByCoordSys && dataByCoordSys.length) {
  49220. this._showAxisTooltip(dataByCoordSys, e);
  49221. } else if (el) {
  49222. this._lastDataByCoordSys = null;
  49223. var seriesDispatcher_1;
  49224. var cmptDispatcher_1;
  49225. findEventDispatcher(el, function (target) {
  49226. // Always show item tooltip if mouse is on the element with dataIndex
  49227. if (getECData(target).dataIndex != null) {
  49228. seriesDispatcher_1 = target;
  49229. return true;
  49230. } // Tooltip provided directly. Like legend.
  49231. if (getECData(target).tooltipConfig != null) {
  49232. cmptDispatcher_1 = target;
  49233. return true;
  49234. }
  49235. }, true);
  49236. if (seriesDispatcher_1) {
  49237. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  49238. } else if (cmptDispatcher_1) {
  49239. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  49240. } else {
  49241. this._hide(dispatchAction);
  49242. }
  49243. } else {
  49244. this._lastDataByCoordSys = null;
  49245. this._hide(dispatchAction);
  49246. }
  49247. };
  49248. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  49249. // showDelay is used in this case: tooltip.enterable is set
  49250. // as true. User intent to move mouse into tooltip and click
  49251. // something. `showDelay` makes it easier to enter the content
  49252. // but tooltip do not move immediately.
  49253. var delay = tooltipModel.get('showDelay');
  49254. cb = bind(cb, this);
  49255. clearTimeout(this._showTimout);
  49256. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  49257. };
  49258. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  49259. var ecModel = this._ecModel;
  49260. var globalTooltipModel = this._tooltipModel;
  49261. var point = [e.offsetX, e.offsetY];
  49262. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  49263. var renderMode = this._renderMode;
  49264. var cbParamsList = [];
  49265. var articleMarkup = createTooltipMarkup('section', {
  49266. blocks: [],
  49267. noHeader: true
  49268. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  49269. var markupTextArrLegacy = [];
  49270. var markupStyleCreator = new TooltipMarkupStyleCreator();
  49271. each(dataByCoordSys, function (itemCoordSys) {
  49272. each(itemCoordSys.dataByAxis, function (axisItem) {
  49273. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  49274. var axisValue = axisItem.value;
  49275. if (!axisModel || axisValue == null) {
  49276. return;
  49277. }
  49278. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  49279. var axisSectionMarkup = createTooltipMarkup('section', {
  49280. header: axisValueLabel,
  49281. noHeader: !trim(axisValueLabel),
  49282. sortBlocks: true,
  49283. blocks: []
  49284. });
  49285. articleMarkup.blocks.push(axisSectionMarkup);
  49286. each(axisItem.seriesDataIndices, function (idxItem) {
  49287. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  49288. var dataIndex = idxItem.dataIndexInside;
  49289. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  49290. if (cbParams.dataIndex < 0) {
  49291. return;
  49292. }
  49293. cbParams.axisDim = axisItem.axisDim;
  49294. cbParams.axisIndex = axisItem.axisIndex;
  49295. cbParams.axisType = axisItem.axisType;
  49296. cbParams.axisId = axisItem.axisId;
  49297. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  49298. value: axisValue
  49299. });
  49300. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  49301. // text in `formatter` callback and use those markers style.
  49302. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  49303. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  49304. var frag = seriesTooltipResult.frag;
  49305. if (frag) {
  49306. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  49307. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  49308. valueFormatter: valueFormatter
  49309. }, frag) : frag);
  49310. }
  49311. if (seriesTooltipResult.text) {
  49312. markupTextArrLegacy.push(seriesTooltipResult.text);
  49313. }
  49314. cbParamsList.push(cbParams);
  49315. });
  49316. });
  49317. }); // In most cases, the second axis is displays upper on the first one.
  49318. // So we reverse it to look better.
  49319. articleMarkup.blocks.reverse();
  49320. markupTextArrLegacy.reverse();
  49321. var positionExpr = e.position;
  49322. var orderMode = singleTooltipModel.get('order');
  49323. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  49324. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  49325. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  49326. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  49327. this._showOrMove(singleTooltipModel, function () {
  49328. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  49329. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  49330. } else {
  49331. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  49332. }
  49333. }); // Do not trigger events here, because this branch only be entered
  49334. // from dispatchAction.
  49335. };
  49336. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  49337. var ecModel = this._ecModel;
  49338. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  49339. // Used when mouseover on a element like markPoint or edge
  49340. // In which case, the data is not main data in series.
  49341. var seriesIndex = ecData.seriesIndex;
  49342. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  49343. var dataModel = ecData.dataModel || seriesModel;
  49344. var dataIndex = ecData.dataIndex;
  49345. var dataType = ecData.dataType;
  49346. var data = dataModel.getData(dataType);
  49347. var renderMode = this._renderMode;
  49348. var positionDefault = e.positionDefault;
  49349. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  49350. position: positionDefault
  49351. } : null);
  49352. var tooltipTrigger = tooltipModel.get('trigger');
  49353. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  49354. return;
  49355. }
  49356. var params = dataModel.getDataParams(dataIndex, dataType);
  49357. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  49358. // text in `formatter` callback and use those markers style.
  49359. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  49360. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  49361. var orderMode = tooltipModel.get('order');
  49362. var valueFormatter = tooltipModel.get('valueFormatter');
  49363. var frag = seriesTooltipResult.frag;
  49364. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  49365. valueFormatter: valueFormatter
  49366. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  49367. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  49368. this._showOrMove(tooltipModel, function () {
  49369. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  49370. }); // FIXME
  49371. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  49372. dispatchAction({
  49373. type: 'showTip',
  49374. dataIndexInside: dataIndex,
  49375. dataIndex: data.getRawIndex(dataIndex),
  49376. seriesIndex: seriesIndex,
  49377. from: this.uid
  49378. });
  49379. };
  49380. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  49381. var ecData = getECData(el);
  49382. var tooltipConfig = ecData.tooltipConfig;
  49383. var tooltipOpt = tooltipConfig.option || {};
  49384. if (isString(tooltipOpt)) {
  49385. var content = tooltipOpt;
  49386. tooltipOpt = {
  49387. content: content,
  49388. // Fixed formatter
  49389. formatter: content
  49390. };
  49391. }
  49392. var tooltipModelCascade = [tooltipOpt];
  49393. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  49394. if (cmpt) {
  49395. tooltipModelCascade.push(cmpt);
  49396. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  49397. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  49398. // by convention, we do not use it as the default formatter for component.
  49399. tooltipModelCascade.push({
  49400. formatter: tooltipOpt.content
  49401. });
  49402. var positionDefault = e.positionDefault;
  49403. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  49404. position: positionDefault
  49405. } : null);
  49406. var defaultHtml = subTooltipModel.get('content');
  49407. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  49408. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  49409. // only works on coordinate system. In fact, we have not found case
  49410. // that requires setting `trigger` nothing on component yet.
  49411. this._showOrMove(subTooltipModel, function () {
  49412. // Use formatterParams from element defined in component
  49413. // Avoid users modify it.
  49414. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  49415. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  49416. }); // If not dispatch showTip, tip may be hide triggered by axis.
  49417. dispatchAction({
  49418. type: 'showTip',
  49419. from: this.uid
  49420. });
  49421. };
  49422. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  49423. // Instead of top level tooltip.
  49424. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  49425. // Reset ticket
  49426. this._ticket = '';
  49427. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  49428. return;
  49429. }
  49430. var tooltipContent = this._tooltipContent;
  49431. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  49432. var formatter = tooltipModel.get('formatter');
  49433. positionExpr = positionExpr || tooltipModel.get('position');
  49434. var html = defaultHtml;
  49435. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  49436. var nearPointColor = nearPoint.color;
  49437. if (formatter) {
  49438. if (isString(formatter)) {
  49439. var useUTC = tooltipModel.ecModel.get('useUTC');
  49440. var params0 = isArray(params) ? params[0] : params;
  49441. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  49442. html = formatter;
  49443. if (isTimeAxis) {
  49444. html = format(params0.axisValue, html, useUTC);
  49445. }
  49446. html = formatTpl(html, params, true);
  49447. } else if (isFunction(formatter)) {
  49448. var callback = bind(function (cbTicket, html) {
  49449. if (cbTicket === this._ticket) {
  49450. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  49451. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  49452. }
  49453. }, this);
  49454. this._ticket = asyncTicket;
  49455. html = formatter(params, asyncTicket, callback);
  49456. } else {
  49457. html = formatter;
  49458. }
  49459. }
  49460. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  49461. tooltipContent.show(tooltipModel, nearPointColor);
  49462. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  49463. };
  49464. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  49465. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  49466. return {
  49467. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  49468. };
  49469. }
  49470. if (!isArray(tooltipDataParams)) {
  49471. return {
  49472. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  49473. };
  49474. }
  49475. };
  49476. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  49477. y, // Mouse y
  49478. content, params, el) {
  49479. var viewWidth = this._api.getWidth();
  49480. var viewHeight = this._api.getHeight();
  49481. positionExpr = positionExpr || tooltipModel.get('position');
  49482. var contentSize = content.getSize();
  49483. var align = tooltipModel.get('align');
  49484. var vAlign = tooltipModel.get('verticalAlign');
  49485. var rect = el && el.getBoundingRect().clone();
  49486. el && rect.applyTransform(el.transform);
  49487. if (isFunction(positionExpr)) {
  49488. // Callback of position can be an array or a string specify the position
  49489. positionExpr = positionExpr([x, y], params, content.el, rect, {
  49490. viewSize: [viewWidth, viewHeight],
  49491. contentSize: contentSize.slice()
  49492. });
  49493. }
  49494. if (isArray(positionExpr)) {
  49495. x = parsePercent$1(positionExpr[0], viewWidth);
  49496. y = parsePercent$1(positionExpr[1], viewHeight);
  49497. } else if (isObject(positionExpr)) {
  49498. var boxLayoutPosition = positionExpr;
  49499. boxLayoutPosition.width = contentSize[0];
  49500. boxLayoutPosition.height = contentSize[1];
  49501. var layoutRect = getLayoutRect(boxLayoutPosition, {
  49502. width: viewWidth,
  49503. height: viewHeight
  49504. });
  49505. x = layoutRect.x;
  49506. y = layoutRect.y;
  49507. align = null; // When positionExpr is left/top/right/bottom,
  49508. // align and verticalAlign will not work.
  49509. vAlign = null;
  49510. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  49511. else if (isString(positionExpr) && el) {
  49512. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  49513. x = pos[0];
  49514. y = pos[1];
  49515. } else {
  49516. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  49517. x = pos[0];
  49518. y = pos[1];
  49519. }
  49520. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  49521. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  49522. if (shouldTooltipConfine(tooltipModel)) {
  49523. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  49524. x = pos[0];
  49525. y = pos[1];
  49526. }
  49527. content.moveTo(x, y);
  49528. }; // FIXME
  49529. // Should we remove this but leave this to user?
  49530. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  49531. var lastCoordSys = this._lastDataByCoordSys;
  49532. var lastCbParamsList = this._cbParamsList;
  49533. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  49534. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  49535. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  49536. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  49537. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  49538. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  49539. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  49540. var thisItem = thisDataByAxis[indexAxis] || {};
  49541. var lastIndices = lastItem.seriesDataIndices || [];
  49542. var newIndices = thisItem.seriesDataIndices || [];
  49543. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  49544. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  49545. var newIdxItem = newIndices[j];
  49546. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  49547. }); // check is cbParams data value changed
  49548. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  49549. var seriesIdx = idxItem.seriesIndex;
  49550. var cbParams = cbParamsList[seriesIdx];
  49551. var lastCbParams = lastCbParamsList[seriesIdx];
  49552. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  49553. contentNotChanged = false;
  49554. }
  49555. });
  49556. });
  49557. });
  49558. this._lastDataByCoordSys = dataByCoordSys;
  49559. this._cbParamsList = cbParamsList;
  49560. return !!contentNotChanged;
  49561. };
  49562. TooltipView.prototype._hide = function (dispatchAction) {
  49563. // Do not directly hideLater here, because this behavior may be prevented
  49564. // in dispatchAction when showTip is dispatched.
  49565. // FIXME
  49566. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  49567. this._lastDataByCoordSys = null;
  49568. dispatchAction({
  49569. type: 'hideTip',
  49570. from: this.uid
  49571. });
  49572. };
  49573. TooltipView.prototype.dispose = function (ecModel, api) {
  49574. if (env.node || !api.getDom()) {
  49575. return;
  49576. }
  49577. clear(this, '_updatePosition');
  49578. this._tooltipContent.dispose();
  49579. unregister('itemTooltip', api);
  49580. };
  49581. TooltipView.type = 'tooltip';
  49582. return TooltipView;
  49583. }(ComponentView);
  49584. /**
  49585. * From top to bottom. (the last one should be globalTooltipModel);
  49586. */
  49587. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  49588. // Last is always tooltip model.
  49589. var ecModel = globalTooltipModel.ecModel;
  49590. var resultModel;
  49591. if (defaultTooltipOption) {
  49592. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  49593. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  49594. } else {
  49595. resultModel = globalTooltipModel;
  49596. }
  49597. for (var i = modelCascade.length - 1; i >= 0; i--) {
  49598. var tooltipOpt = modelCascade[i];
  49599. if (tooltipOpt) {
  49600. if (tooltipOpt instanceof Model) {
  49601. tooltipOpt = tooltipOpt.get('tooltip', true);
  49602. } // In each data item tooltip can be simply write:
  49603. // {
  49604. // value: 10,
  49605. // tooltip: 'Something you need to know'
  49606. // }
  49607. if (isString(tooltipOpt)) {
  49608. tooltipOpt = {
  49609. formatter: tooltipOpt
  49610. };
  49611. }
  49612. if (tooltipOpt) {
  49613. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  49614. }
  49615. }
  49616. }
  49617. return resultModel;
  49618. }
  49619. function makeDispatchAction$1(payload, api) {
  49620. return payload.dispatchAction || bind(api.dispatchAction, api);
  49621. }
  49622. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  49623. var size = content.getSize();
  49624. var width = size[0];
  49625. var height = size[1];
  49626. if (gapH != null) {
  49627. // Add extra 2 pixels for this case:
  49628. // At present the "values" in default tooltip are using CSS `float: right`.
  49629. // When the right edge of the tooltip box is on the right side of the
  49630. // viewport, the `float` layout might push the "values" to the second line.
  49631. if (x + width + gapH + 2 > viewWidth) {
  49632. x -= width + gapH;
  49633. } else {
  49634. x += gapH;
  49635. }
  49636. }
  49637. if (gapV != null) {
  49638. if (y + height + gapV > viewHeight) {
  49639. y -= height + gapV;
  49640. } else {
  49641. y += gapV;
  49642. }
  49643. }
  49644. return [x, y];
  49645. }
  49646. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  49647. var size = content.getSize();
  49648. var width = size[0];
  49649. var height = size[1];
  49650. x = Math.min(x + width, viewWidth) - width;
  49651. y = Math.min(y + height, viewHeight) - height;
  49652. x = Math.max(x, 0);
  49653. y = Math.max(y, 0);
  49654. return [x, y];
  49655. }
  49656. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  49657. var domWidth = contentSize[0];
  49658. var domHeight = contentSize[1];
  49659. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  49660. var x = 0;
  49661. var y = 0;
  49662. var rectWidth = rect.width;
  49663. var rectHeight = rect.height;
  49664. switch (position) {
  49665. case 'inside':
  49666. x = rect.x + rectWidth / 2 - domWidth / 2;
  49667. y = rect.y + rectHeight / 2 - domHeight / 2;
  49668. break;
  49669. case 'top':
  49670. x = rect.x + rectWidth / 2 - domWidth / 2;
  49671. y = rect.y - domHeight - offset;
  49672. break;
  49673. case 'bottom':
  49674. x = rect.x + rectWidth / 2 - domWidth / 2;
  49675. y = rect.y + rectHeight + offset;
  49676. break;
  49677. case 'left':
  49678. x = rect.x - domWidth - offset;
  49679. y = rect.y + rectHeight / 2 - domHeight / 2;
  49680. break;
  49681. case 'right':
  49682. x = rect.x + rectWidth + offset;
  49683. y = rect.y + rectHeight / 2 - domHeight / 2;
  49684. }
  49685. return [x, y];
  49686. }
  49687. function isCenterAlign(align) {
  49688. return align === 'center' || align === 'middle';
  49689. }
  49690. /**
  49691. * Find target component by payload like:
  49692. * ```js
  49693. * { legendId: 'some_id', name: 'xxx' }
  49694. * { toolboxIndex: 1, name: 'xxx' }
  49695. * { geoName: 'some_name', name: 'xxx' }
  49696. * ```
  49697. * PENDING: at present only
  49698. *
  49699. * If not found, return null/undefined.
  49700. */
  49701. function findComponentReference(payload, ecModel, api) {
  49702. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  49703. var componentMainType = queryOptionMap.keys()[0];
  49704. if (!componentMainType || componentMainType === 'series') {
  49705. return;
  49706. }
  49707. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  49708. useDefault: false,
  49709. enableAll: false,
  49710. enableNone: false
  49711. });
  49712. var model = queryResult.models[0];
  49713. if (!model) {
  49714. return;
  49715. }
  49716. var view = api.getViewOfComponentModel(model);
  49717. var el;
  49718. view.group.traverse(function (subEl) {
  49719. var tooltipConfig = getECData(subEl).tooltipConfig;
  49720. if (tooltipConfig && tooltipConfig.name === payload.name) {
  49721. el = subEl;
  49722. return true; // stop
  49723. }
  49724. });
  49725. if (el) {
  49726. return {
  49727. componentMainType: componentMainType,
  49728. componentIndex: model.componentIndex,
  49729. el: el
  49730. };
  49731. }
  49732. }
  49733. function install$c(registers) {
  49734. use(install$7);
  49735. registers.registerComponentModel(TooltipModel);
  49736. registers.registerComponentView(TooltipView);
  49737. /**
  49738. * @action
  49739. * @property {string} type
  49740. * @property {number} seriesIndex
  49741. * @property {number} dataIndex
  49742. * @property {number} [x]
  49743. * @property {number} [y]
  49744. */
  49745. registers.registerAction({
  49746. type: 'showTip',
  49747. event: 'showTip',
  49748. update: 'tooltip:manuallyShowTip'
  49749. }, noop);
  49750. registers.registerAction({
  49751. type: 'hideTip',
  49752. event: 'hideTip',
  49753. update: 'tooltip:manuallyHideTip'
  49754. }, noop);
  49755. }
  49756. var TitleModel =
  49757. /** @class */
  49758. function (_super) {
  49759. __extends(TitleModel, _super);
  49760. function TitleModel() {
  49761. var _this = _super !== null && _super.apply(this, arguments) || this;
  49762. _this.type = TitleModel.type;
  49763. _this.layoutMode = {
  49764. type: 'box',
  49765. ignoreSize: true
  49766. };
  49767. return _this;
  49768. }
  49769. TitleModel.type = 'title';
  49770. TitleModel.defaultOption = {
  49771. // zlevel: 0,
  49772. z: 6,
  49773. show: true,
  49774. text: '',
  49775. target: 'blank',
  49776. subtext: '',
  49777. subtarget: 'blank',
  49778. left: 0,
  49779. top: 0,
  49780. backgroundColor: 'rgba(0,0,0,0)',
  49781. borderColor: '#ccc',
  49782. borderWidth: 0,
  49783. padding: 5,
  49784. itemGap: 10,
  49785. textStyle: {
  49786. fontSize: 18,
  49787. fontWeight: 'bold',
  49788. color: '#464646'
  49789. },
  49790. subtextStyle: {
  49791. fontSize: 12,
  49792. color: '#6E7079'
  49793. }
  49794. };
  49795. return TitleModel;
  49796. }(ComponentModel); // View
  49797. var TitleView =
  49798. /** @class */
  49799. function (_super) {
  49800. __extends(TitleView, _super);
  49801. function TitleView() {
  49802. var _this = _super !== null && _super.apply(this, arguments) || this;
  49803. _this.type = TitleView.type;
  49804. return _this;
  49805. }
  49806. TitleView.prototype.render = function (titleModel, ecModel, api) {
  49807. this.group.removeAll();
  49808. if (!titleModel.get('show')) {
  49809. return;
  49810. }
  49811. var group = this.group;
  49812. var textStyleModel = titleModel.getModel('textStyle');
  49813. var subtextStyleModel = titleModel.getModel('subtextStyle');
  49814. var textAlign = titleModel.get('textAlign');
  49815. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  49816. var textEl = new ZRText({
  49817. style: createTextStyle(textStyleModel, {
  49818. text: titleModel.get('text'),
  49819. fill: textStyleModel.getTextColor()
  49820. }, {
  49821. disableBox: true
  49822. }),
  49823. z2: 10
  49824. });
  49825. var textRect = textEl.getBoundingRect();
  49826. var subText = titleModel.get('subtext');
  49827. var subTextEl = new ZRText({
  49828. style: createTextStyle(subtextStyleModel, {
  49829. text: subText,
  49830. fill: subtextStyleModel.getTextColor(),
  49831. y: textRect.height + titleModel.get('itemGap'),
  49832. verticalAlign: 'top'
  49833. }, {
  49834. disableBox: true
  49835. }),
  49836. z2: 10
  49837. });
  49838. var link = titleModel.get('link');
  49839. var sublink = titleModel.get('sublink');
  49840. var triggerEvent = titleModel.get('triggerEvent', true);
  49841. textEl.silent = !link && !triggerEvent;
  49842. subTextEl.silent = !sublink && !triggerEvent;
  49843. if (link) {
  49844. textEl.on('click', function () {
  49845. windowOpen(link, '_' + titleModel.get('target'));
  49846. });
  49847. }
  49848. if (sublink) {
  49849. subTextEl.on('click', function () {
  49850. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  49851. });
  49852. }
  49853. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  49854. componentType: 'title',
  49855. componentIndex: titleModel.componentIndex
  49856. } : null;
  49857. group.add(textEl);
  49858. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  49859. var groupRect = group.getBoundingRect();
  49860. var layoutOption = titleModel.getBoxLayoutParams();
  49861. layoutOption.width = groupRect.width;
  49862. layoutOption.height = groupRect.height;
  49863. var layoutRect = getLayoutRect(layoutOption, {
  49864. width: api.getWidth(),
  49865. height: api.getHeight()
  49866. }, titleModel.get('padding')); // Adjust text align based on position
  49867. if (!textAlign) {
  49868. // Align left if title is on the left. center and right is same
  49869. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  49870. if (textAlign === 'middle') {
  49871. textAlign = 'center';
  49872. } // Adjust layout by text align
  49873. if (textAlign === 'right') {
  49874. layoutRect.x += layoutRect.width;
  49875. } else if (textAlign === 'center') {
  49876. layoutRect.x += layoutRect.width / 2;
  49877. }
  49878. }
  49879. if (!textVerticalAlign) {
  49880. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  49881. if (textVerticalAlign === 'center') {
  49882. textVerticalAlign = 'middle';
  49883. }
  49884. if (textVerticalAlign === 'bottom') {
  49885. layoutRect.y += layoutRect.height;
  49886. } else if (textVerticalAlign === 'middle') {
  49887. layoutRect.y += layoutRect.height / 2;
  49888. }
  49889. textVerticalAlign = textVerticalAlign || 'top';
  49890. }
  49891. group.x = layoutRect.x;
  49892. group.y = layoutRect.y;
  49893. group.markRedraw();
  49894. var alignStyle = {
  49895. align: textAlign,
  49896. verticalAlign: textVerticalAlign
  49897. };
  49898. textEl.setStyle(alignStyle);
  49899. subTextEl.setStyle(alignStyle); // Render background
  49900. // Get groupRect again because textAlign has been changed
  49901. groupRect = group.getBoundingRect();
  49902. var padding = layoutRect.margin;
  49903. var style = titleModel.getItemStyle(['color', 'opacity']);
  49904. style.fill = titleModel.get('backgroundColor');
  49905. var rect = new Rect({
  49906. shape: {
  49907. x: groupRect.x - padding[3],
  49908. y: groupRect.y - padding[0],
  49909. width: groupRect.width + padding[1] + padding[3],
  49910. height: groupRect.height + padding[0] + padding[2],
  49911. r: titleModel.get('borderRadius')
  49912. },
  49913. style: style,
  49914. subPixelOptimize: true,
  49915. silent: true
  49916. });
  49917. group.add(rect);
  49918. };
  49919. TitleView.type = 'title';
  49920. return TitleView;
  49921. }(ComponentView);
  49922. function install$d(registers) {
  49923. registers.registerComponentModel(TitleModel);
  49924. registers.registerComponentView(TitleView);
  49925. }
  49926. function checkMarkerInSeries(seriesOpts, markerType) {
  49927. if (!seriesOpts) {
  49928. return false;
  49929. }
  49930. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  49931. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  49932. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  49933. return true;
  49934. }
  49935. }
  49936. return false;
  49937. }
  49938. function fillLabel(opt) {
  49939. defaultEmphasis(opt, 'label', ['show']);
  49940. } // { [componentType]: MarkerModel }
  49941. var inner$c = makeInner();
  49942. var MarkerModel =
  49943. /** @class */
  49944. function (_super) {
  49945. __extends(MarkerModel, _super);
  49946. function MarkerModel() {
  49947. var _this = _super !== null && _super.apply(this, arguments) || this;
  49948. _this.type = MarkerModel.type;
  49949. /**
  49950. * If marker model is created by self from series
  49951. */
  49952. _this.createdBySelf = false;
  49953. return _this;
  49954. }
  49955. /**
  49956. * @overrite
  49957. */
  49958. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  49959. if ("development" !== 'production') {
  49960. if (this.type === 'marker') {
  49961. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  49962. }
  49963. }
  49964. this.mergeDefaultAndTheme(option, ecModel);
  49965. this._mergeOption(option, ecModel, false, true);
  49966. };
  49967. MarkerModel.prototype.isAnimationEnabled = function () {
  49968. if (env.node) {
  49969. return false;
  49970. }
  49971. var hostSeries = this.__hostSeries;
  49972. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  49973. };
  49974. /**
  49975. * @overrite
  49976. */
  49977. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  49978. this._mergeOption(newOpt, ecModel, false, false);
  49979. };
  49980. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  49981. var componentType = this.mainType;
  49982. if (!createdBySelf) {
  49983. ecModel.eachSeries(function (seriesModel) {
  49984. // mainType can be markPoint, markLine, markArea
  49985. var markerOpt = seriesModel.get(this.mainType, true);
  49986. var markerModel = inner$c(seriesModel)[componentType];
  49987. if (!markerOpt || !markerOpt.data) {
  49988. inner$c(seriesModel)[componentType] = null;
  49989. return;
  49990. }
  49991. if (!markerModel) {
  49992. if (isInit) {
  49993. // Default label emphasis `position` and `show`
  49994. fillLabel(markerOpt);
  49995. }
  49996. each(markerOpt.data, function (item) {
  49997. // FIXME Overwrite fillLabel method ?
  49998. if (item instanceof Array) {
  49999. fillLabel(item[0]);
  50000. fillLabel(item[1]);
  50001. } else {
  50002. fillLabel(item);
  50003. }
  50004. });
  50005. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  50006. // markerOpt, this, ecModel
  50007. // );
  50008. extend(markerModel, {
  50009. mainType: this.mainType,
  50010. // Use the same series index and name
  50011. seriesIndex: seriesModel.seriesIndex,
  50012. name: seriesModel.name,
  50013. createdBySelf: true
  50014. });
  50015. markerModel.__hostSeries = seriesModel;
  50016. } else {
  50017. markerModel._mergeOption(markerOpt, ecModel, true);
  50018. }
  50019. inner$c(seriesModel)[componentType] = markerModel;
  50020. }, this);
  50021. }
  50022. };
  50023. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  50024. var data = this.getData();
  50025. var value = this.getRawValue(dataIndex);
  50026. var itemName = data.getName(dataIndex);
  50027. return createTooltipMarkup('section', {
  50028. header: this.name,
  50029. blocks: [createTooltipMarkup('nameValue', {
  50030. name: itemName,
  50031. value: value,
  50032. noName: !itemName,
  50033. noValue: value == null
  50034. })]
  50035. });
  50036. };
  50037. MarkerModel.prototype.getData = function () {
  50038. return this._data;
  50039. };
  50040. MarkerModel.prototype.setData = function (data) {
  50041. this._data = data;
  50042. };
  50043. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  50044. componentType) {
  50045. return inner$c(seriesModel)[componentType];
  50046. };
  50047. MarkerModel.type = 'marker';
  50048. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  50049. return MarkerModel;
  50050. }(ComponentModel);
  50051. mixin(MarkerModel, DataFormatMixin.prototype);
  50052. var MarkPointModel =
  50053. /** @class */
  50054. function (_super) {
  50055. __extends(MarkPointModel, _super);
  50056. function MarkPointModel() {
  50057. var _this = _super !== null && _super.apply(this, arguments) || this;
  50058. _this.type = MarkPointModel.type;
  50059. return _this;
  50060. }
  50061. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  50062. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  50063. };
  50064. MarkPointModel.type = 'markPoint';
  50065. MarkPointModel.defaultOption = {
  50066. // zlevel: 0,
  50067. z: 5,
  50068. symbol: 'pin',
  50069. symbolSize: 50,
  50070. // symbolRotate: 0,
  50071. // symbolOffset: [0, 0]
  50072. tooltip: {
  50073. trigger: 'item'
  50074. },
  50075. label: {
  50076. show: true,
  50077. position: 'inside'
  50078. },
  50079. itemStyle: {
  50080. borderWidth: 2
  50081. },
  50082. emphasis: {
  50083. label: {
  50084. show: true
  50085. }
  50086. }
  50087. };
  50088. return MarkPointModel;
  50089. }(MarkerModel);
  50090. function hasXOrY(item) {
  50091. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  50092. }
  50093. function hasXAndY(item) {
  50094. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  50095. }
  50096. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  50097. var coordArr = [];
  50098. var stacked = isDimensionStacked(data, targetDataDim
  50099. /* , otherDataDim */
  50100. );
  50101. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  50102. var value = numCalculate(data, calcDataDim, markerType);
  50103. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  50104. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  50105. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  50106. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  50107. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  50108. precision = Math.min(precision, 20);
  50109. if (precision >= 0) {
  50110. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  50111. }
  50112. return [coordArr, coordArrValue];
  50113. } // TODO Specified percent
  50114. var markerTypeCalculator = {
  50115. min: curry(markerTypeCalculatorWithExtent, 'min'),
  50116. max: curry(markerTypeCalculatorWithExtent, 'max'),
  50117. average: curry(markerTypeCalculatorWithExtent, 'average'),
  50118. median: curry(markerTypeCalculatorWithExtent, 'median')
  50119. };
  50120. /**
  50121. * Transform markPoint data item to format used in List by do the following
  50122. * 1. Calculate statistic like `max`, `min`, `average`
  50123. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  50124. */
  50125. function dataTransform(seriesModel, item) {
  50126. if (!item) {
  50127. return;
  50128. }
  50129. var data = seriesModel.getData();
  50130. var coordSys = seriesModel.coordinateSystem;
  50131. var dims = coordSys && coordSys.dimensions; // 1. If not specify the position with pixel directly
  50132. // 2. If `coord` is not a data array. Which uses `xAxis`,
  50133. // `yAxis` to specify the coord on each dimension
  50134. // parseFloat first because item.x and item.y can be percent string like '20%'
  50135. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  50136. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  50137. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  50138. item = clone(item);
  50139. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  50140. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  50141. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  50142. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  50143. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  50144. // let item use the value without stack.
  50145. item.value = coordInfo[1];
  50146. } else {
  50147. // FIXME Only has one of xAxis and yAxis.
  50148. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  50149. }
  50150. } // x y is provided
  50151. if (item.coord == null || !isArray(dims)) {
  50152. item.coord = [];
  50153. } else {
  50154. // Each coord support max, min, average
  50155. var coord = item.coord;
  50156. for (var i = 0; i < 2; i++) {
  50157. if (markerTypeCalculator[coord[i]]) {
  50158. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  50159. }
  50160. }
  50161. }
  50162. return item;
  50163. }
  50164. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  50165. var ret = {};
  50166. if (item.valueIndex != null || item.valueDim != null) {
  50167. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  50168. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  50169. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  50170. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  50171. } else {
  50172. ret.baseAxis = seriesModel.getBaseAxis();
  50173. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  50174. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  50175. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  50176. }
  50177. return ret;
  50178. }
  50179. function dataDimToCoordDim(seriesModel, dataDim) {
  50180. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  50181. return dimItem && dimItem.coordDim;
  50182. }
  50183. /**
  50184. * Filter data which is out of coordinateSystem range
  50185. * [dataFilter description]
  50186. */
  50187. function dataFilter$1( // Currently only polar and cartesian has containData.
  50188. coordSys, item) {
  50189. // Always return true if there is no coordSys
  50190. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  50191. }
  50192. function zoneFilter( // Currently only polar and cartesian has containData.
  50193. coordSys, item1, item2) {
  50194. // Always return true if there is no coordSys
  50195. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  50196. }
  50197. function createMarkerDimValueGetter(inCoordSys, dims) {
  50198. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  50199. var rawVal = dimIndex < 2 // x, y, radius, angle
  50200. ? item.coord && item.coord[dimIndex] : item.value;
  50201. return parseDataValue(rawVal, dims[dimIndex]);
  50202. } : function (item, dimName, dataIndex, dimIndex) {
  50203. return parseDataValue(item.value, dims[dimIndex]);
  50204. };
  50205. }
  50206. function numCalculate(data, valueDataDim, type) {
  50207. if (type === 'average') {
  50208. var sum_1 = 0;
  50209. var count_1 = 0;
  50210. data.each(valueDataDim, function (val, idx) {
  50211. if (!isNaN(val)) {
  50212. sum_1 += val;
  50213. count_1++;
  50214. }
  50215. });
  50216. return sum_1 / count_1;
  50217. } else if (type === 'median') {
  50218. return data.getMedian(valueDataDim);
  50219. } else {
  50220. // max & min
  50221. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  50222. }
  50223. }
  50224. var inner$d = makeInner();
  50225. var MarkerView =
  50226. /** @class */
  50227. function (_super) {
  50228. __extends(MarkerView, _super);
  50229. function MarkerView() {
  50230. var _this = _super !== null && _super.apply(this, arguments) || this;
  50231. _this.type = MarkerView.type;
  50232. return _this;
  50233. }
  50234. MarkerView.prototype.init = function () {
  50235. this.markerGroupMap = createHashMap();
  50236. };
  50237. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  50238. var _this = this;
  50239. var markerGroupMap = this.markerGroupMap;
  50240. markerGroupMap.each(function (item) {
  50241. inner$d(item).keep = false;
  50242. });
  50243. ecModel.eachSeries(function (seriesModel) {
  50244. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  50245. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  50246. });
  50247. markerGroupMap.each(function (item) {
  50248. !inner$d(item).keep && _this.group.remove(item.group);
  50249. });
  50250. };
  50251. MarkerView.prototype.markKeep = function (drawGroup) {
  50252. inner$d(drawGroup).keep = true;
  50253. };
  50254. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  50255. var _this = this;
  50256. each(seriesModelList, function (seriesModel) {
  50257. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  50258. if (markerModel) {
  50259. var data = markerModel.getData();
  50260. data.eachItemGraphicEl(function (el) {
  50261. if (el) {
  50262. isBlur ? enterBlur(el) : leaveBlur(el);
  50263. }
  50264. });
  50265. }
  50266. });
  50267. };
  50268. MarkerView.type = 'marker';
  50269. return MarkerView;
  50270. }(ComponentView);
  50271. function updateMarkerLayout(mpData, seriesModel, api) {
  50272. var coordSys = seriesModel.coordinateSystem;
  50273. mpData.each(function (idx) {
  50274. var itemModel = mpData.getItemModel(idx);
  50275. var point;
  50276. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  50277. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  50278. if (!isNaN(xPx) && !isNaN(yPx)) {
  50279. point = [xPx, yPx];
  50280. } // Chart like bar may have there own marker positioning logic
  50281. else if (seriesModel.getMarkerPosition) {
  50282. // Use the getMarkerPosition
  50283. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  50284. } else if (coordSys) {
  50285. var x = mpData.get(coordSys.dimensions[0], idx);
  50286. var y = mpData.get(coordSys.dimensions[1], idx);
  50287. point = coordSys.dataToPoint([x, y]);
  50288. } // Use x, y if has any
  50289. if (!isNaN(xPx)) {
  50290. point[0] = xPx;
  50291. }
  50292. if (!isNaN(yPx)) {
  50293. point[1] = yPx;
  50294. }
  50295. mpData.setItemLayout(idx, point);
  50296. });
  50297. }
  50298. var MarkPointView =
  50299. /** @class */
  50300. function (_super) {
  50301. __extends(MarkPointView, _super);
  50302. function MarkPointView() {
  50303. var _this = _super !== null && _super.apply(this, arguments) || this;
  50304. _this.type = MarkPointView.type;
  50305. return _this;
  50306. }
  50307. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  50308. ecModel.eachSeries(function (seriesModel) {
  50309. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  50310. if (mpModel) {
  50311. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  50312. this.markerGroupMap.get(seriesModel.id).updateLayout();
  50313. }
  50314. }, this);
  50315. };
  50316. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  50317. var coordSys = seriesModel.coordinateSystem;
  50318. var seriesId = seriesModel.id;
  50319. var seriesData = seriesModel.getData();
  50320. var symbolDrawMap = this.markerGroupMap;
  50321. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  50322. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  50323. mpModel.setData(mpData);
  50324. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  50325. mpData.each(function (idx) {
  50326. var itemModel = mpData.getItemModel(idx);
  50327. var symbol = itemModel.getShallow('symbol');
  50328. var symbolSize = itemModel.getShallow('symbolSize');
  50329. var symbolRotate = itemModel.getShallow('symbolRotate');
  50330. var symbolOffset = itemModel.getShallow('symbolOffset');
  50331. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  50332. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  50333. var rawIdx = mpModel.getRawValue(idx);
  50334. var dataParams = mpModel.getDataParams(idx);
  50335. if (isFunction(symbol)) {
  50336. symbol = symbol(rawIdx, dataParams);
  50337. }
  50338. if (isFunction(symbolSize)) {
  50339. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  50340. symbolSize = symbolSize(rawIdx, dataParams);
  50341. }
  50342. if (isFunction(symbolRotate)) {
  50343. symbolRotate = symbolRotate(rawIdx, dataParams);
  50344. }
  50345. if (isFunction(symbolOffset)) {
  50346. symbolOffset = symbolOffset(rawIdx, dataParams);
  50347. }
  50348. }
  50349. var style = itemModel.getModel('itemStyle').getItemStyle();
  50350. var color = getVisualFromData(seriesData, 'color');
  50351. if (!style.fill) {
  50352. style.fill = color;
  50353. }
  50354. mpData.setItemVisual(idx, {
  50355. symbol: symbol,
  50356. symbolSize: symbolSize,
  50357. symbolRotate: symbolRotate,
  50358. symbolOffset: symbolOffset,
  50359. symbolKeepAspect: symbolKeepAspect,
  50360. style: style
  50361. });
  50362. }); // TODO Text are wrong
  50363. symbolDraw.updateData(mpData);
  50364. this.group.add(symbolDraw.group); // Set host model for tooltip
  50365. // FIXME
  50366. mpData.eachItemGraphicEl(function (el) {
  50367. el.traverse(function (child) {
  50368. getECData(child).dataModel = mpModel;
  50369. });
  50370. });
  50371. this.markKeep(symbolDraw);
  50372. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  50373. };
  50374. MarkPointView.type = 'markPoint';
  50375. return MarkPointView;
  50376. }(MarkerView);
  50377. function createData(coordSys, seriesModel, mpModel) {
  50378. var coordDimsInfos;
  50379. if (coordSys) {
  50380. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  50381. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  50382. return extend(extend({}, info), {
  50383. name: coordDim,
  50384. // DON'T use ordinalMeta to parse and collect ordinal.
  50385. ordinalMeta: null
  50386. });
  50387. });
  50388. } else {
  50389. coordDimsInfos = [{
  50390. name: 'value',
  50391. type: 'float'
  50392. }];
  50393. }
  50394. var mpData = new SeriesData(coordDimsInfos, mpModel);
  50395. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  50396. if (coordSys) {
  50397. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  50398. }
  50399. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  50400. mpData.initData(dataOpt, null, dimValueGetter);
  50401. return mpData;
  50402. }
  50403. function install$e(registers) {
  50404. registers.registerComponentModel(MarkPointModel);
  50405. registers.registerComponentView(MarkPointView);
  50406. registers.registerPreprocessor(function (opt) {
  50407. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  50408. // Make sure markPoint component is enabled
  50409. opt.markPoint = opt.markPoint || {};
  50410. }
  50411. });
  50412. }
  50413. var MarkLineModel =
  50414. /** @class */
  50415. function (_super) {
  50416. __extends(MarkLineModel, _super);
  50417. function MarkLineModel() {
  50418. var _this = _super !== null && _super.apply(this, arguments) || this;
  50419. _this.type = MarkLineModel.type;
  50420. return _this;
  50421. }
  50422. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  50423. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  50424. };
  50425. MarkLineModel.type = 'markLine';
  50426. MarkLineModel.defaultOption = {
  50427. // zlevel: 0,
  50428. z: 5,
  50429. symbol: ['circle', 'arrow'],
  50430. symbolSize: [8, 16],
  50431. // symbolRotate: 0,
  50432. symbolOffset: 0,
  50433. precision: 2,
  50434. tooltip: {
  50435. trigger: 'item'
  50436. },
  50437. label: {
  50438. show: true,
  50439. position: 'end',
  50440. distance: 5
  50441. },
  50442. lineStyle: {
  50443. type: 'dashed'
  50444. },
  50445. emphasis: {
  50446. label: {
  50447. show: true
  50448. },
  50449. lineStyle: {
  50450. width: 3
  50451. }
  50452. },
  50453. animationEasing: 'linear'
  50454. };
  50455. return MarkLineModel;
  50456. }(MarkerModel);
  50457. var straightLineProto = Line.prototype;
  50458. var bezierCurveProto = BezierCurve.prototype;
  50459. var StraightLineShape =
  50460. /** @class */
  50461. function () {
  50462. function StraightLineShape() {
  50463. // Start point
  50464. this.x1 = 0;
  50465. this.y1 = 0; // End point
  50466. this.x2 = 0;
  50467. this.y2 = 0;
  50468. this.percent = 1;
  50469. }
  50470. return StraightLineShape;
  50471. }();
  50472. var CurveShape =
  50473. /** @class */
  50474. function (_super) {
  50475. __extends(CurveShape, _super);
  50476. function CurveShape() {
  50477. return _super !== null && _super.apply(this, arguments) || this;
  50478. }
  50479. return CurveShape;
  50480. }(StraightLineShape);
  50481. function isStraightLine(shape) {
  50482. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  50483. }
  50484. var ECLinePath =
  50485. /** @class */
  50486. function (_super) {
  50487. __extends(ECLinePath, _super);
  50488. function ECLinePath(opts) {
  50489. var _this = _super.call(this, opts) || this;
  50490. _this.type = 'ec-line';
  50491. return _this;
  50492. }
  50493. ECLinePath.prototype.getDefaultStyle = function () {
  50494. return {
  50495. stroke: '#000',
  50496. fill: null
  50497. };
  50498. };
  50499. ECLinePath.prototype.getDefaultShape = function () {
  50500. return new StraightLineShape();
  50501. };
  50502. ECLinePath.prototype.buildPath = function (ctx, shape) {
  50503. if (isStraightLine(shape)) {
  50504. straightLineProto.buildPath.call(this, ctx, shape);
  50505. } else {
  50506. bezierCurveProto.buildPath.call(this, ctx, shape);
  50507. }
  50508. };
  50509. ECLinePath.prototype.pointAt = function (t) {
  50510. if (isStraightLine(this.shape)) {
  50511. return straightLineProto.pointAt.call(this, t);
  50512. } else {
  50513. return bezierCurveProto.pointAt.call(this, t);
  50514. }
  50515. };
  50516. ECLinePath.prototype.tangentAt = function (t) {
  50517. var shape = this.shape;
  50518. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  50519. return normalize(p, p);
  50520. };
  50521. return ECLinePath;
  50522. }(Path);
  50523. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  50524. function makeSymbolTypeKey(symbolCategory) {
  50525. return '_' + symbolCategory + 'Type';
  50526. }
  50527. /**
  50528. * @inner
  50529. */
  50530. function createSymbol$1(name, lineData, idx) {
  50531. var symbolType = lineData.getItemVisual(idx, name);
  50532. if (!symbolType || symbolType === 'none') {
  50533. return;
  50534. }
  50535. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  50536. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  50537. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  50538. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  50539. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  50540. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  50541. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  50542. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  50543. symbolPath.name = name;
  50544. return symbolPath;
  50545. }
  50546. function createLine(points) {
  50547. var line = new ECLinePath({
  50548. name: 'line',
  50549. subPixelOptimize: true
  50550. });
  50551. setLinePoints(line.shape, points);
  50552. return line;
  50553. }
  50554. function setLinePoints(targetShape, points) {
  50555. targetShape.x1 = points[0][0];
  50556. targetShape.y1 = points[0][1];
  50557. targetShape.x2 = points[1][0];
  50558. targetShape.y2 = points[1][1];
  50559. targetShape.percent = 1;
  50560. var cp1 = points[2];
  50561. if (cp1) {
  50562. targetShape.cpx1 = cp1[0];
  50563. targetShape.cpy1 = cp1[1];
  50564. } else {
  50565. targetShape.cpx1 = NaN;
  50566. targetShape.cpy1 = NaN;
  50567. }
  50568. }
  50569. var Line$1 =
  50570. /** @class */
  50571. function (_super) {
  50572. __extends(Line, _super);
  50573. function Line(lineData, idx, seriesScope) {
  50574. var _this = _super.call(this) || this;
  50575. _this._createLine(lineData, idx, seriesScope);
  50576. return _this;
  50577. }
  50578. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  50579. var seriesModel = lineData.hostModel;
  50580. var linePoints = lineData.getItemLayout(idx);
  50581. var line = createLine(linePoints);
  50582. line.shape.percent = 0;
  50583. initProps(line, {
  50584. shape: {
  50585. percent: 1
  50586. }
  50587. }, seriesModel, idx);
  50588. this.add(line);
  50589. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50590. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  50591. // it will be updated after line#update.
  50592. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  50593. this.add(symbol);
  50594. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  50595. }, this);
  50596. this._updateCommonStl(lineData, idx, seriesScope);
  50597. }; // TODO More strict on the List type in parameters?
  50598. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  50599. var seriesModel = lineData.hostModel;
  50600. var line = this.childOfName('line');
  50601. var linePoints = lineData.getItemLayout(idx);
  50602. var target = {
  50603. shape: {}
  50604. };
  50605. setLinePoints(target.shape, linePoints);
  50606. updateProps(line, target, seriesModel, idx);
  50607. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50608. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  50609. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  50610. if (this[key] !== symbolType) {
  50611. this.remove(this.childOfName(symbolCategory));
  50612. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  50613. this.add(symbol);
  50614. }
  50615. this[key] = symbolType;
  50616. }, this);
  50617. this._updateCommonStl(lineData, idx, seriesScope);
  50618. };
  50619. Line.prototype.getLinePath = function () {
  50620. return this.childAt(0);
  50621. };
  50622. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  50623. var seriesModel = lineData.hostModel;
  50624. var line = this.childOfName('line');
  50625. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  50626. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  50627. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  50628. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  50629. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  50630. var focus = seriesScope && seriesScope.focus;
  50631. var blurScope = seriesScope && seriesScope.blurScope; // Optimization for large dataset
  50632. if (!seriesScope || lineData.hasItemOption) {
  50633. var itemModel = lineData.getItemModel(idx);
  50634. var emphasisModel = itemModel.getModel('emphasis');
  50635. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  50636. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  50637. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  50638. emphasisDisabled = emphasisModel.get('disabled');
  50639. focus = emphasisModel.get('focus');
  50640. blurScope = emphasisModel.get('blurScope');
  50641. labelStatesModels = getLabelStatesModels(itemModel);
  50642. }
  50643. var lineStyle = lineData.getItemVisual(idx, 'style');
  50644. var visualColor = lineStyle.stroke;
  50645. line.useStyle(lineStyle);
  50646. line.style.fill = null;
  50647. line.style.strokeNoScale = true;
  50648. line.ensureState('emphasis').style = emphasisLineStyle;
  50649. line.ensureState('blur').style = blurLineStyle;
  50650. line.ensureState('select').style = selectLineStyle; // Update symbol
  50651. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50652. var symbol = this.childOfName(symbolCategory);
  50653. if (symbol) {
  50654. // Share opacity and color with line.
  50655. symbol.setColor(visualColor);
  50656. symbol.style.opacity = lineStyle.opacity;
  50657. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  50658. var stateName = SPECIAL_STATES[i];
  50659. var lineState = line.getState(stateName);
  50660. if (lineState) {
  50661. var lineStateStyle = lineState.style || {};
  50662. var state = symbol.ensureState(stateName);
  50663. var stateStyle = state.style || (state.style = {});
  50664. if (lineStateStyle.stroke != null) {
  50665. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  50666. }
  50667. if (lineStateStyle.opacity != null) {
  50668. stateStyle.opacity = lineStateStyle.opacity;
  50669. }
  50670. }
  50671. }
  50672. symbol.markRedraw();
  50673. }
  50674. }, this);
  50675. var rawVal = seriesModel.getRawValue(idx);
  50676. setLabelStyle(this, labelStatesModels, {
  50677. labelDataIndex: idx,
  50678. labelFetcher: {
  50679. getFormattedLabel: function (dataIndex, stateName) {
  50680. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  50681. }
  50682. },
  50683. inheritColor: visualColor || '#000',
  50684. defaultOpacity: lineStyle.opacity,
  50685. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  50686. });
  50687. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  50688. // values have to be set on `normalStyle`.
  50689. if (label) {
  50690. var labelNormalModel = labelStatesModels.normal;
  50691. label.__align = label.style.align;
  50692. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  50693. label.__position = labelNormalModel.get('position') || 'middle';
  50694. var distance = labelNormalModel.get('distance');
  50695. if (!isArray(distance)) {
  50696. distance = [distance, distance];
  50697. }
  50698. label.__labelDistance = distance;
  50699. }
  50700. this.setTextConfig({
  50701. position: null,
  50702. local: true,
  50703. inside: false // Can't be inside for stroke element.
  50704. });
  50705. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  50706. };
  50707. Line.prototype.highlight = function () {
  50708. enterEmphasis(this);
  50709. };
  50710. Line.prototype.downplay = function () {
  50711. leaveEmphasis(this);
  50712. };
  50713. Line.prototype.updateLayout = function (lineData, idx) {
  50714. this.setLinePoints(lineData.getItemLayout(idx));
  50715. };
  50716. Line.prototype.setLinePoints = function (points) {
  50717. var linePath = this.childOfName('line');
  50718. setLinePoints(linePath.shape, points);
  50719. linePath.dirty();
  50720. };
  50721. Line.prototype.beforeUpdate = function () {
  50722. var lineGroup = this;
  50723. var symbolFrom = lineGroup.childOfName('fromSymbol');
  50724. var symbolTo = lineGroup.childOfName('toSymbol');
  50725. var label = lineGroup.getTextContent(); // Quick reject
  50726. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  50727. return;
  50728. }
  50729. var invScale = 1;
  50730. var parentNode = this.parent;
  50731. while (parentNode) {
  50732. if (parentNode.scaleX) {
  50733. invScale /= parentNode.scaleX;
  50734. }
  50735. parentNode = parentNode.parent;
  50736. }
  50737. var line = lineGroup.childOfName('line'); // If line not changed
  50738. // FIXME Parent scale changed
  50739. if (!this.__dirty && !line.__dirty) {
  50740. return;
  50741. }
  50742. var percent = line.shape.percent;
  50743. var fromPos = line.pointAt(0);
  50744. var toPos = line.pointAt(percent);
  50745. var d = sub([], toPos, fromPos);
  50746. normalize(d, d);
  50747. function setSymbolRotation(symbol, percent) {
  50748. // Fix #12388
  50749. // when symbol is set to be 'arrow' in markLine,
  50750. // symbolRotate value will be ignored, and compulsively use tangent angle.
  50751. // rotate by default if symbol rotation is not specified
  50752. var specifiedRotation = symbol.__specifiedRotation;
  50753. if (specifiedRotation == null) {
  50754. var tangent = line.tangentAt(percent);
  50755. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  50756. } else {
  50757. symbol.attr('rotation', specifiedRotation);
  50758. }
  50759. }
  50760. if (symbolFrom) {
  50761. symbolFrom.setPosition(fromPos);
  50762. setSymbolRotation(symbolFrom, 0);
  50763. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  50764. symbolFrom.markRedraw();
  50765. }
  50766. if (symbolTo) {
  50767. symbolTo.setPosition(toPos);
  50768. setSymbolRotation(symbolTo, 1);
  50769. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  50770. symbolTo.markRedraw();
  50771. }
  50772. if (label && !label.ignore) {
  50773. label.x = label.y = 0;
  50774. label.originX = label.originY = 0;
  50775. var textAlign = void 0;
  50776. var textVerticalAlign = void 0;
  50777. var distance = label.__labelDistance;
  50778. var distanceX = distance[0] * invScale;
  50779. var distanceY = distance[1] * invScale;
  50780. var halfPercent = percent / 2;
  50781. var tangent = line.tangentAt(halfPercent);
  50782. var n = [tangent[1], -tangent[0]];
  50783. var cp = line.pointAt(halfPercent);
  50784. if (n[1] > 0) {
  50785. n[0] = -n[0];
  50786. n[1] = -n[1];
  50787. }
  50788. var dir = tangent[0] < 0 ? -1 : 1;
  50789. if (label.__position !== 'start' && label.__position !== 'end') {
  50790. var rotation = -Math.atan2(tangent[1], tangent[0]);
  50791. if (toPos[0] < fromPos[0]) {
  50792. rotation = Math.PI + rotation;
  50793. }
  50794. label.rotation = rotation;
  50795. }
  50796. var dy = void 0;
  50797. switch (label.__position) {
  50798. case 'insideStartTop':
  50799. case 'insideMiddleTop':
  50800. case 'insideEndTop':
  50801. case 'middle':
  50802. dy = -distanceY;
  50803. textVerticalAlign = 'bottom';
  50804. break;
  50805. case 'insideStartBottom':
  50806. case 'insideMiddleBottom':
  50807. case 'insideEndBottom':
  50808. dy = distanceY;
  50809. textVerticalAlign = 'top';
  50810. break;
  50811. default:
  50812. dy = 0;
  50813. textVerticalAlign = 'middle';
  50814. }
  50815. switch (label.__position) {
  50816. case 'end':
  50817. label.x = d[0] * distanceX + toPos[0];
  50818. label.y = d[1] * distanceY + toPos[1];
  50819. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  50820. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  50821. break;
  50822. case 'start':
  50823. label.x = -d[0] * distanceX + fromPos[0];
  50824. label.y = -d[1] * distanceY + fromPos[1];
  50825. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  50826. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  50827. break;
  50828. case 'insideStartTop':
  50829. case 'insideStart':
  50830. case 'insideStartBottom':
  50831. label.x = distanceX * dir + fromPos[0];
  50832. label.y = fromPos[1] + dy;
  50833. textAlign = tangent[0] < 0 ? 'right' : 'left';
  50834. label.originX = -distanceX * dir;
  50835. label.originY = -dy;
  50836. break;
  50837. case 'insideMiddleTop':
  50838. case 'insideMiddle':
  50839. case 'insideMiddleBottom':
  50840. case 'middle':
  50841. label.x = cp[0];
  50842. label.y = cp[1] + dy;
  50843. textAlign = 'center';
  50844. label.originY = -dy;
  50845. break;
  50846. case 'insideEndTop':
  50847. case 'insideEnd':
  50848. case 'insideEndBottom':
  50849. label.x = -distanceX * dir + toPos[0];
  50850. label.y = toPos[1] + dy;
  50851. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  50852. label.originX = distanceX * dir;
  50853. label.originY = -dy;
  50854. break;
  50855. }
  50856. label.scaleX = label.scaleY = invScale;
  50857. label.setStyle({
  50858. // Use the user specified text align and baseline first
  50859. verticalAlign: label.__verticalAlign || textVerticalAlign,
  50860. align: label.__align || textAlign
  50861. });
  50862. }
  50863. };
  50864. return Line;
  50865. }(Group);
  50866. var LineDraw =
  50867. /** @class */
  50868. function () {
  50869. function LineDraw(LineCtor) {
  50870. this.group = new Group();
  50871. this._LineCtor = LineCtor || Line$1;
  50872. }
  50873. LineDraw.prototype.updateData = function (lineData) {
  50874. var _this = this; // Remove progressive els.
  50875. this._progressiveEls = null;
  50876. var lineDraw = this;
  50877. var group = lineDraw.group;
  50878. var oldLineData = lineDraw._lineData;
  50879. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  50880. // stream mode to normal mode, where previous elements should be removed.
  50881. if (!oldLineData) {
  50882. group.removeAll();
  50883. }
  50884. var seriesScope = makeSeriesScope$1(lineData);
  50885. lineData.diff(oldLineData).add(function (idx) {
  50886. _this._doAdd(lineData, idx, seriesScope);
  50887. }).update(function (newIdx, oldIdx) {
  50888. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  50889. }).remove(function (idx) {
  50890. group.remove(oldLineData.getItemGraphicEl(idx));
  50891. }).execute();
  50892. };
  50893. LineDraw.prototype.updateLayout = function () {
  50894. var lineData = this._lineData; // Do not support update layout in incremental mode.
  50895. if (!lineData) {
  50896. return;
  50897. }
  50898. lineData.eachItemGraphicEl(function (el, idx) {
  50899. el.updateLayout(lineData, idx);
  50900. }, this);
  50901. };
  50902. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  50903. this._seriesScope = makeSeriesScope$1(lineData);
  50904. this._lineData = null;
  50905. this.group.removeAll();
  50906. };
  50907. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  50908. this._progressiveEls = [];
  50909. function updateIncrementalAndHover(el) {
  50910. if (!el.isGroup && !isEffectObject(el)) {
  50911. el.incremental = true;
  50912. el.ensureState('emphasis').hoverLayer = true;
  50913. }
  50914. }
  50915. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  50916. var itemLayout = lineData.getItemLayout(idx);
  50917. if (lineNeedsDraw(itemLayout)) {
  50918. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  50919. el.traverse(updateIncrementalAndHover);
  50920. this.group.add(el);
  50921. lineData.setItemGraphicEl(idx, el);
  50922. this._progressiveEls.push(el);
  50923. }
  50924. }
  50925. };
  50926. LineDraw.prototype.remove = function () {
  50927. this.group.removeAll();
  50928. };
  50929. LineDraw.prototype.eachRendered = function (cb) {
  50930. traverseElements(this._progressiveEls || this.group, cb);
  50931. };
  50932. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  50933. var itemLayout = lineData.getItemLayout(idx);
  50934. if (!lineNeedsDraw(itemLayout)) {
  50935. return;
  50936. }
  50937. var el = new this._LineCtor(lineData, idx, seriesScope);
  50938. lineData.setItemGraphicEl(idx, el);
  50939. this.group.add(el);
  50940. };
  50941. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  50942. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  50943. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  50944. this.group.remove(itemEl);
  50945. return;
  50946. }
  50947. if (!itemEl) {
  50948. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  50949. } else {
  50950. itemEl.updateData(newLineData, newIdx, seriesScope);
  50951. }
  50952. newLineData.setItemGraphicEl(newIdx, itemEl);
  50953. this.group.add(itemEl);
  50954. };
  50955. return LineDraw;
  50956. }();
  50957. function isEffectObject(el) {
  50958. return el.animators && el.animators.length > 0;
  50959. }
  50960. function makeSeriesScope$1(lineData) {
  50961. var hostModel = lineData.hostModel;
  50962. var emphasisModel = hostModel.getModel('emphasis');
  50963. return {
  50964. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  50965. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  50966. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  50967. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  50968. emphasisDisabled: emphasisModel.get('disabled'),
  50969. blurScope: emphasisModel.get('blurScope'),
  50970. focus: emphasisModel.get('focus'),
  50971. labelStatesModels: getLabelStatesModels(hostModel)
  50972. };
  50973. }
  50974. function isPointNaN(pt) {
  50975. return isNaN(pt[0]) || isNaN(pt[1]);
  50976. }
  50977. function lineNeedsDraw(pts) {
  50978. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  50979. }
  50980. var inner$e = makeInner();
  50981. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  50982. var data = seriesModel.getData();
  50983. var itemArray;
  50984. if (!isArray(item)) {
  50985. // Special type markLine like 'min', 'max', 'average', 'median'
  50986. var mlType = item.type;
  50987. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  50988. // data: [{
  50989. // yAxis: 10
  50990. // }]
  50991. || item.xAxis != null || item.yAxis != null) {
  50992. var valueAxis = void 0;
  50993. var value = void 0;
  50994. if (item.yAxis != null || item.xAxis != null) {
  50995. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  50996. value = retrieve(item.yAxis, item.xAxis);
  50997. } else {
  50998. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  50999. valueAxis = axisInfo.valueAxis;
  51000. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  51001. value = numCalculate(data, valueDataDim, mlType);
  51002. }
  51003. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  51004. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  51005. var mlFrom = clone(item);
  51006. var mlTo = {
  51007. coord: []
  51008. };
  51009. mlFrom.type = null;
  51010. mlFrom.coord = [];
  51011. mlFrom.coord[baseIndex] = -Infinity;
  51012. mlTo.coord[baseIndex] = Infinity;
  51013. var precision = mlModel.get('precision');
  51014. if (precision >= 0 && isNumber(value)) {
  51015. value = +value.toFixed(Math.min(precision, 20));
  51016. }
  51017. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  51018. itemArray = [mlFrom, mlTo, {
  51019. type: mlType,
  51020. valueIndex: item.valueIndex,
  51021. // Force to use the value of calculated value.
  51022. value: value
  51023. }];
  51024. } else {
  51025. // Invalid data
  51026. if ("development" !== 'production') {
  51027. logError('Invalid markLine data.');
  51028. }
  51029. itemArray = [];
  51030. }
  51031. } else {
  51032. itemArray = item;
  51033. }
  51034. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  51035. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  51036. merge(normalizedItem[2], normalizedItem[0]);
  51037. merge(normalizedItem[2], normalizedItem[1]);
  51038. return normalizedItem;
  51039. };
  51040. function isInfinity(val) {
  51041. return !isNaN(val) && !isFinite(val);
  51042. } // If a markLine has one dim
  51043. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  51044. var otherDimIndex = 1 - dimIndex;
  51045. var dimName = coordSys.dimensions[dimIndex];
  51046. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  51047. }
  51048. function markLineFilter(coordSys, item) {
  51049. if (coordSys.type === 'cartesian2d') {
  51050. var fromCoord = item[0].coord;
  51051. var toCoord = item[1].coord; // In case
  51052. // {
  51053. // markLine: {
  51054. // data: [{ yAxis: 2 }]
  51055. // }
  51056. // }
  51057. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  51058. return true;
  51059. }
  51060. }
  51061. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  51062. }
  51063. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  51064. var coordSys = seriesModel.coordinateSystem;
  51065. var itemModel = data.getItemModel(idx);
  51066. var point;
  51067. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  51068. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  51069. if (!isNaN(xPx) && !isNaN(yPx)) {
  51070. point = [xPx, yPx];
  51071. } else {
  51072. // Chart like bar may have there own marker positioning logic
  51073. if (seriesModel.getMarkerPosition) {
  51074. // Use the getMarkerPosition
  51075. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  51076. } else {
  51077. var dims = coordSys.dimensions;
  51078. var x = data.get(dims[0], idx);
  51079. var y = data.get(dims[1], idx);
  51080. point = coordSys.dataToPoint([x, y]);
  51081. } // Expand line to the edge of grid if value on one axis is Inifnity
  51082. // In case
  51083. // markLine: {
  51084. // data: [{
  51085. // yAxis: 2
  51086. // // or
  51087. // type: 'average'
  51088. // }]
  51089. // }
  51090. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  51091. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  51092. var xAxis = coordSys.getAxis('x');
  51093. var yAxis = coordSys.getAxis('y');
  51094. var dims = coordSys.dimensions;
  51095. if (isInfinity(data.get(dims[0], idx))) {
  51096. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  51097. } else if (isInfinity(data.get(dims[1], idx))) {
  51098. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  51099. }
  51100. } // Use x, y if has any
  51101. if (!isNaN(xPx)) {
  51102. point[0] = xPx;
  51103. }
  51104. if (!isNaN(yPx)) {
  51105. point[1] = yPx;
  51106. }
  51107. }
  51108. data.setItemLayout(idx, point);
  51109. }
  51110. var MarkLineView =
  51111. /** @class */
  51112. function (_super) {
  51113. __extends(MarkLineView, _super);
  51114. function MarkLineView() {
  51115. var _this = _super !== null && _super.apply(this, arguments) || this;
  51116. _this.type = MarkLineView.type;
  51117. return _this;
  51118. }
  51119. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  51120. ecModel.eachSeries(function (seriesModel) {
  51121. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  51122. if (mlModel) {
  51123. var mlData_1 = mlModel.getData();
  51124. var fromData_1 = inner$e(mlModel).from;
  51125. var toData_1 = inner$e(mlModel).to; // Update visual and layout of from symbol and to symbol
  51126. fromData_1.each(function (idx) {
  51127. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  51128. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  51129. }); // Update layout of line
  51130. mlData_1.each(function (idx) {
  51131. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  51132. });
  51133. this.markerGroupMap.get(seriesModel.id).updateLayout();
  51134. }
  51135. }, this);
  51136. };
  51137. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  51138. var coordSys = seriesModel.coordinateSystem;
  51139. var seriesId = seriesModel.id;
  51140. var seriesData = seriesModel.getData();
  51141. var lineDrawMap = this.markerGroupMap;
  51142. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  51143. this.group.add(lineDraw.group);
  51144. var mlData = createList$1(coordSys, seriesModel, mlModel);
  51145. var fromData = mlData.from;
  51146. var toData = mlData.to;
  51147. var lineData = mlData.line;
  51148. inner$e(mlModel).from = fromData;
  51149. inner$e(mlModel).to = toData; // Line data for tooltip and formatter
  51150. mlModel.setData(lineData); // TODO
  51151. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  51152. // But the related logic and type definition are not finished yet.
  51153. // Finish it if required
  51154. var symbolType = mlModel.get('symbol');
  51155. var symbolSize = mlModel.get('symbolSize');
  51156. var symbolRotate = mlModel.get('symbolRotate');
  51157. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  51158. if (!isArray(symbolType)) {
  51159. symbolType = [symbolType, symbolType];
  51160. }
  51161. if (!isArray(symbolSize)) {
  51162. symbolSize = [symbolSize, symbolSize];
  51163. }
  51164. if (!isArray(symbolRotate)) {
  51165. symbolRotate = [symbolRotate, symbolRotate];
  51166. }
  51167. if (!isArray(symbolOffset)) {
  51168. symbolOffset = [symbolOffset, symbolOffset];
  51169. } // Update visual and layout of from symbol and to symbol
  51170. mlData.from.each(function (idx) {
  51171. updateDataVisualAndLayout(fromData, idx, true);
  51172. updateDataVisualAndLayout(toData, idx, false);
  51173. }); // Update visual and layout of line
  51174. lineData.each(function (idx) {
  51175. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  51176. // color: lineColor || fromData.getItemVisual(idx, 'color')
  51177. // });
  51178. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  51179. if (lineStyle.stroke == null) {
  51180. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  51181. }
  51182. lineData.setItemVisual(idx, {
  51183. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  51184. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  51185. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  51186. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  51187. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  51188. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  51189. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  51190. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  51191. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  51192. toSymbol: toData.getItemVisual(idx, 'symbol'),
  51193. style: lineStyle
  51194. });
  51195. });
  51196. lineDraw.updateData(lineData); // Set host model for tooltip
  51197. // FIXME
  51198. mlData.line.eachItemGraphicEl(function (el) {
  51199. getECData(el).dataModel = mlModel;
  51200. el.traverse(function (child) {
  51201. getECData(child).dataModel = mlModel;
  51202. });
  51203. });
  51204. function updateDataVisualAndLayout(data, idx, isFrom) {
  51205. var itemModel = data.getItemModel(idx);
  51206. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  51207. var style = itemModel.getModel('itemStyle').getItemStyle();
  51208. if (style.fill == null) {
  51209. style.fill = getVisualFromData(seriesData, 'color');
  51210. }
  51211. data.setItemVisual(idx, {
  51212. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  51213. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  51214. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  51215. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  51216. // TODO: when 2d array is supported, it should ignore parent
  51217. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  51218. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  51219. style: style
  51220. });
  51221. }
  51222. this.markKeep(lineDraw);
  51223. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  51224. };
  51225. MarkLineView.type = 'markLine';
  51226. return MarkLineView;
  51227. }(MarkerView);
  51228. function createList$1(coordSys, seriesModel, mlModel) {
  51229. var coordDimsInfos;
  51230. if (coordSys) {
  51231. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  51232. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  51233. return extend(extend({}, info), {
  51234. name: coordDim,
  51235. // DON'T use ordinalMeta to parse and collect ordinal.
  51236. ordinalMeta: null
  51237. });
  51238. });
  51239. } else {
  51240. coordDimsInfos = [{
  51241. name: 'value',
  51242. type: 'float'
  51243. }];
  51244. }
  51245. var fromData = new SeriesData(coordDimsInfos, mlModel);
  51246. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  51247. var lineData = new SeriesData([], mlModel);
  51248. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  51249. if (coordSys) {
  51250. optData = filter(optData, curry(markLineFilter, coordSys));
  51251. }
  51252. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  51253. fromData.initData(map(optData, function (item) {
  51254. return item[0];
  51255. }), null, dimValueGetter);
  51256. toData.initData(map(optData, function (item) {
  51257. return item[1];
  51258. }), null, dimValueGetter);
  51259. lineData.initData(map(optData, function (item) {
  51260. return item[2];
  51261. }));
  51262. lineData.hasItemOption = true;
  51263. return {
  51264. from: fromData,
  51265. to: toData,
  51266. line: lineData
  51267. };
  51268. }
  51269. function install$f(registers) {
  51270. registers.registerComponentModel(MarkLineModel);
  51271. registers.registerComponentView(MarkLineView);
  51272. registers.registerPreprocessor(function (opt) {
  51273. if (checkMarkerInSeries(opt.series, 'markLine')) {
  51274. // Make sure markLine component is enabled
  51275. opt.markLine = opt.markLine || {};
  51276. }
  51277. });
  51278. }
  51279. var MarkAreaModel =
  51280. /** @class */
  51281. function (_super) {
  51282. __extends(MarkAreaModel, _super);
  51283. function MarkAreaModel() {
  51284. var _this = _super !== null && _super.apply(this, arguments) || this;
  51285. _this.type = MarkAreaModel.type;
  51286. return _this;
  51287. }
  51288. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  51289. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  51290. };
  51291. MarkAreaModel.type = 'markArea';
  51292. MarkAreaModel.defaultOption = {
  51293. // zlevel: 0,
  51294. // PENDING
  51295. z: 1,
  51296. tooltip: {
  51297. trigger: 'item'
  51298. },
  51299. // markArea should fixed on the coordinate system
  51300. animation: false,
  51301. label: {
  51302. show: true,
  51303. position: 'top'
  51304. },
  51305. itemStyle: {
  51306. // color and borderColor default to use color from series
  51307. // color: 'auto'
  51308. // borderColor: 'auto'
  51309. borderWidth: 0
  51310. },
  51311. emphasis: {
  51312. label: {
  51313. show: true,
  51314. position: 'top'
  51315. }
  51316. }
  51317. };
  51318. return MarkAreaModel;
  51319. }(MarkerModel);
  51320. var inner$f = makeInner();
  51321. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  51322. // item may be null
  51323. var item0 = item[0];
  51324. var item1 = item[1];
  51325. if (!item0 || !item1) {
  51326. return;
  51327. }
  51328. var lt = dataTransform(seriesModel, item0);
  51329. var rb = dataTransform(seriesModel, item1); // FIXME make sure lt is less than rb
  51330. var ltCoord = lt.coord;
  51331. var rbCoord = rb.coord;
  51332. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  51333. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  51334. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  51335. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  51336. var result = mergeAll([{}, lt, rb]);
  51337. result.coord = [lt.coord, rb.coord];
  51338. result.x0 = lt.x;
  51339. result.y0 = lt.y;
  51340. result.x1 = rb.x;
  51341. result.y1 = rb.y;
  51342. return result;
  51343. };
  51344. function isInfinity$1(val) {
  51345. return !isNaN(val) && !isFinite(val);
  51346. } // If a markArea has one dim
  51347. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  51348. var otherDimIndex = 1 - dimIndex;
  51349. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  51350. }
  51351. function markAreaFilter(coordSys, item) {
  51352. var fromCoord = item.coord[0];
  51353. var toCoord = item.coord[1];
  51354. var item0 = {
  51355. coord: fromCoord,
  51356. x: item.x0,
  51357. y: item.y0
  51358. };
  51359. var item1 = {
  51360. coord: toCoord,
  51361. x: item.x1,
  51362. y: item.y1
  51363. };
  51364. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  51365. // In case
  51366. // {
  51367. // markArea: {
  51368. // data: [{ yAxis: 2 }]
  51369. // }
  51370. // }
  51371. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  51372. return true;
  51373. } // Directly returning true may also do the work,
  51374. // because markArea will not be shown automatically
  51375. // when it's not included in coordinate system.
  51376. // But filtering ahead can avoid keeping rendering markArea
  51377. // when there are too many of them.
  51378. return zoneFilter(coordSys, item0, item1);
  51379. }
  51380. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  51381. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  51382. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  51383. var coordSys = seriesModel.coordinateSystem;
  51384. var itemModel = data.getItemModel(idx);
  51385. var point;
  51386. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  51387. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  51388. if (!isNaN(xPx) && !isNaN(yPx)) {
  51389. point = [xPx, yPx];
  51390. } else {
  51391. // Chart like bar may have there own marker positioning logic
  51392. if (seriesModel.getMarkerPosition) {
  51393. // Consider the case that user input the right-bottom point first
  51394. // Pick the larger x and y as 'x1' and 'y1'
  51395. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  51396. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  51397. var clampPointValue0 = coordSys.clampData(pointValue0);
  51398. var clampPointValue1 = coordSys.clampData(pointValue1);
  51399. var pointValue = [];
  51400. if (dims[0] === 'x0') {
  51401. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  51402. } else {
  51403. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  51404. }
  51405. if (dims[1] === 'y0') {
  51406. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  51407. } else {
  51408. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  51409. } // Use the getMarkerPosition
  51410. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  51411. } else {
  51412. var x = data.get(dims[0], idx);
  51413. var y = data.get(dims[1], idx);
  51414. var pt = [x, y];
  51415. coordSys.clampData && coordSys.clampData(pt, pt);
  51416. point = coordSys.dataToPoint(pt, true);
  51417. }
  51418. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  51419. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  51420. var xAxis = coordSys.getAxis('x');
  51421. var yAxis = coordSys.getAxis('y');
  51422. var x = data.get(dims[0], idx);
  51423. var y = data.get(dims[1], idx);
  51424. if (isInfinity$1(x)) {
  51425. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  51426. } else if (isInfinity$1(y)) {
  51427. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  51428. }
  51429. } // Use x, y if has any
  51430. if (!isNaN(xPx)) {
  51431. point[0] = xPx;
  51432. }
  51433. if (!isNaN(yPx)) {
  51434. point[1] = yPx;
  51435. }
  51436. }
  51437. return point;
  51438. }
  51439. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  51440. var MarkAreaView =
  51441. /** @class */
  51442. function (_super) {
  51443. __extends(MarkAreaView, _super);
  51444. function MarkAreaView() {
  51445. var _this = _super !== null && _super.apply(this, arguments) || this;
  51446. _this.type = MarkAreaView.type;
  51447. return _this;
  51448. }
  51449. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  51450. ecModel.eachSeries(function (seriesModel) {
  51451. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  51452. if (maModel) {
  51453. var areaData_1 = maModel.getData();
  51454. areaData_1.each(function (idx) {
  51455. var points = map(dimPermutations, function (dim) {
  51456. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  51457. }); // Layout
  51458. areaData_1.setItemLayout(idx, points);
  51459. var el = areaData_1.getItemGraphicEl(idx);
  51460. el.setShape('points', points);
  51461. });
  51462. }
  51463. }, this);
  51464. };
  51465. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  51466. var coordSys = seriesModel.coordinateSystem;
  51467. var seriesId = seriesModel.id;
  51468. var seriesData = seriesModel.getData();
  51469. var areaGroupMap = this.markerGroupMap;
  51470. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  51471. group: new Group()
  51472. });
  51473. this.group.add(polygonGroup.group);
  51474. this.markKeep(polygonGroup);
  51475. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  51476. maModel.setData(areaData); // Update visual and layout of line
  51477. areaData.each(function (idx) {
  51478. // Layout
  51479. var points = map(dimPermutations, function (dim) {
  51480. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  51481. });
  51482. var xAxisScale = coordSys.getAxis('x').scale;
  51483. var yAxisScale = coordSys.getAxis('y').scale;
  51484. var xAxisExtent = xAxisScale.getExtent();
  51485. var yAxisExtent = yAxisScale.getExtent();
  51486. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  51487. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  51488. asc(xPointExtent);
  51489. asc(yPointExtent);
  51490. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]); // If none of the area is inside coordSys, allClipped is set to be true
  51491. // in layout so that label will not be displayed. See #12591
  51492. var allClipped = !overlapped;
  51493. areaData.setItemLayout(idx, {
  51494. points: points,
  51495. allClipped: allClipped
  51496. });
  51497. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  51498. var color$1 = getVisualFromData(seriesData, 'color');
  51499. if (!style.fill) {
  51500. style.fill = color$1;
  51501. if (isString(style.fill)) {
  51502. style.fill = modifyAlpha(style.fill, 0.4);
  51503. }
  51504. }
  51505. if (!style.stroke) {
  51506. style.stroke = color$1;
  51507. } // Visual
  51508. areaData.setItemVisual(idx, 'style', style);
  51509. });
  51510. areaData.diff(inner$f(polygonGroup).data).add(function (idx) {
  51511. var layout = areaData.getItemLayout(idx);
  51512. if (!layout.allClipped) {
  51513. var polygon = new Polygon({
  51514. shape: {
  51515. points: layout.points
  51516. }
  51517. });
  51518. areaData.setItemGraphicEl(idx, polygon);
  51519. polygonGroup.group.add(polygon);
  51520. }
  51521. }).update(function (newIdx, oldIdx) {
  51522. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(oldIdx);
  51523. var layout = areaData.getItemLayout(newIdx);
  51524. if (!layout.allClipped) {
  51525. if (polygon) {
  51526. updateProps(polygon, {
  51527. shape: {
  51528. points: layout.points
  51529. }
  51530. }, maModel, newIdx);
  51531. } else {
  51532. polygon = new Polygon({
  51533. shape: {
  51534. points: layout.points
  51535. }
  51536. });
  51537. }
  51538. areaData.setItemGraphicEl(newIdx, polygon);
  51539. polygonGroup.group.add(polygon);
  51540. } else if (polygon) {
  51541. polygonGroup.group.remove(polygon);
  51542. }
  51543. }).remove(function (idx) {
  51544. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(idx);
  51545. polygonGroup.group.remove(polygon);
  51546. }).execute();
  51547. areaData.eachItemGraphicEl(function (polygon, idx) {
  51548. var itemModel = areaData.getItemModel(idx);
  51549. var style = areaData.getItemVisual(idx, 'style');
  51550. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  51551. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  51552. labelFetcher: maModel,
  51553. labelDataIndex: idx,
  51554. defaultText: areaData.getName(idx) || '',
  51555. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  51556. });
  51557. setStatesStylesFromModel(polygon, itemModel);
  51558. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  51559. getECData(polygon).dataModel = maModel;
  51560. });
  51561. inner$f(polygonGroup).data = areaData;
  51562. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  51563. };
  51564. MarkAreaView.type = 'markArea';
  51565. return MarkAreaView;
  51566. }(MarkerView);
  51567. function createList$2(coordSys, seriesModel, maModel) {
  51568. var areaData;
  51569. var dataDims;
  51570. var dims = ['x0', 'y0', 'x1', 'y1'];
  51571. if (coordSys) {
  51572. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  51573. var data = seriesModel.getData();
  51574. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  51575. return extend(extend({}, info), {
  51576. name: coordDim,
  51577. // DON'T use ordinalMeta to parse and collect ordinal.
  51578. ordinalMeta: null
  51579. });
  51580. });
  51581. dataDims = map(dims, function (dim, idx) {
  51582. return {
  51583. name: dim,
  51584. type: coordDimsInfos_1[idx % 2].type
  51585. };
  51586. });
  51587. areaData = new SeriesData(dataDims, maModel);
  51588. } else {
  51589. dataDims = [{
  51590. name: 'value',
  51591. type: 'float'
  51592. }];
  51593. areaData = new SeriesData(dataDims, maModel);
  51594. }
  51595. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  51596. if (coordSys) {
  51597. optData = filter(optData, curry(markAreaFilter, coordSys));
  51598. }
  51599. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  51600. // TODO should convert to ParsedValue?
  51601. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  51602. return parseDataValue(rawVal, dataDims[dimIndex]);
  51603. } : function (item, dimName, dataIndex, dimIndex) {
  51604. return parseDataValue(item.value, dataDims[dimIndex]);
  51605. };
  51606. areaData.initData(optData, null, dimValueGetter);
  51607. areaData.hasItemOption = true;
  51608. return areaData;
  51609. }
  51610. function install$g(registers) {
  51611. registers.registerComponentModel(MarkAreaModel);
  51612. registers.registerComponentView(MarkAreaView);
  51613. registers.registerPreprocessor(function (opt) {
  51614. if (checkMarkerInSeries(opt.series, 'markArea')) {
  51615. // Make sure markArea component is enabled
  51616. opt.markArea = opt.markArea || {};
  51617. }
  51618. });
  51619. }
  51620. var getDefaultSelectorOptions = function (ecModel, type) {
  51621. if (type === 'all') {
  51622. return {
  51623. type: 'all',
  51624. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  51625. };
  51626. } else if (type === 'inverse') {
  51627. return {
  51628. type: 'inverse',
  51629. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  51630. };
  51631. }
  51632. };
  51633. var LegendModel =
  51634. /** @class */
  51635. function (_super) {
  51636. __extends(LegendModel, _super);
  51637. function LegendModel() {
  51638. var _this = _super !== null && _super.apply(this, arguments) || this;
  51639. _this.type = LegendModel.type;
  51640. _this.layoutMode = {
  51641. type: 'box',
  51642. // legend.width/height are maxWidth/maxHeight actually,
  51643. // whereas real width/height is calculated by its content.
  51644. // (Setting {left: 10, right: 10} does not make sense).
  51645. // So consider the case:
  51646. // `setOption({legend: {left: 10});`
  51647. // then `setOption({legend: {right: 10});`
  51648. // The previous `left` should be cleared by setting `ignoreSize`.
  51649. ignoreSize: true
  51650. };
  51651. return _this;
  51652. }
  51653. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  51654. this.mergeDefaultAndTheme(option, ecModel);
  51655. option.selected = option.selected || {};
  51656. this._updateSelector(option);
  51657. };
  51658. LegendModel.prototype.mergeOption = function (option, ecModel) {
  51659. _super.prototype.mergeOption.call(this, option, ecModel);
  51660. this._updateSelector(option);
  51661. };
  51662. LegendModel.prototype._updateSelector = function (option) {
  51663. var selector = option.selector;
  51664. var ecModel = this.ecModel;
  51665. if (selector === true) {
  51666. selector = option.selector = ['all', 'inverse'];
  51667. }
  51668. if (isArray(selector)) {
  51669. each(selector, function (item, index) {
  51670. isString(item) && (item = {
  51671. type: item
  51672. });
  51673. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  51674. });
  51675. }
  51676. };
  51677. LegendModel.prototype.optionUpdated = function () {
  51678. this._updateData(this.ecModel);
  51679. var legendData = this._data; // If selectedMode is single, try to select one
  51680. if (legendData[0] && this.get('selectedMode') === 'single') {
  51681. var hasSelected = false; // If has any selected in option.selected
  51682. for (var i = 0; i < legendData.length; i++) {
  51683. var name_1 = legendData[i].get('name');
  51684. if (this.isSelected(name_1)) {
  51685. // Force to unselect others
  51686. this.select(name_1);
  51687. hasSelected = true;
  51688. break;
  51689. }
  51690. } // Try select the first if selectedMode is single
  51691. !hasSelected && this.select(legendData[0].get('name'));
  51692. }
  51693. };
  51694. LegendModel.prototype._updateData = function (ecModel) {
  51695. var potentialData = [];
  51696. var availableNames = [];
  51697. ecModel.eachRawSeries(function (seriesModel) {
  51698. var seriesName = seriesModel.name;
  51699. availableNames.push(seriesName);
  51700. var isPotential;
  51701. if (seriesModel.legendVisualProvider) {
  51702. var provider = seriesModel.legendVisualProvider;
  51703. var names = provider.getAllNames();
  51704. if (!ecModel.isSeriesFiltered(seriesModel)) {
  51705. availableNames = availableNames.concat(names);
  51706. }
  51707. if (names.length) {
  51708. potentialData = potentialData.concat(names);
  51709. } else {
  51710. isPotential = true;
  51711. }
  51712. } else {
  51713. isPotential = true;
  51714. }
  51715. if (isPotential && isNameSpecified(seriesModel)) {
  51716. potentialData.push(seriesModel.name);
  51717. }
  51718. });
  51719. /**
  51720. * @type {Array.<string>}
  51721. * @private
  51722. */
  51723. this._availableNames = availableNames; // If legend.data is not specified in option, use availableNames as data,
  51724. // which is convenient for user preparing option.
  51725. var rawData = this.get('data') || potentialData;
  51726. var legendNameMap = createHashMap();
  51727. var legendData = map(rawData, function (dataItem) {
  51728. // Can be string or number
  51729. if (isString(dataItem) || isNumber(dataItem)) {
  51730. dataItem = {
  51731. name: dataItem
  51732. };
  51733. }
  51734. if (legendNameMap.get(dataItem.name)) {
  51735. // remove legend name duplicate
  51736. return null;
  51737. }
  51738. legendNameMap.set(dataItem.name, true);
  51739. return new Model(dataItem, this, this.ecModel);
  51740. }, this);
  51741. /**
  51742. * @type {Array.<module:echarts/model/Model>}
  51743. * @private
  51744. */
  51745. this._data = filter(legendData, function (item) {
  51746. return !!item;
  51747. });
  51748. };
  51749. LegendModel.prototype.getData = function () {
  51750. return this._data;
  51751. };
  51752. LegendModel.prototype.select = function (name) {
  51753. var selected = this.option.selected;
  51754. var selectedMode = this.get('selectedMode');
  51755. if (selectedMode === 'single') {
  51756. var data = this._data;
  51757. each(data, function (dataItem) {
  51758. selected[dataItem.get('name')] = false;
  51759. });
  51760. }
  51761. selected[name] = true;
  51762. };
  51763. LegendModel.prototype.unSelect = function (name) {
  51764. if (this.get('selectedMode') !== 'single') {
  51765. this.option.selected[name] = false;
  51766. }
  51767. };
  51768. LegendModel.prototype.toggleSelected = function (name) {
  51769. var selected = this.option.selected; // Default is true
  51770. if (!selected.hasOwnProperty(name)) {
  51771. selected[name] = true;
  51772. }
  51773. this[selected[name] ? 'unSelect' : 'select'](name);
  51774. };
  51775. LegendModel.prototype.allSelect = function () {
  51776. var data = this._data;
  51777. var selected = this.option.selected;
  51778. each(data, function (dataItem) {
  51779. selected[dataItem.get('name', true)] = true;
  51780. });
  51781. };
  51782. LegendModel.prototype.inverseSelect = function () {
  51783. var data = this._data;
  51784. var selected = this.option.selected;
  51785. each(data, function (dataItem) {
  51786. var name = dataItem.get('name', true); // Initially, default value is true
  51787. if (!selected.hasOwnProperty(name)) {
  51788. selected[name] = true;
  51789. }
  51790. selected[name] = !selected[name];
  51791. });
  51792. };
  51793. LegendModel.prototype.isSelected = function (name) {
  51794. var selected = this.option.selected;
  51795. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  51796. };
  51797. LegendModel.prototype.getOrient = function () {
  51798. return this.get('orient') === 'vertical' ? {
  51799. index: 1,
  51800. name: 'vertical'
  51801. } : {
  51802. index: 0,
  51803. name: 'horizontal'
  51804. };
  51805. };
  51806. LegendModel.type = 'legend.plain';
  51807. LegendModel.dependencies = ['series'];
  51808. LegendModel.defaultOption = {
  51809. // zlevel: 0,
  51810. z: 4,
  51811. show: true,
  51812. orient: 'horizontal',
  51813. left: 'center',
  51814. // right: 'center',
  51815. top: 0,
  51816. // bottom: null,
  51817. align: 'auto',
  51818. backgroundColor: 'rgba(0,0,0,0)',
  51819. borderColor: '#ccc',
  51820. borderRadius: 0,
  51821. borderWidth: 0,
  51822. padding: 5,
  51823. itemGap: 10,
  51824. itemWidth: 25,
  51825. itemHeight: 14,
  51826. symbolRotate: 'inherit',
  51827. symbolKeepAspect: true,
  51828. inactiveColor: '#ccc',
  51829. inactiveBorderColor: '#ccc',
  51830. inactiveBorderWidth: 'auto',
  51831. itemStyle: {
  51832. color: 'inherit',
  51833. opacity: 'inherit',
  51834. borderColor: 'inherit',
  51835. borderWidth: 'auto',
  51836. borderCap: 'inherit',
  51837. borderJoin: 'inherit',
  51838. borderDashOffset: 'inherit',
  51839. borderMiterLimit: 'inherit'
  51840. },
  51841. lineStyle: {
  51842. width: 'auto',
  51843. color: 'inherit',
  51844. inactiveColor: '#ccc',
  51845. inactiveWidth: 2,
  51846. opacity: 'inherit',
  51847. type: 'inherit',
  51848. cap: 'inherit',
  51849. join: 'inherit',
  51850. dashOffset: 'inherit',
  51851. miterLimit: 'inherit'
  51852. },
  51853. textStyle: {
  51854. color: '#333'
  51855. },
  51856. selectedMode: true,
  51857. selector: false,
  51858. selectorLabel: {
  51859. show: true,
  51860. borderRadius: 10,
  51861. padding: [3, 5, 3, 5],
  51862. fontSize: 12,
  51863. fontFamily: 'sans-serif',
  51864. color: '#666',
  51865. borderWidth: 1,
  51866. borderColor: '#666'
  51867. },
  51868. emphasis: {
  51869. selectorLabel: {
  51870. show: true,
  51871. color: '#eee',
  51872. backgroundColor: '#666'
  51873. }
  51874. },
  51875. selectorPosition: 'auto',
  51876. selectorItemGap: 7,
  51877. selectorButtonGap: 10,
  51878. tooltip: {
  51879. show: false
  51880. }
  51881. };
  51882. return LegendModel;
  51883. }(ComponentModel);
  51884. var curry$1 = curry;
  51885. var each$7 = each;
  51886. var Group$1 = Group;
  51887. var LegendView =
  51888. /** @class */
  51889. function (_super) {
  51890. __extends(LegendView, _super);
  51891. function LegendView() {
  51892. var _this = _super !== null && _super.apply(this, arguments) || this;
  51893. _this.type = LegendView.type;
  51894. _this.newlineDisabled = false;
  51895. return _this;
  51896. }
  51897. LegendView.prototype.init = function () {
  51898. this.group.add(this._contentGroup = new Group$1());
  51899. this.group.add(this._selectorGroup = new Group$1());
  51900. this._isFirstRender = true;
  51901. };
  51902. /**
  51903. * @protected
  51904. */
  51905. LegendView.prototype.getContentGroup = function () {
  51906. return this._contentGroup;
  51907. };
  51908. /**
  51909. * @protected
  51910. */
  51911. LegendView.prototype.getSelectorGroup = function () {
  51912. return this._selectorGroup;
  51913. };
  51914. /**
  51915. * @override
  51916. */
  51917. LegendView.prototype.render = function (legendModel, ecModel, api) {
  51918. var isFirstRender = this._isFirstRender;
  51919. this._isFirstRender = false;
  51920. this.resetInner();
  51921. if (!legendModel.get('show', true)) {
  51922. return;
  51923. }
  51924. var itemAlign = legendModel.get('align');
  51925. var orient = legendModel.get('orient');
  51926. if (!itemAlign || itemAlign === 'auto') {
  51927. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  51928. } // selector has been normalized to an array in model
  51929. var selector = legendModel.get('selector', true);
  51930. var selectorPosition = legendModel.get('selectorPosition', true);
  51931. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  51932. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  51933. }
  51934. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  51935. var positionInfo = legendModel.getBoxLayoutParams();
  51936. var viewportSize = {
  51937. width: api.getWidth(),
  51938. height: api.getHeight()
  51939. };
  51940. var padding = legendModel.get('padding');
  51941. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  51942. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  51943. var layoutRect = getLayoutRect(defaults({
  51944. width: mainRect.width,
  51945. height: mainRect.height
  51946. }, positionInfo), viewportSize, padding);
  51947. this.group.x = layoutRect.x - mainRect.x;
  51948. this.group.y = layoutRect.y - mainRect.y;
  51949. this.group.markRedraw(); // Render background after group is layout.
  51950. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  51951. };
  51952. LegendView.prototype.resetInner = function () {
  51953. this.getContentGroup().removeAll();
  51954. this._backgroundEl && this.group.remove(this._backgroundEl);
  51955. this.getSelectorGroup().removeAll();
  51956. };
  51957. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  51958. var contentGroup = this.getContentGroup();
  51959. var legendDrawnMap = createHashMap();
  51960. var selectMode = legendModel.get('selectedMode');
  51961. var excludeSeriesId = [];
  51962. ecModel.eachRawSeries(function (seriesModel) {
  51963. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  51964. });
  51965. each$7(legendModel.getData(), function (legendItemModel, dataIndex) {
  51966. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  51967. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  51968. var g = new Group$1(); // @ts-ignore
  51969. g.newline = true;
  51970. contentGroup.add(g);
  51971. return;
  51972. } // Representitive series.
  51973. var seriesModel = ecModel.getSeriesByName(name)[0];
  51974. if (legendDrawnMap.get(name)) {
  51975. // Have been drawn
  51976. return;
  51977. } // Legend to control series.
  51978. if (seriesModel) {
  51979. var data = seriesModel.getData();
  51980. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  51981. var legendIcon = data.getVisual('legendIcon');
  51982. /**
  51983. * `data.getVisual('style')` may be the color from the register
  51984. * in series. For example, for line series,
  51985. */
  51986. var style = data.getVisual('style');
  51987. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  51988. 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));
  51989. legendDrawnMap.set(name, true);
  51990. } else {
  51991. // Legend to control data. In pie and funnel.
  51992. ecModel.eachRawSeries(function (seriesModel) {
  51993. // In case multiple series has same data name
  51994. if (legendDrawnMap.get(name)) {
  51995. return;
  51996. }
  51997. if (seriesModel.legendVisualProvider) {
  51998. var provider = seriesModel.legendVisualProvider;
  51999. if (!provider.containName(name)) {
  52000. return;
  52001. }
  52002. var idx = provider.indexOfName(name);
  52003. var style = provider.getItemVisual(idx, 'style');
  52004. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  52005. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  52006. // Do not show nothing.
  52007. if (colorArr && colorArr[3] === 0) {
  52008. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  52009. style = extend(extend({}, style), {
  52010. fill: stringify(colorArr, 'rgba')
  52011. });
  52012. }
  52013. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api); // FIXME: consider different series has items with the same name.
  52014. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  52015. // more than one pie series.
  52016. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  52017. legendDrawnMap.set(name, true);
  52018. }
  52019. }, this);
  52020. }
  52021. if ("development" !== 'production') {
  52022. if (!legendDrawnMap.get(name)) {
  52023. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  52024. }
  52025. }
  52026. }, this);
  52027. if (selector) {
  52028. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  52029. }
  52030. };
  52031. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  52032. var selectorGroup = this.getSelectorGroup();
  52033. each$7(selector, function createSelectorButton(selectorItem) {
  52034. var type = selectorItem.type;
  52035. var labelText = new ZRText({
  52036. style: {
  52037. x: 0,
  52038. y: 0,
  52039. align: 'center',
  52040. verticalAlign: 'middle'
  52041. },
  52042. onclick: function () {
  52043. api.dispatchAction({
  52044. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  52045. });
  52046. }
  52047. });
  52048. selectorGroup.add(labelText);
  52049. var labelModel = legendModel.getModel('selectorLabel');
  52050. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  52051. setLabelStyle(labelText, {
  52052. normal: labelModel,
  52053. emphasis: emphasisLabelModel
  52054. }, {
  52055. defaultText: selectorItem.title
  52056. });
  52057. enableHoverEmphasis(labelText);
  52058. });
  52059. };
  52060. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  52061. var drawType = seriesModel.visualDrawType;
  52062. var itemWidth = legendModel.get('itemWidth');
  52063. var itemHeight = legendModel.get('itemHeight');
  52064. var isSelected = legendModel.isSelected(name);
  52065. var iconRotate = legendItemModel.get('symbolRotate');
  52066. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  52067. var legendIconType = legendItemModel.get('icon');
  52068. legendIcon = legendIconType || legendIcon || 'roundRect';
  52069. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  52070. var itemGroup = new Group$1();
  52071. var textStyleModel = legendItemModel.getModel('textStyle');
  52072. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  52073. // Series has specific way to define legend icon
  52074. itemGroup.add(seriesModel.getLegendIcon({
  52075. itemWidth: itemWidth,
  52076. itemHeight: itemHeight,
  52077. icon: legendIcon,
  52078. iconRotate: iconRotate,
  52079. itemStyle: style.itemStyle,
  52080. lineStyle: style.lineStyle,
  52081. symbolKeepAspect: symbolKeepAspect
  52082. }));
  52083. } else {
  52084. // Use default legend icon policy for most series
  52085. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  52086. itemGroup.add(getDefaultLegendIcon({
  52087. itemWidth: itemWidth,
  52088. itemHeight: itemHeight,
  52089. icon: legendIcon,
  52090. iconRotate: rotate,
  52091. itemStyle: style.itemStyle,
  52092. lineStyle: style.lineStyle,
  52093. symbolKeepAspect: symbolKeepAspect
  52094. }));
  52095. }
  52096. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  52097. var textAlign = itemAlign;
  52098. var formatter = legendModel.get('formatter');
  52099. var content = name;
  52100. if (isString(formatter) && formatter) {
  52101. content = formatter.replace('{name}', name != null ? name : '');
  52102. } else if (isFunction(formatter)) {
  52103. content = formatter(name);
  52104. }
  52105. var inactiveColor = legendItemModel.get('inactiveColor');
  52106. itemGroup.add(new ZRText({
  52107. style: createTextStyle(textStyleModel, {
  52108. text: content,
  52109. x: textX,
  52110. y: itemHeight / 2,
  52111. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  52112. align: textAlign,
  52113. verticalAlign: 'middle'
  52114. })
  52115. })); // Add a invisible rect to increase the area of mouse hover
  52116. var hitRect = new Rect({
  52117. shape: itemGroup.getBoundingRect(),
  52118. invisible: true
  52119. });
  52120. var tooltipModel = legendItemModel.getModel('tooltip');
  52121. if (tooltipModel.get('show')) {
  52122. setTooltipConfig({
  52123. el: hitRect,
  52124. componentModel: legendModel,
  52125. itemName: name,
  52126. itemTooltipOption: tooltipModel.option
  52127. });
  52128. }
  52129. itemGroup.add(hitRect);
  52130. itemGroup.eachChild(function (child) {
  52131. child.silent = true;
  52132. });
  52133. hitRect.silent = !selectMode;
  52134. this.getContentGroup().add(itemGroup);
  52135. enableHoverEmphasis(itemGroup); // @ts-ignore
  52136. itemGroup.__legendDataIndex = dataIndex;
  52137. return itemGroup;
  52138. };
  52139. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  52140. var contentGroup = this.getContentGroup();
  52141. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  52142. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  52143. var contentRect = contentGroup.getBoundingRect();
  52144. var contentPos = [-contentRect.x, -contentRect.y];
  52145. selectorGroup.markRedraw();
  52146. contentGroup.markRedraw();
  52147. if (selector) {
  52148. // Place buttons in selectorGroup
  52149. box( // Buttons in selectorGroup always layout horizontally
  52150. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  52151. var selectorRect = selectorGroup.getBoundingRect();
  52152. var selectorPos = [-selectorRect.x, -selectorRect.y];
  52153. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  52154. var orientIdx = legendModel.getOrient().index;
  52155. var wh = orientIdx === 0 ? 'width' : 'height';
  52156. var hw = orientIdx === 0 ? 'height' : 'width';
  52157. var yx = orientIdx === 0 ? 'y' : 'x';
  52158. if (selectorPosition === 'end') {
  52159. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  52160. } else {
  52161. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  52162. } // Always align selector to content as 'middle'
  52163. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  52164. selectorGroup.x = selectorPos[0];
  52165. selectorGroup.y = selectorPos[1];
  52166. contentGroup.x = contentPos[0];
  52167. contentGroup.y = contentPos[1];
  52168. var mainRect = {
  52169. x: 0,
  52170. y: 0
  52171. };
  52172. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  52173. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  52174. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  52175. return mainRect;
  52176. } else {
  52177. contentGroup.x = contentPos[0];
  52178. contentGroup.y = contentPos[1];
  52179. return this.group.getBoundingRect();
  52180. }
  52181. };
  52182. /**
  52183. * @protected
  52184. */
  52185. LegendView.prototype.remove = function () {
  52186. this.getContentGroup().removeAll();
  52187. this._isFirstRender = true;
  52188. };
  52189. LegendView.type = 'legend.plain';
  52190. return LegendView;
  52191. }(ComponentView);
  52192. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  52193. /**
  52194. * Use series style if is inherit;
  52195. * elsewise, use legend style
  52196. */
  52197. function handleCommonProps(style, visualStyle) {
  52198. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  52199. if (style.lineWidth === 'auto') {
  52200. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  52201. }
  52202. each$7(style, function (propVal, propName) {
  52203. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  52204. });
  52205. } // itemStyle
  52206. var itemStyleModel = legendItemModel.getModel('itemStyle');
  52207. var itemStyle = itemStyleModel.getItemStyle();
  52208. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  52209. var decalStyle = itemStyleModel.getShallow('decal');
  52210. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  52211. if (itemStyle.fill === 'inherit') {
  52212. /**
  52213. * Series with visualDrawType as 'stroke' should have
  52214. * series stroke as legend fill
  52215. */
  52216. itemStyle.fill = itemVisualStyle[drawType];
  52217. }
  52218. if (itemStyle.stroke === 'inherit') {
  52219. /**
  52220. * icon type with "emptyXXX" should use fill color
  52221. * in visual style
  52222. */
  52223. itemStyle.stroke = itemVisualStyle[iconBrushType];
  52224. }
  52225. if (itemStyle.opacity === 'inherit') {
  52226. /**
  52227. * Use lineStyle.opacity if drawType is stroke
  52228. */
  52229. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  52230. }
  52231. handleCommonProps(itemStyle, itemVisualStyle); // lineStyle
  52232. var legendLineModel = legendItemModel.getModel('lineStyle');
  52233. var lineStyle = legendLineModel.getLineStyle();
  52234. handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color
  52235. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  52236. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  52237. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  52238. if (!isSelected) {
  52239. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  52240. /**
  52241. * Since stroke is set to be inactiveBorderColor, it may occur that
  52242. * there is no border in series but border in legend, so we need to
  52243. * use border only when series has border if is set to be auto
  52244. */
  52245. var visualHasBorder = itemStyle[iconBrushType];
  52246. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  52247. itemStyle.fill = legendItemModel.get('inactiveColor');
  52248. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  52249. lineStyle.stroke = legendLineModel.get('inactiveColor');
  52250. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  52251. }
  52252. return {
  52253. itemStyle: itemStyle,
  52254. lineStyle: lineStyle
  52255. };
  52256. }
  52257. function getDefaultLegendIcon(opt) {
  52258. var symboType = opt.icon || 'roundRect';
  52259. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  52260. icon.setStyle(opt.itemStyle);
  52261. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  52262. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  52263. if (symboType.indexOf('empty') > -1) {
  52264. icon.style.stroke = icon.style.fill;
  52265. icon.style.fill = '#fff';
  52266. icon.style.lineWidth = 2;
  52267. }
  52268. return icon;
  52269. }
  52270. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  52271. // downplay before unselect
  52272. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  52273. api.dispatchAction({
  52274. type: 'legendToggleSelect',
  52275. name: seriesName != null ? seriesName : dataName
  52276. }); // highlight after select
  52277. // TODO highlight immediately may cause animation loss.
  52278. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  52279. }
  52280. function isUseHoverLayer(api) {
  52281. var list = api.getZr().storage.getDisplayList();
  52282. var emphasisState;
  52283. var i = 0;
  52284. var len = list.length;
  52285. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  52286. i++;
  52287. }
  52288. return emphasisState && emphasisState.hoverLayer;
  52289. }
  52290. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  52291. // If element hover will move to a hoverLayer.
  52292. if (!isUseHoverLayer(api)) {
  52293. api.dispatchAction({
  52294. type: 'highlight',
  52295. seriesName: seriesName,
  52296. name: dataName,
  52297. excludeSeriesId: excludeSeriesId
  52298. });
  52299. }
  52300. }
  52301. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  52302. // If element hover will move to a hoverLayer.
  52303. if (!isUseHoverLayer(api)) {
  52304. api.dispatchAction({
  52305. type: 'downplay',
  52306. seriesName: seriesName,
  52307. name: dataName,
  52308. excludeSeriesId: excludeSeriesId
  52309. });
  52310. }
  52311. }
  52312. /*
  52313. * Licensed to the Apache Software Foundation (ASF) under one
  52314. * or more contributor license agreements. See the NOTICE file
  52315. * distributed with this work for additional information
  52316. * regarding copyright ownership. The ASF licenses this file
  52317. * to you under the Apache License, Version 2.0 (the
  52318. * "License"); you may not use this file except in compliance
  52319. * with the License. You may obtain a copy of the License at
  52320. *
  52321. * http://www.apache.org/licenses/LICENSE-2.0
  52322. *
  52323. * Unless required by applicable law or agreed to in writing,
  52324. * software distributed under the License is distributed on an
  52325. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52326. * KIND, either express or implied. See the License for the
  52327. * specific language governing permissions and limitations
  52328. * under the License.
  52329. */
  52330. /**
  52331. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52332. */
  52333. /*
  52334. * Licensed to the Apache Software Foundation (ASF) under one
  52335. * or more contributor license agreements. See the NOTICE file
  52336. * distributed with this work for additional information
  52337. * regarding copyright ownership. The ASF licenses this file
  52338. * to you under the Apache License, Version 2.0 (the
  52339. * "License"); you may not use this file except in compliance
  52340. * with the License. You may obtain a copy of the License at
  52341. *
  52342. * http://www.apache.org/licenses/LICENSE-2.0
  52343. *
  52344. * Unless required by applicable law or agreed to in writing,
  52345. * software distributed under the License is distributed on an
  52346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52347. * KIND, either express or implied. See the License for the
  52348. * specific language governing permissions and limitations
  52349. * under the License.
  52350. */
  52351. function legendFilter(ecModel) {
  52352. var legendModels = ecModel.findComponents({
  52353. mainType: 'legend'
  52354. });
  52355. if (legendModels && legendModels.length) {
  52356. ecModel.filterSeries(function (series) {
  52357. // If in any legend component the status is not selected.
  52358. // Because in legend series is assumed selected when it is not in the legend data.
  52359. for (var i = 0; i < legendModels.length; i++) {
  52360. if (!legendModels[i].isSelected(series.name)) {
  52361. return false;
  52362. }
  52363. }
  52364. return true;
  52365. });
  52366. }
  52367. }
  52368. function legendSelectActionHandler(methodName, payload, ecModel) {
  52369. var selectedMap = {};
  52370. var isToggleSelect = methodName === 'toggleSelected';
  52371. var isSelected; // Update all legend components
  52372. ecModel.eachComponent('legend', function (legendModel) {
  52373. if (isToggleSelect && isSelected != null) {
  52374. // Force other legend has same selected status
  52375. // Or the first is toggled to true and other are toggled to false
  52376. // In the case one legend has some item unSelected in option. And if other legend
  52377. // doesn't has the item, they will assume it is selected.
  52378. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  52379. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  52380. legendModel[methodName]();
  52381. } else {
  52382. legendModel[methodName](payload.name);
  52383. isSelected = legendModel.isSelected(payload.name);
  52384. }
  52385. var legendData = legendModel.getData();
  52386. each(legendData, function (model) {
  52387. var name = model.get('name'); // Wrap element
  52388. if (name === '\n' || name === '') {
  52389. return;
  52390. }
  52391. var isItemSelected = legendModel.isSelected(name);
  52392. if (selectedMap.hasOwnProperty(name)) {
  52393. // Unselected if any legend is unselected
  52394. selectedMap[name] = selectedMap[name] && isItemSelected;
  52395. } else {
  52396. selectedMap[name] = isItemSelected;
  52397. }
  52398. });
  52399. }); // Return the event explicitly
  52400. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  52401. selected: selectedMap
  52402. } : {
  52403. name: payload.name,
  52404. selected: selectedMap
  52405. };
  52406. }
  52407. function installLegendAction(registers) {
  52408. /**
  52409. * @event legendToggleSelect
  52410. * @type {Object}
  52411. * @property {string} type 'legendToggleSelect'
  52412. * @property {string} [from]
  52413. * @property {string} name Series name or data item name
  52414. */
  52415. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  52416. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  52417. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  52418. /**
  52419. * @event legendSelect
  52420. * @type {Object}
  52421. * @property {string} type 'legendSelect'
  52422. * @property {string} name Series name or data item name
  52423. */
  52424. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  52425. /**
  52426. * @event legendUnSelect
  52427. * @type {Object}
  52428. * @property {string} type 'legendUnSelect'
  52429. * @property {string} name Series name or data item name
  52430. */
  52431. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  52432. }
  52433. function install$h(registers) {
  52434. registers.registerComponentModel(LegendModel);
  52435. registers.registerComponentView(LegendView);
  52436. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  52437. registers.registerSubTypeDefaulter('legend', function () {
  52438. return 'plain';
  52439. });
  52440. installLegendAction(registers);
  52441. }
  52442. var ScrollableLegendModel =
  52443. /** @class */
  52444. function (_super) {
  52445. __extends(ScrollableLegendModel, _super);
  52446. function ScrollableLegendModel() {
  52447. var _this = _super !== null && _super.apply(this, arguments) || this;
  52448. _this.type = ScrollableLegendModel.type;
  52449. return _this;
  52450. }
  52451. /**
  52452. * @param {number} scrollDataIndex
  52453. */
  52454. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  52455. this.option.scrollDataIndex = scrollDataIndex;
  52456. };
  52457. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  52458. var inputPositionParams = getLayoutParams(option);
  52459. _super.prototype.init.call(this, option, parentModel, ecModel);
  52460. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  52461. };
  52462. /**
  52463. * @override
  52464. */
  52465. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  52466. _super.prototype.mergeOption.call(this, option, ecModel);
  52467. mergeAndNormalizeLayoutParams(this, this.option, option);
  52468. };
  52469. ScrollableLegendModel.type = 'legend.scroll';
  52470. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  52471. scrollDataIndex: 0,
  52472. pageButtonItemGap: 5,
  52473. pageButtonGap: null,
  52474. pageButtonPosition: 'end',
  52475. pageFormatter: '{current}/{total}',
  52476. pageIcons: {
  52477. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  52478. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  52479. },
  52480. pageIconColor: '#2f4554',
  52481. pageIconInactiveColor: '#aaa',
  52482. pageIconSize: 15,
  52483. pageTextStyle: {
  52484. color: '#333'
  52485. },
  52486. animationDurationUpdate: 800
  52487. });
  52488. return ScrollableLegendModel;
  52489. }(LegendModel);
  52490. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  52491. var orient = legendModel.getOrient();
  52492. var ignoreSize = [1, 1];
  52493. ignoreSize[orient.index] = 0;
  52494. mergeLayoutParam(target, raw, {
  52495. type: 'box',
  52496. ignoreSize: !!ignoreSize
  52497. });
  52498. }
  52499. var Group$2 = Group;
  52500. var WH = ['width', 'height'];
  52501. var XY = ['x', 'y'];
  52502. var ScrollableLegendView =
  52503. /** @class */
  52504. function (_super) {
  52505. __extends(ScrollableLegendView, _super);
  52506. function ScrollableLegendView() {
  52507. var _this = _super !== null && _super.apply(this, arguments) || this;
  52508. _this.type = ScrollableLegendView.type;
  52509. _this.newlineDisabled = true;
  52510. _this._currentIndex = 0;
  52511. return _this;
  52512. }
  52513. ScrollableLegendView.prototype.init = function () {
  52514. _super.prototype.init.call(this);
  52515. this.group.add(this._containerGroup = new Group$2());
  52516. this._containerGroup.add(this.getContentGroup());
  52517. this.group.add(this._controllerGroup = new Group$2());
  52518. };
  52519. /**
  52520. * @override
  52521. */
  52522. ScrollableLegendView.prototype.resetInner = function () {
  52523. _super.prototype.resetInner.call(this);
  52524. this._controllerGroup.removeAll();
  52525. this._containerGroup.removeClipPath();
  52526. this._containerGroup.__rectSize = null;
  52527. };
  52528. /**
  52529. * @override
  52530. */
  52531. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  52532. var self = this; // Render content items.
  52533. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  52534. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  52535. // e.g., '3/12345' should not overlap with the control arrow button.
  52536. var pageIconSize = legendModel.get('pageIconSize', true);
  52537. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  52538. createPageButton('pagePrev', 0);
  52539. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  52540. controllerGroup.add(new ZRText({
  52541. name: 'pageText',
  52542. style: {
  52543. // Placeholder to calculate a proper layout.
  52544. text: 'xx/xx',
  52545. fill: pageTextStyleModel.getTextColor(),
  52546. font: pageTextStyleModel.getFont(),
  52547. verticalAlign: 'middle',
  52548. align: 'center'
  52549. },
  52550. silent: true
  52551. }));
  52552. createPageButton('pageNext', 1);
  52553. function createPageButton(name, iconIdx) {
  52554. var pageDataIndexName = name + 'DataIndex';
  52555. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  52556. // Buttons will be created in each render, so we do not need
  52557. // to worry about avoiding using legendModel kept in scope.
  52558. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  52559. }, {
  52560. x: -pageIconSizeArr[0] / 2,
  52561. y: -pageIconSizeArr[1] / 2,
  52562. width: pageIconSizeArr[0],
  52563. height: pageIconSizeArr[1]
  52564. });
  52565. icon.name = name;
  52566. controllerGroup.add(icon);
  52567. }
  52568. };
  52569. /**
  52570. * @override
  52571. */
  52572. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  52573. var selectorGroup = this.getSelectorGroup();
  52574. var orientIdx = legendModel.getOrient().index;
  52575. var wh = WH[orientIdx];
  52576. var xy = XY[orientIdx];
  52577. var hw = WH[1 - orientIdx];
  52578. var yx = XY[1 - orientIdx];
  52579. selector && box( // Buttons in selectorGroup always layout horizontally
  52580. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  52581. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  52582. var selectorRect = selectorGroup.getBoundingRect();
  52583. var selectorPos = [-selectorRect.x, -selectorRect.y];
  52584. var processMaxSize = clone(maxSize);
  52585. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  52586. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  52587. if (selector) {
  52588. if (selectorPosition === 'end') {
  52589. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  52590. } else {
  52591. var offset = selectorRect[wh] + selectorButtonGap;
  52592. selectorPos[orientIdx] -= offset;
  52593. mainRect[xy] -= offset;
  52594. }
  52595. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  52596. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  52597. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  52598. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  52599. selectorGroup.x = selectorPos[0];
  52600. selectorGroup.y = selectorPos[1];
  52601. selectorGroup.markRedraw();
  52602. }
  52603. return mainRect;
  52604. };
  52605. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  52606. var contentGroup = this.getContentGroup();
  52607. var containerGroup = this._containerGroup;
  52608. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  52609. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  52610. box( // Buttons in controller are layout always horizontally.
  52611. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  52612. var contentRect = contentGroup.getBoundingRect();
  52613. var controllerRect = controllerGroup.getBoundingRect();
  52614. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  52615. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  52616. // If first rendering, `contentGroup.position` is [0, 0], which
  52617. // does not make sense and may cause unexepcted animation if adopted.
  52618. if (!isFirstRender) {
  52619. contentPos[orientIdx] = contentGroup[xy];
  52620. } // Layout container group based on 0.
  52621. var containerPos = [0, 0];
  52622. var controllerPos = [-controllerRect.x, -controllerRect.y];
  52623. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  52624. if (showController) {
  52625. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  52626. if (pageButtonPosition === 'end') {
  52627. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  52628. } // controller is on the left / top.
  52629. else {
  52630. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  52631. }
  52632. } // Always align controller to content as 'middle'.
  52633. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  52634. contentGroup.setPosition(contentPos);
  52635. containerGroup.setPosition(containerPos);
  52636. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  52637. // mainRect should not be calculated by `this.group.getBoundingRect()`
  52638. // for sake of the overflow.
  52639. var mainRect = {
  52640. x: 0,
  52641. y: 0
  52642. }; // Consider content may be overflow (should be clipped).
  52643. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  52644. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  52645. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  52646. containerGroup.__rectSize = maxSize[wh];
  52647. if (showController) {
  52648. var clipShape = {
  52649. x: 0,
  52650. y: 0
  52651. };
  52652. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  52653. clipShape[hw] = mainRect[hw];
  52654. containerGroup.setClipPath(new Rect({
  52655. shape: clipShape
  52656. })); // Consider content may be larger than container, container rect
  52657. // can not be obtained from `containerGroup.getBoundingRect()`.
  52658. containerGroup.__rectSize = clipShape[wh];
  52659. } else {
  52660. // Do not remove or ignore controller. Keep them set as placeholders.
  52661. controllerGroup.eachChild(function (child) {
  52662. child.attr({
  52663. invisible: true,
  52664. silent: true
  52665. });
  52666. });
  52667. } // Content translate animation.
  52668. var pageInfo = this._getPageInfo(legendModel);
  52669. pageInfo.pageIndex != null && updateProps(contentGroup, {
  52670. x: pageInfo.contentPosition[0],
  52671. y: pageInfo.contentPosition[1]
  52672. }, // When switch from "show controller" to "not show controller", view should be
  52673. // updated immediately without animation, otherwise causes weird effect.
  52674. showController ? legendModel : null);
  52675. this._updatePageInfoView(legendModel, pageInfo);
  52676. return mainRect;
  52677. };
  52678. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  52679. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  52680. scrollDataIndex != null && api.dispatchAction({
  52681. type: 'legendScroll',
  52682. scrollDataIndex: scrollDataIndex,
  52683. legendId: legendModel.id
  52684. });
  52685. };
  52686. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  52687. var controllerGroup = this._controllerGroup;
  52688. each(['pagePrev', 'pageNext'], function (name) {
  52689. var key = name + 'DataIndex';
  52690. var canJump = pageInfo[key] != null;
  52691. var icon = controllerGroup.childOfName(name);
  52692. if (icon) {
  52693. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  52694. icon.cursor = canJump ? 'pointer' : 'default';
  52695. }
  52696. });
  52697. var pageText = controllerGroup.childOfName('pageText');
  52698. var pageFormatter = legendModel.get('pageFormatter');
  52699. var pageIndex = pageInfo.pageIndex;
  52700. var current = pageIndex != null ? pageIndex + 1 : 0;
  52701. var total = pageInfo.pageCount;
  52702. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  52703. current: current,
  52704. total: total
  52705. }));
  52706. };
  52707. /**
  52708. * contentPosition: Array.<number>, null when data item not found.
  52709. * pageIndex: number, null when data item not found.
  52710. * pageCount: number, always be a number, can be 0.
  52711. * pagePrevDataIndex: number, null when no previous page.
  52712. * pageNextDataIndex: number, null when no next page.
  52713. * }
  52714. */
  52715. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  52716. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  52717. var contentGroup = this.getContentGroup();
  52718. var containerRectSize = this._containerGroup.__rectSize;
  52719. var orientIdx = legendModel.getOrient().index;
  52720. var wh = WH[orientIdx];
  52721. var xy = XY[orientIdx];
  52722. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  52723. var children = contentGroup.children();
  52724. var targetItem = children[targetItemIndex];
  52725. var itemCount = children.length;
  52726. var pCount = !itemCount ? 0 : 1;
  52727. var result = {
  52728. contentPosition: [contentGroup.x, contentGroup.y],
  52729. pageCount: pCount,
  52730. pageIndex: pCount - 1,
  52731. pagePrevDataIndex: null,
  52732. pageNextDataIndex: null
  52733. };
  52734. if (!targetItem) {
  52735. return result;
  52736. }
  52737. var targetItemInfo = getItemInfo(targetItem);
  52738. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  52739. // (1) Always align based on the left/top most item.
  52740. // (2) It is user-friendly that the last item shown in the
  52741. // current window is shown at the begining of next window.
  52742. // Otherwise if half of the last item is cut by the window,
  52743. // it will have no chance to display entirely.
  52744. // (3) Consider that item size probably be different, we
  52745. // have calculate pageIndex by size rather than item index,
  52746. // and we can not get page index directly by division.
  52747. // (4) The window is to narrow to contain more than
  52748. // one item, we should make sure that the page can be fliped.
  52749. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  52750. currItemInfo = getItemInfo(children[i]);
  52751. if ( // Half of the last item is out of the window.
  52752. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  52753. // can be started at the current item or the last item.
  52754. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  52755. if (winEndItemInfo.i > winStartItemInfo.i) {
  52756. winStartItemInfo = winEndItemInfo;
  52757. } else {
  52758. // e.g., when page size is smaller than item size.
  52759. winStartItemInfo = currItemInfo;
  52760. }
  52761. if (winStartItemInfo) {
  52762. if (result.pageNextDataIndex == null) {
  52763. result.pageNextDataIndex = winStartItemInfo.i;
  52764. }
  52765. ++result.pageCount;
  52766. }
  52767. }
  52768. winEndItemInfo = currItemInfo;
  52769. }
  52770. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  52771. currItemInfo = getItemInfo(children[i]);
  52772. if ( // If the the end item does not intersect with the window started
  52773. // from the current item, a page can be settled.
  52774. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  52775. winStartItemInfo.i < winEndItemInfo.i) {
  52776. winEndItemInfo = winStartItemInfo;
  52777. if (result.pagePrevDataIndex == null) {
  52778. result.pagePrevDataIndex = winStartItemInfo.i;
  52779. }
  52780. ++result.pageCount;
  52781. ++result.pageIndex;
  52782. }
  52783. winStartItemInfo = currItemInfo;
  52784. }
  52785. return result;
  52786. function getItemInfo(el) {
  52787. if (el) {
  52788. var itemRect = el.getBoundingRect();
  52789. var start = itemRect[xy] + el[xy];
  52790. return {
  52791. s: start,
  52792. e: start + itemRect[wh],
  52793. i: el.__legendDataIndex
  52794. };
  52795. }
  52796. }
  52797. function intersect(itemInfo, winStart) {
  52798. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  52799. }
  52800. };
  52801. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  52802. if (!this._showController) {
  52803. return 0;
  52804. }
  52805. var index;
  52806. var contentGroup = this.getContentGroup();
  52807. var defaultIndex;
  52808. contentGroup.eachChild(function (child, idx) {
  52809. var legendDataIdx = child.__legendDataIndex; // FIXME
  52810. // If the given targetDataIndex (from model) is illegal,
  52811. // we use defaultIndex. But the index on the legend model and
  52812. // action payload is still illegal. That case will not be
  52813. // changed until some scenario requires.
  52814. if (defaultIndex == null && legendDataIdx != null) {
  52815. defaultIndex = idx;
  52816. }
  52817. if (legendDataIdx === targetDataIndex) {
  52818. index = idx;
  52819. }
  52820. });
  52821. return index != null ? index : defaultIndex;
  52822. };
  52823. ScrollableLegendView.type = 'legend.scroll';
  52824. return ScrollableLegendView;
  52825. }(LegendView);
  52826. /*
  52827. * Licensed to the Apache Software Foundation (ASF) under one
  52828. * or more contributor license agreements. See the NOTICE file
  52829. * distributed with this work for additional information
  52830. * regarding copyright ownership. The ASF licenses this file
  52831. * to you under the Apache License, Version 2.0 (the
  52832. * "License"); you may not use this file except in compliance
  52833. * with the License. You may obtain a copy of the License at
  52834. *
  52835. * http://www.apache.org/licenses/LICENSE-2.0
  52836. *
  52837. * Unless required by applicable law or agreed to in writing,
  52838. * software distributed under the License is distributed on an
  52839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52840. * KIND, either express or implied. See the License for the
  52841. * specific language governing permissions and limitations
  52842. * under the License.
  52843. */
  52844. /**
  52845. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52846. */
  52847. /*
  52848. * Licensed to the Apache Software Foundation (ASF) under one
  52849. * or more contributor license agreements. See the NOTICE file
  52850. * distributed with this work for additional information
  52851. * regarding copyright ownership. The ASF licenses this file
  52852. * to you under the Apache License, Version 2.0 (the
  52853. * "License"); you may not use this file except in compliance
  52854. * with the License. You may obtain a copy of the License at
  52855. *
  52856. * http://www.apache.org/licenses/LICENSE-2.0
  52857. *
  52858. * Unless required by applicable law or agreed to in writing,
  52859. * software distributed under the License is distributed on an
  52860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52861. * KIND, either express or implied. See the License for the
  52862. * specific language governing permissions and limitations
  52863. * under the License.
  52864. */
  52865. function installScrollableLegendAction(registers) {
  52866. /**
  52867. * @event legendScroll
  52868. * @type {Object}
  52869. * @property {string} type 'legendScroll'
  52870. * @property {string} scrollDataIndex
  52871. */
  52872. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  52873. var scrollDataIndex = payload.scrollDataIndex;
  52874. scrollDataIndex != null && ecModel.eachComponent({
  52875. mainType: 'legend',
  52876. subType: 'scroll',
  52877. query: payload
  52878. }, function (legendModel) {
  52879. legendModel.setScrollDataIndex(scrollDataIndex);
  52880. });
  52881. });
  52882. }
  52883. function install$i(registers) {
  52884. use(install$h);
  52885. registers.registerComponentModel(ScrollableLegendModel);
  52886. registers.registerComponentView(ScrollableLegendView);
  52887. installScrollableLegendAction(registers);
  52888. }
  52889. function install$j(registers) {
  52890. use(install$h);
  52891. use(install$i);
  52892. }
  52893. var InsideZoomModel =
  52894. /** @class */
  52895. function (_super) {
  52896. __extends(InsideZoomModel, _super);
  52897. function InsideZoomModel() {
  52898. var _this = _super !== null && _super.apply(this, arguments) || this;
  52899. _this.type = InsideZoomModel.type;
  52900. return _this;
  52901. }
  52902. InsideZoomModel.type = 'dataZoom.inside';
  52903. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  52904. disabled: false,
  52905. zoomLock: false,
  52906. zoomOnMouseWheel: true,
  52907. moveOnMouseMove: true,
  52908. moveOnMouseWheel: false,
  52909. preventDefaultMouseMove: true
  52910. });
  52911. return InsideZoomModel;
  52912. }(DataZoomModel);
  52913. var RoamController =
  52914. /** @class */
  52915. function (_super) {
  52916. __extends(RoamController, _super);
  52917. function RoamController(zr) {
  52918. var _this = _super.call(this) || this;
  52919. _this._zr = zr; // Avoid two roamController bind the same handler
  52920. var mousedownHandler = bind(_this._mousedownHandler, _this);
  52921. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  52922. var mouseupHandler = bind(_this._mouseupHandler, _this);
  52923. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  52924. var pinchHandler = bind(_this._pinchHandler, _this);
  52925. /**
  52926. * Notice: only enable needed types. For example, if 'zoom'
  52927. * is not needed, 'zoom' should not be enabled, otherwise
  52928. * default mousewheel behaviour (scroll page) will be disabled.
  52929. */
  52930. _this.enable = function (controlType, opt) {
  52931. // Disable previous first
  52932. this.disable();
  52933. this._opt = defaults(clone(opt) || {}, {
  52934. zoomOnMouseWheel: true,
  52935. moveOnMouseMove: true,
  52936. // By default, wheel do not trigger move.
  52937. moveOnMouseWheel: false,
  52938. preventDefaultMouseMove: true
  52939. });
  52940. if (controlType == null) {
  52941. controlType = true;
  52942. }
  52943. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  52944. zr.on('mousedown', mousedownHandler);
  52945. zr.on('mousemove', mousemoveHandler);
  52946. zr.on('mouseup', mouseupHandler);
  52947. }
  52948. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  52949. zr.on('mousewheel', mousewheelHandler);
  52950. zr.on('pinch', pinchHandler);
  52951. }
  52952. };
  52953. _this.disable = function () {
  52954. zr.off('mousedown', mousedownHandler);
  52955. zr.off('mousemove', mousemoveHandler);
  52956. zr.off('mouseup', mouseupHandler);
  52957. zr.off('mousewheel', mousewheelHandler);
  52958. zr.off('pinch', pinchHandler);
  52959. };
  52960. return _this;
  52961. }
  52962. RoamController.prototype.isDragging = function () {
  52963. return this._dragging;
  52964. };
  52965. RoamController.prototype.isPinching = function () {
  52966. return this._pinching;
  52967. };
  52968. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  52969. this.pointerChecker = pointerChecker;
  52970. };
  52971. RoamController.prototype.dispose = function () {
  52972. this.disable();
  52973. };
  52974. RoamController.prototype._mousedownHandler = function (e) {
  52975. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  52976. return;
  52977. }
  52978. var el = e.target;
  52979. while (el) {
  52980. if (el.draggable) {
  52981. return;
  52982. } // check if host is draggable
  52983. el = el.__hostTarget || el.parent;
  52984. }
  52985. var x = e.offsetX;
  52986. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  52987. // Mouse can be out of target when mouse moving.
  52988. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  52989. this._x = x;
  52990. this._y = y;
  52991. this._dragging = true;
  52992. }
  52993. };
  52994. RoamController.prototype._mousemoveHandler = function (e) {
  52995. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  52996. return;
  52997. }
  52998. var x = e.offsetX;
  52999. var y = e.offsetY;
  53000. var oldX = this._x;
  53001. var oldY = this._y;
  53002. var dx = x - oldX;
  53003. var dy = y - oldY;
  53004. this._x = x;
  53005. this._y = y;
  53006. this._opt.preventDefaultMouseMove && stop(e.event);
  53007. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  53008. dx: dx,
  53009. dy: dy,
  53010. oldX: oldX,
  53011. oldY: oldY,
  53012. newX: x,
  53013. newY: y,
  53014. isAvailableBehavior: null
  53015. });
  53016. };
  53017. RoamController.prototype._mouseupHandler = function (e) {
  53018. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  53019. this._dragging = false;
  53020. }
  53021. };
  53022. RoamController.prototype._mousewheelHandler = function (e) {
  53023. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  53024. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  53025. var wheelDelta = e.wheelDelta;
  53026. var absWheelDeltaDelta = Math.abs(wheelDelta);
  53027. var originX = e.offsetX;
  53028. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  53029. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  53030. return;
  53031. } // If both `shouldZoom` and `shouldMove` is true, trigger
  53032. // their event both, and the final behavior is determined
  53033. // by event listener themselves.
  53034. if (shouldZoom) {
  53035. // Convenience:
  53036. // Mac and VM Windows on Mac: scroll up: zoom out.
  53037. // Windows: scroll up: zoom in.
  53038. // FIXME: Should do more test in different environment.
  53039. // wheelDelta is too complicated in difference nvironment
  53040. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  53041. // although it has been normallized by zrender.
  53042. // wheelDelta of mouse wheel is bigger than touch pad.
  53043. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  53044. var scale = wheelDelta > 0 ? factor : 1 / factor;
  53045. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  53046. scale: scale,
  53047. originX: originX,
  53048. originY: originY,
  53049. isAvailableBehavior: null
  53050. });
  53051. }
  53052. if (shouldMove) {
  53053. // FIXME: Should do more test in different environment.
  53054. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  53055. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  53056. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  53057. scrollDelta: scrollDelta,
  53058. originX: originX,
  53059. originY: originY,
  53060. isAvailableBehavior: null
  53061. });
  53062. }
  53063. };
  53064. RoamController.prototype._pinchHandler = function (e) {
  53065. if (isTaken(this._zr, 'globalPan')) {
  53066. return;
  53067. }
  53068. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  53069. checkPointerAndTrigger(this, 'zoom', null, e, {
  53070. scale: scale,
  53071. originX: e.pinchX,
  53072. originY: e.pinchY,
  53073. isAvailableBehavior: null
  53074. });
  53075. };
  53076. return RoamController;
  53077. }(Eventful);
  53078. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  53079. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  53080. // When mouse is out of roamController rect,
  53081. // default befavoius should not be be disabled, otherwise
  53082. // page sliding is disabled, contrary to expectation.
  53083. stop(e.event);
  53084. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  53085. }
  53086. }
  53087. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  53088. // Also provide behavior checker for event listener, for some case that
  53089. // multiple components share one listener.
  53090. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  53091. controller.trigger(eventName, contollerEvent);
  53092. } // settings: {
  53093. // zoomOnMouseWheel
  53094. // moveOnMouseMove
  53095. // moveOnMouseWheel
  53096. // }
  53097. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  53098. function isAvailableBehavior(behaviorToCheck, e, settings) {
  53099. var setting = settings[behaviorToCheck];
  53100. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  53101. }
  53102. var inner$g = makeInner();
  53103. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  53104. inner$g(api).coordSysRecordMap.each(function (coordSysRecord) {
  53105. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  53106. if (dzInfo) {
  53107. dzInfo.getRange = getRange;
  53108. }
  53109. });
  53110. }
  53111. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  53112. var coordSysRecordMap = inner$g(api).coordSysRecordMap;
  53113. var coordSysKeyArr = coordSysRecordMap.keys();
  53114. for (var i = 0; i < coordSysKeyArr.length; i++) {
  53115. var coordSysKey = coordSysKeyArr[i];
  53116. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  53117. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  53118. if (dataZoomInfoMap) {
  53119. var dzUid = dataZoomModel.uid;
  53120. var dzInfo = dataZoomInfoMap.get(dzUid);
  53121. if (dzInfo) {
  53122. dataZoomInfoMap.removeKey(dzUid);
  53123. if (!dataZoomInfoMap.keys().length) {
  53124. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  53125. }
  53126. }
  53127. }
  53128. }
  53129. }
  53130. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  53131. if (coordSysRecord) {
  53132. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  53133. var controller = coordSysRecord.controller;
  53134. controller && controller.dispose();
  53135. }
  53136. }
  53137. function createCoordSysRecord(api, coordSysModel) {
  53138. // These init props will never change after record created.
  53139. var coordSysRecord = {
  53140. model: coordSysModel,
  53141. containsPoint: curry(containsPoint, coordSysModel),
  53142. dispatchAction: curry(dispatchAction, api),
  53143. dataZoomInfoMap: null,
  53144. controller: null
  53145. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  53146. // because coordSysRecord not completed yet.
  53147. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  53148. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  53149. controller.on(eventName, function (event) {
  53150. var batch = [];
  53151. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  53152. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  53153. // moveOnMouseWheel, ...) enabled.
  53154. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  53155. return;
  53156. }
  53157. var method = (dzInfo.getRange || {})[eventName];
  53158. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  53159. !dzInfo.model.get('disabled', true) && range && batch.push({
  53160. dataZoomId: dzInfo.model.id,
  53161. start: range[0],
  53162. end: range[1]
  53163. });
  53164. });
  53165. batch.length && coordSysRecord.dispatchAction(batch);
  53166. });
  53167. });
  53168. return coordSysRecord;
  53169. }
  53170. /**
  53171. * This action will be throttled.
  53172. */
  53173. function dispatchAction(api, batch) {
  53174. if (!api.isDisposed()) {
  53175. api.dispatchAction({
  53176. type: 'dataZoom',
  53177. animation: {
  53178. easing: 'cubicOut',
  53179. duration: 100
  53180. },
  53181. batch: batch
  53182. });
  53183. }
  53184. }
  53185. function containsPoint(coordSysModel, e, x, y) {
  53186. return coordSysModel.coordinateSystem.containPoint([x, y]);
  53187. }
  53188. /**
  53189. * Merge roamController settings when multiple dataZooms share one roamController.
  53190. */
  53191. function mergeControllerParams(dataZoomInfoMap) {
  53192. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  53193. // as string, it is probably revert to reserved word by compress tool. See #7411.
  53194. var prefix = 'type_';
  53195. var typePriority = {
  53196. 'type_true': 2,
  53197. 'type_move': 1,
  53198. 'type_false': 0,
  53199. 'type_undefined': -1
  53200. };
  53201. var preventDefaultMouseMove = true;
  53202. dataZoomInfoMap.each(function (dataZoomInfo) {
  53203. var dataZoomModel = dataZoomInfo.model;
  53204. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  53205. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  53206. controlType = oneType;
  53207. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  53208. // users may be confused why it does not work when multiple insideZooms exist.
  53209. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  53210. });
  53211. return {
  53212. controlType: controlType,
  53213. opt: {
  53214. // RoamController will enable all of these functionalities,
  53215. // and the final behavior is determined by its event listener
  53216. // provided by each inside zoom.
  53217. zoomOnMouseWheel: true,
  53218. moveOnMouseMove: true,
  53219. moveOnMouseWheel: true,
  53220. preventDefaultMouseMove: !!preventDefaultMouseMove
  53221. }
  53222. };
  53223. }
  53224. function installDataZoomRoamProcessor(registers) {
  53225. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  53226. var apiInner = inner$g(api);
  53227. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  53228. coordSysRecordMap.each(function (coordSysRecord) {
  53229. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  53230. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  53231. coordSysRecord.dataZoomInfoMap = null;
  53232. });
  53233. ecModel.eachComponent({
  53234. mainType: 'dataZoom',
  53235. subType: 'inside'
  53236. }, function (dataZoomModel) {
  53237. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  53238. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  53239. var coordSysUid = dzCoordSysInfo.model.uid;
  53240. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  53241. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  53242. dataZoomInfoMap.set(dataZoomModel.uid, {
  53243. dzReferCoordSysInfo: dzCoordSysInfo,
  53244. model: dataZoomModel,
  53245. getRange: null
  53246. });
  53247. });
  53248. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  53249. // (2) Clear coord sys if not refered by any dataZoom.
  53250. coordSysRecordMap.each(function (coordSysRecord) {
  53251. var controller = coordSysRecord.controller;
  53252. var firstDzInfo;
  53253. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  53254. if (dataZoomInfoMap) {
  53255. var firstDzKey = dataZoomInfoMap.keys()[0];
  53256. if (firstDzKey != null) {
  53257. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  53258. }
  53259. }
  53260. if (!firstDzInfo) {
  53261. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  53262. return;
  53263. }
  53264. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  53265. controller.enable(controllerParams.controlType, controllerParams.opt);
  53266. controller.setPointerChecker(coordSysRecord.containsPoint);
  53267. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  53268. });
  53269. });
  53270. }
  53271. var InsideZoomView =
  53272. /** @class */
  53273. function (_super) {
  53274. __extends(InsideZoomView, _super);
  53275. function InsideZoomView() {
  53276. var _this = _super !== null && _super.apply(this, arguments) || this;
  53277. _this.type = 'dataZoom.inside';
  53278. return _this;
  53279. }
  53280. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  53281. _super.prototype.render.apply(this, arguments);
  53282. if (dataZoomModel.noTarget()) {
  53283. this._clear();
  53284. return;
  53285. } // Hence the `throttle` util ensures to preserve command order,
  53286. // here simply updating range all the time will not cause missing
  53287. // any of the the roam change.
  53288. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  53289. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  53290. pan: bind(getRangeHandlers.pan, this),
  53291. zoom: bind(getRangeHandlers.zoom, this),
  53292. scrollMove: bind(getRangeHandlers.scrollMove, this)
  53293. });
  53294. };
  53295. InsideZoomView.prototype.dispose = function () {
  53296. this._clear();
  53297. _super.prototype.dispose.apply(this, arguments);
  53298. };
  53299. InsideZoomView.prototype._clear = function () {
  53300. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  53301. this.range = null;
  53302. };
  53303. InsideZoomView.type = 'dataZoom.inside';
  53304. return InsideZoomView;
  53305. }(DataZoomView);
  53306. var getRangeHandlers = {
  53307. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  53308. var lastRange = this.range;
  53309. var range = lastRange.slice(); // Calculate transform by the first axis.
  53310. var axisModel = coordSysInfo.axisModels[0];
  53311. if (!axisModel) {
  53312. return;
  53313. }
  53314. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  53315. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  53316. var scale = Math.max(1 / e.scale, 0);
  53317. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  53318. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  53319. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  53320. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  53321. this.range = range;
  53322. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  53323. return range;
  53324. }
  53325. },
  53326. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  53327. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  53328. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  53329. }),
  53330. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  53331. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  53332. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  53333. })
  53334. };
  53335. function makeMover(getPercentDelta) {
  53336. return function (coordSysInfo, coordSysMainType, controller, e) {
  53337. var lastRange = this.range;
  53338. var range = lastRange.slice(); // Calculate transform by the first axis.
  53339. var axisModel = coordSysInfo.axisModels[0];
  53340. if (!axisModel) {
  53341. return;
  53342. }
  53343. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  53344. sliderMove(percentDelta, range, [0, 100], 'all');
  53345. this.range = range;
  53346. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  53347. return range;
  53348. }
  53349. };
  53350. }
  53351. var getDirectionInfo = {
  53352. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  53353. var axis = axisModel.axis;
  53354. var ret = {};
  53355. var rect = coordSysInfo.model.coordinateSystem.getRect();
  53356. oldPoint = oldPoint || [0, 0];
  53357. if (axis.dim === 'x') {
  53358. ret.pixel = newPoint[0] - oldPoint[0];
  53359. ret.pixelLength = rect.width;
  53360. ret.pixelStart = rect.x;
  53361. ret.signal = axis.inverse ? 1 : -1;
  53362. } else {
  53363. // axis.dim === 'y'
  53364. ret.pixel = newPoint[1] - oldPoint[1];
  53365. ret.pixelLength = rect.height;
  53366. ret.pixelStart = rect.y;
  53367. ret.signal = axis.inverse ? -1 : 1;
  53368. }
  53369. return ret;
  53370. },
  53371. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  53372. var axis = axisModel.axis;
  53373. var ret = {};
  53374. var polar = coordSysInfo.model.coordinateSystem;
  53375. var radiusExtent = polar.getRadiusAxis().getExtent();
  53376. var angleExtent = polar.getAngleAxis().getExtent();
  53377. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  53378. newPoint = polar.pointToCoord(newPoint);
  53379. if (axisModel.mainType === 'radiusAxis') {
  53380. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  53381. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  53382. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  53383. ret.pixelStart = radiusExtent[0];
  53384. ret.signal = axis.inverse ? 1 : -1;
  53385. } else {
  53386. // 'angleAxis'
  53387. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  53388. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  53389. ret.pixelLength = angleExtent[1] - angleExtent[0];
  53390. ret.pixelStart = angleExtent[0];
  53391. ret.signal = axis.inverse ? -1 : 1;
  53392. }
  53393. return ret;
  53394. },
  53395. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  53396. var axis = axisModel.axis;
  53397. var rect = coordSysInfo.model.coordinateSystem.getRect();
  53398. var ret = {};
  53399. oldPoint = oldPoint || [0, 0];
  53400. if (axis.orient === 'horizontal') {
  53401. ret.pixel = newPoint[0] - oldPoint[0];
  53402. ret.pixelLength = rect.width;
  53403. ret.pixelStart = rect.x;
  53404. ret.signal = axis.inverse ? 1 : -1;
  53405. } else {
  53406. // 'vertical'
  53407. ret.pixel = newPoint[1] - oldPoint[1];
  53408. ret.pixelLength = rect.height;
  53409. ret.pixelStart = rect.y;
  53410. ret.signal = axis.inverse ? -1 : 1;
  53411. }
  53412. return ret;
  53413. }
  53414. };
  53415. function install$k(registers) {
  53416. installCommon(registers);
  53417. registers.registerComponentModel(InsideZoomModel);
  53418. registers.registerComponentView(InsideZoomView);
  53419. installDataZoomRoamProcessor(registers);
  53420. }
  53421. var SliderZoomModel =
  53422. /** @class */
  53423. function (_super) {
  53424. __extends(SliderZoomModel, _super);
  53425. function SliderZoomModel() {
  53426. var _this = _super !== null && _super.apply(this, arguments) || this;
  53427. _this.type = SliderZoomModel.type;
  53428. return _this;
  53429. }
  53430. SliderZoomModel.type = 'dataZoom.slider';
  53431. SliderZoomModel.layoutMode = 'box';
  53432. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  53433. show: true,
  53434. // deault value can only be drived in view stage.
  53435. right: 'ph',
  53436. top: 'ph',
  53437. width: 'ph',
  53438. height: 'ph',
  53439. left: null,
  53440. bottom: null,
  53441. borderColor: '#d2dbee',
  53442. borderRadius: 3,
  53443. backgroundColor: 'rgba(47,69,84,0)',
  53444. // dataBackgroundColor: '#ddd',
  53445. dataBackground: {
  53446. lineStyle: {
  53447. color: '#d2dbee',
  53448. width: 0.5
  53449. },
  53450. areaStyle: {
  53451. color: '#d2dbee',
  53452. opacity: 0.2
  53453. }
  53454. },
  53455. selectedDataBackground: {
  53456. lineStyle: {
  53457. color: '#8fb0f7',
  53458. width: 0.5
  53459. },
  53460. areaStyle: {
  53461. color: '#8fb0f7',
  53462. opacity: 0.2
  53463. }
  53464. },
  53465. // Color of selected window.
  53466. fillerColor: 'rgba(135,175,274,0.2)',
  53467. 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',
  53468. // Percent of the slider height
  53469. handleSize: '100%',
  53470. handleStyle: {
  53471. color: '#fff',
  53472. borderColor: '#ACB8D1'
  53473. },
  53474. moveHandleSize: 7,
  53475. 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',
  53476. moveHandleStyle: {
  53477. color: '#D2DBEE',
  53478. opacity: 0.7
  53479. },
  53480. showDetail: true,
  53481. showDataShadow: 'auto',
  53482. realtime: true,
  53483. zoomLock: false,
  53484. textStyle: {
  53485. color: '#6E7079'
  53486. },
  53487. brushSelect: true,
  53488. brushStyle: {
  53489. color: 'rgba(135,175,274,0.15)'
  53490. },
  53491. emphasis: {
  53492. handleStyle: {
  53493. borderColor: '#8FB0F7'
  53494. },
  53495. moveHandleStyle: {
  53496. color: '#8FB0F7'
  53497. }
  53498. }
  53499. });
  53500. return SliderZoomModel;
  53501. }(DataZoomModel);
  53502. var Rect$1 = Rect; // Constants
  53503. var DEFAULT_LOCATION_EDGE_GAP = 7;
  53504. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  53505. var DEFAULT_FILLER_SIZE = 30;
  53506. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  53507. var HORIZONTAL = 'horizontal';
  53508. var VERTICAL = 'vertical';
  53509. var LABEL_GAP = 5;
  53510. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  53511. var REALTIME_ANIMATION_CONFIG = {
  53512. easing: 'cubicOut',
  53513. duration: 100,
  53514. delay: 0
  53515. };
  53516. var SliderZoomView =
  53517. /** @class */
  53518. function (_super) {
  53519. __extends(SliderZoomView, _super);
  53520. function SliderZoomView() {
  53521. var _this = _super !== null && _super.apply(this, arguments) || this;
  53522. _this.type = SliderZoomView.type;
  53523. _this._displayables = {};
  53524. return _this;
  53525. }
  53526. SliderZoomView.prototype.init = function (ecModel, api) {
  53527. this.api = api; // A unique handler for each dataZoom component
  53528. this._onBrush = bind(this._onBrush, this);
  53529. this._onBrushEnd = bind(this._onBrushEnd, this);
  53530. };
  53531. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  53532. _super.prototype.render.apply(this, arguments);
  53533. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  53534. this._orient = dataZoomModel.getOrient();
  53535. if (dataZoomModel.get('show') === false) {
  53536. this.group.removeAll();
  53537. return;
  53538. }
  53539. if (dataZoomModel.noTarget()) {
  53540. this._clear();
  53541. this.group.removeAll();
  53542. return;
  53543. } // Notice: this._resetInterval() should not be executed when payload.type
  53544. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  53545. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  53546. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  53547. this._buildView();
  53548. }
  53549. this._updateView();
  53550. };
  53551. SliderZoomView.prototype.dispose = function () {
  53552. this._clear();
  53553. _super.prototype.dispose.apply(this, arguments);
  53554. };
  53555. SliderZoomView.prototype._clear = function () {
  53556. clear(this, '_dispatchZoomAction');
  53557. var zr = this.api.getZr();
  53558. zr.off('mousemove', this._onBrush);
  53559. zr.off('mouseup', this._onBrushEnd);
  53560. };
  53561. SliderZoomView.prototype._buildView = function () {
  53562. var thisGroup = this.group;
  53563. thisGroup.removeAll();
  53564. this._brushing = false;
  53565. this._displayables.brushRect = null;
  53566. this._resetLocation();
  53567. this._resetInterval();
  53568. var barGroup = this._displayables.sliderGroup = new Group();
  53569. this._renderBackground();
  53570. this._renderHandle();
  53571. this._renderDataShadow();
  53572. thisGroup.add(barGroup);
  53573. this._positionGroup();
  53574. };
  53575. SliderZoomView.prototype._resetLocation = function () {
  53576. var dataZoomModel = this.dataZoomModel;
  53577. var api = this.api;
  53578. var showMoveHandle = dataZoomModel.get('brushSelect');
  53579. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  53580. // auto-adapt according to target grid.
  53581. var coordRect = this._findCoordRect();
  53582. var ecSize = {
  53583. width: api.getWidth(),
  53584. height: api.getHeight()
  53585. }; // Default align by coordinate system rect.
  53586. var positionInfo = this._orient === HORIZONTAL ? {
  53587. // Why using 'right', because right should be used in vertical,
  53588. // and it is better to be consistent for dealing with position param merge.
  53589. right: ecSize.width - coordRect.x - coordRect.width,
  53590. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  53591. width: coordRect.width,
  53592. height: DEFAULT_FILLER_SIZE
  53593. } : {
  53594. right: DEFAULT_LOCATION_EDGE_GAP,
  53595. top: coordRect.y,
  53596. width: DEFAULT_FILLER_SIZE,
  53597. height: coordRect.height
  53598. }; // Do not write back to option and replace value 'ph', because
  53599. // the 'ph' value should be recalculated when resize.
  53600. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  53601. each(['right', 'top', 'width', 'height'], function (name) {
  53602. if (layoutParams[name] === 'ph') {
  53603. layoutParams[name] = positionInfo[name];
  53604. }
  53605. });
  53606. var layoutRect = getLayoutRect(layoutParams, ecSize);
  53607. this._location = {
  53608. x: layoutRect.x,
  53609. y: layoutRect.y
  53610. };
  53611. this._size = [layoutRect.width, layoutRect.height];
  53612. this._orient === VERTICAL && this._size.reverse();
  53613. };
  53614. SliderZoomView.prototype._positionGroup = function () {
  53615. var thisGroup = this.group;
  53616. var location = this._location;
  53617. var orient = this._orient; // Just use the first axis to determine mapping.
  53618. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  53619. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  53620. var sliderGroup = this._displayables.sliderGroup;
  53621. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  53622. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  53623. scaleY: otherAxisInverse ? 1 : -1,
  53624. scaleX: 1
  53625. } : orient === HORIZONTAL && inverse ? {
  53626. scaleY: otherAxisInverse ? 1 : -1,
  53627. scaleX: -1
  53628. } : orient === VERTICAL && !inverse ? {
  53629. scaleY: otherAxisInverse ? -1 : 1,
  53630. scaleX: 1,
  53631. rotation: Math.PI / 2
  53632. } // Don't use Math.PI, considering shadow direction.
  53633. : {
  53634. scaleY: otherAxisInverse ? -1 : 1,
  53635. scaleX: -1,
  53636. rotation: Math.PI / 2
  53637. }); // Position barGroup
  53638. var rect = thisGroup.getBoundingRect([sliderGroup]);
  53639. thisGroup.x = location.x - rect.x;
  53640. thisGroup.y = location.y - rect.y;
  53641. thisGroup.markRedraw();
  53642. };
  53643. SliderZoomView.prototype._getViewExtent = function () {
  53644. return [0, this._size[0]];
  53645. };
  53646. SliderZoomView.prototype._renderBackground = function () {
  53647. var dataZoomModel = this.dataZoomModel;
  53648. var size = this._size;
  53649. var barGroup = this._displayables.sliderGroup;
  53650. var brushSelect = dataZoomModel.get('brushSelect');
  53651. barGroup.add(new Rect$1({
  53652. silent: true,
  53653. shape: {
  53654. x: 0,
  53655. y: 0,
  53656. width: size[0],
  53657. height: size[1]
  53658. },
  53659. style: {
  53660. fill: dataZoomModel.get('backgroundColor')
  53661. },
  53662. z2: -40
  53663. })); // Click panel, over shadow, below handles.
  53664. var clickPanel = new Rect$1({
  53665. shape: {
  53666. x: 0,
  53667. y: 0,
  53668. width: size[0],
  53669. height: size[1]
  53670. },
  53671. style: {
  53672. fill: 'transparent'
  53673. },
  53674. z2: 0,
  53675. onclick: bind(this._onClickPanel, this)
  53676. });
  53677. var zr = this.api.getZr();
  53678. if (brushSelect) {
  53679. clickPanel.on('mousedown', this._onBrushStart, this);
  53680. clickPanel.cursor = 'crosshair';
  53681. zr.on('mousemove', this._onBrush);
  53682. zr.on('mouseup', this._onBrushEnd);
  53683. } else {
  53684. zr.off('mousemove', this._onBrush);
  53685. zr.off('mouseup', this._onBrushEnd);
  53686. }
  53687. barGroup.add(clickPanel);
  53688. };
  53689. SliderZoomView.prototype._renderDataShadow = function () {
  53690. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  53691. this._displayables.dataShadowSegs = [];
  53692. if (!info) {
  53693. return;
  53694. }
  53695. var size = this._size;
  53696. var oldSize = this._shadowSize || [];
  53697. var seriesModel = info.series;
  53698. var data = seriesModel.getRawData();
  53699. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  53700. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  53701. : info.otherDim;
  53702. if (otherDim == null) {
  53703. return;
  53704. }
  53705. var polygonPts = this._shadowPolygonPts;
  53706. var polylinePts = this._shadowPolylinePts; // Not re-render if data doesn't change.
  53707. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  53708. var otherDataExtent_1 = data.getDataExtent(otherDim); // Nice extent.
  53709. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  53710. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  53711. var otherShadowExtent_1 = [0, size[1]];
  53712. var thisShadowExtent = [0, size[0]];
  53713. var areaPoints_1 = [[size[0], 0], [0, 0]];
  53714. var linePoints_1 = [];
  53715. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  53716. var thisCoord_1 = 0; // Optimize for large data shadow
  53717. var stride_1 = Math.round(data.count() / size[0]);
  53718. var lastIsEmpty_1;
  53719. data.each([otherDim], function (value, index) {
  53720. if (stride_1 > 0 && index % stride_1) {
  53721. thisCoord_1 += step_1;
  53722. return;
  53723. } // FIXME
  53724. // Should consider axis.min/axis.max when drawing dataShadow.
  53725. // FIXME
  53726. // 应该使用统一的空判断?还是在list里进行空判断?
  53727. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  53728. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true); // Attempt to draw data shadow precisely when there are empty value.
  53729. if (isEmpty && !lastIsEmpty_1 && index) {
  53730. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  53731. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  53732. } else if (!isEmpty && lastIsEmpty_1) {
  53733. areaPoints_1.push([thisCoord_1, 0]);
  53734. linePoints_1.push([thisCoord_1, 0]);
  53735. }
  53736. areaPoints_1.push([thisCoord_1, otherCoord]);
  53737. linePoints_1.push([thisCoord_1, otherCoord]);
  53738. thisCoord_1 += step_1;
  53739. lastIsEmpty_1 = isEmpty;
  53740. });
  53741. polygonPts = this._shadowPolygonPts = areaPoints_1;
  53742. polylinePts = this._shadowPolylinePts = linePoints_1;
  53743. }
  53744. this._shadowData = data;
  53745. this._shadowDim = otherDim;
  53746. this._shadowSize = [size[0], size[1]];
  53747. var dataZoomModel = this.dataZoomModel;
  53748. function createDataShadowGroup(isSelectedArea) {
  53749. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  53750. var group = new Group();
  53751. var polygon = new Polygon({
  53752. shape: {
  53753. points: polygonPts
  53754. },
  53755. segmentIgnoreThreshold: 1,
  53756. style: model.getModel('areaStyle').getAreaStyle(),
  53757. silent: true,
  53758. z2: -20
  53759. });
  53760. var polyline = new Polyline({
  53761. shape: {
  53762. points: polylinePts
  53763. },
  53764. segmentIgnoreThreshold: 1,
  53765. style: model.getModel('lineStyle').getLineStyle(),
  53766. silent: true,
  53767. z2: -19
  53768. });
  53769. group.add(polygon);
  53770. group.add(polyline);
  53771. return group;
  53772. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  53773. for (var i = 0; i < 3; i++) {
  53774. var group = createDataShadowGroup(i === 1);
  53775. this._displayables.sliderGroup.add(group);
  53776. this._displayables.dataShadowSegs.push(group);
  53777. }
  53778. };
  53779. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  53780. var dataZoomModel = this.dataZoomModel;
  53781. var showDataShadow = dataZoomModel.get('showDataShadow');
  53782. if (showDataShadow === false) {
  53783. return;
  53784. } // Find a representative series.
  53785. var result;
  53786. var ecModel = this.ecModel;
  53787. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  53788. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  53789. each(seriesModels, function (seriesModel) {
  53790. if (result) {
  53791. return;
  53792. }
  53793. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  53794. return;
  53795. }
  53796. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  53797. var otherDim = getOtherDim(axisDim);
  53798. var otherAxisInverse;
  53799. var coordSys = seriesModel.coordinateSystem;
  53800. if (otherDim != null && coordSys.getOtherAxis) {
  53801. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  53802. }
  53803. otherDim = seriesModel.getData().mapDimension(otherDim);
  53804. result = {
  53805. thisAxis: thisAxis,
  53806. series: seriesModel,
  53807. thisDim: axisDim,
  53808. otherDim: otherDim,
  53809. otherAxisInverse: otherAxisInverse
  53810. };
  53811. }, this);
  53812. }, this);
  53813. return result;
  53814. };
  53815. SliderZoomView.prototype._renderHandle = function () {
  53816. var thisGroup = this.group;
  53817. var displayables = this._displayables;
  53818. var handles = displayables.handles = [null, null];
  53819. var handleLabels = displayables.handleLabels = [null, null];
  53820. var sliderGroup = this._displayables.sliderGroup;
  53821. var size = this._size;
  53822. var dataZoomModel = this.dataZoomModel;
  53823. var api = this.api;
  53824. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  53825. var brushSelect = dataZoomModel.get('brushSelect');
  53826. var filler = displayables.filler = new Rect$1({
  53827. silent: brushSelect,
  53828. style: {
  53829. fill: dataZoomModel.get('fillerColor')
  53830. },
  53831. textConfig: {
  53832. position: 'inside'
  53833. }
  53834. });
  53835. sliderGroup.add(filler); // Frame border.
  53836. sliderGroup.add(new Rect$1({
  53837. silent: true,
  53838. subPixelOptimize: true,
  53839. shape: {
  53840. x: 0,
  53841. y: 0,
  53842. width: size[0],
  53843. height: size[1],
  53844. r: borderRadius
  53845. },
  53846. style: {
  53847. // deprecated option
  53848. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  53849. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  53850. fill: 'rgba(0,0,0,0)'
  53851. }
  53852. })); // Left and right handle to resize
  53853. each([0, 1], function (handleIndex) {
  53854. var iconStr = dataZoomModel.get('handleIcon');
  53855. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  53856. // Compatitable with the old icon parsers. Which can use a path string without path://
  53857. iconStr = 'path://' + iconStr;
  53858. if ("development" !== 'production') {
  53859. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  53860. }
  53861. }
  53862. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  53863. path.attr({
  53864. cursor: getCursor(this._orient),
  53865. draggable: true,
  53866. drift: bind(this._onDragMove, this, handleIndex),
  53867. ondragend: bind(this._onDragEnd, this),
  53868. onmouseover: bind(this._showDataInfo, this, true),
  53869. onmouseout: bind(this._showDataInfo, this, false),
  53870. z2: 5
  53871. });
  53872. var bRect = path.getBoundingRect();
  53873. var handleSize = dataZoomModel.get('handleSize');
  53874. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  53875. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  53876. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  53877. path.style.strokeNoScale = true;
  53878. path.rectHover = true;
  53879. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  53880. enableHoverEmphasis(path);
  53881. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  53882. // Compatitable with previous version
  53883. if (handleColor != null) {
  53884. path.style.fill = handleColor;
  53885. }
  53886. sliderGroup.add(handles[handleIndex] = path);
  53887. var textStyleModel = dataZoomModel.getModel('textStyle');
  53888. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  53889. silent: true,
  53890. invisible: true,
  53891. style: createTextStyle(textStyleModel, {
  53892. x: 0,
  53893. y: 0,
  53894. text: '',
  53895. verticalAlign: 'middle',
  53896. align: 'center',
  53897. fill: textStyleModel.getTextColor(),
  53898. font: textStyleModel.getFont()
  53899. }),
  53900. z2: 10
  53901. }));
  53902. }, this); // Handle to move. Only visible when brushSelect is set true.
  53903. var actualMoveZone = filler;
  53904. if (brushSelect) {
  53905. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  53906. var moveHandle_1 = displayables.moveHandle = new Rect({
  53907. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  53908. silent: true,
  53909. shape: {
  53910. r: [0, 0, 2, 2],
  53911. y: size[1] - 0.5,
  53912. height: moveHandleHeight
  53913. }
  53914. });
  53915. var iconSize = moveHandleHeight * 0.8;
  53916. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  53917. moveHandleIcon.silent = true;
  53918. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  53919. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  53920. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  53921. actualMoveZone = displayables.moveZone = new Rect({
  53922. invisible: true,
  53923. shape: {
  53924. y: size[1] - moveZoneExpandSize,
  53925. height: moveHandleHeight + moveZoneExpandSize
  53926. }
  53927. });
  53928. actualMoveZone.on('mouseover', function () {
  53929. api.enterEmphasis(moveHandle_1);
  53930. }).on('mouseout', function () {
  53931. api.leaveEmphasis(moveHandle_1);
  53932. });
  53933. sliderGroup.add(moveHandle_1);
  53934. sliderGroup.add(moveHandleIcon);
  53935. sliderGroup.add(actualMoveZone);
  53936. }
  53937. actualMoveZone.attr({
  53938. draggable: true,
  53939. cursor: getCursor(this._orient),
  53940. drift: bind(this._onDragMove, this, 'all'),
  53941. ondragstart: bind(this._showDataInfo, this, true),
  53942. ondragend: bind(this._onDragEnd, this),
  53943. onmouseover: bind(this._showDataInfo, this, true),
  53944. onmouseout: bind(this._showDataInfo, this, false)
  53945. });
  53946. };
  53947. SliderZoomView.prototype._resetInterval = function () {
  53948. var range = this._range = this.dataZoomModel.getPercentRange();
  53949. var viewExtent = this._getViewExtent();
  53950. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  53951. };
  53952. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  53953. var dataZoomModel = this.dataZoomModel;
  53954. var handleEnds = this._handleEnds;
  53955. var viewExtend = this._getViewExtent();
  53956. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  53957. var percentExtent = [0, 100];
  53958. 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);
  53959. var lastRange = this._range;
  53960. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  53961. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  53962. };
  53963. SliderZoomView.prototype._updateView = function (nonRealtime) {
  53964. var displaybles = this._displayables;
  53965. var handleEnds = this._handleEnds;
  53966. var handleInterval = asc(handleEnds.slice());
  53967. var size = this._size;
  53968. each([0, 1], function (handleIndex) {
  53969. // Handles
  53970. var handle = displaybles.handles[handleIndex];
  53971. var handleHeight = this._handleHeight;
  53972. handle.attr({
  53973. scaleX: handleHeight / 2,
  53974. scaleY: handleHeight / 2,
  53975. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  53976. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  53977. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  53978. y: size[1] / 2 - handleHeight / 2
  53979. });
  53980. }, this); // Filler
  53981. displaybles.filler.setShape({
  53982. x: handleInterval[0],
  53983. y: 0,
  53984. width: handleInterval[1] - handleInterval[0],
  53985. height: size[1]
  53986. });
  53987. var viewExtent = {
  53988. x: handleInterval[0],
  53989. width: handleInterval[1] - handleInterval[0]
  53990. }; // Move handle
  53991. if (displaybles.moveHandle) {
  53992. displaybles.moveHandle.setShape(viewExtent);
  53993. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  53994. displaybles.moveZone.getBoundingRect();
  53995. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  53996. } // update clip path of shadow.
  53997. var dataShadowSegs = displaybles.dataShadowSegs;
  53998. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  53999. for (var i = 0; i < dataShadowSegs.length; i++) {
  54000. var segGroup = dataShadowSegs[i];
  54001. var clipPath = segGroup.getClipPath();
  54002. if (!clipPath) {
  54003. clipPath = new Rect();
  54004. segGroup.setClipPath(clipPath);
  54005. }
  54006. clipPath.setShape({
  54007. x: segIntervals[i],
  54008. y: 0,
  54009. width: segIntervals[i + 1] - segIntervals[i],
  54010. height: size[1]
  54011. });
  54012. }
  54013. this._updateDataInfo(nonRealtime);
  54014. };
  54015. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  54016. var dataZoomModel = this.dataZoomModel;
  54017. var displaybles = this._displayables;
  54018. var handleLabels = displaybles.handleLabels;
  54019. var orient = this._orient;
  54020. var labelTexts = ['', '']; // FIXME
  54021. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  54022. if (dataZoomModel.get('showDetail')) {
  54023. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  54024. if (axisProxy) {
  54025. var axis = axisProxy.getAxisModel().axis;
  54026. var range = this._range;
  54027. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  54028. ? axisProxy.calculateDataWindow({
  54029. start: range[0],
  54030. end: range[1]
  54031. }).valueWindow : axisProxy.getDataValueWindow();
  54032. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  54033. }
  54034. }
  54035. var orderedHandleEnds = asc(this._handleEnds.slice());
  54036. setLabel.call(this, 0);
  54037. setLabel.call(this, 1);
  54038. function setLabel(handleIndex) {
  54039. // Label
  54040. // Text should not transform by barGroup.
  54041. // Ignore handlers transform
  54042. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  54043. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  54044. var offset = this._handleWidth / 2 + LABEL_GAP;
  54045. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  54046. handleLabels[handleIndex].setStyle({
  54047. x: textPoint[0],
  54048. y: textPoint[1],
  54049. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  54050. align: orient === HORIZONTAL ? direction : 'center',
  54051. text: labelTexts[handleIndex]
  54052. });
  54053. }
  54054. };
  54055. SliderZoomView.prototype._formatLabel = function (value, axis) {
  54056. var dataZoomModel = this.dataZoomModel;
  54057. var labelFormatter = dataZoomModel.get('labelFormatter');
  54058. var labelPrecision = dataZoomModel.get('labelPrecision');
  54059. if (labelPrecision == null || labelPrecision === 'auto') {
  54060. labelPrecision = axis.getPixelPrecision();
  54061. }
  54062. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  54063. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  54064. value: Math.round(value)
  54065. }) // param of toFixed should less then 20.
  54066. : value.toFixed(Math.min(labelPrecision, 20));
  54067. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  54068. };
  54069. /**
  54070. * @param showOrHide true: show, false: hide
  54071. */
  54072. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  54073. // Always show when drgging.
  54074. showOrHide = this._dragging || showOrHide;
  54075. var displayables = this._displayables;
  54076. var handleLabels = displayables.handleLabels;
  54077. handleLabels[0].attr('invisible', !showOrHide);
  54078. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  54079. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  54080. };
  54081. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  54082. this._dragging = true; // For mobile device, prevent screen slider on the button.
  54083. stop(event.event); // Transform dx, dy to bar coordination.
  54084. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  54085. var vertex = applyTransform$1([dx, dy], barTransform, true);
  54086. var changed = this._updateInterval(handleIndex, vertex[0]);
  54087. var realtime = this.dataZoomModel.get('realtime');
  54088. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  54089. // which cause bad visual effect when progressive enabled.
  54090. changed && realtime && this._dispatchZoomAction(true);
  54091. };
  54092. SliderZoomView.prototype._onDragEnd = function () {
  54093. this._dragging = false;
  54094. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  54095. // drag end will cause the whole view rerender, which is unnecessary.
  54096. var realtime = this.dataZoomModel.get('realtime');
  54097. !realtime && this._dispatchZoomAction(false);
  54098. };
  54099. SliderZoomView.prototype._onClickPanel = function (e) {
  54100. var size = this._size;
  54101. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  54102. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  54103. return;
  54104. }
  54105. var handleEnds = this._handleEnds;
  54106. var center = (handleEnds[0] + handleEnds[1]) / 2;
  54107. var changed = this._updateInterval('all', localPoint[0] - center);
  54108. this._updateView();
  54109. changed && this._dispatchZoomAction(false);
  54110. };
  54111. SliderZoomView.prototype._onBrushStart = function (e) {
  54112. var x = e.offsetX;
  54113. var y = e.offsetY;
  54114. this._brushStart = new Point(x, y);
  54115. this._brushing = true;
  54116. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  54117. };
  54118. SliderZoomView.prototype._onBrushEnd = function (e) {
  54119. if (!this._brushing) {
  54120. return;
  54121. }
  54122. var brushRect = this._displayables.brushRect;
  54123. this._brushing = false;
  54124. if (!brushRect) {
  54125. return;
  54126. }
  54127. brushRect.attr('ignore', true);
  54128. var brushShape = brushRect.shape;
  54129. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  54130. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  54131. // Will treat it as a click
  54132. return;
  54133. }
  54134. var viewExtend = this._getViewExtent();
  54135. var percentExtent = [0, 100];
  54136. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  54137. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  54138. this._updateView();
  54139. this._dispatchZoomAction(false);
  54140. };
  54141. SliderZoomView.prototype._onBrush = function (e) {
  54142. if (this._brushing) {
  54143. // For mobile device, prevent screen slider on the button.
  54144. stop(e.event);
  54145. this._updateBrushRect(e.offsetX, e.offsetY);
  54146. }
  54147. };
  54148. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  54149. var displayables = this._displayables;
  54150. var dataZoomModel = this.dataZoomModel;
  54151. var brushRect = displayables.brushRect;
  54152. if (!brushRect) {
  54153. brushRect = displayables.brushRect = new Rect$1({
  54154. silent: true,
  54155. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  54156. });
  54157. displayables.sliderGroup.add(brushRect);
  54158. }
  54159. brushRect.attr('ignore', false);
  54160. var brushStart = this._brushStart;
  54161. var sliderGroup = this._displayables.sliderGroup;
  54162. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  54163. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  54164. var size = this._size;
  54165. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  54166. brushRect.setShape({
  54167. x: startPoint[0],
  54168. y: 0,
  54169. width: endPoint[0] - startPoint[0],
  54170. height: size[1]
  54171. });
  54172. };
  54173. /**
  54174. * This action will be throttled.
  54175. */
  54176. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  54177. var range = this._range;
  54178. this.api.dispatchAction({
  54179. type: 'dataZoom',
  54180. from: this.uid,
  54181. dataZoomId: this.dataZoomModel.id,
  54182. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  54183. start: range[0],
  54184. end: range[1]
  54185. });
  54186. };
  54187. SliderZoomView.prototype._findCoordRect = function () {
  54188. // Find the grid corresponding to the first axis referred by dataZoom.
  54189. var rect;
  54190. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  54191. if (!rect && coordSysInfoList.length) {
  54192. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  54193. rect = coordSys.getRect && coordSys.getRect();
  54194. }
  54195. if (!rect) {
  54196. var width = this.api.getWidth();
  54197. var height = this.api.getHeight();
  54198. rect = {
  54199. x: width * 0.2,
  54200. y: height * 0.2,
  54201. width: width * 0.6,
  54202. height: height * 0.6
  54203. };
  54204. }
  54205. return rect;
  54206. };
  54207. SliderZoomView.type = 'dataZoom.slider';
  54208. return SliderZoomView;
  54209. }(DataZoomView);
  54210. function getOtherDim(thisDim) {
  54211. // FIXME
  54212. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  54213. var map = {
  54214. x: 'y',
  54215. y: 'x',
  54216. radius: 'angle',
  54217. angle: 'radius'
  54218. };
  54219. return map[thisDim];
  54220. }
  54221. function getCursor(orient) {
  54222. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  54223. }
  54224. function install$l(registers) {
  54225. registers.registerComponentModel(SliderZoomModel);
  54226. registers.registerComponentView(SliderZoomView);
  54227. installCommon(registers);
  54228. }
  54229. function install$m(registers) {
  54230. use(install$k);
  54231. use(install$l); // Do not install './dataZoomSelect',
  54232. // since it only work for toolbox dataZoom.
  54233. }
  54234. var DEFAULT_OPTION = {
  54235. label: {
  54236. enabled: true
  54237. },
  54238. decal: {
  54239. show: false
  54240. }
  54241. };
  54242. var inner$h = makeInner();
  54243. var decalPaletteScope = {};
  54244. function ariaVisual(ecModel, api) {
  54245. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  54246. if (!ariaModel.get('enabled')) {
  54247. return;
  54248. }
  54249. var defaultOption = clone(DEFAULT_OPTION);
  54250. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  54251. merge(ariaModel.option, defaultOption, false);
  54252. setDecal();
  54253. setLabel();
  54254. function setDecal() {
  54255. var decalModel = ariaModel.getModel('decal');
  54256. var useDecal = decalModel.get('show');
  54257. if (useDecal) {
  54258. // Each type of series use one scope.
  54259. // Pie and funnel are using different scopes.
  54260. var paletteScopeGroupByType_1 = createHashMap();
  54261. ecModel.eachSeries(function (seriesModel) {
  54262. if (seriesModel.isColorBySeries()) {
  54263. return;
  54264. }
  54265. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  54266. if (!decalScope) {
  54267. decalScope = {};
  54268. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  54269. }
  54270. inner$h(seriesModel).scope = decalScope;
  54271. });
  54272. ecModel.eachRawSeries(function (seriesModel) {
  54273. if (ecModel.isSeriesFiltered(seriesModel)) {
  54274. return;
  54275. }
  54276. if (isFunction(seriesModel.enableAriaDecal)) {
  54277. // Let series define how to use decal palette on data
  54278. seriesModel.enableAriaDecal();
  54279. return;
  54280. }
  54281. var data = seriesModel.getData();
  54282. if (!seriesModel.isColorBySeries()) {
  54283. var dataAll_1 = seriesModel.getRawData();
  54284. var idxMap_1 = {};
  54285. var decalScope_1 = inner$h(seriesModel).scope;
  54286. data.each(function (idx) {
  54287. var rawIdx = data.getRawIndex(idx);
  54288. idxMap_1[rawIdx] = idx;
  54289. });
  54290. var dataCount_1 = dataAll_1.count();
  54291. dataAll_1.each(function (rawIdx) {
  54292. var idx = idxMap_1[rawIdx];
  54293. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  54294. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  54295. var specifiedDecal = data.getItemVisual(idx, 'decal');
  54296. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  54297. });
  54298. } else {
  54299. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  54300. var specifiedDecal = data.getVisual('decal');
  54301. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  54302. }
  54303. function mergeDecal(specifiedDecal, paletteDecal) {
  54304. // Merge decal from palette to decal from itemStyle.
  54305. // User do not need to specify all of the decal props.
  54306. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  54307. resultDecal.dirty = true;
  54308. return resultDecal;
  54309. }
  54310. });
  54311. }
  54312. }
  54313. function setLabel() {
  54314. var labelLocale = ecModel.getLocaleModel().get('aria');
  54315. var labelModel = ariaModel.getModel('label');
  54316. labelModel.option = defaults(labelModel.option, labelLocale);
  54317. if (!labelModel.get('enabled')) {
  54318. return;
  54319. }
  54320. var dom = api.getZr().dom;
  54321. if (labelModel.get('description')) {
  54322. dom.setAttribute('aria-label', labelModel.get('description'));
  54323. return;
  54324. }
  54325. var seriesCnt = ecModel.getSeriesCount();
  54326. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  54327. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  54328. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  54329. var ariaLabel;
  54330. if (seriesCnt < 1) {
  54331. // No series, no aria label
  54332. return;
  54333. } else {
  54334. var title = getTitle();
  54335. if (title) {
  54336. var withTitle = labelModel.get(['general', 'withTitle']);
  54337. ariaLabel = replace(withTitle, {
  54338. title: title
  54339. });
  54340. } else {
  54341. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  54342. }
  54343. var seriesLabels_1 = [];
  54344. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  54345. ariaLabel += replace(prefix, {
  54346. seriesCount: seriesCnt
  54347. });
  54348. ecModel.eachSeries(function (seriesModel, idx) {
  54349. if (idx < displaySeriesCnt) {
  54350. var seriesLabel = void 0;
  54351. var seriesName = seriesModel.get('name');
  54352. var withName = seriesName ? 'withName' : 'withoutName';
  54353. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  54354. seriesLabel = replace(seriesLabel, {
  54355. seriesId: seriesModel.seriesIndex,
  54356. seriesName: seriesModel.get('name'),
  54357. seriesType: getSeriesTypeName(seriesModel.subType)
  54358. });
  54359. var data = seriesModel.getData();
  54360. if (data.count() > maxDataCnt) {
  54361. // Show part of data
  54362. var partialLabel = labelModel.get(['data', 'partialData']);
  54363. seriesLabel += replace(partialLabel, {
  54364. displayCnt: maxDataCnt
  54365. });
  54366. } else {
  54367. seriesLabel += labelModel.get(['data', 'allData']);
  54368. }
  54369. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  54370. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  54371. var dataLabels = [];
  54372. for (var i = 0; i < data.count(); i++) {
  54373. if (i < maxDataCnt) {
  54374. var name_1 = data.getName(i);
  54375. var value = data.getValues(i);
  54376. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  54377. dataLabels.push(replace(dataLabel, {
  54378. name: name_1,
  54379. value: value.join(middleSeparator_1)
  54380. }));
  54381. }
  54382. }
  54383. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  54384. seriesLabels_1.push(seriesLabel);
  54385. }
  54386. });
  54387. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  54388. var middleSeparator = separatorModel.get('middle');
  54389. var endSeparator = separatorModel.get('end');
  54390. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  54391. dom.setAttribute('aria-label', ariaLabel);
  54392. }
  54393. }
  54394. function replace(str, keyValues) {
  54395. if (!isString(str)) {
  54396. return str;
  54397. }
  54398. var result = str;
  54399. each(keyValues, function (value, key) {
  54400. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  54401. });
  54402. return result;
  54403. }
  54404. function getTitle() {
  54405. var title = ecModel.get('title');
  54406. if (title && title.length) {
  54407. title = title[0];
  54408. }
  54409. return title && title.text;
  54410. }
  54411. function getSeriesTypeName(type) {
  54412. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  54413. }
  54414. }
  54415. function ariaPreprocessor(option) {
  54416. if (!option || !option.aria) {
  54417. return;
  54418. }
  54419. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  54420. if (aria.show != null) {
  54421. aria.enabled = aria.show;
  54422. }
  54423. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  54424. each(['description', 'general', 'series', 'data'], function (name) {
  54425. if (aria[name] != null) {
  54426. aria.label[name] = aria[name];
  54427. }
  54428. });
  54429. }
  54430. function install$n(registers) {
  54431. registers.registerPreprocessor(ariaPreprocessor);
  54432. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  54433. }
  54434. var DatasetModel =
  54435. /** @class */
  54436. function (_super) {
  54437. __extends(DatasetModel, _super);
  54438. function DatasetModel() {
  54439. var _this = _super !== null && _super.apply(this, arguments) || this;
  54440. _this.type = 'dataset';
  54441. return _this;
  54442. }
  54443. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  54444. _super.prototype.init.call(this, option, parentModel, ecModel);
  54445. this._sourceManager = new SourceManager(this);
  54446. disableTransformOptionMerge(this);
  54447. };
  54448. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  54449. _super.prototype.mergeOption.call(this, newOption, ecModel);
  54450. disableTransformOptionMerge(this);
  54451. };
  54452. DatasetModel.prototype.optionUpdated = function () {
  54453. this._sourceManager.dirty();
  54454. };
  54455. DatasetModel.prototype.getSourceManager = function () {
  54456. return this._sourceManager;
  54457. };
  54458. DatasetModel.type = 'dataset';
  54459. DatasetModel.defaultOption = {
  54460. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  54461. };
  54462. return DatasetModel;
  54463. }(ComponentModel);
  54464. var DatasetView =
  54465. /** @class */
  54466. function (_super) {
  54467. __extends(DatasetView, _super);
  54468. function DatasetView() {
  54469. var _this = _super !== null && _super.apply(this, arguments) || this;
  54470. _this.type = 'dataset';
  54471. return _this;
  54472. }
  54473. DatasetView.type = 'dataset';
  54474. return DatasetView;
  54475. }(ComponentView);
  54476. function install$o(registers) {
  54477. registers.registerComponentModel(DatasetModel);
  54478. registers.registerComponentView(DatasetView);
  54479. }
  54480. use([install$1]);
  54481. use([install]);
  54482. use([install$2, install$3, install$4, install$6]);
  54483. 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]);
  54484. exports.Axis = Axis;
  54485. exports.ChartView = ChartView;
  54486. exports.ComponentModel = ComponentModel;
  54487. exports.ComponentView = ComponentView;
  54488. exports.List = SeriesData;
  54489. exports.Model = Model;
  54490. exports.PRIORITY = PRIORITY;
  54491. exports.SeriesModel = SeriesModel;
  54492. exports.color = color;
  54493. exports.connect = connect;
  54494. exports.dataTool = dataTool;
  54495. exports.dependencies = dependencies;
  54496. exports.disConnect = disConnect;
  54497. exports.disconnect = disconnect;
  54498. exports.dispose = dispose$1;
  54499. exports.env = env;
  54500. exports.extendChartView = extendChartView;
  54501. exports.extendComponentModel = extendComponentModel;
  54502. exports.extendComponentView = extendComponentView;
  54503. exports.extendSeriesModel = extendSeriesModel;
  54504. exports.format = format$1;
  54505. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  54506. exports.getInstanceByDom = getInstanceByDom;
  54507. exports.getInstanceById = getInstanceById;
  54508. exports.getMap = getMap;
  54509. exports.graphic = graphic$1;
  54510. exports.helper = helper;
  54511. exports.init = init$1;
  54512. exports.innerDrawElementOnCanvas = brushSingle;
  54513. exports.matrix = matrix;
  54514. exports.number = number;
  54515. exports.parseGeoJSON = parseGeoJSON;
  54516. exports.parseGeoJson = parseGeoJSON;
  54517. exports.registerAction = registerAction;
  54518. exports.registerCoordinateSystem = registerCoordinateSystem;
  54519. exports.registerLayout = registerLayout;
  54520. exports.registerLoading = registerLoading;
  54521. exports.registerLocale = registerLocale;
  54522. exports.registerMap = registerMap;
  54523. exports.registerPostInit = registerPostInit;
  54524. exports.registerPostUpdate = registerPostUpdate;
  54525. exports.registerPreprocessor = registerPreprocessor;
  54526. exports.registerProcessor = registerProcessor;
  54527. exports.registerTheme = registerTheme;
  54528. exports.registerTransform = registerTransform;
  54529. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  54530. exports.registerVisual = registerVisual;
  54531. exports.setCanvasCreator = setCanvasCreator;
  54532. exports.setPlatformAPI = setPlatformAPI;
  54533. exports.throttle = throttle;
  54534. exports.time = time;
  54535. exports.use = use;
  54536. exports.util = util$1;
  54537. exports.vector = vector;
  54538. exports.version = version$1;
  54539. exports.zrUtil = util;
  54540. exports.zrender = zrender;
  54541. Object.defineProperty(exports, '__esModule', { value: true });
  54542. })));
  54543. //# sourceMappingURL=echarts.common.js.map