echarts.common.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067
  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 = /^([0-9]*?)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 HashMap = (function () {
  623. function HashMap(obj) {
  624. this.data = {};
  625. var isArr = isArray(obj);
  626. this.data = {};
  627. var thisMap = this;
  628. (obj instanceof HashMap)
  629. ? obj.each(visit)
  630. : (obj && each(obj, visit));
  631. function visit(value, key) {
  632. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  633. }
  634. }
  635. HashMap.prototype.get = function (key) {
  636. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  637. };
  638. HashMap.prototype.set = function (key, value) {
  639. return (this.data[key] = value);
  640. };
  641. HashMap.prototype.each = function (cb, context) {
  642. for (var key in this.data) {
  643. if (this.data.hasOwnProperty(key)) {
  644. cb.call(context, this.data[key], key);
  645. }
  646. }
  647. };
  648. HashMap.prototype.keys = function () {
  649. return keys(this.data);
  650. };
  651. HashMap.prototype.removeKey = function (key) {
  652. delete this.data[key];
  653. };
  654. return HashMap;
  655. }());
  656. function createHashMap(obj) {
  657. return new HashMap(obj);
  658. }
  659. function concatArray(a, b) {
  660. var newArray = new a.constructor(a.length + b.length);
  661. for (var i = 0; i < a.length; i++) {
  662. newArray[i] = a[i];
  663. }
  664. var offset = a.length;
  665. for (var i = 0; i < b.length; i++) {
  666. newArray[i + offset] = b[i];
  667. }
  668. return newArray;
  669. }
  670. function createObject(proto, properties) {
  671. var obj;
  672. if (Object.create) {
  673. obj = Object.create(proto);
  674. }
  675. else {
  676. var StyleCtor = function () { };
  677. StyleCtor.prototype = proto;
  678. obj = new StyleCtor();
  679. }
  680. if (properties) {
  681. extend(obj, properties);
  682. }
  683. return obj;
  684. }
  685. function disableUserSelect(dom) {
  686. var domStyle = dom.style;
  687. domStyle.webkitUserSelect = 'none';
  688. domStyle.userSelect = 'none';
  689. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  690. domStyle['-webkit-touch-callout'] = 'none';
  691. }
  692. function hasOwn(own, prop) {
  693. return own.hasOwnProperty(prop);
  694. }
  695. function noop() { }
  696. var RADIAN_TO_DEGREE = 180 / Math.PI;
  697. var util = /*#__PURE__*/Object.freeze({
  698. __proto__: null,
  699. guid: guid,
  700. logError: logError,
  701. clone: clone,
  702. merge: merge,
  703. mergeAll: mergeAll,
  704. extend: extend,
  705. defaults: defaults,
  706. createCanvas: createCanvas,
  707. indexOf: indexOf,
  708. inherits: inherits,
  709. mixin: mixin,
  710. isArrayLike: isArrayLike,
  711. each: each,
  712. map: map,
  713. reduce: reduce,
  714. filter: filter,
  715. find: find,
  716. keys: keys,
  717. bind: bind,
  718. curry: curry,
  719. isArray: isArray,
  720. isFunction: isFunction,
  721. isString: isString,
  722. isStringSafe: isStringSafe,
  723. isNumber: isNumber,
  724. isObject: isObject,
  725. isBuiltInObject: isBuiltInObject,
  726. isTypedArray: isTypedArray,
  727. isDom: isDom,
  728. isGradientObject: isGradientObject,
  729. isImagePatternObject: isImagePatternObject,
  730. isRegExp: isRegExp,
  731. eqNaN: eqNaN,
  732. retrieve: retrieve,
  733. retrieve2: retrieve2,
  734. retrieve3: retrieve3,
  735. slice: slice,
  736. normalizeCssArray: normalizeCssArray,
  737. assert: assert,
  738. trim: trim,
  739. setAsPrimitive: setAsPrimitive,
  740. isPrimitive: isPrimitive,
  741. HashMap: HashMap,
  742. createHashMap: createHashMap,
  743. concatArray: concatArray,
  744. createObject: createObject,
  745. disableUserSelect: disableUserSelect,
  746. hasOwn: hasOwn,
  747. noop: noop,
  748. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  749. });
  750. function create(x, y) {
  751. if (x == null) {
  752. x = 0;
  753. }
  754. if (y == null) {
  755. y = 0;
  756. }
  757. return [x, y];
  758. }
  759. function copy(out, v) {
  760. out[0] = v[0];
  761. out[1] = v[1];
  762. return out;
  763. }
  764. function clone$1(v) {
  765. return [v[0], v[1]];
  766. }
  767. function set(out, a, b) {
  768. out[0] = a;
  769. out[1] = b;
  770. return out;
  771. }
  772. function add(out, v1, v2) {
  773. out[0] = v1[0] + v2[0];
  774. out[1] = v1[1] + v2[1];
  775. return out;
  776. }
  777. function scaleAndAdd(out, v1, v2, a) {
  778. out[0] = v1[0] + v2[0] * a;
  779. out[1] = v1[1] + v2[1] * a;
  780. return out;
  781. }
  782. function sub(out, v1, v2) {
  783. out[0] = v1[0] - v2[0];
  784. out[1] = v1[1] - v2[1];
  785. return out;
  786. }
  787. function len(v) {
  788. return Math.sqrt(lenSquare(v));
  789. }
  790. var length = len;
  791. function lenSquare(v) {
  792. return v[0] * v[0] + v[1] * v[1];
  793. }
  794. var lengthSquare = lenSquare;
  795. function mul(out, v1, v2) {
  796. out[0] = v1[0] * v2[0];
  797. out[1] = v1[1] * v2[1];
  798. return out;
  799. }
  800. function div(out, v1, v2) {
  801. out[0] = v1[0] / v2[0];
  802. out[1] = v1[1] / v2[1];
  803. return out;
  804. }
  805. function dot(v1, v2) {
  806. return v1[0] * v2[0] + v1[1] * v2[1];
  807. }
  808. function scale(out, v, s) {
  809. out[0] = v[0] * s;
  810. out[1] = v[1] * s;
  811. return out;
  812. }
  813. function normalize(out, v) {
  814. var d = len(v);
  815. if (d === 0) {
  816. out[0] = 0;
  817. out[1] = 0;
  818. }
  819. else {
  820. out[0] = v[0] / d;
  821. out[1] = v[1] / d;
  822. }
  823. return out;
  824. }
  825. function distance(v1, v2) {
  826. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  827. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  828. }
  829. var dist = distance;
  830. function distanceSquare(v1, v2) {
  831. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  832. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  833. }
  834. var distSquare = distanceSquare;
  835. function negate(out, v) {
  836. out[0] = -v[0];
  837. out[1] = -v[1];
  838. return out;
  839. }
  840. function lerp(out, v1, v2, t) {
  841. out[0] = v1[0] + t * (v2[0] - v1[0]);
  842. out[1] = v1[1] + t * (v2[1] - v1[1]);
  843. return out;
  844. }
  845. function applyTransform(out, v, m) {
  846. var x = v[0];
  847. var y = v[1];
  848. out[0] = m[0] * x + m[2] * y + m[4];
  849. out[1] = m[1] * x + m[3] * y + m[5];
  850. return out;
  851. }
  852. function min(out, v1, v2) {
  853. out[0] = Math.min(v1[0], v2[0]);
  854. out[1] = Math.min(v1[1], v2[1]);
  855. return out;
  856. }
  857. function max(out, v1, v2) {
  858. out[0] = Math.max(v1[0], v2[0]);
  859. out[1] = Math.max(v1[1], v2[1]);
  860. return out;
  861. }
  862. var vector = /*#__PURE__*/Object.freeze({
  863. __proto__: null,
  864. create: create,
  865. copy: copy,
  866. clone: clone$1,
  867. set: set,
  868. add: add,
  869. scaleAndAdd: scaleAndAdd,
  870. sub: sub,
  871. len: len,
  872. length: length,
  873. lenSquare: lenSquare,
  874. lengthSquare: lengthSquare,
  875. mul: mul,
  876. div: div,
  877. dot: dot,
  878. scale: scale,
  879. normalize: normalize,
  880. distance: distance,
  881. dist: dist,
  882. distanceSquare: distanceSquare,
  883. distSquare: distSquare,
  884. negate: negate,
  885. lerp: lerp,
  886. applyTransform: applyTransform,
  887. min: min,
  888. max: max
  889. });
  890. var Param = (function () {
  891. function Param(target, e) {
  892. this.target = target;
  893. this.topTarget = e && e.topTarget;
  894. }
  895. return Param;
  896. }());
  897. var Draggable = (function () {
  898. function Draggable(handler) {
  899. this.handler = handler;
  900. handler.on('mousedown', this._dragStart, this);
  901. handler.on('mousemove', this._drag, this);
  902. handler.on('mouseup', this._dragEnd, this);
  903. }
  904. Draggable.prototype._dragStart = function (e) {
  905. var draggingTarget = e.target;
  906. while (draggingTarget && !draggingTarget.draggable) {
  907. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  908. }
  909. if (draggingTarget) {
  910. this._draggingTarget = draggingTarget;
  911. draggingTarget.dragging = true;
  912. this._x = e.offsetX;
  913. this._y = e.offsetY;
  914. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  915. }
  916. };
  917. Draggable.prototype._drag = function (e) {
  918. var draggingTarget = this._draggingTarget;
  919. if (draggingTarget) {
  920. var x = e.offsetX;
  921. var y = e.offsetY;
  922. var dx = x - this._x;
  923. var dy = y - this._y;
  924. this._x = x;
  925. this._y = y;
  926. draggingTarget.drift(dx, dy, e);
  927. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  928. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  929. var lastDropTarget = this._dropTarget;
  930. this._dropTarget = dropTarget;
  931. if (draggingTarget !== dropTarget) {
  932. if (lastDropTarget && dropTarget !== lastDropTarget) {
  933. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  934. }
  935. if (dropTarget && dropTarget !== lastDropTarget) {
  936. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  937. }
  938. }
  939. }
  940. };
  941. Draggable.prototype._dragEnd = function (e) {
  942. var draggingTarget = this._draggingTarget;
  943. if (draggingTarget) {
  944. draggingTarget.dragging = false;
  945. }
  946. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  947. if (this._dropTarget) {
  948. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  949. }
  950. this._draggingTarget = null;
  951. this._dropTarget = null;
  952. };
  953. return Draggable;
  954. }());
  955. var Eventful = (function () {
  956. function Eventful(eventProcessors) {
  957. if (eventProcessors) {
  958. this._$eventProcessor = eventProcessors;
  959. }
  960. }
  961. Eventful.prototype.on = function (event, query, handler, context) {
  962. if (!this._$handlers) {
  963. this._$handlers = {};
  964. }
  965. var _h = this._$handlers;
  966. if (typeof query === 'function') {
  967. context = handler;
  968. handler = query;
  969. query = null;
  970. }
  971. if (!handler || !event) {
  972. return this;
  973. }
  974. var eventProcessor = this._$eventProcessor;
  975. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  976. query = eventProcessor.normalizeQuery(query);
  977. }
  978. if (!_h[event]) {
  979. _h[event] = [];
  980. }
  981. for (var i = 0; i < _h[event].length; i++) {
  982. if (_h[event][i].h === handler) {
  983. return this;
  984. }
  985. }
  986. var wrap = {
  987. h: handler,
  988. query: query,
  989. ctx: (context || this),
  990. callAtLast: handler.zrEventfulCallAtLast
  991. };
  992. var lastIndex = _h[event].length - 1;
  993. var lastWrap = _h[event][lastIndex];
  994. (lastWrap && lastWrap.callAtLast)
  995. ? _h[event].splice(lastIndex, 0, wrap)
  996. : _h[event].push(wrap);
  997. return this;
  998. };
  999. Eventful.prototype.isSilent = function (eventName) {
  1000. var _h = this._$handlers;
  1001. return !_h || !_h[eventName] || !_h[eventName].length;
  1002. };
  1003. Eventful.prototype.off = function (eventType, handler) {
  1004. var _h = this._$handlers;
  1005. if (!_h) {
  1006. return this;
  1007. }
  1008. if (!eventType) {
  1009. this._$handlers = {};
  1010. return this;
  1011. }
  1012. if (handler) {
  1013. if (_h[eventType]) {
  1014. var newList = [];
  1015. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1016. if (_h[eventType][i].h !== handler) {
  1017. newList.push(_h[eventType][i]);
  1018. }
  1019. }
  1020. _h[eventType] = newList;
  1021. }
  1022. if (_h[eventType] && _h[eventType].length === 0) {
  1023. delete _h[eventType];
  1024. }
  1025. }
  1026. else {
  1027. delete _h[eventType];
  1028. }
  1029. return this;
  1030. };
  1031. Eventful.prototype.trigger = function (eventType) {
  1032. var args = [];
  1033. for (var _i = 1; _i < arguments.length; _i++) {
  1034. args[_i - 1] = arguments[_i];
  1035. }
  1036. if (!this._$handlers) {
  1037. return this;
  1038. }
  1039. var _h = this._$handlers[eventType];
  1040. var eventProcessor = this._$eventProcessor;
  1041. if (_h) {
  1042. var argLen = args.length;
  1043. var len = _h.length;
  1044. for (var i = 0; i < len; i++) {
  1045. var hItem = _h[i];
  1046. if (eventProcessor
  1047. && eventProcessor.filter
  1048. && hItem.query != null
  1049. && !eventProcessor.filter(eventType, hItem.query)) {
  1050. continue;
  1051. }
  1052. switch (argLen) {
  1053. case 0:
  1054. hItem.h.call(hItem.ctx);
  1055. break;
  1056. case 1:
  1057. hItem.h.call(hItem.ctx, args[0]);
  1058. break;
  1059. case 2:
  1060. hItem.h.call(hItem.ctx, args[0], args[1]);
  1061. break;
  1062. default:
  1063. hItem.h.apply(hItem.ctx, args);
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. eventProcessor && eventProcessor.afterTrigger
  1069. && eventProcessor.afterTrigger(eventType);
  1070. return this;
  1071. };
  1072. Eventful.prototype.triggerWithContext = function (type) {
  1073. var args = [];
  1074. for (var _i = 1; _i < arguments.length; _i++) {
  1075. args[_i - 1] = arguments[_i];
  1076. }
  1077. if (!this._$handlers) {
  1078. return this;
  1079. }
  1080. var _h = this._$handlers[type];
  1081. var eventProcessor = this._$eventProcessor;
  1082. if (_h) {
  1083. var argLen = args.length;
  1084. var ctx = args[argLen - 1];
  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(type, hItem.query)) {
  1092. continue;
  1093. }
  1094. switch (argLen) {
  1095. case 0:
  1096. hItem.h.call(ctx);
  1097. break;
  1098. case 1:
  1099. hItem.h.call(ctx, args[0]);
  1100. break;
  1101. case 2:
  1102. hItem.h.call(ctx, args[0], args[1]);
  1103. break;
  1104. default:
  1105. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. eventProcessor && eventProcessor.afterTrigger
  1111. && eventProcessor.afterTrigger(type);
  1112. return this;
  1113. };
  1114. return Eventful;
  1115. }());
  1116. var LN2 = Math.log(2);
  1117. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1118. var cacheKey = rowMask + '-' + colMask;
  1119. var fullRank = rows.length;
  1120. if (detCache.hasOwnProperty(cacheKey)) {
  1121. return detCache[cacheKey];
  1122. }
  1123. if (rank === 1) {
  1124. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1125. return rows[rowStart][colStart];
  1126. }
  1127. var subRowMask = rowMask | (1 << rowStart);
  1128. var subRowStart = rowStart + 1;
  1129. while (rowMask & (1 << subRowStart)) {
  1130. subRowStart++;
  1131. }
  1132. var sum = 0;
  1133. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1134. var colTag = 1 << j;
  1135. if (!(colTag & colMask)) {
  1136. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1137. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1138. colLocalIdx++;
  1139. }
  1140. }
  1141. detCache[cacheKey] = sum;
  1142. return sum;
  1143. }
  1144. function buildTransformer(src, dest) {
  1145. var mA = [
  1146. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1147. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1148. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1149. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1150. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1151. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1152. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1153. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1154. ];
  1155. var detCache = {};
  1156. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1157. if (det === 0) {
  1158. return;
  1159. }
  1160. var vh = [];
  1161. for (var i = 0; i < 8; i++) {
  1162. for (var j = 0; j < 8; j++) {
  1163. vh[j] == null && (vh[j] = 0);
  1164. vh[j] += ((i + j) % 2 ? -1 : 1)
  1165. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1166. / det * dest[i];
  1167. }
  1168. }
  1169. return function (out, srcPointX, srcPointY) {
  1170. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1171. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1172. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1173. };
  1174. }
  1175. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1176. var _calcOut = [];
  1177. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1178. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1179. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1180. }
  1181. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1182. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1183. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1184. var markers = prepareCoordMarkers(el, saved);
  1185. var transformer = preparePointerTransformer(markers, saved, inverse);
  1186. if (transformer) {
  1187. transformer(out, inX, inY);
  1188. return true;
  1189. }
  1190. }
  1191. return false;
  1192. }
  1193. function prepareCoordMarkers(el, saved) {
  1194. var markers = saved.markers;
  1195. if (markers) {
  1196. return markers;
  1197. }
  1198. markers = saved.markers = [];
  1199. var propLR = ['left', 'right'];
  1200. var propTB = ['top', 'bottom'];
  1201. for (var i = 0; i < 4; i++) {
  1202. var marker = document.createElement('div');
  1203. var stl = marker.style;
  1204. var idxLR = i % 2;
  1205. var idxTB = (i >> 1) % 2;
  1206. stl.cssText = [
  1207. 'position: absolute',
  1208. 'visibility: hidden',
  1209. 'padding: 0',
  1210. 'margin: 0',
  1211. 'border-width: 0',
  1212. 'user-select: none',
  1213. 'width:0',
  1214. 'height:0',
  1215. propLR[idxLR] + ':0',
  1216. propTB[idxTB] + ':0',
  1217. propLR[1 - idxLR] + ':auto',
  1218. propTB[1 - idxTB] + ':auto',
  1219. ''
  1220. ].join('!important;');
  1221. el.appendChild(marker);
  1222. markers.push(marker);
  1223. }
  1224. return markers;
  1225. }
  1226. function preparePointerTransformer(markers, saved, inverse) {
  1227. var transformerName = inverse ? 'invTrans' : 'trans';
  1228. var transformer = saved[transformerName];
  1229. var oldSrcCoords = saved.srcCoords;
  1230. var srcCoords = [];
  1231. var destCoords = [];
  1232. var oldCoordTheSame = true;
  1233. for (var i = 0; i < 4; i++) {
  1234. var rect = markers[i].getBoundingClientRect();
  1235. var ii = 2 * i;
  1236. var x = rect.left;
  1237. var y = rect.top;
  1238. srcCoords.push(x, y);
  1239. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1240. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1241. }
  1242. return (oldCoordTheSame && transformer)
  1243. ? transformer
  1244. : (saved.srcCoords = srcCoords,
  1245. saved[transformerName] = inverse
  1246. ? buildTransformer(destCoords, srcCoords)
  1247. : buildTransformer(srcCoords, destCoords));
  1248. }
  1249. function isCanvasEl(el) {
  1250. return el.nodeName.toUpperCase() === 'CANVAS';
  1251. }
  1252. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1253. var _calcOut$1 = [];
  1254. var firefoxNotSupportOffsetXY = env.browser.firefox
  1255. && +env.browser.version.split('.')[0] < 39;
  1256. function clientToLocal(el, e, out, calculate) {
  1257. out = out || {};
  1258. if (calculate) {
  1259. calculateZrXY(el, e, out);
  1260. }
  1261. else if (firefoxNotSupportOffsetXY
  1262. && e.layerX != null
  1263. && e.layerX !== e.offsetX) {
  1264. out.zrX = e.layerX;
  1265. out.zrY = e.layerY;
  1266. }
  1267. else if (e.offsetX != null) {
  1268. out.zrX = e.offsetX;
  1269. out.zrY = e.offsetY;
  1270. }
  1271. else {
  1272. calculateZrXY(el, e, out);
  1273. }
  1274. return out;
  1275. }
  1276. function calculateZrXY(el, e, out) {
  1277. if (env.domSupported && el.getBoundingClientRect) {
  1278. var ex = e.clientX;
  1279. var ey = e.clientY;
  1280. if (isCanvasEl(el)) {
  1281. var box = el.getBoundingClientRect();
  1282. out.zrX = ex - box.left;
  1283. out.zrY = ey - box.top;
  1284. return;
  1285. }
  1286. else {
  1287. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1288. out.zrX = _calcOut$1[0];
  1289. out.zrY = _calcOut$1[1];
  1290. return;
  1291. }
  1292. }
  1293. }
  1294. out.zrX = out.zrY = 0;
  1295. }
  1296. function getNativeEvent(e) {
  1297. return e
  1298. || window.event;
  1299. }
  1300. function normalizeEvent(el, e, calculate) {
  1301. e = getNativeEvent(e);
  1302. if (e.zrX != null) {
  1303. return e;
  1304. }
  1305. var eventType = e.type;
  1306. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1307. if (!isTouch) {
  1308. clientToLocal(el, e, e, calculate);
  1309. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1310. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1311. }
  1312. else {
  1313. var touch = eventType !== 'touchend'
  1314. ? e.targetTouches[0]
  1315. : e.changedTouches[0];
  1316. touch && clientToLocal(el, touch, e, calculate);
  1317. }
  1318. var button = e.button;
  1319. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1320. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1321. }
  1322. return e;
  1323. }
  1324. function getWheelDeltaMayPolyfill(e) {
  1325. var rawWheelDelta = e.wheelDelta;
  1326. if (rawWheelDelta) {
  1327. return rawWheelDelta;
  1328. }
  1329. var deltaX = e.deltaX;
  1330. var deltaY = e.deltaY;
  1331. if (deltaX == null || deltaY == null) {
  1332. return rawWheelDelta;
  1333. }
  1334. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1335. var sign = deltaY > 0 ? -1
  1336. : deltaY < 0 ? 1
  1337. : deltaX > 0 ? -1
  1338. : 1;
  1339. return 3 * delta * sign;
  1340. }
  1341. function addEventListener(el, name, handler, opt) {
  1342. el.addEventListener(name, handler, opt);
  1343. }
  1344. function removeEventListener(el, name, handler, opt) {
  1345. el.removeEventListener(name, handler, opt);
  1346. }
  1347. var stop = function (e) {
  1348. e.preventDefault();
  1349. e.stopPropagation();
  1350. e.cancelBubble = true;
  1351. };
  1352. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1353. return e.which === 2 || e.which === 3;
  1354. }
  1355. var GestureMgr = (function () {
  1356. function GestureMgr() {
  1357. this._track = [];
  1358. }
  1359. GestureMgr.prototype.recognize = function (event, target, root) {
  1360. this._doTrack(event, target, root);
  1361. return this._recognize(event);
  1362. };
  1363. GestureMgr.prototype.clear = function () {
  1364. this._track.length = 0;
  1365. return this;
  1366. };
  1367. GestureMgr.prototype._doTrack = function (event, target, root) {
  1368. var touches = event.touches;
  1369. if (!touches) {
  1370. return;
  1371. }
  1372. var trackItem = {
  1373. points: [],
  1374. touches: [],
  1375. target: target,
  1376. event: event
  1377. };
  1378. for (var i = 0, len = touches.length; i < len; i++) {
  1379. var touch = touches[i];
  1380. var pos = clientToLocal(root, touch, {});
  1381. trackItem.points.push([pos.zrX, pos.zrY]);
  1382. trackItem.touches.push(touch);
  1383. }
  1384. this._track.push(trackItem);
  1385. };
  1386. GestureMgr.prototype._recognize = function (event) {
  1387. for (var eventName in recognizers) {
  1388. if (recognizers.hasOwnProperty(eventName)) {
  1389. var gestureInfo = recognizers[eventName](this._track, event);
  1390. if (gestureInfo) {
  1391. return gestureInfo;
  1392. }
  1393. }
  1394. }
  1395. };
  1396. return GestureMgr;
  1397. }());
  1398. function dist$1(pointPair) {
  1399. var dx = pointPair[1][0] - pointPair[0][0];
  1400. var dy = pointPair[1][1] - pointPair[0][1];
  1401. return Math.sqrt(dx * dx + dy * dy);
  1402. }
  1403. function center(pointPair) {
  1404. return [
  1405. (pointPair[0][0] + pointPair[1][0]) / 2,
  1406. (pointPair[0][1] + pointPair[1][1]) / 2
  1407. ];
  1408. }
  1409. var recognizers = {
  1410. pinch: function (tracks, event) {
  1411. var trackLen = tracks.length;
  1412. if (!trackLen) {
  1413. return;
  1414. }
  1415. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1416. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1417. if (pinchPre
  1418. && pinchPre.length > 1
  1419. && pinchEnd
  1420. && pinchEnd.length > 1) {
  1421. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1422. !isFinite(pinchScale) && (pinchScale = 1);
  1423. event.pinchScale = pinchScale;
  1424. var pinchCenter = center(pinchEnd);
  1425. event.pinchX = pinchCenter[0];
  1426. event.pinchY = pinchCenter[1];
  1427. return {
  1428. type: 'pinch',
  1429. target: tracks[0].target,
  1430. event: event
  1431. };
  1432. }
  1433. }
  1434. };
  1435. var SILENT = 'silent';
  1436. function makeEventPacket(eveType, targetInfo, event) {
  1437. return {
  1438. type: eveType,
  1439. event: event,
  1440. target: targetInfo.target,
  1441. topTarget: targetInfo.topTarget,
  1442. cancelBubble: false,
  1443. offsetX: event.zrX,
  1444. offsetY: event.zrY,
  1445. gestureEvent: event.gestureEvent,
  1446. pinchX: event.pinchX,
  1447. pinchY: event.pinchY,
  1448. pinchScale: event.pinchScale,
  1449. wheelDelta: event.zrDelta,
  1450. zrByTouch: event.zrByTouch,
  1451. which: event.which,
  1452. stop: stopEvent
  1453. };
  1454. }
  1455. function stopEvent() {
  1456. stop(this.event);
  1457. }
  1458. var EmptyProxy = (function (_super) {
  1459. __extends(EmptyProxy, _super);
  1460. function EmptyProxy() {
  1461. var _this = _super !== null && _super.apply(this, arguments) || this;
  1462. _this.handler = null;
  1463. return _this;
  1464. }
  1465. EmptyProxy.prototype.dispose = function () { };
  1466. EmptyProxy.prototype.setCursor = function () { };
  1467. return EmptyProxy;
  1468. }(Eventful));
  1469. var HoveredResult = (function () {
  1470. function HoveredResult(x, y) {
  1471. this.x = x;
  1472. this.y = y;
  1473. }
  1474. return HoveredResult;
  1475. }());
  1476. var handlerNames = [
  1477. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1478. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1479. ];
  1480. var Handler = (function (_super) {
  1481. __extends(Handler, _super);
  1482. function Handler(storage, painter, proxy, painterRoot) {
  1483. var _this = _super.call(this) || this;
  1484. _this._hovered = new HoveredResult(0, 0);
  1485. _this.storage = storage;
  1486. _this.painter = painter;
  1487. _this.painterRoot = painterRoot;
  1488. proxy = proxy || new EmptyProxy();
  1489. _this.proxy = null;
  1490. _this.setHandlerProxy(proxy);
  1491. _this._draggingMgr = new Draggable(_this);
  1492. return _this;
  1493. }
  1494. Handler.prototype.setHandlerProxy = function (proxy) {
  1495. if (this.proxy) {
  1496. this.proxy.dispose();
  1497. }
  1498. if (proxy) {
  1499. each(handlerNames, function (name) {
  1500. proxy.on && proxy.on(name, this[name], this);
  1501. }, this);
  1502. proxy.handler = this;
  1503. }
  1504. this.proxy = proxy;
  1505. };
  1506. Handler.prototype.mousemove = function (event) {
  1507. var x = event.zrX;
  1508. var y = event.zrY;
  1509. var isOutside = isOutsideBoundary(this, x, y);
  1510. var lastHovered = this._hovered;
  1511. var lastHoveredTarget = lastHovered.target;
  1512. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1513. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1514. lastHoveredTarget = lastHovered.target;
  1515. }
  1516. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1517. var hoveredTarget = hovered.target;
  1518. var proxy = this.proxy;
  1519. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1520. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1521. this.dispatchToElement(lastHovered, 'mouseout', event);
  1522. }
  1523. this.dispatchToElement(hovered, 'mousemove', event);
  1524. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1525. this.dispatchToElement(hovered, 'mouseover', event);
  1526. }
  1527. };
  1528. Handler.prototype.mouseout = function (event) {
  1529. var eventControl = event.zrEventControl;
  1530. if (eventControl !== 'only_globalout') {
  1531. this.dispatchToElement(this._hovered, 'mouseout', event);
  1532. }
  1533. if (eventControl !== 'no_globalout') {
  1534. this.trigger('globalout', { type: 'globalout', event: event });
  1535. }
  1536. };
  1537. Handler.prototype.resize = function () {
  1538. this._hovered = new HoveredResult(0, 0);
  1539. };
  1540. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1541. var handler = this[eventName];
  1542. handler && handler.call(this, eventArgs);
  1543. };
  1544. Handler.prototype.dispose = function () {
  1545. this.proxy.dispose();
  1546. this.storage = null;
  1547. this.proxy = null;
  1548. this.painter = null;
  1549. };
  1550. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1551. var proxy = this.proxy;
  1552. proxy.setCursor && proxy.setCursor(cursorStyle);
  1553. };
  1554. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1555. targetInfo = targetInfo || {};
  1556. var el = targetInfo.target;
  1557. if (el && el.silent) {
  1558. return;
  1559. }
  1560. var eventKey = ('on' + eventName);
  1561. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1562. while (el) {
  1563. el[eventKey]
  1564. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1565. el.trigger(eventName, eventPacket);
  1566. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1567. if (eventPacket.cancelBubble) {
  1568. break;
  1569. }
  1570. }
  1571. if (!eventPacket.cancelBubble) {
  1572. this.trigger(eventName, eventPacket);
  1573. if (this.painter && this.painter.eachOtherLayer) {
  1574. this.painter.eachOtherLayer(function (layer) {
  1575. if (typeof (layer[eventKey]) === 'function') {
  1576. layer[eventKey].call(layer, eventPacket);
  1577. }
  1578. if (layer.trigger) {
  1579. layer.trigger(eventName, eventPacket);
  1580. }
  1581. });
  1582. }
  1583. }
  1584. };
  1585. Handler.prototype.findHover = function (x, y, exclude) {
  1586. var list = this.storage.getDisplayList();
  1587. var out = new HoveredResult(x, y);
  1588. for (var i = list.length - 1; i >= 0; i--) {
  1589. var hoverCheckResult = void 0;
  1590. if (list[i] !== exclude
  1591. && !list[i].ignore
  1592. && (hoverCheckResult = isHover(list[i], x, y))) {
  1593. !out.topTarget && (out.topTarget = list[i]);
  1594. if (hoverCheckResult !== SILENT) {
  1595. out.target = list[i];
  1596. break;
  1597. }
  1598. }
  1599. }
  1600. return out;
  1601. };
  1602. Handler.prototype.processGesture = function (event, stage) {
  1603. if (!this._gestureMgr) {
  1604. this._gestureMgr = new GestureMgr();
  1605. }
  1606. var gestureMgr = this._gestureMgr;
  1607. stage === 'start' && gestureMgr.clear();
  1608. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1609. stage === 'end' && gestureMgr.clear();
  1610. if (gestureInfo) {
  1611. var type = gestureInfo.type;
  1612. event.gestureEvent = type;
  1613. var res = new HoveredResult();
  1614. res.target = gestureInfo.target;
  1615. this.dispatchToElement(res, type, gestureInfo.event);
  1616. }
  1617. };
  1618. return Handler;
  1619. }(Eventful));
  1620. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1621. Handler.prototype[name] = function (event) {
  1622. var x = event.zrX;
  1623. var y = event.zrY;
  1624. var isOutside = isOutsideBoundary(this, x, y);
  1625. var hovered;
  1626. var hoveredTarget;
  1627. if (name !== 'mouseup' || !isOutside) {
  1628. hovered = this.findHover(x, y);
  1629. hoveredTarget = hovered.target;
  1630. }
  1631. if (name === 'mousedown') {
  1632. this._downEl = hoveredTarget;
  1633. this._downPoint = [event.zrX, event.zrY];
  1634. this._upEl = hoveredTarget;
  1635. }
  1636. else if (name === 'mouseup') {
  1637. this._upEl = hoveredTarget;
  1638. }
  1639. else if (name === 'click') {
  1640. if (this._downEl !== this._upEl
  1641. || !this._downPoint
  1642. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1643. return;
  1644. }
  1645. this._downPoint = null;
  1646. }
  1647. this.dispatchToElement(hovered, name, event);
  1648. };
  1649. });
  1650. function isHover(displayable, x, y) {
  1651. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1652. var el = displayable;
  1653. var isSilent = void 0;
  1654. var ignoreClip = false;
  1655. while (el) {
  1656. if (el.ignoreClip) {
  1657. ignoreClip = true;
  1658. }
  1659. if (!ignoreClip) {
  1660. var clipPath = el.getClipPath();
  1661. if (clipPath && !clipPath.contain(x, y)) {
  1662. return false;
  1663. }
  1664. if (el.silent) {
  1665. isSilent = true;
  1666. }
  1667. }
  1668. var hostEl = el.__hostTarget;
  1669. el = hostEl ? hostEl : el.parent;
  1670. }
  1671. return isSilent ? SILENT : true;
  1672. }
  1673. return false;
  1674. }
  1675. function isOutsideBoundary(handlerInstance, x, y) {
  1676. var painter = handlerInstance.painter;
  1677. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1678. }
  1679. var DEFAULT_MIN_MERGE = 32;
  1680. var DEFAULT_MIN_GALLOPING = 7;
  1681. function minRunLength(n) {
  1682. var r = 0;
  1683. while (n >= DEFAULT_MIN_MERGE) {
  1684. r |= n & 1;
  1685. n >>= 1;
  1686. }
  1687. return n + r;
  1688. }
  1689. function makeAscendingRun(array, lo, hi, compare) {
  1690. var runHi = lo + 1;
  1691. if (runHi === hi) {
  1692. return 1;
  1693. }
  1694. if (compare(array[runHi++], array[lo]) < 0) {
  1695. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  1696. runHi++;
  1697. }
  1698. reverseRun(array, lo, runHi);
  1699. }
  1700. else {
  1701. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  1702. runHi++;
  1703. }
  1704. }
  1705. return runHi - lo;
  1706. }
  1707. function reverseRun(array, lo, hi) {
  1708. hi--;
  1709. while (lo < hi) {
  1710. var t = array[lo];
  1711. array[lo++] = array[hi];
  1712. array[hi--] = t;
  1713. }
  1714. }
  1715. function binaryInsertionSort(array, lo, hi, start, compare) {
  1716. if (start === lo) {
  1717. start++;
  1718. }
  1719. for (; start < hi; start++) {
  1720. var pivot = array[start];
  1721. var left = lo;
  1722. var right = start;
  1723. var mid;
  1724. while (left < right) {
  1725. mid = left + right >>> 1;
  1726. if (compare(pivot, array[mid]) < 0) {
  1727. right = mid;
  1728. }
  1729. else {
  1730. left = mid + 1;
  1731. }
  1732. }
  1733. var n = start - left;
  1734. switch (n) {
  1735. case 3:
  1736. array[left + 3] = array[left + 2];
  1737. case 2:
  1738. array[left + 2] = array[left + 1];
  1739. case 1:
  1740. array[left + 1] = array[left];
  1741. break;
  1742. default:
  1743. while (n > 0) {
  1744. array[left + n] = array[left + n - 1];
  1745. n--;
  1746. }
  1747. }
  1748. array[left] = pivot;
  1749. }
  1750. }
  1751. function gallopLeft(value, array, start, length, hint, compare) {
  1752. var lastOffset = 0;
  1753. var maxOffset = 0;
  1754. var offset = 1;
  1755. if (compare(value, array[start + hint]) > 0) {
  1756. maxOffset = length - hint;
  1757. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  1758. lastOffset = offset;
  1759. offset = (offset << 1) + 1;
  1760. if (offset <= 0) {
  1761. offset = maxOffset;
  1762. }
  1763. }
  1764. if (offset > maxOffset) {
  1765. offset = maxOffset;
  1766. }
  1767. lastOffset += hint;
  1768. offset += hint;
  1769. }
  1770. else {
  1771. maxOffset = hint + 1;
  1772. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  1773. lastOffset = offset;
  1774. offset = (offset << 1) + 1;
  1775. if (offset <= 0) {
  1776. offset = maxOffset;
  1777. }
  1778. }
  1779. if (offset > maxOffset) {
  1780. offset = maxOffset;
  1781. }
  1782. var tmp = lastOffset;
  1783. lastOffset = hint - offset;
  1784. offset = hint - tmp;
  1785. }
  1786. lastOffset++;
  1787. while (lastOffset < offset) {
  1788. var m = lastOffset + (offset - lastOffset >>> 1);
  1789. if (compare(value, array[start + m]) > 0) {
  1790. lastOffset = m + 1;
  1791. }
  1792. else {
  1793. offset = m;
  1794. }
  1795. }
  1796. return offset;
  1797. }
  1798. function gallopRight(value, array, start, length, hint, compare) {
  1799. var lastOffset = 0;
  1800. var maxOffset = 0;
  1801. var offset = 1;
  1802. if (compare(value, array[start + hint]) < 0) {
  1803. maxOffset = hint + 1;
  1804. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  1805. lastOffset = offset;
  1806. offset = (offset << 1) + 1;
  1807. if (offset <= 0) {
  1808. offset = maxOffset;
  1809. }
  1810. }
  1811. if (offset > maxOffset) {
  1812. offset = maxOffset;
  1813. }
  1814. var tmp = lastOffset;
  1815. lastOffset = hint - offset;
  1816. offset = hint - tmp;
  1817. }
  1818. else {
  1819. maxOffset = length - hint;
  1820. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  1821. lastOffset = offset;
  1822. offset = (offset << 1) + 1;
  1823. if (offset <= 0) {
  1824. offset = maxOffset;
  1825. }
  1826. }
  1827. if (offset > maxOffset) {
  1828. offset = maxOffset;
  1829. }
  1830. lastOffset += hint;
  1831. offset += hint;
  1832. }
  1833. lastOffset++;
  1834. while (lastOffset < offset) {
  1835. var m = lastOffset + (offset - lastOffset >>> 1);
  1836. if (compare(value, array[start + m]) < 0) {
  1837. offset = m;
  1838. }
  1839. else {
  1840. lastOffset = m + 1;
  1841. }
  1842. }
  1843. return offset;
  1844. }
  1845. function TimSort(array, compare) {
  1846. var minGallop = DEFAULT_MIN_GALLOPING;
  1847. var length = 0;
  1848. var runStart;
  1849. var runLength;
  1850. var stackSize = 0;
  1851. length = array.length;
  1852. var tmp = [];
  1853. runStart = [];
  1854. runLength = [];
  1855. function pushRun(_runStart, _runLength) {
  1856. runStart[stackSize] = _runStart;
  1857. runLength[stackSize] = _runLength;
  1858. stackSize += 1;
  1859. }
  1860. function mergeRuns() {
  1861. while (stackSize > 1) {
  1862. var n = stackSize - 2;
  1863. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  1864. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  1865. if (runLength[n - 1] < runLength[n + 1]) {
  1866. n--;
  1867. }
  1868. }
  1869. else if (runLength[n] > runLength[n + 1]) {
  1870. break;
  1871. }
  1872. mergeAt(n);
  1873. }
  1874. }
  1875. function forceMergeRuns() {
  1876. while (stackSize > 1) {
  1877. var n = stackSize - 2;
  1878. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  1879. n--;
  1880. }
  1881. mergeAt(n);
  1882. }
  1883. }
  1884. function mergeAt(i) {
  1885. var start1 = runStart[i];
  1886. var length1 = runLength[i];
  1887. var start2 = runStart[i + 1];
  1888. var length2 = runLength[i + 1];
  1889. runLength[i] = length1 + length2;
  1890. if (i === stackSize - 3) {
  1891. runStart[i + 1] = runStart[i + 2];
  1892. runLength[i + 1] = runLength[i + 2];
  1893. }
  1894. stackSize--;
  1895. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  1896. start1 += k;
  1897. length1 -= k;
  1898. if (length1 === 0) {
  1899. return;
  1900. }
  1901. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  1902. if (length2 === 0) {
  1903. return;
  1904. }
  1905. if (length1 <= length2) {
  1906. mergeLow(start1, length1, start2, length2);
  1907. }
  1908. else {
  1909. mergeHigh(start1, length1, start2, length2);
  1910. }
  1911. }
  1912. function mergeLow(start1, length1, start2, length2) {
  1913. var i = 0;
  1914. for (i = 0; i < length1; i++) {
  1915. tmp[i] = array[start1 + i];
  1916. }
  1917. var cursor1 = 0;
  1918. var cursor2 = start2;
  1919. var dest = start1;
  1920. array[dest++] = array[cursor2++];
  1921. if (--length2 === 0) {
  1922. for (i = 0; i < length1; i++) {
  1923. array[dest + i] = tmp[cursor1 + i];
  1924. }
  1925. return;
  1926. }
  1927. if (length1 === 1) {
  1928. for (i = 0; i < length2; i++) {
  1929. array[dest + i] = array[cursor2 + i];
  1930. }
  1931. array[dest + length2] = tmp[cursor1];
  1932. return;
  1933. }
  1934. var _minGallop = minGallop;
  1935. var count1;
  1936. var count2;
  1937. var exit;
  1938. while (1) {
  1939. count1 = 0;
  1940. count2 = 0;
  1941. exit = false;
  1942. do {
  1943. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  1944. array[dest++] = array[cursor2++];
  1945. count2++;
  1946. count1 = 0;
  1947. if (--length2 === 0) {
  1948. exit = true;
  1949. break;
  1950. }
  1951. }
  1952. else {
  1953. array[dest++] = tmp[cursor1++];
  1954. count1++;
  1955. count2 = 0;
  1956. if (--length1 === 1) {
  1957. exit = true;
  1958. break;
  1959. }
  1960. }
  1961. } while ((count1 | count2) < _minGallop);
  1962. if (exit) {
  1963. break;
  1964. }
  1965. do {
  1966. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  1967. if (count1 !== 0) {
  1968. for (i = 0; i < count1; i++) {
  1969. array[dest + i] = tmp[cursor1 + i];
  1970. }
  1971. dest += count1;
  1972. cursor1 += count1;
  1973. length1 -= count1;
  1974. if (length1 <= 1) {
  1975. exit = true;
  1976. break;
  1977. }
  1978. }
  1979. array[dest++] = array[cursor2++];
  1980. if (--length2 === 0) {
  1981. exit = true;
  1982. break;
  1983. }
  1984. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  1985. if (count2 !== 0) {
  1986. for (i = 0; i < count2; i++) {
  1987. array[dest + i] = array[cursor2 + i];
  1988. }
  1989. dest += count2;
  1990. cursor2 += count2;
  1991. length2 -= count2;
  1992. if (length2 === 0) {
  1993. exit = true;
  1994. break;
  1995. }
  1996. }
  1997. array[dest++] = tmp[cursor1++];
  1998. if (--length1 === 1) {
  1999. exit = true;
  2000. break;
  2001. }
  2002. _minGallop--;
  2003. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2004. if (exit) {
  2005. break;
  2006. }
  2007. if (_minGallop < 0) {
  2008. _minGallop = 0;
  2009. }
  2010. _minGallop += 2;
  2011. }
  2012. minGallop = _minGallop;
  2013. minGallop < 1 && (minGallop = 1);
  2014. if (length1 === 1) {
  2015. for (i = 0; i < length2; i++) {
  2016. array[dest + i] = array[cursor2 + i];
  2017. }
  2018. array[dest + length2] = tmp[cursor1];
  2019. }
  2020. else if (length1 === 0) {
  2021. throw new Error();
  2022. }
  2023. else {
  2024. for (i = 0; i < length1; i++) {
  2025. array[dest + i] = tmp[cursor1 + i];
  2026. }
  2027. }
  2028. }
  2029. function mergeHigh(start1, length1, start2, length2) {
  2030. var i = 0;
  2031. for (i = 0; i < length2; i++) {
  2032. tmp[i] = array[start2 + i];
  2033. }
  2034. var cursor1 = start1 + length1 - 1;
  2035. var cursor2 = length2 - 1;
  2036. var dest = start2 + length2 - 1;
  2037. var customCursor = 0;
  2038. var customDest = 0;
  2039. array[dest--] = array[cursor1--];
  2040. if (--length1 === 0) {
  2041. customCursor = dest - (length2 - 1);
  2042. for (i = 0; i < length2; i++) {
  2043. array[customCursor + i] = tmp[i];
  2044. }
  2045. return;
  2046. }
  2047. if (length2 === 1) {
  2048. dest -= length1;
  2049. cursor1 -= length1;
  2050. customDest = dest + 1;
  2051. customCursor = cursor1 + 1;
  2052. for (i = length1 - 1; i >= 0; i--) {
  2053. array[customDest + i] = array[customCursor + i];
  2054. }
  2055. array[dest] = tmp[cursor2];
  2056. return;
  2057. }
  2058. var _minGallop = minGallop;
  2059. while (true) {
  2060. var count1 = 0;
  2061. var count2 = 0;
  2062. var exit = false;
  2063. do {
  2064. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2065. array[dest--] = array[cursor1--];
  2066. count1++;
  2067. count2 = 0;
  2068. if (--length1 === 0) {
  2069. exit = true;
  2070. break;
  2071. }
  2072. }
  2073. else {
  2074. array[dest--] = tmp[cursor2--];
  2075. count2++;
  2076. count1 = 0;
  2077. if (--length2 === 1) {
  2078. exit = true;
  2079. break;
  2080. }
  2081. }
  2082. } while ((count1 | count2) < _minGallop);
  2083. if (exit) {
  2084. break;
  2085. }
  2086. do {
  2087. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2088. if (count1 !== 0) {
  2089. dest -= count1;
  2090. cursor1 -= count1;
  2091. length1 -= count1;
  2092. customDest = dest + 1;
  2093. customCursor = cursor1 + 1;
  2094. for (i = count1 - 1; i >= 0; i--) {
  2095. array[customDest + i] = array[customCursor + i];
  2096. }
  2097. if (length1 === 0) {
  2098. exit = true;
  2099. break;
  2100. }
  2101. }
  2102. array[dest--] = tmp[cursor2--];
  2103. if (--length2 === 1) {
  2104. exit = true;
  2105. break;
  2106. }
  2107. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2108. if (count2 !== 0) {
  2109. dest -= count2;
  2110. cursor2 -= count2;
  2111. length2 -= count2;
  2112. customDest = dest + 1;
  2113. customCursor = cursor2 + 1;
  2114. for (i = 0; i < count2; i++) {
  2115. array[customDest + i] = tmp[customCursor + i];
  2116. }
  2117. if (length2 <= 1) {
  2118. exit = true;
  2119. break;
  2120. }
  2121. }
  2122. array[dest--] = array[cursor1--];
  2123. if (--length1 === 0) {
  2124. exit = true;
  2125. break;
  2126. }
  2127. _minGallop--;
  2128. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2129. if (exit) {
  2130. break;
  2131. }
  2132. if (_minGallop < 0) {
  2133. _minGallop = 0;
  2134. }
  2135. _minGallop += 2;
  2136. }
  2137. minGallop = _minGallop;
  2138. if (minGallop < 1) {
  2139. minGallop = 1;
  2140. }
  2141. if (length2 === 1) {
  2142. dest -= length1;
  2143. cursor1 -= length1;
  2144. customDest = dest + 1;
  2145. customCursor = cursor1 + 1;
  2146. for (i = length1 - 1; i >= 0; i--) {
  2147. array[customDest + i] = array[customCursor + i];
  2148. }
  2149. array[dest] = tmp[cursor2];
  2150. }
  2151. else if (length2 === 0) {
  2152. throw new Error();
  2153. }
  2154. else {
  2155. customCursor = dest - (length2 - 1);
  2156. for (i = 0; i < length2; i++) {
  2157. array[customCursor + i] = tmp[i];
  2158. }
  2159. }
  2160. }
  2161. return {
  2162. mergeRuns: mergeRuns,
  2163. forceMergeRuns: forceMergeRuns,
  2164. pushRun: pushRun
  2165. };
  2166. }
  2167. function sort(array, compare, lo, hi) {
  2168. if (!lo) {
  2169. lo = 0;
  2170. }
  2171. if (!hi) {
  2172. hi = array.length;
  2173. }
  2174. var remaining = hi - lo;
  2175. if (remaining < 2) {
  2176. return;
  2177. }
  2178. var runLength = 0;
  2179. if (remaining < DEFAULT_MIN_MERGE) {
  2180. runLength = makeAscendingRun(array, lo, hi, compare);
  2181. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2182. return;
  2183. }
  2184. var ts = TimSort(array, compare);
  2185. var minRun = minRunLength(remaining);
  2186. do {
  2187. runLength = makeAscendingRun(array, lo, hi, compare);
  2188. if (runLength < minRun) {
  2189. var force = remaining;
  2190. if (force > minRun) {
  2191. force = minRun;
  2192. }
  2193. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2194. runLength = force;
  2195. }
  2196. ts.pushRun(lo, runLength);
  2197. ts.mergeRuns();
  2198. remaining -= runLength;
  2199. lo += runLength;
  2200. } while (remaining !== 0);
  2201. ts.forceMergeRuns();
  2202. }
  2203. var REDRAW_BIT = 1;
  2204. var STYLE_CHANGED_BIT = 2;
  2205. var SHAPE_CHANGED_BIT = 4;
  2206. var invalidZErrorLogged = false;
  2207. function logInvalidZError() {
  2208. if (invalidZErrorLogged) {
  2209. return;
  2210. }
  2211. invalidZErrorLogged = true;
  2212. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2213. }
  2214. function shapeCompareFunc(a, b) {
  2215. if (a.zlevel === b.zlevel) {
  2216. if (a.z === b.z) {
  2217. return a.z2 - b.z2;
  2218. }
  2219. return a.z - b.z;
  2220. }
  2221. return a.zlevel - b.zlevel;
  2222. }
  2223. var Storage = (function () {
  2224. function Storage() {
  2225. this._roots = [];
  2226. this._displayList = [];
  2227. this._displayListLen = 0;
  2228. this.displayableSortFunc = shapeCompareFunc;
  2229. }
  2230. Storage.prototype.traverse = function (cb, context) {
  2231. for (var i = 0; i < this._roots.length; i++) {
  2232. this._roots[i].traverse(cb, context);
  2233. }
  2234. };
  2235. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2236. includeIgnore = includeIgnore || false;
  2237. var displayList = this._displayList;
  2238. if (update || !displayList.length) {
  2239. this.updateDisplayList(includeIgnore);
  2240. }
  2241. return displayList;
  2242. };
  2243. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2244. this._displayListLen = 0;
  2245. var roots = this._roots;
  2246. var displayList = this._displayList;
  2247. for (var i = 0, len = roots.length; i < len; i++) {
  2248. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2249. }
  2250. displayList.length = this._displayListLen;
  2251. sort(displayList, shapeCompareFunc);
  2252. };
  2253. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2254. if (el.ignore && !includeIgnore) {
  2255. return;
  2256. }
  2257. el.beforeUpdate();
  2258. el.update();
  2259. el.afterUpdate();
  2260. var userSetClipPath = el.getClipPath();
  2261. if (el.ignoreClip) {
  2262. clipPaths = null;
  2263. }
  2264. else if (userSetClipPath) {
  2265. if (clipPaths) {
  2266. clipPaths = clipPaths.slice();
  2267. }
  2268. else {
  2269. clipPaths = [];
  2270. }
  2271. var currentClipPath = userSetClipPath;
  2272. var parentClipPath = el;
  2273. while (currentClipPath) {
  2274. currentClipPath.parent = parentClipPath;
  2275. currentClipPath.updateTransform();
  2276. clipPaths.push(currentClipPath);
  2277. parentClipPath = currentClipPath;
  2278. currentClipPath = currentClipPath.getClipPath();
  2279. }
  2280. }
  2281. if (el.childrenRef) {
  2282. var children = el.childrenRef();
  2283. for (var i = 0; i < children.length; i++) {
  2284. var child = children[i];
  2285. if (el.__dirty) {
  2286. child.__dirty |= REDRAW_BIT;
  2287. }
  2288. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2289. }
  2290. el.__dirty = 0;
  2291. }
  2292. else {
  2293. var disp = el;
  2294. if (clipPaths && clipPaths.length) {
  2295. disp.__clipPaths = clipPaths;
  2296. }
  2297. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2298. disp.__clipPaths = [];
  2299. }
  2300. if (isNaN(disp.z)) {
  2301. logInvalidZError();
  2302. disp.z = 0;
  2303. }
  2304. if (isNaN(disp.z2)) {
  2305. logInvalidZError();
  2306. disp.z2 = 0;
  2307. }
  2308. if (isNaN(disp.zlevel)) {
  2309. logInvalidZError();
  2310. disp.zlevel = 0;
  2311. }
  2312. this._displayList[this._displayListLen++] = disp;
  2313. }
  2314. var decalEl = el.getDecalElement && el.getDecalElement();
  2315. if (decalEl) {
  2316. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2317. }
  2318. var textGuide = el.getTextGuideLine();
  2319. if (textGuide) {
  2320. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2321. }
  2322. var textEl = el.getTextContent();
  2323. if (textEl) {
  2324. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2325. }
  2326. };
  2327. Storage.prototype.addRoot = function (el) {
  2328. if (el.__zr && el.__zr.storage === this) {
  2329. return;
  2330. }
  2331. this._roots.push(el);
  2332. };
  2333. Storage.prototype.delRoot = function (el) {
  2334. if (el instanceof Array) {
  2335. for (var i = 0, l = el.length; i < l; i++) {
  2336. this.delRoot(el[i]);
  2337. }
  2338. return;
  2339. }
  2340. var idx = indexOf(this._roots, el);
  2341. if (idx >= 0) {
  2342. this._roots.splice(idx, 1);
  2343. }
  2344. };
  2345. Storage.prototype.delAllRoots = function () {
  2346. this._roots = [];
  2347. this._displayList = [];
  2348. this._displayListLen = 0;
  2349. return;
  2350. };
  2351. Storage.prototype.getRoots = function () {
  2352. return this._roots;
  2353. };
  2354. Storage.prototype.dispose = function () {
  2355. this._displayList = null;
  2356. this._roots = null;
  2357. };
  2358. return Storage;
  2359. }());
  2360. var requestAnimationFrame;
  2361. requestAnimationFrame = (env.hasGlobalWindow
  2362. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2363. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2364. || window.mozRequestAnimationFrame
  2365. || window.webkitRequestAnimationFrame)) || function (func) {
  2366. return setTimeout(func, 16);
  2367. };
  2368. var requestAnimationFrame$1 = requestAnimationFrame;
  2369. var easingFuncs = {
  2370. linear: function (k) {
  2371. return k;
  2372. },
  2373. quadraticIn: function (k) {
  2374. return k * k;
  2375. },
  2376. quadraticOut: function (k) {
  2377. return k * (2 - k);
  2378. },
  2379. quadraticInOut: function (k) {
  2380. if ((k *= 2) < 1) {
  2381. return 0.5 * k * k;
  2382. }
  2383. return -0.5 * (--k * (k - 2) - 1);
  2384. },
  2385. cubicIn: function (k) {
  2386. return k * k * k;
  2387. },
  2388. cubicOut: function (k) {
  2389. return --k * k * k + 1;
  2390. },
  2391. cubicInOut: function (k) {
  2392. if ((k *= 2) < 1) {
  2393. return 0.5 * k * k * k;
  2394. }
  2395. return 0.5 * ((k -= 2) * k * k + 2);
  2396. },
  2397. quarticIn: function (k) {
  2398. return k * k * k * k;
  2399. },
  2400. quarticOut: function (k) {
  2401. return 1 - (--k * k * k * k);
  2402. },
  2403. quarticInOut: function (k) {
  2404. if ((k *= 2) < 1) {
  2405. return 0.5 * k * k * k * k;
  2406. }
  2407. return -0.5 * ((k -= 2) * k * k * k - 2);
  2408. },
  2409. quinticIn: function (k) {
  2410. return k * k * k * k * k;
  2411. },
  2412. quinticOut: function (k) {
  2413. return --k * k * k * k * k + 1;
  2414. },
  2415. quinticInOut: function (k) {
  2416. if ((k *= 2) < 1) {
  2417. return 0.5 * k * k * k * k * k;
  2418. }
  2419. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2420. },
  2421. sinusoidalIn: function (k) {
  2422. return 1 - Math.cos(k * Math.PI / 2);
  2423. },
  2424. sinusoidalOut: function (k) {
  2425. return Math.sin(k * Math.PI / 2);
  2426. },
  2427. sinusoidalInOut: function (k) {
  2428. return 0.5 * (1 - Math.cos(Math.PI * k));
  2429. },
  2430. exponentialIn: function (k) {
  2431. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2432. },
  2433. exponentialOut: function (k) {
  2434. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2435. },
  2436. exponentialInOut: function (k) {
  2437. if (k === 0) {
  2438. return 0;
  2439. }
  2440. if (k === 1) {
  2441. return 1;
  2442. }
  2443. if ((k *= 2) < 1) {
  2444. return 0.5 * Math.pow(1024, k - 1);
  2445. }
  2446. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2447. },
  2448. circularIn: function (k) {
  2449. return 1 - Math.sqrt(1 - k * k);
  2450. },
  2451. circularOut: function (k) {
  2452. return Math.sqrt(1 - (--k * k));
  2453. },
  2454. circularInOut: function (k) {
  2455. if ((k *= 2) < 1) {
  2456. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2457. }
  2458. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2459. },
  2460. elasticIn: function (k) {
  2461. var s;
  2462. var a = 0.1;
  2463. var p = 0.4;
  2464. if (k === 0) {
  2465. return 0;
  2466. }
  2467. if (k === 1) {
  2468. return 1;
  2469. }
  2470. if (!a || a < 1) {
  2471. a = 1;
  2472. s = p / 4;
  2473. }
  2474. else {
  2475. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2476. }
  2477. return -(a * Math.pow(2, 10 * (k -= 1))
  2478. * Math.sin((k - s) * (2 * Math.PI) / p));
  2479. },
  2480. elasticOut: function (k) {
  2481. var s;
  2482. var a = 0.1;
  2483. var p = 0.4;
  2484. if (k === 0) {
  2485. return 0;
  2486. }
  2487. if (k === 1) {
  2488. return 1;
  2489. }
  2490. if (!a || a < 1) {
  2491. a = 1;
  2492. s = p / 4;
  2493. }
  2494. else {
  2495. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2496. }
  2497. return (a * Math.pow(2, -10 * k)
  2498. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2499. },
  2500. elasticInOut: function (k) {
  2501. var s;
  2502. var a = 0.1;
  2503. var p = 0.4;
  2504. if (k === 0) {
  2505. return 0;
  2506. }
  2507. if (k === 1) {
  2508. return 1;
  2509. }
  2510. if (!a || a < 1) {
  2511. a = 1;
  2512. s = p / 4;
  2513. }
  2514. else {
  2515. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2516. }
  2517. if ((k *= 2) < 1) {
  2518. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2519. * Math.sin((k - s) * (2 * Math.PI) / p));
  2520. }
  2521. return a * Math.pow(2, -10 * (k -= 1))
  2522. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2523. },
  2524. backIn: function (k) {
  2525. var s = 1.70158;
  2526. return k * k * ((s + 1) * k - s);
  2527. },
  2528. backOut: function (k) {
  2529. var s = 1.70158;
  2530. return --k * k * ((s + 1) * k + s) + 1;
  2531. },
  2532. backInOut: function (k) {
  2533. var s = 1.70158 * 1.525;
  2534. if ((k *= 2) < 1) {
  2535. return 0.5 * (k * k * ((s + 1) * k - s));
  2536. }
  2537. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2538. },
  2539. bounceIn: function (k) {
  2540. return 1 - easingFuncs.bounceOut(1 - k);
  2541. },
  2542. bounceOut: function (k) {
  2543. if (k < (1 / 2.75)) {
  2544. return 7.5625 * k * k;
  2545. }
  2546. else if (k < (2 / 2.75)) {
  2547. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2548. }
  2549. else if (k < (2.5 / 2.75)) {
  2550. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2551. }
  2552. else {
  2553. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2554. }
  2555. },
  2556. bounceInOut: function (k) {
  2557. if (k < 0.5) {
  2558. return easingFuncs.bounceIn(k * 2) * 0.5;
  2559. }
  2560. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2561. }
  2562. };
  2563. var mathPow = Math.pow;
  2564. var mathSqrt = Math.sqrt;
  2565. var EPSILON = 1e-8;
  2566. var EPSILON_NUMERIC = 1e-4;
  2567. var THREE_SQRT = mathSqrt(3);
  2568. var ONE_THIRD = 1 / 3;
  2569. var _v0 = create();
  2570. var _v1 = create();
  2571. var _v2 = create();
  2572. function isAroundZero(val) {
  2573. return val > -EPSILON && val < EPSILON;
  2574. }
  2575. function isNotAroundZero(val) {
  2576. return val > EPSILON || val < -EPSILON;
  2577. }
  2578. function cubicAt(p0, p1, p2, p3, t) {
  2579. var onet = 1 - t;
  2580. return onet * onet * (onet * p0 + 3 * t * p1)
  2581. + t * t * (t * p3 + 3 * onet * p2);
  2582. }
  2583. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  2584. var onet = 1 - t;
  2585. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  2586. + (p3 - p2) * t * t);
  2587. }
  2588. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  2589. var a = p3 + 3 * (p1 - p2) - p0;
  2590. var b = 3 * (p2 - p1 * 2 + p0);
  2591. var c = 3 * (p1 - p0);
  2592. var d = p0 - val;
  2593. var A = b * b - 3 * a * c;
  2594. var B = b * c - 9 * a * d;
  2595. var C = c * c - 3 * b * d;
  2596. var n = 0;
  2597. if (isAroundZero(A) && isAroundZero(B)) {
  2598. if (isAroundZero(b)) {
  2599. roots[0] = 0;
  2600. }
  2601. else {
  2602. var t1 = -c / b;
  2603. if (t1 >= 0 && t1 <= 1) {
  2604. roots[n++] = t1;
  2605. }
  2606. }
  2607. }
  2608. else {
  2609. var disc = B * B - 4 * A * C;
  2610. if (isAroundZero(disc)) {
  2611. var K = B / A;
  2612. var t1 = -b / a + K;
  2613. var t2 = -K / 2;
  2614. if (t1 >= 0 && t1 <= 1) {
  2615. roots[n++] = t1;
  2616. }
  2617. if (t2 >= 0 && t2 <= 1) {
  2618. roots[n++] = t2;
  2619. }
  2620. }
  2621. else if (disc > 0) {
  2622. var discSqrt = mathSqrt(disc);
  2623. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  2624. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  2625. if (Y1 < 0) {
  2626. Y1 = -mathPow(-Y1, ONE_THIRD);
  2627. }
  2628. else {
  2629. Y1 = mathPow(Y1, ONE_THIRD);
  2630. }
  2631. if (Y2 < 0) {
  2632. Y2 = -mathPow(-Y2, ONE_THIRD);
  2633. }
  2634. else {
  2635. Y2 = mathPow(Y2, ONE_THIRD);
  2636. }
  2637. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  2638. if (t1 >= 0 && t1 <= 1) {
  2639. roots[n++] = t1;
  2640. }
  2641. }
  2642. else {
  2643. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  2644. var theta = Math.acos(T) / 3;
  2645. var ASqrt = mathSqrt(A);
  2646. var tmp = Math.cos(theta);
  2647. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  2648. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  2649. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  2650. if (t1 >= 0 && t1 <= 1) {
  2651. roots[n++] = t1;
  2652. }
  2653. if (t2 >= 0 && t2 <= 1) {
  2654. roots[n++] = t2;
  2655. }
  2656. if (t3 >= 0 && t3 <= 1) {
  2657. roots[n++] = t3;
  2658. }
  2659. }
  2660. }
  2661. return n;
  2662. }
  2663. function cubicExtrema(p0, p1, p2, p3, extrema) {
  2664. var b = 6 * p2 - 12 * p1 + 6 * p0;
  2665. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  2666. var c = 3 * p1 - 3 * p0;
  2667. var n = 0;
  2668. if (isAroundZero(a)) {
  2669. if (isNotAroundZero(b)) {
  2670. var t1 = -c / b;
  2671. if (t1 >= 0 && t1 <= 1) {
  2672. extrema[n++] = t1;
  2673. }
  2674. }
  2675. }
  2676. else {
  2677. var disc = b * b - 4 * a * c;
  2678. if (isAroundZero(disc)) {
  2679. extrema[0] = -b / (2 * a);
  2680. }
  2681. else if (disc > 0) {
  2682. var discSqrt = mathSqrt(disc);
  2683. var t1 = (-b + discSqrt) / (2 * a);
  2684. var t2 = (-b - discSqrt) / (2 * a);
  2685. if (t1 >= 0 && t1 <= 1) {
  2686. extrema[n++] = t1;
  2687. }
  2688. if (t2 >= 0 && t2 <= 1) {
  2689. extrema[n++] = t2;
  2690. }
  2691. }
  2692. }
  2693. return n;
  2694. }
  2695. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  2696. var p01 = (p1 - p0) * t + p0;
  2697. var p12 = (p2 - p1) * t + p1;
  2698. var p23 = (p3 - p2) * t + p2;
  2699. var p012 = (p12 - p01) * t + p01;
  2700. var p123 = (p23 - p12) * t + p12;
  2701. var p0123 = (p123 - p012) * t + p012;
  2702. out[0] = p0;
  2703. out[1] = p01;
  2704. out[2] = p012;
  2705. out[3] = p0123;
  2706. out[4] = p0123;
  2707. out[5] = p123;
  2708. out[6] = p23;
  2709. out[7] = p3;
  2710. }
  2711. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  2712. var t;
  2713. var interval = 0.005;
  2714. var d = Infinity;
  2715. var prev;
  2716. var next;
  2717. var d1;
  2718. var d2;
  2719. _v0[0] = x;
  2720. _v0[1] = y;
  2721. for (var _t = 0; _t < 1; _t += 0.05) {
  2722. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  2723. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  2724. d1 = distSquare(_v0, _v1);
  2725. if (d1 < d) {
  2726. t = _t;
  2727. d = d1;
  2728. }
  2729. }
  2730. d = Infinity;
  2731. for (var i = 0; i < 32; i++) {
  2732. if (interval < EPSILON_NUMERIC) {
  2733. break;
  2734. }
  2735. prev = t - interval;
  2736. next = t + interval;
  2737. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  2738. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  2739. d1 = distSquare(_v1, _v0);
  2740. if (prev >= 0 && d1 < d) {
  2741. t = prev;
  2742. d = d1;
  2743. }
  2744. else {
  2745. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  2746. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  2747. d2 = distSquare(_v2, _v0);
  2748. if (next <= 1 && d2 < d) {
  2749. t = next;
  2750. d = d2;
  2751. }
  2752. else {
  2753. interval *= 0.5;
  2754. }
  2755. }
  2756. }
  2757. if (out) {
  2758. out[0] = cubicAt(x0, x1, x2, x3, t);
  2759. out[1] = cubicAt(y0, y1, y2, y3, t);
  2760. }
  2761. return mathSqrt(d);
  2762. }
  2763. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  2764. var px = x0;
  2765. var py = y0;
  2766. var d = 0;
  2767. var step = 1 / iteration;
  2768. for (var i = 1; i <= iteration; i++) {
  2769. var t = i * step;
  2770. var x = cubicAt(x0, x1, x2, x3, t);
  2771. var y = cubicAt(y0, y1, y2, y3, t);
  2772. var dx = x - px;
  2773. var dy = y - py;
  2774. d += Math.sqrt(dx * dx + dy * dy);
  2775. px = x;
  2776. py = y;
  2777. }
  2778. return d;
  2779. }
  2780. function quadraticAt(p0, p1, p2, t) {
  2781. var onet = 1 - t;
  2782. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  2783. }
  2784. function quadraticDerivativeAt(p0, p1, p2, t) {
  2785. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  2786. }
  2787. function quadraticRootAt(p0, p1, p2, val, roots) {
  2788. var a = p0 - 2 * p1 + p2;
  2789. var b = 2 * (p1 - p0);
  2790. var c = p0 - val;
  2791. var n = 0;
  2792. if (isAroundZero(a)) {
  2793. if (isNotAroundZero(b)) {
  2794. var t1 = -c / b;
  2795. if (t1 >= 0 && t1 <= 1) {
  2796. roots[n++] = t1;
  2797. }
  2798. }
  2799. }
  2800. else {
  2801. var disc = b * b - 4 * a * c;
  2802. if (isAroundZero(disc)) {
  2803. var t1 = -b / (2 * a);
  2804. if (t1 >= 0 && t1 <= 1) {
  2805. roots[n++] = t1;
  2806. }
  2807. }
  2808. else if (disc > 0) {
  2809. var discSqrt = mathSqrt(disc);
  2810. var t1 = (-b + discSqrt) / (2 * a);
  2811. var t2 = (-b - discSqrt) / (2 * a);
  2812. if (t1 >= 0 && t1 <= 1) {
  2813. roots[n++] = t1;
  2814. }
  2815. if (t2 >= 0 && t2 <= 1) {
  2816. roots[n++] = t2;
  2817. }
  2818. }
  2819. }
  2820. return n;
  2821. }
  2822. function quadraticExtremum(p0, p1, p2) {
  2823. var divider = p0 + p2 - 2 * p1;
  2824. if (divider === 0) {
  2825. return 0.5;
  2826. }
  2827. else {
  2828. return (p0 - p1) / divider;
  2829. }
  2830. }
  2831. function quadraticSubdivide(p0, p1, p2, t, out) {
  2832. var p01 = (p1 - p0) * t + p0;
  2833. var p12 = (p2 - p1) * t + p1;
  2834. var p012 = (p12 - p01) * t + p01;
  2835. out[0] = p0;
  2836. out[1] = p01;
  2837. out[2] = p012;
  2838. out[3] = p012;
  2839. out[4] = p12;
  2840. out[5] = p2;
  2841. }
  2842. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  2843. var t;
  2844. var interval = 0.005;
  2845. var d = Infinity;
  2846. _v0[0] = x;
  2847. _v0[1] = y;
  2848. for (var _t = 0; _t < 1; _t += 0.05) {
  2849. _v1[0] = quadraticAt(x0, x1, x2, _t);
  2850. _v1[1] = quadraticAt(y0, y1, y2, _t);
  2851. var d1 = distSquare(_v0, _v1);
  2852. if (d1 < d) {
  2853. t = _t;
  2854. d = d1;
  2855. }
  2856. }
  2857. d = Infinity;
  2858. for (var i = 0; i < 32; i++) {
  2859. if (interval < EPSILON_NUMERIC) {
  2860. break;
  2861. }
  2862. var prev = t - interval;
  2863. var next = t + interval;
  2864. _v1[0] = quadraticAt(x0, x1, x2, prev);
  2865. _v1[1] = quadraticAt(y0, y1, y2, prev);
  2866. var d1 = distSquare(_v1, _v0);
  2867. if (prev >= 0 && d1 < d) {
  2868. t = prev;
  2869. d = d1;
  2870. }
  2871. else {
  2872. _v2[0] = quadraticAt(x0, x1, x2, next);
  2873. _v2[1] = quadraticAt(y0, y1, y2, next);
  2874. var d2 = distSquare(_v2, _v0);
  2875. if (next <= 1 && d2 < d) {
  2876. t = next;
  2877. d = d2;
  2878. }
  2879. else {
  2880. interval *= 0.5;
  2881. }
  2882. }
  2883. }
  2884. if (out) {
  2885. out[0] = quadraticAt(x0, x1, x2, t);
  2886. out[1] = quadraticAt(y0, y1, y2, t);
  2887. }
  2888. return mathSqrt(d);
  2889. }
  2890. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  2891. var px = x0;
  2892. var py = y0;
  2893. var d = 0;
  2894. var step = 1 / iteration;
  2895. for (var i = 1; i <= iteration; i++) {
  2896. var t = i * step;
  2897. var x = quadraticAt(x0, x1, x2, t);
  2898. var y = quadraticAt(y0, y1, y2, t);
  2899. var dx = x - px;
  2900. var dy = y - py;
  2901. d += Math.sqrt(dx * dx + dy * dy);
  2902. px = x;
  2903. py = y;
  2904. }
  2905. return d;
  2906. }
  2907. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  2908. function createCubicEasingFunc(cubicEasingStr) {
  2909. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  2910. if (cubic) {
  2911. var points = cubic[1].split(',');
  2912. var a_1 = +trim(points[0]);
  2913. var b_1 = +trim(points[1]);
  2914. var c_1 = +trim(points[2]);
  2915. var d_1 = +trim(points[3]);
  2916. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  2917. return;
  2918. }
  2919. var roots_1 = [];
  2920. return function (p) {
  2921. return p <= 0
  2922. ? 0 : p >= 1
  2923. ? 1
  2924. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  2925. };
  2926. }
  2927. }
  2928. var Clip = (function () {
  2929. function Clip(opts) {
  2930. this._inited = false;
  2931. this._startTime = 0;
  2932. this._pausedTime = 0;
  2933. this._paused = false;
  2934. this._life = opts.life || 1000;
  2935. this._delay = opts.delay || 0;
  2936. this.loop = opts.loop || false;
  2937. this.onframe = opts.onframe || noop;
  2938. this.ondestroy = opts.ondestroy || noop;
  2939. this.onrestart = opts.onrestart || noop;
  2940. opts.easing && this.setEasing(opts.easing);
  2941. }
  2942. Clip.prototype.step = function (globalTime, deltaTime) {
  2943. if (!this._inited) {
  2944. this._startTime = globalTime + this._delay;
  2945. this._inited = true;
  2946. }
  2947. if (this._paused) {
  2948. this._pausedTime += deltaTime;
  2949. return;
  2950. }
  2951. var life = this._life;
  2952. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  2953. var percent = elapsedTime / life;
  2954. if (percent < 0) {
  2955. percent = 0;
  2956. }
  2957. percent = Math.min(percent, 1);
  2958. var easingFunc = this.easingFunc;
  2959. var schedule = easingFunc ? easingFunc(percent) : percent;
  2960. this.onframe(schedule);
  2961. if (percent === 1) {
  2962. if (this.loop) {
  2963. var remainder = elapsedTime % life;
  2964. this._startTime = globalTime - remainder;
  2965. this._pausedTime = 0;
  2966. this.onrestart();
  2967. }
  2968. else {
  2969. return true;
  2970. }
  2971. }
  2972. return false;
  2973. };
  2974. Clip.prototype.pause = function () {
  2975. this._paused = true;
  2976. };
  2977. Clip.prototype.resume = function () {
  2978. this._paused = false;
  2979. };
  2980. Clip.prototype.setEasing = function (easing) {
  2981. this.easing = easing;
  2982. this.easingFunc = isFunction(easing)
  2983. ? easing
  2984. : easingFuncs[easing] || createCubicEasingFunc(easing);
  2985. };
  2986. return Clip;
  2987. }());
  2988. var Entry = (function () {
  2989. function Entry(val) {
  2990. this.value = val;
  2991. }
  2992. return Entry;
  2993. }());
  2994. var LinkedList = (function () {
  2995. function LinkedList() {
  2996. this._len = 0;
  2997. }
  2998. LinkedList.prototype.insert = function (val) {
  2999. var entry = new Entry(val);
  3000. this.insertEntry(entry);
  3001. return entry;
  3002. };
  3003. LinkedList.prototype.insertEntry = function (entry) {
  3004. if (!this.head) {
  3005. this.head = this.tail = entry;
  3006. }
  3007. else {
  3008. this.tail.next = entry;
  3009. entry.prev = this.tail;
  3010. entry.next = null;
  3011. this.tail = entry;
  3012. }
  3013. this._len++;
  3014. };
  3015. LinkedList.prototype.remove = function (entry) {
  3016. var prev = entry.prev;
  3017. var next = entry.next;
  3018. if (prev) {
  3019. prev.next = next;
  3020. }
  3021. else {
  3022. this.head = next;
  3023. }
  3024. if (next) {
  3025. next.prev = prev;
  3026. }
  3027. else {
  3028. this.tail = prev;
  3029. }
  3030. entry.next = entry.prev = null;
  3031. this._len--;
  3032. };
  3033. LinkedList.prototype.len = function () {
  3034. return this._len;
  3035. };
  3036. LinkedList.prototype.clear = function () {
  3037. this.head = this.tail = null;
  3038. this._len = 0;
  3039. };
  3040. return LinkedList;
  3041. }());
  3042. var LRU = (function () {
  3043. function LRU(maxSize) {
  3044. this._list = new LinkedList();
  3045. this._maxSize = 10;
  3046. this._map = {};
  3047. this._maxSize = maxSize;
  3048. }
  3049. LRU.prototype.put = function (key, value) {
  3050. var list = this._list;
  3051. var map = this._map;
  3052. var removed = null;
  3053. if (map[key] == null) {
  3054. var len = list.len();
  3055. var entry = this._lastRemovedEntry;
  3056. if (len >= this._maxSize && len > 0) {
  3057. var leastUsedEntry = list.head;
  3058. list.remove(leastUsedEntry);
  3059. delete map[leastUsedEntry.key];
  3060. removed = leastUsedEntry.value;
  3061. this._lastRemovedEntry = leastUsedEntry;
  3062. }
  3063. if (entry) {
  3064. entry.value = value;
  3065. }
  3066. else {
  3067. entry = new Entry(value);
  3068. }
  3069. entry.key = key;
  3070. list.insertEntry(entry);
  3071. map[key] = entry;
  3072. }
  3073. return removed;
  3074. };
  3075. LRU.prototype.get = function (key) {
  3076. var entry = this._map[key];
  3077. var list = this._list;
  3078. if (entry != null) {
  3079. if (entry !== list.tail) {
  3080. list.remove(entry);
  3081. list.insertEntry(entry);
  3082. }
  3083. return entry.value;
  3084. }
  3085. };
  3086. LRU.prototype.clear = function () {
  3087. this._list.clear();
  3088. this._map = {};
  3089. };
  3090. LRU.prototype.len = function () {
  3091. return this._list.len();
  3092. };
  3093. return LRU;
  3094. }());
  3095. var kCSSColorTable = {
  3096. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3097. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3098. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3099. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3100. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3101. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3102. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3103. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3104. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3105. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3106. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3107. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3108. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3109. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3110. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3111. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3112. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3113. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3114. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3115. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3116. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3117. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3118. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3119. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3120. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3121. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3122. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3123. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3124. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3125. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3126. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3127. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3128. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3129. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3130. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3131. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3132. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3133. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3134. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3135. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3136. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3137. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3138. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3139. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3140. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3141. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3142. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3143. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3144. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3145. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3146. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3147. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3148. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3149. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3150. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3151. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3152. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3153. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3154. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3155. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3156. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3157. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3158. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3159. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3160. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3161. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3162. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3163. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3164. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3165. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3166. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3167. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3168. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3169. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3170. };
  3171. function clampCssByte(i) {
  3172. i = Math.round(i);
  3173. return i < 0 ? 0 : i > 255 ? 255 : i;
  3174. }
  3175. function clampCssAngle(i) {
  3176. i = Math.round(i);
  3177. return i < 0 ? 0 : i > 360 ? 360 : i;
  3178. }
  3179. function clampCssFloat(f) {
  3180. return f < 0 ? 0 : f > 1 ? 1 : f;
  3181. }
  3182. function parseCssInt(val) {
  3183. var str = val;
  3184. if (str.length && str.charAt(str.length - 1) === '%') {
  3185. return clampCssByte(parseFloat(str) / 100 * 255);
  3186. }
  3187. return clampCssByte(parseInt(str, 10));
  3188. }
  3189. function parseCssFloat(val) {
  3190. var str = val;
  3191. if (str.length && str.charAt(str.length - 1) === '%') {
  3192. return clampCssFloat(parseFloat(str) / 100);
  3193. }
  3194. return clampCssFloat(parseFloat(str));
  3195. }
  3196. function cssHueToRgb(m1, m2, h) {
  3197. if (h < 0) {
  3198. h += 1;
  3199. }
  3200. else if (h > 1) {
  3201. h -= 1;
  3202. }
  3203. if (h * 6 < 1) {
  3204. return m1 + (m2 - m1) * h * 6;
  3205. }
  3206. if (h * 2 < 1) {
  3207. return m2;
  3208. }
  3209. if (h * 3 < 2) {
  3210. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3211. }
  3212. return m1;
  3213. }
  3214. function lerpNumber(a, b, p) {
  3215. return a + (b - a) * p;
  3216. }
  3217. function setRgba(out, r, g, b, a) {
  3218. out[0] = r;
  3219. out[1] = g;
  3220. out[2] = b;
  3221. out[3] = a;
  3222. return out;
  3223. }
  3224. function copyRgba(out, a) {
  3225. out[0] = a[0];
  3226. out[1] = a[1];
  3227. out[2] = a[2];
  3228. out[3] = a[3];
  3229. return out;
  3230. }
  3231. var colorCache = new LRU(20);
  3232. var lastRemovedArr = null;
  3233. function putToCache(colorStr, rgbaArr) {
  3234. if (lastRemovedArr) {
  3235. copyRgba(lastRemovedArr, rgbaArr);
  3236. }
  3237. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3238. }
  3239. function parse(colorStr, rgbaArr) {
  3240. if (!colorStr) {
  3241. return;
  3242. }
  3243. rgbaArr = rgbaArr || [];
  3244. var cached = colorCache.get(colorStr);
  3245. if (cached) {
  3246. return copyRgba(rgbaArr, cached);
  3247. }
  3248. colorStr = colorStr + '';
  3249. var str = colorStr.replace(/ /g, '').toLowerCase();
  3250. if (str in kCSSColorTable) {
  3251. copyRgba(rgbaArr, kCSSColorTable[str]);
  3252. putToCache(colorStr, rgbaArr);
  3253. return rgbaArr;
  3254. }
  3255. var strLen = str.length;
  3256. if (str.charAt(0) === '#') {
  3257. if (strLen === 4 || strLen === 5) {
  3258. var iv = parseInt(str.slice(1, 4), 16);
  3259. if (!(iv >= 0 && iv <= 0xfff)) {
  3260. setRgba(rgbaArr, 0, 0, 0, 1);
  3261. return;
  3262. }
  3263. 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);
  3264. putToCache(colorStr, rgbaArr);
  3265. return rgbaArr;
  3266. }
  3267. else if (strLen === 7 || strLen === 9) {
  3268. var iv = parseInt(str.slice(1, 7), 16);
  3269. if (!(iv >= 0 && iv <= 0xffffff)) {
  3270. setRgba(rgbaArr, 0, 0, 0, 1);
  3271. return;
  3272. }
  3273. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3274. putToCache(colorStr, rgbaArr);
  3275. return rgbaArr;
  3276. }
  3277. return;
  3278. }
  3279. var op = str.indexOf('(');
  3280. var ep = str.indexOf(')');
  3281. if (op !== -1 && ep + 1 === strLen) {
  3282. var fname = str.substr(0, op);
  3283. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3284. var alpha = 1;
  3285. switch (fname) {
  3286. case 'rgba':
  3287. if (params.length !== 4) {
  3288. return params.length === 3
  3289. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3290. : setRgba(rgbaArr, 0, 0, 0, 1);
  3291. }
  3292. alpha = parseCssFloat(params.pop());
  3293. case 'rgb':
  3294. if (params.length !== 3) {
  3295. setRgba(rgbaArr, 0, 0, 0, 1);
  3296. return;
  3297. }
  3298. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  3299. putToCache(colorStr, rgbaArr);
  3300. return rgbaArr;
  3301. case 'hsla':
  3302. if (params.length !== 4) {
  3303. setRgba(rgbaArr, 0, 0, 0, 1);
  3304. return;
  3305. }
  3306. params[3] = parseCssFloat(params[3]);
  3307. hsla2rgba(params, rgbaArr);
  3308. putToCache(colorStr, rgbaArr);
  3309. return rgbaArr;
  3310. case 'hsl':
  3311. if (params.length !== 3) {
  3312. setRgba(rgbaArr, 0, 0, 0, 1);
  3313. return;
  3314. }
  3315. hsla2rgba(params, rgbaArr);
  3316. putToCache(colorStr, rgbaArr);
  3317. return rgbaArr;
  3318. default:
  3319. return;
  3320. }
  3321. }
  3322. setRgba(rgbaArr, 0, 0, 0, 1);
  3323. return;
  3324. }
  3325. function hsla2rgba(hsla, rgba) {
  3326. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3327. var s = parseCssFloat(hsla[1]);
  3328. var l = parseCssFloat(hsla[2]);
  3329. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3330. var m1 = l * 2 - m2;
  3331. rgba = rgba || [];
  3332. 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);
  3333. if (hsla.length === 4) {
  3334. rgba[3] = hsla[3];
  3335. }
  3336. return rgba;
  3337. }
  3338. function rgba2hsla(rgba) {
  3339. if (!rgba) {
  3340. return;
  3341. }
  3342. var R = rgba[0] / 255;
  3343. var G = rgba[1] / 255;
  3344. var B = rgba[2] / 255;
  3345. var vMin = Math.min(R, G, B);
  3346. var vMax = Math.max(R, G, B);
  3347. var delta = vMax - vMin;
  3348. var L = (vMax + vMin) / 2;
  3349. var H;
  3350. var S;
  3351. if (delta === 0) {
  3352. H = 0;
  3353. S = 0;
  3354. }
  3355. else {
  3356. if (L < 0.5) {
  3357. S = delta / (vMax + vMin);
  3358. }
  3359. else {
  3360. S = delta / (2 - vMax - vMin);
  3361. }
  3362. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3363. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3364. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3365. if (R === vMax) {
  3366. H = deltaB - deltaG;
  3367. }
  3368. else if (G === vMax) {
  3369. H = (1 / 3) + deltaR - deltaB;
  3370. }
  3371. else if (B === vMax) {
  3372. H = (2 / 3) + deltaG - deltaR;
  3373. }
  3374. if (H < 0) {
  3375. H += 1;
  3376. }
  3377. if (H > 1) {
  3378. H -= 1;
  3379. }
  3380. }
  3381. var hsla = [H * 360, S, L];
  3382. if (rgba[3] != null) {
  3383. hsla.push(rgba[3]);
  3384. }
  3385. return hsla;
  3386. }
  3387. function lift(color, level) {
  3388. var colorArr = parse(color);
  3389. if (colorArr) {
  3390. for (var i = 0; i < 3; i++) {
  3391. if (level < 0) {
  3392. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3393. }
  3394. else {
  3395. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3396. }
  3397. if (colorArr[i] > 255) {
  3398. colorArr[i] = 255;
  3399. }
  3400. else if (colorArr[i] < 0) {
  3401. colorArr[i] = 0;
  3402. }
  3403. }
  3404. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3405. }
  3406. }
  3407. function toHex(color) {
  3408. var colorArr = parse(color);
  3409. if (colorArr) {
  3410. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3411. }
  3412. }
  3413. function fastLerp(normalizedValue, colors, out) {
  3414. if (!(colors && colors.length)
  3415. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3416. return;
  3417. }
  3418. out = out || [];
  3419. var value = normalizedValue * (colors.length - 1);
  3420. var leftIndex = Math.floor(value);
  3421. var rightIndex = Math.ceil(value);
  3422. var leftColor = colors[leftIndex];
  3423. var rightColor = colors[rightIndex];
  3424. var dv = value - leftIndex;
  3425. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3426. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3427. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3428. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3429. return out;
  3430. }
  3431. var fastMapToColor = fastLerp;
  3432. function lerp$1(normalizedValue, colors, fullOutput) {
  3433. if (!(colors && colors.length)
  3434. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3435. return;
  3436. }
  3437. var value = normalizedValue * (colors.length - 1);
  3438. var leftIndex = Math.floor(value);
  3439. var rightIndex = Math.ceil(value);
  3440. var leftColor = parse(colors[leftIndex]);
  3441. var rightColor = parse(colors[rightIndex]);
  3442. var dv = value - leftIndex;
  3443. var color = stringify([
  3444. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3445. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3446. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3447. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3448. ], 'rgba');
  3449. return fullOutput
  3450. ? {
  3451. color: color,
  3452. leftIndex: leftIndex,
  3453. rightIndex: rightIndex,
  3454. value: value
  3455. }
  3456. : color;
  3457. }
  3458. var mapToColor = lerp$1;
  3459. function modifyHSL(color, h, s, l) {
  3460. var colorArr = parse(color);
  3461. if (color) {
  3462. colorArr = rgba2hsla(colorArr);
  3463. h != null && (colorArr[0] = clampCssAngle(h));
  3464. s != null && (colorArr[1] = parseCssFloat(s));
  3465. l != null && (colorArr[2] = parseCssFloat(l));
  3466. return stringify(hsla2rgba(colorArr), 'rgba');
  3467. }
  3468. }
  3469. function modifyAlpha(color, alpha) {
  3470. var colorArr = parse(color);
  3471. if (colorArr && alpha != null) {
  3472. colorArr[3] = clampCssFloat(alpha);
  3473. return stringify(colorArr, 'rgba');
  3474. }
  3475. }
  3476. function stringify(arrColor, type) {
  3477. if (!arrColor || !arrColor.length) {
  3478. return;
  3479. }
  3480. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3481. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3482. colorStr += ',' + arrColor[3];
  3483. }
  3484. return type + '(' + colorStr + ')';
  3485. }
  3486. function lum(color, backgroundLum) {
  3487. var arr = parse(color);
  3488. return arr
  3489. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  3490. + (1 - arr[3]) * backgroundLum
  3491. : 0;
  3492. }
  3493. function random() {
  3494. return stringify([
  3495. Math.round(Math.random() * 255),
  3496. Math.round(Math.random() * 255),
  3497. Math.round(Math.random() * 255)
  3498. ], 'rgb');
  3499. }
  3500. var color = /*#__PURE__*/Object.freeze({
  3501. __proto__: null,
  3502. parse: parse,
  3503. lift: lift,
  3504. toHex: toHex,
  3505. fastLerp: fastLerp,
  3506. fastMapToColor: fastMapToColor,
  3507. lerp: lerp$1,
  3508. mapToColor: mapToColor,
  3509. modifyHSL: modifyHSL,
  3510. modifyAlpha: modifyAlpha,
  3511. stringify: stringify,
  3512. lum: lum,
  3513. random: random
  3514. });
  3515. var mathRound = Math.round;
  3516. function normalizeColor(color) {
  3517. var opacity;
  3518. if (!color || color === 'transparent') {
  3519. color = 'none';
  3520. }
  3521. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  3522. var arr = parse(color);
  3523. if (arr) {
  3524. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  3525. opacity = arr[3];
  3526. }
  3527. }
  3528. return {
  3529. color: color,
  3530. opacity: opacity == null ? 1 : opacity
  3531. };
  3532. }
  3533. var EPSILON$1 = 1e-4;
  3534. function isAroundZero$1(transform) {
  3535. return transform < EPSILON$1 && transform > -EPSILON$1;
  3536. }
  3537. function round3(transform) {
  3538. return mathRound(transform * 1e3) / 1e3;
  3539. }
  3540. function round4(transform) {
  3541. return mathRound(transform * 1e4) / 1e4;
  3542. }
  3543. function getMatrixStr(m) {
  3544. return 'matrix('
  3545. + round3(m[0]) + ','
  3546. + round3(m[1]) + ','
  3547. + round3(m[2]) + ','
  3548. + round3(m[3]) + ','
  3549. + round4(m[4]) + ','
  3550. + round4(m[5])
  3551. + ')';
  3552. }
  3553. var TEXT_ALIGN_TO_ANCHOR = {
  3554. left: 'start',
  3555. right: 'end',
  3556. center: 'middle',
  3557. middle: 'middle'
  3558. };
  3559. function adjustTextY(y, lineHeight, textBaseline) {
  3560. if (textBaseline === 'top') {
  3561. y += lineHeight / 2;
  3562. }
  3563. else if (textBaseline === 'bottom') {
  3564. y -= lineHeight / 2;
  3565. }
  3566. return y;
  3567. }
  3568. function hasShadow(style) {
  3569. return style
  3570. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  3571. }
  3572. function getShadowKey(displayable) {
  3573. var style = displayable.style;
  3574. var globalScale = displayable.getGlobalScale();
  3575. return [
  3576. style.shadowColor,
  3577. (style.shadowBlur || 0).toFixed(2),
  3578. (style.shadowOffsetX || 0).toFixed(2),
  3579. (style.shadowOffsetY || 0).toFixed(2),
  3580. globalScale[0],
  3581. globalScale[1]
  3582. ].join(',');
  3583. }
  3584. function isImagePattern(val) {
  3585. return val && (!!val.image);
  3586. }
  3587. function isSVGPattern(val) {
  3588. return val && (!!val.svgElement);
  3589. }
  3590. function isPattern(val) {
  3591. return isImagePattern(val) || isSVGPattern(val);
  3592. }
  3593. function isLinearGradient(val) {
  3594. return val.type === 'linear';
  3595. }
  3596. function isRadialGradient(val) {
  3597. return val.type === 'radial';
  3598. }
  3599. function isGradient(val) {
  3600. return val && (val.type === 'linear'
  3601. || val.type === 'radial');
  3602. }
  3603. function getIdURL(id) {
  3604. return "url(#" + id + ")";
  3605. }
  3606. function getPathPrecision(el) {
  3607. var scale = el.getGlobalScale();
  3608. var size = Math.max(scale[0], scale[1]);
  3609. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  3610. }
  3611. function getSRTTransformString(transform) {
  3612. var x = transform.x || 0;
  3613. var y = transform.y || 0;
  3614. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  3615. var scaleX = retrieve2(transform.scaleX, 1);
  3616. var scaleY = retrieve2(transform.scaleY, 1);
  3617. var skewX = transform.skewX || 0;
  3618. var skewY = transform.skewY || 0;
  3619. var res = [];
  3620. if (x || y) {
  3621. res.push("translate(" + x + "px," + y + "px)");
  3622. }
  3623. if (rotation) {
  3624. res.push("rotate(" + rotation + ")");
  3625. }
  3626. if (scaleX !== 1 || scaleY !== 1) {
  3627. res.push("scale(" + scaleX + "," + scaleY + ")");
  3628. }
  3629. if (skewX || skewY) {
  3630. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  3631. }
  3632. return res.join(' ');
  3633. }
  3634. var encodeBase64 = (function () {
  3635. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  3636. return function (str) {
  3637. return window.btoa(unescape(str));
  3638. };
  3639. }
  3640. if (typeof Buffer !== 'undefined') {
  3641. return function (str) {
  3642. return Buffer.from(str).toString('base64');
  3643. };
  3644. }
  3645. return function (str) {
  3646. if ("development" !== 'production') {
  3647. logError('Base64 isn\'t natively supported in the current environment.');
  3648. }
  3649. return null;
  3650. };
  3651. })();
  3652. var arraySlice = Array.prototype.slice;
  3653. function interpolateNumber(p0, p1, percent) {
  3654. return (p1 - p0) * percent + p0;
  3655. }
  3656. function interpolate1DArray(out, p0, p1, percent) {
  3657. var len = p0.length;
  3658. for (var i = 0; i < len; i++) {
  3659. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3660. }
  3661. return out;
  3662. }
  3663. function interpolate2DArray(out, p0, p1, percent) {
  3664. var len = p0.length;
  3665. var len2 = len && p0[0].length;
  3666. for (var i = 0; i < len; i++) {
  3667. if (!out[i]) {
  3668. out[i] = [];
  3669. }
  3670. for (var j = 0; j < len2; j++) {
  3671. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  3672. }
  3673. }
  3674. return out;
  3675. }
  3676. function add1DArray(out, p0, p1, sign) {
  3677. var len = p0.length;
  3678. for (var i = 0; i < len; i++) {
  3679. out[i] = p0[i] + p1[i] * sign;
  3680. }
  3681. return out;
  3682. }
  3683. function add2DArray(out, p0, p1, sign) {
  3684. var len = p0.length;
  3685. var len2 = len && p0[0].length;
  3686. for (var i = 0; i < len; i++) {
  3687. if (!out[i]) {
  3688. out[i] = [];
  3689. }
  3690. for (var j = 0; j < len2; j++) {
  3691. out[i][j] = p0[i][j] + p1[i][j] * sign;
  3692. }
  3693. }
  3694. return out;
  3695. }
  3696. function fillColorStops(val0, val1) {
  3697. var len0 = val0.length;
  3698. var len1 = val1.length;
  3699. var shorterArr = len0 > len1 ? val1 : val0;
  3700. var shorterLen = Math.min(len0, len1);
  3701. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  3702. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  3703. shorterArr.push({
  3704. offset: last.offset,
  3705. color: last.color.slice()
  3706. });
  3707. }
  3708. }
  3709. function fillArray(val0, val1, arrDim) {
  3710. var arr0 = val0;
  3711. var arr1 = val1;
  3712. if (!arr0.push || !arr1.push) {
  3713. return;
  3714. }
  3715. var arr0Len = arr0.length;
  3716. var arr1Len = arr1.length;
  3717. if (arr0Len !== arr1Len) {
  3718. var isPreviousLarger = arr0Len > arr1Len;
  3719. if (isPreviousLarger) {
  3720. arr0.length = arr1Len;
  3721. }
  3722. else {
  3723. for (var i = arr0Len; i < arr1Len; i++) {
  3724. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  3725. }
  3726. }
  3727. }
  3728. var len2 = arr0[0] && arr0[0].length;
  3729. for (var i = 0; i < arr0.length; i++) {
  3730. if (arrDim === 1) {
  3731. if (isNaN(arr0[i])) {
  3732. arr0[i] = arr1[i];
  3733. }
  3734. }
  3735. else {
  3736. for (var j = 0; j < len2; j++) {
  3737. if (isNaN(arr0[i][j])) {
  3738. arr0[i][j] = arr1[i][j];
  3739. }
  3740. }
  3741. }
  3742. }
  3743. }
  3744. function cloneValue(value) {
  3745. if (isArrayLike(value)) {
  3746. var len = value.length;
  3747. if (isArrayLike(value[0])) {
  3748. var ret = [];
  3749. for (var i = 0; i < len; i++) {
  3750. ret.push(arraySlice.call(value[i]));
  3751. }
  3752. return ret;
  3753. }
  3754. return arraySlice.call(value);
  3755. }
  3756. return value;
  3757. }
  3758. function rgba2String(rgba) {
  3759. rgba[0] = Math.floor(rgba[0]) || 0;
  3760. rgba[1] = Math.floor(rgba[1]) || 0;
  3761. rgba[2] = Math.floor(rgba[2]) || 0;
  3762. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  3763. return 'rgba(' + rgba.join(',') + ')';
  3764. }
  3765. function guessArrayDim(value) {
  3766. return isArrayLike(value && value[0]) ? 2 : 1;
  3767. }
  3768. var VALUE_TYPE_NUMBER = 0;
  3769. var VALUE_TYPE_1D_ARRAY = 1;
  3770. var VALUE_TYPE_2D_ARRAY = 2;
  3771. var VALUE_TYPE_COLOR = 3;
  3772. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  3773. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  3774. var VALUE_TYPE_UNKOWN = 6;
  3775. function isGradientValueType(valType) {
  3776. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  3777. }
  3778. function isArrayValueType(valType) {
  3779. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  3780. }
  3781. var tmpRgba = [0, 0, 0, 0];
  3782. var Track = (function () {
  3783. function Track(propName) {
  3784. this.keyframes = [];
  3785. this.discrete = false;
  3786. this._invalid = false;
  3787. this._needsSort = false;
  3788. this._lastFr = 0;
  3789. this._lastFrP = 0;
  3790. this.propName = propName;
  3791. }
  3792. Track.prototype.isFinished = function () {
  3793. return this._finished;
  3794. };
  3795. Track.prototype.setFinished = function () {
  3796. this._finished = true;
  3797. if (this._additiveTrack) {
  3798. this._additiveTrack.setFinished();
  3799. }
  3800. };
  3801. Track.prototype.needsAnimate = function () {
  3802. return this.keyframes.length >= 1;
  3803. };
  3804. Track.prototype.getAdditiveTrack = function () {
  3805. return this._additiveTrack;
  3806. };
  3807. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  3808. this._needsSort = true;
  3809. var keyframes = this.keyframes;
  3810. var len = keyframes.length;
  3811. var discrete = false;
  3812. var valType = VALUE_TYPE_UNKOWN;
  3813. var value = rawValue;
  3814. if (isArrayLike(rawValue)) {
  3815. var arrayDim = guessArrayDim(rawValue);
  3816. valType = arrayDim;
  3817. if (arrayDim === 1 && !isNumber(rawValue[0])
  3818. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  3819. discrete = true;
  3820. }
  3821. }
  3822. else {
  3823. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  3824. valType = VALUE_TYPE_NUMBER;
  3825. }
  3826. else if (isString(rawValue)) {
  3827. if (!isNaN(+rawValue)) {
  3828. valType = VALUE_TYPE_NUMBER;
  3829. }
  3830. else {
  3831. var colorArray = parse(rawValue);
  3832. if (colorArray) {
  3833. value = colorArray;
  3834. valType = VALUE_TYPE_COLOR;
  3835. }
  3836. }
  3837. }
  3838. else if (isGradientObject(rawValue)) {
  3839. var parsedGradient = extend({}, value);
  3840. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  3841. offset: colorStop.offset,
  3842. color: parse(colorStop.color)
  3843. }); });
  3844. if (isLinearGradient(rawValue)) {
  3845. valType = VALUE_TYPE_LINEAR_GRADIENT;
  3846. }
  3847. else if (isRadialGradient(rawValue)) {
  3848. valType = VALUE_TYPE_RADIAL_GRADIENT;
  3849. }
  3850. value = parsedGradient;
  3851. }
  3852. }
  3853. if (len === 0) {
  3854. this.valType = valType;
  3855. }
  3856. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  3857. discrete = true;
  3858. }
  3859. this.discrete = this.discrete || discrete;
  3860. var kf = {
  3861. time: time,
  3862. value: value,
  3863. rawValue: rawValue,
  3864. percent: 0
  3865. };
  3866. if (easing) {
  3867. kf.easing = easing;
  3868. kf.easingFunc = isFunction(easing)
  3869. ? easing
  3870. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3871. }
  3872. keyframes.push(kf);
  3873. return kf;
  3874. };
  3875. Track.prototype.prepare = function (maxTime, additiveTrack) {
  3876. var kfs = this.keyframes;
  3877. if (this._needsSort) {
  3878. kfs.sort(function (a, b) {
  3879. return a.time - b.time;
  3880. });
  3881. }
  3882. var valType = this.valType;
  3883. var kfsLen = kfs.length;
  3884. var lastKf = kfs[kfsLen - 1];
  3885. var isDiscrete = this.discrete;
  3886. var isArr = isArrayValueType(valType);
  3887. var isGradient = isGradientValueType(valType);
  3888. for (var i = 0; i < kfsLen; i++) {
  3889. var kf = kfs[i];
  3890. var value = kf.value;
  3891. var lastValue = lastKf.value;
  3892. kf.percent = kf.time / maxTime;
  3893. if (!isDiscrete) {
  3894. if (isArr && i !== kfsLen - 1) {
  3895. fillArray(value, lastValue, valType);
  3896. }
  3897. else if (isGradient) {
  3898. fillColorStops(value.colorStops, lastValue.colorStops);
  3899. }
  3900. }
  3901. }
  3902. if (!isDiscrete
  3903. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  3904. && additiveTrack
  3905. && this.needsAnimate()
  3906. && additiveTrack.needsAnimate()
  3907. && valType === additiveTrack.valType
  3908. && !additiveTrack._finished) {
  3909. this._additiveTrack = additiveTrack;
  3910. var startValue = kfs[0].value;
  3911. for (var i = 0; i < kfsLen; i++) {
  3912. if (valType === VALUE_TYPE_NUMBER) {
  3913. kfs[i].additiveValue = kfs[i].value - startValue;
  3914. }
  3915. else if (valType === VALUE_TYPE_COLOR) {
  3916. kfs[i].additiveValue =
  3917. add1DArray([], kfs[i].value, startValue, -1);
  3918. }
  3919. else if (isArrayValueType(valType)) {
  3920. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  3921. ? add1DArray([], kfs[i].value, startValue, -1)
  3922. : add2DArray([], kfs[i].value, startValue, -1);
  3923. }
  3924. }
  3925. }
  3926. };
  3927. Track.prototype.step = function (target, percent) {
  3928. if (this._finished) {
  3929. return;
  3930. }
  3931. if (this._additiveTrack && this._additiveTrack._finished) {
  3932. this._additiveTrack = null;
  3933. }
  3934. var isAdditive = this._additiveTrack != null;
  3935. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3936. var valType = this.valType;
  3937. var keyframes = this.keyframes;
  3938. var kfsNum = keyframes.length;
  3939. var propName = this.propName;
  3940. var isValueColor = valType === VALUE_TYPE_COLOR;
  3941. var frameIdx;
  3942. var lastFrame = this._lastFr;
  3943. var mathMin = Math.min;
  3944. var frame;
  3945. var nextFrame;
  3946. if (kfsNum === 1) {
  3947. frame = nextFrame = keyframes[0];
  3948. }
  3949. else {
  3950. if (percent < 0) {
  3951. frameIdx = 0;
  3952. }
  3953. else if (percent < this._lastFrP) {
  3954. var start = mathMin(lastFrame + 1, kfsNum - 1);
  3955. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3956. if (keyframes[frameIdx].percent <= percent) {
  3957. break;
  3958. }
  3959. }
  3960. frameIdx = mathMin(frameIdx, kfsNum - 2);
  3961. }
  3962. else {
  3963. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  3964. if (keyframes[frameIdx].percent > percent) {
  3965. break;
  3966. }
  3967. }
  3968. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  3969. }
  3970. nextFrame = keyframes[frameIdx + 1];
  3971. frame = keyframes[frameIdx];
  3972. }
  3973. if (!(frame && nextFrame)) {
  3974. return;
  3975. }
  3976. this._lastFr = frameIdx;
  3977. this._lastFrP = percent;
  3978. var interval = (nextFrame.percent - frame.percent);
  3979. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  3980. if (nextFrame.easingFunc) {
  3981. w = nextFrame.easingFunc(w);
  3982. }
  3983. var targetArr = isAdditive ? this._additiveValue
  3984. : (isValueColor ? tmpRgba : target[propName]);
  3985. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  3986. targetArr = this._additiveValue = [];
  3987. }
  3988. if (this.discrete) {
  3989. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  3990. }
  3991. else if (isArrayValueType(valType)) {
  3992. valType === VALUE_TYPE_1D_ARRAY
  3993. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3994. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3995. }
  3996. else if (isGradientValueType(valType)) {
  3997. var val = frame[valueKey];
  3998. var nextVal_1 = nextFrame[valueKey];
  3999. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4000. target[propName] = {
  4001. type: isLinearGradient_1 ? 'linear' : 'radial',
  4002. x: interpolateNumber(val.x, nextVal_1.x, w),
  4003. y: interpolateNumber(val.y, nextVal_1.y, w),
  4004. colorStops: map(val.colorStops, function (colorStop, idx) {
  4005. var nextColorStop = nextVal_1.colorStops[idx];
  4006. return {
  4007. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4008. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4009. };
  4010. }),
  4011. global: nextVal_1.global
  4012. };
  4013. if (isLinearGradient_1) {
  4014. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4015. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4016. }
  4017. else {
  4018. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4019. }
  4020. }
  4021. else if (isValueColor) {
  4022. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4023. if (!isAdditive) {
  4024. target[propName] = rgba2String(targetArr);
  4025. }
  4026. }
  4027. else {
  4028. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4029. if (isAdditive) {
  4030. this._additiveValue = value;
  4031. }
  4032. else {
  4033. target[propName] = value;
  4034. }
  4035. }
  4036. if (isAdditive) {
  4037. this._addToTarget(target);
  4038. }
  4039. };
  4040. Track.prototype._addToTarget = function (target) {
  4041. var valType = this.valType;
  4042. var propName = this.propName;
  4043. var additiveValue = this._additiveValue;
  4044. if (valType === VALUE_TYPE_NUMBER) {
  4045. target[propName] = target[propName] + additiveValue;
  4046. }
  4047. else if (valType === VALUE_TYPE_COLOR) {
  4048. parse(target[propName], tmpRgba);
  4049. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4050. target[propName] = rgba2String(tmpRgba);
  4051. }
  4052. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4053. add1DArray(target[propName], target[propName], additiveValue, 1);
  4054. }
  4055. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4056. add2DArray(target[propName], target[propName], additiveValue, 1);
  4057. }
  4058. };
  4059. return Track;
  4060. }());
  4061. var Animator = (function () {
  4062. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4063. this._tracks = {};
  4064. this._trackKeys = [];
  4065. this._maxTime = 0;
  4066. this._started = 0;
  4067. this._clip = null;
  4068. this._target = target;
  4069. this._loop = loop;
  4070. if (loop && additiveTo) {
  4071. logError('Can\' use additive animation on looped animation.');
  4072. return;
  4073. }
  4074. this._additiveAnimators = additiveTo;
  4075. this._allowDiscrete = allowDiscreteAnimation;
  4076. }
  4077. Animator.prototype.getMaxTime = function () {
  4078. return this._maxTime;
  4079. };
  4080. Animator.prototype.getDelay = function () {
  4081. return this._delay;
  4082. };
  4083. Animator.prototype.getLoop = function () {
  4084. return this._loop;
  4085. };
  4086. Animator.prototype.getTarget = function () {
  4087. return this._target;
  4088. };
  4089. Animator.prototype.changeTarget = function (target) {
  4090. this._target = target;
  4091. };
  4092. Animator.prototype.when = function (time, props, easing) {
  4093. return this.whenWithKeys(time, props, keys(props), easing);
  4094. };
  4095. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4096. var tracks = this._tracks;
  4097. for (var i = 0; i < propNames.length; i++) {
  4098. var propName = propNames[i];
  4099. var track = tracks[propName];
  4100. if (!track) {
  4101. track = tracks[propName] = new Track(propName);
  4102. var initialValue = void 0;
  4103. var additiveTrack = this._getAdditiveTrack(propName);
  4104. if (additiveTrack) {
  4105. var addtiveTrackKfs = additiveTrack.keyframes;
  4106. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4107. initialValue = lastFinalKf && lastFinalKf.value;
  4108. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4109. initialValue = rgba2String(initialValue);
  4110. }
  4111. }
  4112. else {
  4113. initialValue = this._target[propName];
  4114. }
  4115. if (initialValue == null) {
  4116. continue;
  4117. }
  4118. if (time > 0) {
  4119. track.addKeyframe(0, cloneValue(initialValue), easing);
  4120. }
  4121. this._trackKeys.push(propName);
  4122. }
  4123. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4124. }
  4125. this._maxTime = Math.max(this._maxTime, time);
  4126. return this;
  4127. };
  4128. Animator.prototype.pause = function () {
  4129. this._clip.pause();
  4130. this._paused = true;
  4131. };
  4132. Animator.prototype.resume = function () {
  4133. this._clip.resume();
  4134. this._paused = false;
  4135. };
  4136. Animator.prototype.isPaused = function () {
  4137. return !!this._paused;
  4138. };
  4139. Animator.prototype.duration = function (duration) {
  4140. this._maxTime = duration;
  4141. this._force = true;
  4142. return this;
  4143. };
  4144. Animator.prototype._doneCallback = function () {
  4145. this._setTracksFinished();
  4146. this._clip = null;
  4147. var doneList = this._doneCbs;
  4148. if (doneList) {
  4149. var len = doneList.length;
  4150. for (var i = 0; i < len; i++) {
  4151. doneList[i].call(this);
  4152. }
  4153. }
  4154. };
  4155. Animator.prototype._abortedCallback = function () {
  4156. this._setTracksFinished();
  4157. var animation = this.animation;
  4158. var abortedList = this._abortedCbs;
  4159. if (animation) {
  4160. animation.removeClip(this._clip);
  4161. }
  4162. this._clip = null;
  4163. if (abortedList) {
  4164. for (var i = 0; i < abortedList.length; i++) {
  4165. abortedList[i].call(this);
  4166. }
  4167. }
  4168. };
  4169. Animator.prototype._setTracksFinished = function () {
  4170. var tracks = this._tracks;
  4171. var tracksKeys = this._trackKeys;
  4172. for (var i = 0; i < tracksKeys.length; i++) {
  4173. tracks[tracksKeys[i]].setFinished();
  4174. }
  4175. };
  4176. Animator.prototype._getAdditiveTrack = function (trackName) {
  4177. var additiveTrack;
  4178. var additiveAnimators = this._additiveAnimators;
  4179. if (additiveAnimators) {
  4180. for (var i = 0; i < additiveAnimators.length; i++) {
  4181. var track = additiveAnimators[i].getTrack(trackName);
  4182. if (track) {
  4183. additiveTrack = track;
  4184. }
  4185. }
  4186. }
  4187. return additiveTrack;
  4188. };
  4189. Animator.prototype.start = function (easing) {
  4190. if (this._started > 0) {
  4191. return;
  4192. }
  4193. this._started = 1;
  4194. var self = this;
  4195. var tracks = [];
  4196. var maxTime = this._maxTime || 0;
  4197. for (var i = 0; i < this._trackKeys.length; i++) {
  4198. var propName = this._trackKeys[i];
  4199. var track = this._tracks[propName];
  4200. var additiveTrack = this._getAdditiveTrack(propName);
  4201. var kfs = track.keyframes;
  4202. var kfsNum = kfs.length;
  4203. track.prepare(maxTime, additiveTrack);
  4204. if (track.needsAnimate()) {
  4205. if (!this._allowDiscrete && track.discrete) {
  4206. var lastKf = kfs[kfsNum - 1];
  4207. if (lastKf) {
  4208. self._target[track.propName] = lastKf.rawValue;
  4209. }
  4210. track.setFinished();
  4211. }
  4212. else {
  4213. tracks.push(track);
  4214. }
  4215. }
  4216. }
  4217. if (tracks.length || this._force) {
  4218. var clip = new Clip({
  4219. life: maxTime,
  4220. loop: this._loop,
  4221. delay: this._delay || 0,
  4222. onframe: function (percent) {
  4223. self._started = 2;
  4224. var additiveAnimators = self._additiveAnimators;
  4225. if (additiveAnimators) {
  4226. var stillHasAdditiveAnimator = false;
  4227. for (var i = 0; i < additiveAnimators.length; i++) {
  4228. if (additiveAnimators[i]._clip) {
  4229. stillHasAdditiveAnimator = true;
  4230. break;
  4231. }
  4232. }
  4233. if (!stillHasAdditiveAnimator) {
  4234. self._additiveAnimators = null;
  4235. }
  4236. }
  4237. for (var i = 0; i < tracks.length; i++) {
  4238. tracks[i].step(self._target, percent);
  4239. }
  4240. var onframeList = self._onframeCbs;
  4241. if (onframeList) {
  4242. for (var i = 0; i < onframeList.length; i++) {
  4243. onframeList[i](self._target, percent);
  4244. }
  4245. }
  4246. },
  4247. ondestroy: function () {
  4248. self._doneCallback();
  4249. }
  4250. });
  4251. this._clip = clip;
  4252. if (this.animation) {
  4253. this.animation.addClip(clip);
  4254. }
  4255. if (easing) {
  4256. clip.setEasing(easing);
  4257. }
  4258. }
  4259. else {
  4260. this._doneCallback();
  4261. }
  4262. return this;
  4263. };
  4264. Animator.prototype.stop = function (forwardToLast) {
  4265. if (!this._clip) {
  4266. return;
  4267. }
  4268. var clip = this._clip;
  4269. if (forwardToLast) {
  4270. clip.onframe(1);
  4271. }
  4272. this._abortedCallback();
  4273. };
  4274. Animator.prototype.delay = function (time) {
  4275. this._delay = time;
  4276. return this;
  4277. };
  4278. Animator.prototype.during = function (cb) {
  4279. if (cb) {
  4280. if (!this._onframeCbs) {
  4281. this._onframeCbs = [];
  4282. }
  4283. this._onframeCbs.push(cb);
  4284. }
  4285. return this;
  4286. };
  4287. Animator.prototype.done = function (cb) {
  4288. if (cb) {
  4289. if (!this._doneCbs) {
  4290. this._doneCbs = [];
  4291. }
  4292. this._doneCbs.push(cb);
  4293. }
  4294. return this;
  4295. };
  4296. Animator.prototype.aborted = function (cb) {
  4297. if (cb) {
  4298. if (!this._abortedCbs) {
  4299. this._abortedCbs = [];
  4300. }
  4301. this._abortedCbs.push(cb);
  4302. }
  4303. return this;
  4304. };
  4305. Animator.prototype.getClip = function () {
  4306. return this._clip;
  4307. };
  4308. Animator.prototype.getTrack = function (propName) {
  4309. return this._tracks[propName];
  4310. };
  4311. Animator.prototype.getTracks = function () {
  4312. var _this = this;
  4313. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4314. };
  4315. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4316. if (!propNames.length || !this._clip) {
  4317. return true;
  4318. }
  4319. var tracks = this._tracks;
  4320. var tracksKeys = this._trackKeys;
  4321. for (var i = 0; i < propNames.length; i++) {
  4322. var track = tracks[propNames[i]];
  4323. if (track && !track.isFinished()) {
  4324. if (forwardToLast) {
  4325. track.step(this._target, 1);
  4326. }
  4327. else if (this._started === 1) {
  4328. track.step(this._target, 0);
  4329. }
  4330. track.setFinished();
  4331. }
  4332. }
  4333. var allAborted = true;
  4334. for (var i = 0; i < tracksKeys.length; i++) {
  4335. if (!tracks[tracksKeys[i]].isFinished()) {
  4336. allAborted = false;
  4337. break;
  4338. }
  4339. }
  4340. if (allAborted) {
  4341. this._abortedCallback();
  4342. }
  4343. return allAborted;
  4344. };
  4345. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4346. if (!target) {
  4347. return;
  4348. }
  4349. trackKeys = trackKeys || this._trackKeys;
  4350. for (var i = 0; i < trackKeys.length; i++) {
  4351. var propName = trackKeys[i];
  4352. var track = this._tracks[propName];
  4353. if (!track || track.isFinished()) {
  4354. continue;
  4355. }
  4356. var kfs = track.keyframes;
  4357. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4358. if (kf) {
  4359. target[propName] = cloneValue(kf.rawValue);
  4360. }
  4361. }
  4362. };
  4363. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4364. trackKeys = trackKeys || keys(finalProps);
  4365. for (var i = 0; i < trackKeys.length; i++) {
  4366. var propName = trackKeys[i];
  4367. var track = this._tracks[propName];
  4368. if (!track) {
  4369. continue;
  4370. }
  4371. var kfs = track.keyframes;
  4372. if (kfs.length > 1) {
  4373. var lastKf = kfs.pop();
  4374. track.addKeyframe(lastKf.time, finalProps[propName]);
  4375. track.prepare(this._maxTime, track.getAdditiveTrack());
  4376. }
  4377. }
  4378. };
  4379. return Animator;
  4380. }());
  4381. function getTime() {
  4382. return new Date().getTime();
  4383. }
  4384. var Animation = (function (_super) {
  4385. __extends(Animation, _super);
  4386. function Animation(opts) {
  4387. var _this = _super.call(this) || this;
  4388. _this._running = false;
  4389. _this._time = 0;
  4390. _this._pausedTime = 0;
  4391. _this._pauseStart = 0;
  4392. _this._paused = false;
  4393. opts = opts || {};
  4394. _this.stage = opts.stage || {};
  4395. return _this;
  4396. }
  4397. Animation.prototype.addClip = function (clip) {
  4398. if (clip.animation) {
  4399. this.removeClip(clip);
  4400. }
  4401. if (!this._head) {
  4402. this._head = this._tail = clip;
  4403. }
  4404. else {
  4405. this._tail.next = clip;
  4406. clip.prev = this._tail;
  4407. clip.next = null;
  4408. this._tail = clip;
  4409. }
  4410. clip.animation = this;
  4411. };
  4412. Animation.prototype.addAnimator = function (animator) {
  4413. animator.animation = this;
  4414. var clip = animator.getClip();
  4415. if (clip) {
  4416. this.addClip(clip);
  4417. }
  4418. };
  4419. Animation.prototype.removeClip = function (clip) {
  4420. if (!clip.animation) {
  4421. return;
  4422. }
  4423. var prev = clip.prev;
  4424. var next = clip.next;
  4425. if (prev) {
  4426. prev.next = next;
  4427. }
  4428. else {
  4429. this._head = next;
  4430. }
  4431. if (next) {
  4432. next.prev = prev;
  4433. }
  4434. else {
  4435. this._tail = prev;
  4436. }
  4437. clip.next = clip.prev = clip.animation = null;
  4438. };
  4439. Animation.prototype.removeAnimator = function (animator) {
  4440. var clip = animator.getClip();
  4441. if (clip) {
  4442. this.removeClip(clip);
  4443. }
  4444. animator.animation = null;
  4445. };
  4446. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4447. var time = getTime() - this._pausedTime;
  4448. var delta = time - this._time;
  4449. var clip = this._head;
  4450. while (clip) {
  4451. var nextClip = clip.next;
  4452. var finished = clip.step(time, delta);
  4453. if (finished) {
  4454. clip.ondestroy();
  4455. this.removeClip(clip);
  4456. clip = nextClip;
  4457. }
  4458. else {
  4459. clip = nextClip;
  4460. }
  4461. }
  4462. this._time = time;
  4463. if (!notTriggerFrameAndStageUpdate) {
  4464. this.trigger('frame', delta);
  4465. this.stage.update && this.stage.update();
  4466. }
  4467. };
  4468. Animation.prototype._startLoop = function () {
  4469. var self = this;
  4470. this._running = true;
  4471. function step() {
  4472. if (self._running) {
  4473. requestAnimationFrame$1(step);
  4474. !self._paused && self.update();
  4475. }
  4476. }
  4477. requestAnimationFrame$1(step);
  4478. };
  4479. Animation.prototype.start = function () {
  4480. if (this._running) {
  4481. return;
  4482. }
  4483. this._time = getTime();
  4484. this._pausedTime = 0;
  4485. this._startLoop();
  4486. };
  4487. Animation.prototype.stop = function () {
  4488. this._running = false;
  4489. };
  4490. Animation.prototype.pause = function () {
  4491. if (!this._paused) {
  4492. this._pauseStart = getTime();
  4493. this._paused = true;
  4494. }
  4495. };
  4496. Animation.prototype.resume = function () {
  4497. if (this._paused) {
  4498. this._pausedTime += getTime() - this._pauseStart;
  4499. this._paused = false;
  4500. }
  4501. };
  4502. Animation.prototype.clear = function () {
  4503. var clip = this._head;
  4504. while (clip) {
  4505. var nextClip = clip.next;
  4506. clip.prev = clip.next = clip.animation = null;
  4507. clip = nextClip;
  4508. }
  4509. this._head = this._tail = null;
  4510. };
  4511. Animation.prototype.isFinished = function () {
  4512. return this._head == null;
  4513. };
  4514. Animation.prototype.animate = function (target, options) {
  4515. options = options || {};
  4516. this.start();
  4517. var animator = new Animator(target, options.loop);
  4518. this.addAnimator(animator);
  4519. return animator;
  4520. };
  4521. return Animation;
  4522. }(Eventful));
  4523. var TOUCH_CLICK_DELAY = 300;
  4524. var globalEventSupported = env.domSupported;
  4525. var localNativeListenerNames = (function () {
  4526. var mouseHandlerNames = [
  4527. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  4528. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  4529. ];
  4530. var touchHandlerNames = [
  4531. 'touchstart', 'touchend', 'touchmove'
  4532. ];
  4533. var pointerEventNameMap = {
  4534. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  4535. };
  4536. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  4537. var nm = name.replace('mouse', 'pointer');
  4538. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  4539. });
  4540. return {
  4541. mouse: mouseHandlerNames,
  4542. touch: touchHandlerNames,
  4543. pointer: pointerHandlerNames
  4544. };
  4545. })();
  4546. var globalNativeListenerNames = {
  4547. mouse: ['mousemove', 'mouseup'],
  4548. pointer: ['pointermove', 'pointerup']
  4549. };
  4550. var wheelEventSupported = false;
  4551. function isPointerFromTouch(event) {
  4552. var pointerType = event.pointerType;
  4553. return pointerType === 'pen' || pointerType === 'touch';
  4554. }
  4555. function setTouchTimer(scope) {
  4556. scope.touching = true;
  4557. if (scope.touchTimer != null) {
  4558. clearTimeout(scope.touchTimer);
  4559. scope.touchTimer = null;
  4560. }
  4561. scope.touchTimer = setTimeout(function () {
  4562. scope.touching = false;
  4563. scope.touchTimer = null;
  4564. }, 700);
  4565. }
  4566. function markTouch(event) {
  4567. event && (event.zrByTouch = true);
  4568. }
  4569. function normalizeGlobalEvent(instance, event) {
  4570. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  4571. }
  4572. function isLocalEl(instance, el) {
  4573. var elTmp = el;
  4574. var isLocal = false;
  4575. while (elTmp && elTmp.nodeType !== 9
  4576. && !(isLocal = elTmp.domBelongToZr
  4577. || (elTmp !== el && elTmp === instance.painterRoot))) {
  4578. elTmp = elTmp.parentNode;
  4579. }
  4580. return isLocal;
  4581. }
  4582. var FakeGlobalEvent = (function () {
  4583. function FakeGlobalEvent(instance, event) {
  4584. this.stopPropagation = noop;
  4585. this.stopImmediatePropagation = noop;
  4586. this.preventDefault = noop;
  4587. this.type = event.type;
  4588. this.target = this.currentTarget = instance.dom;
  4589. this.pointerType = event.pointerType;
  4590. this.clientX = event.clientX;
  4591. this.clientY = event.clientY;
  4592. }
  4593. return FakeGlobalEvent;
  4594. }());
  4595. var localDOMHandlers = {
  4596. mousedown: function (event) {
  4597. event = normalizeEvent(this.dom, event);
  4598. this.__mayPointerCapture = [event.zrX, event.zrY];
  4599. this.trigger('mousedown', event);
  4600. },
  4601. mousemove: function (event) {
  4602. event = normalizeEvent(this.dom, event);
  4603. var downPoint = this.__mayPointerCapture;
  4604. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  4605. this.__togglePointerCapture(true);
  4606. }
  4607. this.trigger('mousemove', event);
  4608. },
  4609. mouseup: function (event) {
  4610. event = normalizeEvent(this.dom, event);
  4611. this.__togglePointerCapture(false);
  4612. this.trigger('mouseup', event);
  4613. },
  4614. mouseout: function (event) {
  4615. event = normalizeEvent(this.dom, event);
  4616. var element = event.toElement || event.relatedTarget;
  4617. if (!isLocalEl(this, element)) {
  4618. if (this.__pointerCapturing) {
  4619. event.zrEventControl = 'no_globalout';
  4620. }
  4621. this.trigger('mouseout', event);
  4622. }
  4623. },
  4624. wheel: function (event) {
  4625. wheelEventSupported = true;
  4626. event = normalizeEvent(this.dom, event);
  4627. this.trigger('mousewheel', event);
  4628. },
  4629. mousewheel: function (event) {
  4630. if (wheelEventSupported) {
  4631. return;
  4632. }
  4633. event = normalizeEvent(this.dom, event);
  4634. this.trigger('mousewheel', event);
  4635. },
  4636. touchstart: function (event) {
  4637. event = normalizeEvent(this.dom, event);
  4638. markTouch(event);
  4639. this.__lastTouchMoment = new Date();
  4640. this.handler.processGesture(event, 'start');
  4641. localDOMHandlers.mousemove.call(this, event);
  4642. localDOMHandlers.mousedown.call(this, event);
  4643. },
  4644. touchmove: function (event) {
  4645. event = normalizeEvent(this.dom, event);
  4646. markTouch(event);
  4647. this.handler.processGesture(event, 'change');
  4648. localDOMHandlers.mousemove.call(this, event);
  4649. },
  4650. touchend: function (event) {
  4651. event = normalizeEvent(this.dom, event);
  4652. markTouch(event);
  4653. this.handler.processGesture(event, 'end');
  4654. localDOMHandlers.mouseup.call(this, event);
  4655. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  4656. localDOMHandlers.click.call(this, event);
  4657. }
  4658. },
  4659. pointerdown: function (event) {
  4660. localDOMHandlers.mousedown.call(this, event);
  4661. },
  4662. pointermove: function (event) {
  4663. if (!isPointerFromTouch(event)) {
  4664. localDOMHandlers.mousemove.call(this, event);
  4665. }
  4666. },
  4667. pointerup: function (event) {
  4668. localDOMHandlers.mouseup.call(this, event);
  4669. },
  4670. pointerout: function (event) {
  4671. if (!isPointerFromTouch(event)) {
  4672. localDOMHandlers.mouseout.call(this, event);
  4673. }
  4674. }
  4675. };
  4676. each(['click', 'dblclick', 'contextmenu'], function (name) {
  4677. localDOMHandlers[name] = function (event) {
  4678. event = normalizeEvent(this.dom, event);
  4679. this.trigger(name, event);
  4680. };
  4681. });
  4682. var globalDOMHandlers = {
  4683. pointermove: function (event) {
  4684. if (!isPointerFromTouch(event)) {
  4685. globalDOMHandlers.mousemove.call(this, event);
  4686. }
  4687. },
  4688. pointerup: function (event) {
  4689. globalDOMHandlers.mouseup.call(this, event);
  4690. },
  4691. mousemove: function (event) {
  4692. this.trigger('mousemove', event);
  4693. },
  4694. mouseup: function (event) {
  4695. var pointerCaptureReleasing = this.__pointerCapturing;
  4696. this.__togglePointerCapture(false);
  4697. this.trigger('mouseup', event);
  4698. if (pointerCaptureReleasing) {
  4699. event.zrEventControl = 'only_globalout';
  4700. this.trigger('mouseout', event);
  4701. }
  4702. }
  4703. };
  4704. function mountLocalDOMEventListeners(instance, scope) {
  4705. var domHandlers = scope.domHandlers;
  4706. if (env.pointerEventsSupported) {
  4707. each(localNativeListenerNames.pointer, function (nativeEventName) {
  4708. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4709. domHandlers[nativeEventName].call(instance, event);
  4710. });
  4711. });
  4712. }
  4713. else {
  4714. if (env.touchEventsSupported) {
  4715. each(localNativeListenerNames.touch, function (nativeEventName) {
  4716. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4717. domHandlers[nativeEventName].call(instance, event);
  4718. setTouchTimer(scope);
  4719. });
  4720. });
  4721. }
  4722. each(localNativeListenerNames.mouse, function (nativeEventName) {
  4723. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4724. event = getNativeEvent(event);
  4725. if (!scope.touching) {
  4726. domHandlers[nativeEventName].call(instance, event);
  4727. }
  4728. });
  4729. });
  4730. }
  4731. }
  4732. function mountGlobalDOMEventListeners(instance, scope) {
  4733. if (env.pointerEventsSupported) {
  4734. each(globalNativeListenerNames.pointer, mount);
  4735. }
  4736. else if (!env.touchEventsSupported) {
  4737. each(globalNativeListenerNames.mouse, mount);
  4738. }
  4739. function mount(nativeEventName) {
  4740. function nativeEventListener(event) {
  4741. event = getNativeEvent(event);
  4742. if (!isLocalEl(instance, event.target)) {
  4743. event = normalizeGlobalEvent(instance, event);
  4744. scope.domHandlers[nativeEventName].call(instance, event);
  4745. }
  4746. }
  4747. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  4748. }
  4749. }
  4750. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  4751. scope.mounted[nativeEventName] = listener;
  4752. scope.listenerOpts[nativeEventName] = opt;
  4753. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  4754. }
  4755. function unmountDOMEventListeners(scope) {
  4756. var mounted = scope.mounted;
  4757. for (var nativeEventName in mounted) {
  4758. if (mounted.hasOwnProperty(nativeEventName)) {
  4759. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  4760. }
  4761. }
  4762. scope.mounted = {};
  4763. }
  4764. var DOMHandlerScope = (function () {
  4765. function DOMHandlerScope(domTarget, domHandlers) {
  4766. this.mounted = {};
  4767. this.listenerOpts = {};
  4768. this.touching = false;
  4769. this.domTarget = domTarget;
  4770. this.domHandlers = domHandlers;
  4771. }
  4772. return DOMHandlerScope;
  4773. }());
  4774. var HandlerDomProxy = (function (_super) {
  4775. __extends(HandlerDomProxy, _super);
  4776. function HandlerDomProxy(dom, painterRoot) {
  4777. var _this = _super.call(this) || this;
  4778. _this.__pointerCapturing = false;
  4779. _this.dom = dom;
  4780. _this.painterRoot = painterRoot;
  4781. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  4782. if (globalEventSupported) {
  4783. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  4784. }
  4785. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  4786. return _this;
  4787. }
  4788. HandlerDomProxy.prototype.dispose = function () {
  4789. unmountDOMEventListeners(this._localHandlerScope);
  4790. if (globalEventSupported) {
  4791. unmountDOMEventListeners(this._globalHandlerScope);
  4792. }
  4793. };
  4794. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  4795. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  4796. };
  4797. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  4798. this.__mayPointerCapture = null;
  4799. if (globalEventSupported
  4800. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  4801. this.__pointerCapturing = isPointerCapturing;
  4802. var globalHandlerScope = this._globalHandlerScope;
  4803. isPointerCapturing
  4804. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  4805. : unmountDOMEventListeners(globalHandlerScope);
  4806. }
  4807. };
  4808. return HandlerDomProxy;
  4809. }(Eventful));
  4810. var dpr = 1;
  4811. if (env.hasGlobalWindow) {
  4812. dpr = Math.max(window.devicePixelRatio
  4813. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  4814. || 1, 1);
  4815. }
  4816. var devicePixelRatio = dpr;
  4817. var DARK_MODE_THRESHOLD = 0.4;
  4818. var DARK_LABEL_COLOR = '#333';
  4819. var LIGHT_LABEL_COLOR = '#ccc';
  4820. var LIGHTER_LABEL_COLOR = '#eee';
  4821. function create$1() {
  4822. return [1, 0, 0, 1, 0, 0];
  4823. }
  4824. function identity(out) {
  4825. out[0] = 1;
  4826. out[1] = 0;
  4827. out[2] = 0;
  4828. out[3] = 1;
  4829. out[4] = 0;
  4830. out[5] = 0;
  4831. return out;
  4832. }
  4833. function copy$1(out, m) {
  4834. out[0] = m[0];
  4835. out[1] = m[1];
  4836. out[2] = m[2];
  4837. out[3] = m[3];
  4838. out[4] = m[4];
  4839. out[5] = m[5];
  4840. return out;
  4841. }
  4842. function mul$1(out, m1, m2) {
  4843. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  4844. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  4845. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  4846. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  4847. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  4848. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  4849. out[0] = out0;
  4850. out[1] = out1;
  4851. out[2] = out2;
  4852. out[3] = out3;
  4853. out[4] = out4;
  4854. out[5] = out5;
  4855. return out;
  4856. }
  4857. function translate(out, a, v) {
  4858. out[0] = a[0];
  4859. out[1] = a[1];
  4860. out[2] = a[2];
  4861. out[3] = a[3];
  4862. out[4] = a[4] + v[0];
  4863. out[5] = a[5] + v[1];
  4864. return out;
  4865. }
  4866. function rotate(out, a, rad) {
  4867. var aa = a[0];
  4868. var ac = a[2];
  4869. var atx = a[4];
  4870. var ab = a[1];
  4871. var ad = a[3];
  4872. var aty = a[5];
  4873. var st = Math.sin(rad);
  4874. var ct = Math.cos(rad);
  4875. out[0] = aa * ct + ab * st;
  4876. out[1] = -aa * st + ab * ct;
  4877. out[2] = ac * ct + ad * st;
  4878. out[3] = -ac * st + ct * ad;
  4879. out[4] = ct * atx + st * aty;
  4880. out[5] = ct * aty - st * atx;
  4881. return out;
  4882. }
  4883. function scale$1(out, a, v) {
  4884. var vx = v[0];
  4885. var vy = v[1];
  4886. out[0] = a[0] * vx;
  4887. out[1] = a[1] * vy;
  4888. out[2] = a[2] * vx;
  4889. out[3] = a[3] * vy;
  4890. out[4] = a[4] * vx;
  4891. out[5] = a[5] * vy;
  4892. return out;
  4893. }
  4894. function invert(out, a) {
  4895. var aa = a[0];
  4896. var ac = a[2];
  4897. var atx = a[4];
  4898. var ab = a[1];
  4899. var ad = a[3];
  4900. var aty = a[5];
  4901. var det = aa * ad - ab * ac;
  4902. if (!det) {
  4903. return null;
  4904. }
  4905. det = 1.0 / det;
  4906. out[0] = ad * det;
  4907. out[1] = -ab * det;
  4908. out[2] = -ac * det;
  4909. out[3] = aa * det;
  4910. out[4] = (ac * aty - ad * atx) * det;
  4911. out[5] = (ab * atx - aa * aty) * det;
  4912. return out;
  4913. }
  4914. function clone$2(a) {
  4915. var b = create$1();
  4916. copy$1(b, a);
  4917. return b;
  4918. }
  4919. var matrix = /*#__PURE__*/Object.freeze({
  4920. __proto__: null,
  4921. create: create$1,
  4922. identity: identity,
  4923. copy: copy$1,
  4924. mul: mul$1,
  4925. translate: translate,
  4926. rotate: rotate,
  4927. scale: scale$1,
  4928. invert: invert,
  4929. clone: clone$2
  4930. });
  4931. var mIdentity = identity;
  4932. var EPSILON$2 = 5e-5;
  4933. function isNotAroundZero$1(val) {
  4934. return val > EPSILON$2 || val < -EPSILON$2;
  4935. }
  4936. var scaleTmp = [];
  4937. var tmpTransform = [];
  4938. var originTransform = create$1();
  4939. var abs = Math.abs;
  4940. var Transformable = (function () {
  4941. function Transformable() {
  4942. }
  4943. Transformable.prototype.getLocalTransform = function (m) {
  4944. return Transformable.getLocalTransform(this, m);
  4945. };
  4946. Transformable.prototype.setPosition = function (arr) {
  4947. this.x = arr[0];
  4948. this.y = arr[1];
  4949. };
  4950. Transformable.prototype.setScale = function (arr) {
  4951. this.scaleX = arr[0];
  4952. this.scaleY = arr[1];
  4953. };
  4954. Transformable.prototype.setSkew = function (arr) {
  4955. this.skewX = arr[0];
  4956. this.skewY = arr[1];
  4957. };
  4958. Transformable.prototype.setOrigin = function (arr) {
  4959. this.originX = arr[0];
  4960. this.originY = arr[1];
  4961. };
  4962. Transformable.prototype.needLocalTransform = function () {
  4963. return isNotAroundZero$1(this.rotation)
  4964. || isNotAroundZero$1(this.x)
  4965. || isNotAroundZero$1(this.y)
  4966. || isNotAroundZero$1(this.scaleX - 1)
  4967. || isNotAroundZero$1(this.scaleY - 1)
  4968. || isNotAroundZero$1(this.skewX)
  4969. || isNotAroundZero$1(this.skewY);
  4970. };
  4971. Transformable.prototype.updateTransform = function () {
  4972. var parentTransform = this.parent && this.parent.transform;
  4973. var needLocalTransform = this.needLocalTransform();
  4974. var m = this.transform;
  4975. if (!(needLocalTransform || parentTransform)) {
  4976. m && mIdentity(m);
  4977. return;
  4978. }
  4979. m = m || create$1();
  4980. if (needLocalTransform) {
  4981. this.getLocalTransform(m);
  4982. }
  4983. else {
  4984. mIdentity(m);
  4985. }
  4986. if (parentTransform) {
  4987. if (needLocalTransform) {
  4988. mul$1(m, parentTransform, m);
  4989. }
  4990. else {
  4991. copy$1(m, parentTransform);
  4992. }
  4993. }
  4994. this.transform = m;
  4995. this._resolveGlobalScaleRatio(m);
  4996. };
  4997. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  4998. var globalScaleRatio = this.globalScaleRatio;
  4999. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5000. this.getGlobalScale(scaleTmp);
  5001. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5002. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5003. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5004. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5005. m[0] *= sx;
  5006. m[1] *= sx;
  5007. m[2] *= sy;
  5008. m[3] *= sy;
  5009. }
  5010. this.invTransform = this.invTransform || create$1();
  5011. invert(this.invTransform, m);
  5012. };
  5013. Transformable.prototype.getComputedTransform = function () {
  5014. var transformNode = this;
  5015. var ancestors = [];
  5016. while (transformNode) {
  5017. ancestors.push(transformNode);
  5018. transformNode = transformNode.parent;
  5019. }
  5020. while (transformNode = ancestors.pop()) {
  5021. transformNode.updateTransform();
  5022. }
  5023. return this.transform;
  5024. };
  5025. Transformable.prototype.setLocalTransform = function (m) {
  5026. if (!m) {
  5027. return;
  5028. }
  5029. var sx = m[0] * m[0] + m[1] * m[1];
  5030. var sy = m[2] * m[2] + m[3] * m[3];
  5031. var rotation = Math.atan2(m[1], m[0]);
  5032. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5033. sy = Math.sqrt(sy) * Math.cos(shearX);
  5034. sx = Math.sqrt(sx);
  5035. this.skewX = shearX;
  5036. this.skewY = 0;
  5037. this.rotation = -rotation;
  5038. this.x = +m[4];
  5039. this.y = +m[5];
  5040. this.scaleX = sx;
  5041. this.scaleY = sy;
  5042. this.originX = 0;
  5043. this.originY = 0;
  5044. };
  5045. Transformable.prototype.decomposeTransform = function () {
  5046. if (!this.transform) {
  5047. return;
  5048. }
  5049. var parent = this.parent;
  5050. var m = this.transform;
  5051. if (parent && parent.transform) {
  5052. mul$1(tmpTransform, parent.invTransform, m);
  5053. m = tmpTransform;
  5054. }
  5055. var ox = this.originX;
  5056. var oy = this.originY;
  5057. if (ox || oy) {
  5058. originTransform[4] = ox;
  5059. originTransform[5] = oy;
  5060. mul$1(tmpTransform, m, originTransform);
  5061. tmpTransform[4] -= ox;
  5062. tmpTransform[5] -= oy;
  5063. m = tmpTransform;
  5064. }
  5065. this.setLocalTransform(m);
  5066. };
  5067. Transformable.prototype.getGlobalScale = function (out) {
  5068. var m = this.transform;
  5069. out = out || [];
  5070. if (!m) {
  5071. out[0] = 1;
  5072. out[1] = 1;
  5073. return out;
  5074. }
  5075. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5076. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5077. if (m[0] < 0) {
  5078. out[0] = -out[0];
  5079. }
  5080. if (m[3] < 0) {
  5081. out[1] = -out[1];
  5082. }
  5083. return out;
  5084. };
  5085. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5086. var v2 = [x, y];
  5087. var invTransform = this.invTransform;
  5088. if (invTransform) {
  5089. applyTransform(v2, v2, invTransform);
  5090. }
  5091. return v2;
  5092. };
  5093. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5094. var v2 = [x, y];
  5095. var transform = this.transform;
  5096. if (transform) {
  5097. applyTransform(v2, v2, transform);
  5098. }
  5099. return v2;
  5100. };
  5101. Transformable.prototype.getLineScale = function () {
  5102. var m = this.transform;
  5103. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5104. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5105. : 1;
  5106. };
  5107. Transformable.prototype.copyTransform = function (source) {
  5108. copyTransform(this, source);
  5109. };
  5110. Transformable.getLocalTransform = function (target, m) {
  5111. m = m || [];
  5112. var ox = target.originX || 0;
  5113. var oy = target.originY || 0;
  5114. var sx = target.scaleX;
  5115. var sy = target.scaleY;
  5116. var ax = target.anchorX;
  5117. var ay = target.anchorY;
  5118. var rotation = target.rotation || 0;
  5119. var x = target.x;
  5120. var y = target.y;
  5121. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5122. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5123. if (ox || oy || ax || ay) {
  5124. var dx = ox + ax;
  5125. var dy = oy + ay;
  5126. m[4] = -dx * sx - skewX * dy * sy;
  5127. m[5] = -dy * sy - skewY * dx * sx;
  5128. }
  5129. else {
  5130. m[4] = m[5] = 0;
  5131. }
  5132. m[0] = sx;
  5133. m[3] = sy;
  5134. m[1] = skewY * sx;
  5135. m[2] = skewX * sy;
  5136. rotation && rotate(m, m, rotation);
  5137. m[4] += ox + x;
  5138. m[5] += oy + y;
  5139. return m;
  5140. };
  5141. Transformable.initDefaultProps = (function () {
  5142. var proto = Transformable.prototype;
  5143. proto.scaleX =
  5144. proto.scaleY =
  5145. proto.globalScaleRatio = 1;
  5146. proto.x =
  5147. proto.y =
  5148. proto.originX =
  5149. proto.originY =
  5150. proto.skewX =
  5151. proto.skewY =
  5152. proto.rotation =
  5153. proto.anchorX =
  5154. proto.anchorY = 0;
  5155. })();
  5156. return Transformable;
  5157. }());
  5158. var TRANSFORMABLE_PROPS = [
  5159. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5160. ];
  5161. function copyTransform(target, source) {
  5162. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5163. var propName = TRANSFORMABLE_PROPS[i];
  5164. target[propName] = source[propName];
  5165. }
  5166. }
  5167. var Point = (function () {
  5168. function Point(x, y) {
  5169. this.x = x || 0;
  5170. this.y = y || 0;
  5171. }
  5172. Point.prototype.copy = function (other) {
  5173. this.x = other.x;
  5174. this.y = other.y;
  5175. return this;
  5176. };
  5177. Point.prototype.clone = function () {
  5178. return new Point(this.x, this.y);
  5179. };
  5180. Point.prototype.set = function (x, y) {
  5181. this.x = x;
  5182. this.y = y;
  5183. return this;
  5184. };
  5185. Point.prototype.equal = function (other) {
  5186. return other.x === this.x && other.y === this.y;
  5187. };
  5188. Point.prototype.add = function (other) {
  5189. this.x += other.x;
  5190. this.y += other.y;
  5191. return this;
  5192. };
  5193. Point.prototype.scale = function (scalar) {
  5194. this.x *= scalar;
  5195. this.y *= scalar;
  5196. };
  5197. Point.prototype.scaleAndAdd = function (other, scalar) {
  5198. this.x += other.x * scalar;
  5199. this.y += other.y * scalar;
  5200. };
  5201. Point.prototype.sub = function (other) {
  5202. this.x -= other.x;
  5203. this.y -= other.y;
  5204. return this;
  5205. };
  5206. Point.prototype.dot = function (other) {
  5207. return this.x * other.x + this.y * other.y;
  5208. };
  5209. Point.prototype.len = function () {
  5210. return Math.sqrt(this.x * this.x + this.y * this.y);
  5211. };
  5212. Point.prototype.lenSquare = function () {
  5213. return this.x * this.x + this.y * this.y;
  5214. };
  5215. Point.prototype.normalize = function () {
  5216. var len = this.len();
  5217. this.x /= len;
  5218. this.y /= len;
  5219. return this;
  5220. };
  5221. Point.prototype.distance = function (other) {
  5222. var dx = this.x - other.x;
  5223. var dy = this.y - other.y;
  5224. return Math.sqrt(dx * dx + dy * dy);
  5225. };
  5226. Point.prototype.distanceSquare = function (other) {
  5227. var dx = this.x - other.x;
  5228. var dy = this.y - other.y;
  5229. return dx * dx + dy * dy;
  5230. };
  5231. Point.prototype.negate = function () {
  5232. this.x = -this.x;
  5233. this.y = -this.y;
  5234. return this;
  5235. };
  5236. Point.prototype.transform = function (m) {
  5237. if (!m) {
  5238. return;
  5239. }
  5240. var x = this.x;
  5241. var y = this.y;
  5242. this.x = m[0] * x + m[2] * y + m[4];
  5243. this.y = m[1] * x + m[3] * y + m[5];
  5244. return this;
  5245. };
  5246. Point.prototype.toArray = function (out) {
  5247. out[0] = this.x;
  5248. out[1] = this.y;
  5249. return out;
  5250. };
  5251. Point.prototype.fromArray = function (input) {
  5252. this.x = input[0];
  5253. this.y = input[1];
  5254. };
  5255. Point.set = function (p, x, y) {
  5256. p.x = x;
  5257. p.y = y;
  5258. };
  5259. Point.copy = function (p, p2) {
  5260. p.x = p2.x;
  5261. p.y = p2.y;
  5262. };
  5263. Point.len = function (p) {
  5264. return Math.sqrt(p.x * p.x + p.y * p.y);
  5265. };
  5266. Point.lenSquare = function (p) {
  5267. return p.x * p.x + p.y * p.y;
  5268. };
  5269. Point.dot = function (p0, p1) {
  5270. return p0.x * p1.x + p0.y * p1.y;
  5271. };
  5272. Point.add = function (out, p0, p1) {
  5273. out.x = p0.x + p1.x;
  5274. out.y = p0.y + p1.y;
  5275. };
  5276. Point.sub = function (out, p0, p1) {
  5277. out.x = p0.x - p1.x;
  5278. out.y = p0.y - p1.y;
  5279. };
  5280. Point.scale = function (out, p0, scalar) {
  5281. out.x = p0.x * scalar;
  5282. out.y = p0.y * scalar;
  5283. };
  5284. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  5285. out.x = p0.x + p1.x * scalar;
  5286. out.y = p0.y + p1.y * scalar;
  5287. };
  5288. Point.lerp = function (out, p0, p1, t) {
  5289. var onet = 1 - t;
  5290. out.x = onet * p0.x + t * p1.x;
  5291. out.y = onet * p0.y + t * p1.y;
  5292. };
  5293. return Point;
  5294. }());
  5295. var mathMin = Math.min;
  5296. var mathMax = Math.max;
  5297. var lt = new Point();
  5298. var rb = new Point();
  5299. var lb = new Point();
  5300. var rt = new Point();
  5301. var minTv = new Point();
  5302. var maxTv = new Point();
  5303. var BoundingRect = (function () {
  5304. function BoundingRect(x, y, width, height) {
  5305. if (width < 0) {
  5306. x = x + width;
  5307. width = -width;
  5308. }
  5309. if (height < 0) {
  5310. y = y + height;
  5311. height = -height;
  5312. }
  5313. this.x = x;
  5314. this.y = y;
  5315. this.width = width;
  5316. this.height = height;
  5317. }
  5318. BoundingRect.prototype.union = function (other) {
  5319. var x = mathMin(other.x, this.x);
  5320. var y = mathMin(other.y, this.y);
  5321. if (isFinite(this.x) && isFinite(this.width)) {
  5322. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  5323. }
  5324. else {
  5325. this.width = other.width;
  5326. }
  5327. if (isFinite(this.y) && isFinite(this.height)) {
  5328. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  5329. }
  5330. else {
  5331. this.height = other.height;
  5332. }
  5333. this.x = x;
  5334. this.y = y;
  5335. };
  5336. BoundingRect.prototype.applyTransform = function (m) {
  5337. BoundingRect.applyTransform(this, this, m);
  5338. };
  5339. BoundingRect.prototype.calculateTransform = function (b) {
  5340. var a = this;
  5341. var sx = b.width / a.width;
  5342. var sy = b.height / a.height;
  5343. var m = create$1();
  5344. translate(m, m, [-a.x, -a.y]);
  5345. scale$1(m, m, [sx, sy]);
  5346. translate(m, m, [b.x, b.y]);
  5347. return m;
  5348. };
  5349. BoundingRect.prototype.intersect = function (b, mtv) {
  5350. if (!b) {
  5351. return false;
  5352. }
  5353. if (!(b instanceof BoundingRect)) {
  5354. b = BoundingRect.create(b);
  5355. }
  5356. var a = this;
  5357. var ax0 = a.x;
  5358. var ax1 = a.x + a.width;
  5359. var ay0 = a.y;
  5360. var ay1 = a.y + a.height;
  5361. var bx0 = b.x;
  5362. var bx1 = b.x + b.width;
  5363. var by0 = b.y;
  5364. var by1 = b.y + b.height;
  5365. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5366. if (mtv) {
  5367. var dMin = Infinity;
  5368. var dMax = 0;
  5369. var d0 = Math.abs(ax1 - bx0);
  5370. var d1 = Math.abs(bx1 - ax0);
  5371. var d2 = Math.abs(ay1 - by0);
  5372. var d3 = Math.abs(by1 - ay0);
  5373. var dx = Math.min(d0, d1);
  5374. var dy = Math.min(d2, d3);
  5375. if (ax1 < bx0 || bx1 < ax0) {
  5376. if (dx > dMax) {
  5377. dMax = dx;
  5378. if (d0 < d1) {
  5379. Point.set(maxTv, -d0, 0);
  5380. }
  5381. else {
  5382. Point.set(maxTv, d1, 0);
  5383. }
  5384. }
  5385. }
  5386. else {
  5387. if (dx < dMin) {
  5388. dMin = dx;
  5389. if (d0 < d1) {
  5390. Point.set(minTv, d0, 0);
  5391. }
  5392. else {
  5393. Point.set(minTv, -d1, 0);
  5394. }
  5395. }
  5396. }
  5397. if (ay1 < by0 || by1 < ay0) {
  5398. if (dy > dMax) {
  5399. dMax = dy;
  5400. if (d2 < d3) {
  5401. Point.set(maxTv, 0, -d2);
  5402. }
  5403. else {
  5404. Point.set(maxTv, 0, d3);
  5405. }
  5406. }
  5407. }
  5408. else {
  5409. if (dx < dMin) {
  5410. dMin = dx;
  5411. if (d2 < d3) {
  5412. Point.set(minTv, 0, d2);
  5413. }
  5414. else {
  5415. Point.set(minTv, 0, -d3);
  5416. }
  5417. }
  5418. }
  5419. }
  5420. if (mtv) {
  5421. Point.copy(mtv, overlap ? minTv : maxTv);
  5422. }
  5423. return overlap;
  5424. };
  5425. BoundingRect.prototype.contain = function (x, y) {
  5426. var rect = this;
  5427. return x >= rect.x
  5428. && x <= (rect.x + rect.width)
  5429. && y >= rect.y
  5430. && y <= (rect.y + rect.height);
  5431. };
  5432. BoundingRect.prototype.clone = function () {
  5433. return new BoundingRect(this.x, this.y, this.width, this.height);
  5434. };
  5435. BoundingRect.prototype.copy = function (other) {
  5436. BoundingRect.copy(this, other);
  5437. };
  5438. BoundingRect.prototype.plain = function () {
  5439. return {
  5440. x: this.x,
  5441. y: this.y,
  5442. width: this.width,
  5443. height: this.height
  5444. };
  5445. };
  5446. BoundingRect.prototype.isFinite = function () {
  5447. return isFinite(this.x)
  5448. && isFinite(this.y)
  5449. && isFinite(this.width)
  5450. && isFinite(this.height);
  5451. };
  5452. BoundingRect.prototype.isZero = function () {
  5453. return this.width === 0 || this.height === 0;
  5454. };
  5455. BoundingRect.create = function (rect) {
  5456. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5457. };
  5458. BoundingRect.copy = function (target, source) {
  5459. target.x = source.x;
  5460. target.y = source.y;
  5461. target.width = source.width;
  5462. target.height = source.height;
  5463. };
  5464. BoundingRect.applyTransform = function (target, source, m) {
  5465. if (!m) {
  5466. if (target !== source) {
  5467. BoundingRect.copy(target, source);
  5468. }
  5469. return;
  5470. }
  5471. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  5472. var sx = m[0];
  5473. var sy = m[3];
  5474. var tx = m[4];
  5475. var ty = m[5];
  5476. target.x = source.x * sx + tx;
  5477. target.y = source.y * sy + ty;
  5478. target.width = source.width * sx;
  5479. target.height = source.height * sy;
  5480. if (target.width < 0) {
  5481. target.x += target.width;
  5482. target.width = -target.width;
  5483. }
  5484. if (target.height < 0) {
  5485. target.y += target.height;
  5486. target.height = -target.height;
  5487. }
  5488. return;
  5489. }
  5490. lt.x = lb.x = source.x;
  5491. lt.y = rt.y = source.y;
  5492. rb.x = rt.x = source.x + source.width;
  5493. rb.y = lb.y = source.y + source.height;
  5494. lt.transform(m);
  5495. rt.transform(m);
  5496. rb.transform(m);
  5497. lb.transform(m);
  5498. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  5499. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  5500. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  5501. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  5502. target.width = maxX - target.x;
  5503. target.height = maxY - target.y;
  5504. };
  5505. return BoundingRect;
  5506. }());
  5507. var textWidthCache = {};
  5508. function getWidth(text, font) {
  5509. font = font || DEFAULT_FONT;
  5510. var cacheOfFont = textWidthCache[font];
  5511. if (!cacheOfFont) {
  5512. cacheOfFont = textWidthCache[font] = new LRU(500);
  5513. }
  5514. var width = cacheOfFont.get(text);
  5515. if (width == null) {
  5516. width = platformApi.measureText(text, font).width;
  5517. cacheOfFont.put(text, width);
  5518. }
  5519. return width;
  5520. }
  5521. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5522. var width = getWidth(text, font);
  5523. var height = getLineHeight(font);
  5524. var x = adjustTextX(0, width, textAlign);
  5525. var y = adjustTextY$1(0, height, textBaseline);
  5526. var rect = new BoundingRect(x, y, width, height);
  5527. return rect;
  5528. }
  5529. function getBoundingRect(text, font, textAlign, textBaseline) {
  5530. var textLines = ((text || '') + '').split('\n');
  5531. var len = textLines.length;
  5532. if (len === 1) {
  5533. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5534. }
  5535. else {
  5536. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5537. for (var i = 0; i < textLines.length; i++) {
  5538. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5539. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5540. }
  5541. return uniondRect;
  5542. }
  5543. }
  5544. function adjustTextX(x, width, textAlign) {
  5545. if (textAlign === 'right') {
  5546. x -= width;
  5547. }
  5548. else if (textAlign === 'center') {
  5549. x -= width / 2;
  5550. }
  5551. return x;
  5552. }
  5553. function adjustTextY$1(y, height, verticalAlign) {
  5554. if (verticalAlign === 'middle') {
  5555. y -= height / 2;
  5556. }
  5557. else if (verticalAlign === 'bottom') {
  5558. y -= height;
  5559. }
  5560. return y;
  5561. }
  5562. function getLineHeight(font) {
  5563. return getWidth('国', font);
  5564. }
  5565. function parsePercent(value, maxValue) {
  5566. if (typeof value === 'string') {
  5567. if (value.lastIndexOf('%') >= 0) {
  5568. return parseFloat(value) / 100 * maxValue;
  5569. }
  5570. return parseFloat(value);
  5571. }
  5572. return value;
  5573. }
  5574. function calculateTextPosition(out, opts, rect) {
  5575. var textPosition = opts.position || 'inside';
  5576. var distance = opts.distance != null ? opts.distance : 5;
  5577. var height = rect.height;
  5578. var width = rect.width;
  5579. var halfHeight = height / 2;
  5580. var x = rect.x;
  5581. var y = rect.y;
  5582. var textAlign = 'left';
  5583. var textVerticalAlign = 'top';
  5584. if (textPosition instanceof Array) {
  5585. x += parsePercent(textPosition[0], rect.width);
  5586. y += parsePercent(textPosition[1], rect.height);
  5587. textAlign = null;
  5588. textVerticalAlign = null;
  5589. }
  5590. else {
  5591. switch (textPosition) {
  5592. case 'left':
  5593. x -= distance;
  5594. y += halfHeight;
  5595. textAlign = 'right';
  5596. textVerticalAlign = 'middle';
  5597. break;
  5598. case 'right':
  5599. x += distance + width;
  5600. y += halfHeight;
  5601. textVerticalAlign = 'middle';
  5602. break;
  5603. case 'top':
  5604. x += width / 2;
  5605. y -= distance;
  5606. textAlign = 'center';
  5607. textVerticalAlign = 'bottom';
  5608. break;
  5609. case 'bottom':
  5610. x += width / 2;
  5611. y += height + distance;
  5612. textAlign = 'center';
  5613. break;
  5614. case 'inside':
  5615. x += width / 2;
  5616. y += halfHeight;
  5617. textAlign = 'center';
  5618. textVerticalAlign = 'middle';
  5619. break;
  5620. case 'insideLeft':
  5621. x += distance;
  5622. y += halfHeight;
  5623. textVerticalAlign = 'middle';
  5624. break;
  5625. case 'insideRight':
  5626. x += width - distance;
  5627. y += halfHeight;
  5628. textAlign = 'right';
  5629. textVerticalAlign = 'middle';
  5630. break;
  5631. case 'insideTop':
  5632. x += width / 2;
  5633. y += distance;
  5634. textAlign = 'center';
  5635. break;
  5636. case 'insideBottom':
  5637. x += width / 2;
  5638. y += height - distance;
  5639. textAlign = 'center';
  5640. textVerticalAlign = 'bottom';
  5641. break;
  5642. case 'insideTopLeft':
  5643. x += distance;
  5644. y += distance;
  5645. break;
  5646. case 'insideTopRight':
  5647. x += width - distance;
  5648. y += distance;
  5649. textAlign = 'right';
  5650. break;
  5651. case 'insideBottomLeft':
  5652. x += distance;
  5653. y += height - distance;
  5654. textVerticalAlign = 'bottom';
  5655. break;
  5656. case 'insideBottomRight':
  5657. x += width - distance;
  5658. y += height - distance;
  5659. textAlign = 'right';
  5660. textVerticalAlign = 'bottom';
  5661. break;
  5662. }
  5663. }
  5664. out = out || {};
  5665. out.x = x;
  5666. out.y = y;
  5667. out.align = textAlign;
  5668. out.verticalAlign = textVerticalAlign;
  5669. return out;
  5670. }
  5671. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5672. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5673. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5674. obj[key] = true;
  5675. return obj;
  5676. }, { ignore: false });
  5677. var tmpTextPosCalcRes = {};
  5678. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5679. var Element = (function () {
  5680. function Element(props) {
  5681. this.id = guid();
  5682. this.animators = [];
  5683. this.currentStates = [];
  5684. this.states = {};
  5685. this._init(props);
  5686. }
  5687. Element.prototype._init = function (props) {
  5688. this.attr(props);
  5689. };
  5690. Element.prototype.drift = function (dx, dy, e) {
  5691. switch (this.draggable) {
  5692. case 'horizontal':
  5693. dy = 0;
  5694. break;
  5695. case 'vertical':
  5696. dx = 0;
  5697. break;
  5698. }
  5699. var m = this.transform;
  5700. if (!m) {
  5701. m = this.transform = [1, 0, 0, 1, 0, 0];
  5702. }
  5703. m[4] += dx;
  5704. m[5] += dy;
  5705. this.decomposeTransform();
  5706. this.markRedraw();
  5707. };
  5708. Element.prototype.beforeUpdate = function () { };
  5709. Element.prototype.afterUpdate = function () { };
  5710. Element.prototype.update = function () {
  5711. this.updateTransform();
  5712. if (this.__dirty) {
  5713. this.updateInnerText();
  5714. }
  5715. };
  5716. Element.prototype.updateInnerText = function (forceUpdate) {
  5717. var textEl = this._textContent;
  5718. if (textEl && (!textEl.ignore || forceUpdate)) {
  5719. if (!this.textConfig) {
  5720. this.textConfig = {};
  5721. }
  5722. var textConfig = this.textConfig;
  5723. var isLocal = textConfig.local;
  5724. var innerTransformable = textEl.innerTransformable;
  5725. var textAlign = void 0;
  5726. var textVerticalAlign = void 0;
  5727. var textStyleChanged = false;
  5728. innerTransformable.parent = isLocal ? this : null;
  5729. var innerOrigin = false;
  5730. innerTransformable.copyTransform(textEl);
  5731. if (textConfig.position != null) {
  5732. var layoutRect = tmpBoundingRect;
  5733. if (textConfig.layoutRect) {
  5734. layoutRect.copy(textConfig.layoutRect);
  5735. }
  5736. else {
  5737. layoutRect.copy(this.getBoundingRect());
  5738. }
  5739. if (!isLocal) {
  5740. layoutRect.applyTransform(this.transform);
  5741. }
  5742. if (this.calculateTextPosition) {
  5743. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5744. }
  5745. else {
  5746. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5747. }
  5748. innerTransformable.x = tmpTextPosCalcRes.x;
  5749. innerTransformable.y = tmpTextPosCalcRes.y;
  5750. textAlign = tmpTextPosCalcRes.align;
  5751. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5752. var textOrigin = textConfig.origin;
  5753. if (textOrigin && textConfig.rotation != null) {
  5754. var relOriginX = void 0;
  5755. var relOriginY = void 0;
  5756. if (textOrigin === 'center') {
  5757. relOriginX = layoutRect.width * 0.5;
  5758. relOriginY = layoutRect.height * 0.5;
  5759. }
  5760. else {
  5761. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5762. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5763. }
  5764. innerOrigin = true;
  5765. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5766. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5767. }
  5768. }
  5769. if (textConfig.rotation != null) {
  5770. innerTransformable.rotation = textConfig.rotation;
  5771. }
  5772. var textOffset = textConfig.offset;
  5773. if (textOffset) {
  5774. innerTransformable.x += textOffset[0];
  5775. innerTransformable.y += textOffset[1];
  5776. if (!innerOrigin) {
  5777. innerTransformable.originX = -textOffset[0];
  5778. innerTransformable.originY = -textOffset[1];
  5779. }
  5780. }
  5781. var isInside = textConfig.inside == null
  5782. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5783. : textConfig.inside;
  5784. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5785. var textFill = void 0;
  5786. var textStroke = void 0;
  5787. var autoStroke = void 0;
  5788. if (isInside && this.canBeInsideText()) {
  5789. textFill = textConfig.insideFill;
  5790. textStroke = textConfig.insideStroke;
  5791. if (textFill == null || textFill === 'auto') {
  5792. textFill = this.getInsideTextFill();
  5793. }
  5794. if (textStroke == null || textStroke === 'auto') {
  5795. textStroke = this.getInsideTextStroke(textFill);
  5796. autoStroke = true;
  5797. }
  5798. }
  5799. else {
  5800. textFill = textConfig.outsideFill;
  5801. textStroke = textConfig.outsideStroke;
  5802. if (textFill == null || textFill === 'auto') {
  5803. textFill = this.getOutsideFill();
  5804. }
  5805. if (textStroke == null || textStroke === 'auto') {
  5806. textStroke = this.getOutsideStroke(textFill);
  5807. autoStroke = true;
  5808. }
  5809. }
  5810. textFill = textFill || '#000';
  5811. if (textFill !== innerTextDefaultStyle.fill
  5812. || textStroke !== innerTextDefaultStyle.stroke
  5813. || autoStroke !== innerTextDefaultStyle.autoStroke
  5814. || textAlign !== innerTextDefaultStyle.align
  5815. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5816. textStyleChanged = true;
  5817. innerTextDefaultStyle.fill = textFill;
  5818. innerTextDefaultStyle.stroke = textStroke;
  5819. innerTextDefaultStyle.autoStroke = autoStroke;
  5820. innerTextDefaultStyle.align = textAlign;
  5821. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5822. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5823. }
  5824. textEl.__dirty |= REDRAW_BIT;
  5825. if (textStyleChanged) {
  5826. textEl.dirtyStyle(true);
  5827. }
  5828. }
  5829. };
  5830. Element.prototype.canBeInsideText = function () {
  5831. return true;
  5832. };
  5833. Element.prototype.getInsideTextFill = function () {
  5834. return '#fff';
  5835. };
  5836. Element.prototype.getInsideTextStroke = function (textFill) {
  5837. return '#000';
  5838. };
  5839. Element.prototype.getOutsideFill = function () {
  5840. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5841. };
  5842. Element.prototype.getOutsideStroke = function (textFill) {
  5843. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5844. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5845. if (!colorArr) {
  5846. colorArr = [255, 255, 255, 1];
  5847. }
  5848. var alpha = colorArr[3];
  5849. var isDark = this.__zr.isDarkMode();
  5850. for (var i = 0; i < 3; i++) {
  5851. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5852. }
  5853. colorArr[3] = 1;
  5854. return stringify(colorArr, 'rgba');
  5855. };
  5856. Element.prototype.traverse = function (cb, context) { };
  5857. Element.prototype.attrKV = function (key, value) {
  5858. if (key === 'textConfig') {
  5859. this.setTextConfig(value);
  5860. }
  5861. else if (key === 'textContent') {
  5862. this.setTextContent(value);
  5863. }
  5864. else if (key === 'clipPath') {
  5865. this.setClipPath(value);
  5866. }
  5867. else if (key === 'extra') {
  5868. this.extra = this.extra || {};
  5869. extend(this.extra, value);
  5870. }
  5871. else {
  5872. this[key] = value;
  5873. }
  5874. };
  5875. Element.prototype.hide = function () {
  5876. this.ignore = true;
  5877. this.markRedraw();
  5878. };
  5879. Element.prototype.show = function () {
  5880. this.ignore = false;
  5881. this.markRedraw();
  5882. };
  5883. Element.prototype.attr = function (keyOrObj, value) {
  5884. if (typeof keyOrObj === 'string') {
  5885. this.attrKV(keyOrObj, value);
  5886. }
  5887. else if (isObject(keyOrObj)) {
  5888. var obj = keyOrObj;
  5889. var keysArr = keys(obj);
  5890. for (var i = 0; i < keysArr.length; i++) {
  5891. var key = keysArr[i];
  5892. this.attrKV(key, keyOrObj[key]);
  5893. }
  5894. }
  5895. this.markRedraw();
  5896. return this;
  5897. };
  5898. Element.prototype.saveCurrentToNormalState = function (toState) {
  5899. this._innerSaveToNormal(toState);
  5900. var normalState = this._normalState;
  5901. for (var i = 0; i < this.animators.length; i++) {
  5902. var animator = this.animators[i];
  5903. var fromStateTransition = animator.__fromStateTransition;
  5904. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  5905. continue;
  5906. }
  5907. var targetName = animator.targetName;
  5908. var target = targetName
  5909. ? normalState[targetName] : normalState;
  5910. animator.saveTo(target);
  5911. }
  5912. };
  5913. Element.prototype._innerSaveToNormal = function (toState) {
  5914. var normalState = this._normalState;
  5915. if (!normalState) {
  5916. normalState = this._normalState = {};
  5917. }
  5918. if (toState.textConfig && !normalState.textConfig) {
  5919. normalState.textConfig = this.textConfig;
  5920. }
  5921. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  5922. };
  5923. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  5924. for (var i = 0; i < primaryKeys.length; i++) {
  5925. var key = primaryKeys[i];
  5926. if (toState[key] != null && !(key in normalState)) {
  5927. normalState[key] = this[key];
  5928. }
  5929. }
  5930. };
  5931. Element.prototype.hasState = function () {
  5932. return this.currentStates.length > 0;
  5933. };
  5934. Element.prototype.getState = function (name) {
  5935. return this.states[name];
  5936. };
  5937. Element.prototype.ensureState = function (name) {
  5938. var states = this.states;
  5939. if (!states[name]) {
  5940. states[name] = {};
  5941. }
  5942. return states[name];
  5943. };
  5944. Element.prototype.clearStates = function (noAnimation) {
  5945. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  5946. };
  5947. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  5948. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  5949. var hasStates = this.hasState();
  5950. if (!hasStates && toNormalState) {
  5951. return;
  5952. }
  5953. var currentStates = this.currentStates;
  5954. var animationCfg = this.stateTransition;
  5955. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  5956. return;
  5957. }
  5958. var state;
  5959. if (this.stateProxy && !toNormalState) {
  5960. state = this.stateProxy(stateName);
  5961. }
  5962. if (!state) {
  5963. state = (this.states && this.states[stateName]);
  5964. }
  5965. if (!state && !toNormalState) {
  5966. logError("State " + stateName + " not exists.");
  5967. return;
  5968. }
  5969. if (!toNormalState) {
  5970. this.saveCurrentToNormalState(state);
  5971. }
  5972. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  5973. if (useHoverLayer) {
  5974. this._toggleHoverLayerFlag(true);
  5975. }
  5976. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5977. var textContent = this._textContent;
  5978. var textGuide = this._textGuide;
  5979. if (textContent) {
  5980. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5981. }
  5982. if (textGuide) {
  5983. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5984. }
  5985. if (toNormalState) {
  5986. this.currentStates = [];
  5987. this._normalState = {};
  5988. }
  5989. else {
  5990. if (!keepCurrentStates) {
  5991. this.currentStates = [stateName];
  5992. }
  5993. else {
  5994. this.currentStates.push(stateName);
  5995. }
  5996. }
  5997. this._updateAnimationTargets();
  5998. this.markRedraw();
  5999. if (!useHoverLayer && this.__inHover) {
  6000. this._toggleHoverLayerFlag(false);
  6001. this.__dirty &= ~REDRAW_BIT;
  6002. }
  6003. return state;
  6004. };
  6005. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6006. if (!states.length) {
  6007. this.clearStates();
  6008. }
  6009. else {
  6010. var stateObjects = [];
  6011. var currentStates = this.currentStates;
  6012. var len = states.length;
  6013. var notChange = len === currentStates.length;
  6014. if (notChange) {
  6015. for (var i = 0; i < len; i++) {
  6016. if (states[i] !== currentStates[i]) {
  6017. notChange = false;
  6018. break;
  6019. }
  6020. }
  6021. }
  6022. if (notChange) {
  6023. return;
  6024. }
  6025. for (var i = 0; i < len; i++) {
  6026. var stateName = states[i];
  6027. var stateObj = void 0;
  6028. if (this.stateProxy) {
  6029. stateObj = this.stateProxy(stateName, states);
  6030. }
  6031. if (!stateObj) {
  6032. stateObj = this.states[stateName];
  6033. }
  6034. if (stateObj) {
  6035. stateObjects.push(stateObj);
  6036. }
  6037. }
  6038. var lastStateObj = stateObjects[len - 1];
  6039. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6040. if (useHoverLayer) {
  6041. this._toggleHoverLayerFlag(true);
  6042. }
  6043. var mergedState = this._mergeStates(stateObjects);
  6044. var animationCfg = this.stateTransition;
  6045. this.saveCurrentToNormalState(mergedState);
  6046. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6047. var textContent = this._textContent;
  6048. var textGuide = this._textGuide;
  6049. if (textContent) {
  6050. textContent.useStates(states, noAnimation, useHoverLayer);
  6051. }
  6052. if (textGuide) {
  6053. textGuide.useStates(states, noAnimation, useHoverLayer);
  6054. }
  6055. this._updateAnimationTargets();
  6056. this.currentStates = states.slice();
  6057. this.markRedraw();
  6058. if (!useHoverLayer && this.__inHover) {
  6059. this._toggleHoverLayerFlag(false);
  6060. this.__dirty &= ~REDRAW_BIT;
  6061. }
  6062. }
  6063. };
  6064. Element.prototype._updateAnimationTargets = function () {
  6065. for (var i = 0; i < this.animators.length; i++) {
  6066. var animator = this.animators[i];
  6067. if (animator.targetName) {
  6068. animator.changeTarget(this[animator.targetName]);
  6069. }
  6070. }
  6071. };
  6072. Element.prototype.removeState = function (state) {
  6073. var idx = indexOf(this.currentStates, state);
  6074. if (idx >= 0) {
  6075. var currentStates = this.currentStates.slice();
  6076. currentStates.splice(idx, 1);
  6077. this.useStates(currentStates);
  6078. }
  6079. };
  6080. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6081. var currentStates = this.currentStates.slice();
  6082. var idx = indexOf(currentStates, oldState);
  6083. var newStateExists = indexOf(currentStates, newState) >= 0;
  6084. if (idx >= 0) {
  6085. if (!newStateExists) {
  6086. currentStates[idx] = newState;
  6087. }
  6088. else {
  6089. currentStates.splice(idx, 1);
  6090. }
  6091. }
  6092. else if (forceAdd && !newStateExists) {
  6093. currentStates.push(newState);
  6094. }
  6095. this.useStates(currentStates);
  6096. };
  6097. Element.prototype.toggleState = function (state, enable) {
  6098. if (enable) {
  6099. this.useState(state, true);
  6100. }
  6101. else {
  6102. this.removeState(state);
  6103. }
  6104. };
  6105. Element.prototype._mergeStates = function (states) {
  6106. var mergedState = {};
  6107. var mergedTextConfig;
  6108. for (var i = 0; i < states.length; i++) {
  6109. var state = states[i];
  6110. extend(mergedState, state);
  6111. if (state.textConfig) {
  6112. mergedTextConfig = mergedTextConfig || {};
  6113. extend(mergedTextConfig, state.textConfig);
  6114. }
  6115. }
  6116. if (mergedTextConfig) {
  6117. mergedState.textConfig = mergedTextConfig;
  6118. }
  6119. return mergedState;
  6120. };
  6121. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6122. var needsRestoreToNormal = !(state && keepCurrentStates);
  6123. if (state && state.textConfig) {
  6124. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6125. extend(this.textConfig, state.textConfig);
  6126. }
  6127. else if (needsRestoreToNormal) {
  6128. if (normalState.textConfig) {
  6129. this.textConfig = normalState.textConfig;
  6130. }
  6131. }
  6132. var transitionTarget = {};
  6133. var hasTransition = false;
  6134. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6135. var key = PRIMARY_STATES_KEYS[i];
  6136. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6137. if (state && state[key] != null) {
  6138. if (propNeedsTransition) {
  6139. hasTransition = true;
  6140. transitionTarget[key] = state[key];
  6141. }
  6142. else {
  6143. this[key] = state[key];
  6144. }
  6145. }
  6146. else if (needsRestoreToNormal) {
  6147. if (normalState[key] != null) {
  6148. if (propNeedsTransition) {
  6149. hasTransition = true;
  6150. transitionTarget[key] = normalState[key];
  6151. }
  6152. else {
  6153. this[key] = normalState[key];
  6154. }
  6155. }
  6156. }
  6157. }
  6158. if (!transition) {
  6159. for (var i = 0; i < this.animators.length; i++) {
  6160. var animator = this.animators[i];
  6161. var targetName = animator.targetName;
  6162. if (!animator.getLoop()) {
  6163. animator.__changeFinalValue(targetName
  6164. ? (state || normalState)[targetName]
  6165. : (state || normalState));
  6166. }
  6167. }
  6168. }
  6169. if (hasTransition) {
  6170. this._transitionState(stateName, transitionTarget, animationCfg);
  6171. }
  6172. };
  6173. Element.prototype._attachComponent = function (componentEl) {
  6174. if (componentEl.__zr && !componentEl.__hostTarget) {
  6175. if ("development" !== 'production') {
  6176. throw new Error('Text element has been added to zrender.');
  6177. }
  6178. return;
  6179. }
  6180. if (componentEl === this) {
  6181. if ("development" !== 'production') {
  6182. throw new Error('Recursive component attachment.');
  6183. }
  6184. return;
  6185. }
  6186. var zr = this.__zr;
  6187. if (zr) {
  6188. componentEl.addSelfToZr(zr);
  6189. }
  6190. componentEl.__zr = zr;
  6191. componentEl.__hostTarget = this;
  6192. };
  6193. Element.prototype._detachComponent = function (componentEl) {
  6194. if (componentEl.__zr) {
  6195. componentEl.removeSelfFromZr(componentEl.__zr);
  6196. }
  6197. componentEl.__zr = null;
  6198. componentEl.__hostTarget = null;
  6199. };
  6200. Element.prototype.getClipPath = function () {
  6201. return this._clipPath;
  6202. };
  6203. Element.prototype.setClipPath = function (clipPath) {
  6204. if (this._clipPath && this._clipPath !== clipPath) {
  6205. this.removeClipPath();
  6206. }
  6207. this._attachComponent(clipPath);
  6208. this._clipPath = clipPath;
  6209. this.markRedraw();
  6210. };
  6211. Element.prototype.removeClipPath = function () {
  6212. var clipPath = this._clipPath;
  6213. if (clipPath) {
  6214. this._detachComponent(clipPath);
  6215. this._clipPath = null;
  6216. this.markRedraw();
  6217. }
  6218. };
  6219. Element.prototype.getTextContent = function () {
  6220. return this._textContent;
  6221. };
  6222. Element.prototype.setTextContent = function (textEl) {
  6223. var previousTextContent = this._textContent;
  6224. if (previousTextContent === textEl) {
  6225. return;
  6226. }
  6227. if (previousTextContent && previousTextContent !== textEl) {
  6228. this.removeTextContent();
  6229. }
  6230. if ("development" !== 'production') {
  6231. if (textEl.__zr && !textEl.__hostTarget) {
  6232. throw new Error('Text element has been added to zrender.');
  6233. }
  6234. }
  6235. textEl.innerTransformable = new Transformable();
  6236. this._attachComponent(textEl);
  6237. this._textContent = textEl;
  6238. this.markRedraw();
  6239. };
  6240. Element.prototype.setTextConfig = function (cfg) {
  6241. if (!this.textConfig) {
  6242. this.textConfig = {};
  6243. }
  6244. extend(this.textConfig, cfg);
  6245. this.markRedraw();
  6246. };
  6247. Element.prototype.removeTextConfig = function () {
  6248. this.textConfig = null;
  6249. this.markRedraw();
  6250. };
  6251. Element.prototype.removeTextContent = function () {
  6252. var textEl = this._textContent;
  6253. if (textEl) {
  6254. textEl.innerTransformable = null;
  6255. this._detachComponent(textEl);
  6256. this._textContent = null;
  6257. this._innerTextDefaultStyle = null;
  6258. this.markRedraw();
  6259. }
  6260. };
  6261. Element.prototype.getTextGuideLine = function () {
  6262. return this._textGuide;
  6263. };
  6264. Element.prototype.setTextGuideLine = function (guideLine) {
  6265. if (this._textGuide && this._textGuide !== guideLine) {
  6266. this.removeTextGuideLine();
  6267. }
  6268. this._attachComponent(guideLine);
  6269. this._textGuide = guideLine;
  6270. this.markRedraw();
  6271. };
  6272. Element.prototype.removeTextGuideLine = function () {
  6273. var textGuide = this._textGuide;
  6274. if (textGuide) {
  6275. this._detachComponent(textGuide);
  6276. this._textGuide = null;
  6277. this.markRedraw();
  6278. }
  6279. };
  6280. Element.prototype.markRedraw = function () {
  6281. this.__dirty |= REDRAW_BIT;
  6282. var zr = this.__zr;
  6283. if (zr) {
  6284. if (this.__inHover) {
  6285. zr.refreshHover();
  6286. }
  6287. else {
  6288. zr.refresh();
  6289. }
  6290. }
  6291. if (this.__hostTarget) {
  6292. this.__hostTarget.markRedraw();
  6293. }
  6294. };
  6295. Element.prototype.dirty = function () {
  6296. this.markRedraw();
  6297. };
  6298. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6299. this.__inHover = inHover;
  6300. var textContent = this._textContent;
  6301. var textGuide = this._textGuide;
  6302. if (textContent) {
  6303. textContent.__inHover = inHover;
  6304. }
  6305. if (textGuide) {
  6306. textGuide.__inHover = inHover;
  6307. }
  6308. };
  6309. Element.prototype.addSelfToZr = function (zr) {
  6310. if (this.__zr === zr) {
  6311. return;
  6312. }
  6313. this.__zr = zr;
  6314. var animators = this.animators;
  6315. if (animators) {
  6316. for (var i = 0; i < animators.length; i++) {
  6317. zr.animation.addAnimator(animators[i]);
  6318. }
  6319. }
  6320. if (this._clipPath) {
  6321. this._clipPath.addSelfToZr(zr);
  6322. }
  6323. if (this._textContent) {
  6324. this._textContent.addSelfToZr(zr);
  6325. }
  6326. if (this._textGuide) {
  6327. this._textGuide.addSelfToZr(zr);
  6328. }
  6329. };
  6330. Element.prototype.removeSelfFromZr = function (zr) {
  6331. if (!this.__zr) {
  6332. return;
  6333. }
  6334. this.__zr = null;
  6335. var animators = this.animators;
  6336. if (animators) {
  6337. for (var i = 0; i < animators.length; i++) {
  6338. zr.animation.removeAnimator(animators[i]);
  6339. }
  6340. }
  6341. if (this._clipPath) {
  6342. this._clipPath.removeSelfFromZr(zr);
  6343. }
  6344. if (this._textContent) {
  6345. this._textContent.removeSelfFromZr(zr);
  6346. }
  6347. if (this._textGuide) {
  6348. this._textGuide.removeSelfFromZr(zr);
  6349. }
  6350. };
  6351. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6352. var target = key ? this[key] : this;
  6353. if ("development" !== 'production') {
  6354. if (!target) {
  6355. logError('Property "'
  6356. + key
  6357. + '" is not existed in element '
  6358. + this.id);
  6359. return;
  6360. }
  6361. }
  6362. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6363. key && (animator.targetName = key);
  6364. this.addAnimator(animator, key);
  6365. return animator;
  6366. };
  6367. Element.prototype.addAnimator = function (animator, key) {
  6368. var zr = this.__zr;
  6369. var el = this;
  6370. animator.during(function () {
  6371. el.updateDuringAnimation(key);
  6372. }).done(function () {
  6373. var animators = el.animators;
  6374. var idx = indexOf(animators, animator);
  6375. if (idx >= 0) {
  6376. animators.splice(idx, 1);
  6377. }
  6378. });
  6379. this.animators.push(animator);
  6380. if (zr) {
  6381. zr.animation.addAnimator(animator);
  6382. }
  6383. zr && zr.wakeUp();
  6384. };
  6385. Element.prototype.updateDuringAnimation = function (key) {
  6386. this.markRedraw();
  6387. };
  6388. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6389. var animators = this.animators;
  6390. var len = animators.length;
  6391. var leftAnimators = [];
  6392. for (var i = 0; i < len; i++) {
  6393. var animator = animators[i];
  6394. if (!scope || scope === animator.scope) {
  6395. animator.stop(forwardToLast);
  6396. }
  6397. else {
  6398. leftAnimators.push(animator);
  6399. }
  6400. }
  6401. this.animators = leftAnimators;
  6402. return this;
  6403. };
  6404. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6405. animateTo(this, target, cfg, animationProps);
  6406. };
  6407. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6408. animateTo(this, target, cfg, animationProps, true);
  6409. };
  6410. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6411. var animators = animateTo(this, target, cfg, animationProps);
  6412. for (var i = 0; i < animators.length; i++) {
  6413. animators[i].__fromStateTransition = stateName;
  6414. }
  6415. };
  6416. Element.prototype.getBoundingRect = function () {
  6417. return null;
  6418. };
  6419. Element.prototype.getPaintRect = function () {
  6420. return null;
  6421. };
  6422. Element.initDefaultProps = (function () {
  6423. var elProto = Element.prototype;
  6424. elProto.type = 'element';
  6425. elProto.name = '';
  6426. elProto.ignore =
  6427. elProto.silent =
  6428. elProto.isGroup =
  6429. elProto.draggable =
  6430. elProto.dragging =
  6431. elProto.ignoreClip =
  6432. elProto.__inHover = false;
  6433. elProto.__dirty = REDRAW_BIT;
  6434. var logs = {};
  6435. function logDeprecatedError(key, xKey, yKey) {
  6436. if (!logs[key + xKey + yKey]) {
  6437. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6438. logs[key + xKey + yKey] = true;
  6439. }
  6440. }
  6441. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6442. Object.defineProperty(elProto, key, {
  6443. get: function () {
  6444. if ("development" !== 'production') {
  6445. logDeprecatedError(key, xKey, yKey);
  6446. }
  6447. if (!this[privateKey]) {
  6448. var pos = this[privateKey] = [];
  6449. enhanceArray(this, pos);
  6450. }
  6451. return this[privateKey];
  6452. },
  6453. set: function (pos) {
  6454. if ("development" !== 'production') {
  6455. logDeprecatedError(key, xKey, yKey);
  6456. }
  6457. this[xKey] = pos[0];
  6458. this[yKey] = pos[1];
  6459. this[privateKey] = pos;
  6460. enhanceArray(this, pos);
  6461. }
  6462. });
  6463. function enhanceArray(self, pos) {
  6464. Object.defineProperty(pos, 0, {
  6465. get: function () {
  6466. return self[xKey];
  6467. },
  6468. set: function (val) {
  6469. self[xKey] = val;
  6470. }
  6471. });
  6472. Object.defineProperty(pos, 1, {
  6473. get: function () {
  6474. return self[yKey];
  6475. },
  6476. set: function (val) {
  6477. self[yKey] = val;
  6478. }
  6479. });
  6480. }
  6481. }
  6482. if (Object.defineProperty) {
  6483. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6484. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6485. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6486. }
  6487. })();
  6488. return Element;
  6489. }());
  6490. mixin(Element, Eventful);
  6491. mixin(Element, Transformable);
  6492. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6493. cfg = cfg || {};
  6494. var animators = [];
  6495. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6496. var finishCount = animators.length;
  6497. var doneHappened = false;
  6498. var cfgDone = cfg.done;
  6499. var cfgAborted = cfg.aborted;
  6500. var doneCb = function () {
  6501. doneHappened = true;
  6502. finishCount--;
  6503. if (finishCount <= 0) {
  6504. doneHappened
  6505. ? (cfgDone && cfgDone())
  6506. : (cfgAborted && cfgAborted());
  6507. }
  6508. };
  6509. var abortedCb = function () {
  6510. finishCount--;
  6511. if (finishCount <= 0) {
  6512. doneHappened
  6513. ? (cfgDone && cfgDone())
  6514. : (cfgAborted && cfgAborted());
  6515. }
  6516. };
  6517. if (!finishCount) {
  6518. cfgDone && cfgDone();
  6519. }
  6520. if (animators.length > 0 && cfg.during) {
  6521. animators[0].during(function (target, percent) {
  6522. cfg.during(percent);
  6523. });
  6524. }
  6525. for (var i = 0; i < animators.length; i++) {
  6526. var animator = animators[i];
  6527. if (doneCb) {
  6528. animator.done(doneCb);
  6529. }
  6530. if (abortedCb) {
  6531. animator.aborted(abortedCb);
  6532. }
  6533. if (cfg.force) {
  6534. animator.duration(cfg.duration);
  6535. }
  6536. animator.start(cfg.easing);
  6537. }
  6538. return animators;
  6539. }
  6540. function copyArrShallow(source, target, len) {
  6541. for (var i = 0; i < len; i++) {
  6542. source[i] = target[i];
  6543. }
  6544. }
  6545. function is2DArray(value) {
  6546. return isArrayLike(value[0]);
  6547. }
  6548. function copyValue(target, source, key) {
  6549. if (isArrayLike(source[key])) {
  6550. if (!isArrayLike(target[key])) {
  6551. target[key] = [];
  6552. }
  6553. if (isTypedArray(source[key])) {
  6554. var len = source[key].length;
  6555. if (target[key].length !== len) {
  6556. target[key] = new (source[key].constructor)(len);
  6557. copyArrShallow(target[key], source[key], len);
  6558. }
  6559. }
  6560. else {
  6561. var sourceArr = source[key];
  6562. var targetArr = target[key];
  6563. var len0 = sourceArr.length;
  6564. if (is2DArray(sourceArr)) {
  6565. var len1 = sourceArr[0].length;
  6566. for (var i = 0; i < len0; i++) {
  6567. if (!targetArr[i]) {
  6568. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6569. }
  6570. else {
  6571. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6572. }
  6573. }
  6574. }
  6575. else {
  6576. copyArrShallow(targetArr, sourceArr, len0);
  6577. }
  6578. targetArr.length = sourceArr.length;
  6579. }
  6580. }
  6581. else {
  6582. target[key] = source[key];
  6583. }
  6584. }
  6585. function isValueSame(val1, val2) {
  6586. return val1 === val2
  6587. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6588. }
  6589. function is1DArraySame(arr0, arr1) {
  6590. var len = arr0.length;
  6591. if (len !== arr1.length) {
  6592. return false;
  6593. }
  6594. for (var i = 0; i < len; i++) {
  6595. if (arr0[i] !== arr1[i]) {
  6596. return false;
  6597. }
  6598. }
  6599. return true;
  6600. }
  6601. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6602. var targetKeys = keys(target);
  6603. var duration = cfg.duration;
  6604. var delay = cfg.delay;
  6605. var additive = cfg.additive;
  6606. var setToFinal = cfg.setToFinal;
  6607. var animateAll = !isObject(animationProps);
  6608. var existsAnimators = animatable.animators;
  6609. var animationKeys = [];
  6610. for (var k = 0; k < targetKeys.length; k++) {
  6611. var innerKey = targetKeys[k];
  6612. var targetVal = target[innerKey];
  6613. if (targetVal != null && animateObj[innerKey] != null
  6614. && (animateAll || animationProps[innerKey])) {
  6615. if (isObject(targetVal)
  6616. && !isArrayLike(targetVal)
  6617. && !isGradientObject(targetVal)) {
  6618. if (topKey) {
  6619. if (!reverse) {
  6620. animateObj[innerKey] = targetVal;
  6621. animatable.updateDuringAnimation(topKey);
  6622. }
  6623. continue;
  6624. }
  6625. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6626. }
  6627. else {
  6628. animationKeys.push(innerKey);
  6629. }
  6630. }
  6631. else if (!reverse) {
  6632. animateObj[innerKey] = targetVal;
  6633. animatable.updateDuringAnimation(topKey);
  6634. animationKeys.push(innerKey);
  6635. }
  6636. }
  6637. var keyLen = animationKeys.length;
  6638. if (!additive && keyLen) {
  6639. for (var i = 0; i < existsAnimators.length; i++) {
  6640. var animator = existsAnimators[i];
  6641. if (animator.targetName === topKey) {
  6642. var allAborted = animator.stopTracks(animationKeys);
  6643. if (allAborted) {
  6644. var idx = indexOf(existsAnimators, animator);
  6645. existsAnimators.splice(idx, 1);
  6646. }
  6647. }
  6648. }
  6649. }
  6650. if (!cfg.force) {
  6651. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6652. keyLen = animationKeys.length;
  6653. }
  6654. if (keyLen > 0
  6655. || (cfg.force && !animators.length)) {
  6656. var revertedSource = void 0;
  6657. var reversedTarget = void 0;
  6658. var sourceClone = void 0;
  6659. if (reverse) {
  6660. reversedTarget = {};
  6661. if (setToFinal) {
  6662. revertedSource = {};
  6663. }
  6664. for (var i = 0; i < keyLen; i++) {
  6665. var innerKey = animationKeys[i];
  6666. reversedTarget[innerKey] = animateObj[innerKey];
  6667. if (setToFinal) {
  6668. revertedSource[innerKey] = target[innerKey];
  6669. }
  6670. else {
  6671. animateObj[innerKey] = target[innerKey];
  6672. }
  6673. }
  6674. }
  6675. else if (setToFinal) {
  6676. sourceClone = {};
  6677. for (var i = 0; i < keyLen; i++) {
  6678. var innerKey = animationKeys[i];
  6679. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6680. copyValue(animateObj, target, innerKey);
  6681. }
  6682. }
  6683. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6684. animator.targetName = topKey;
  6685. if (cfg.scope) {
  6686. animator.scope = cfg.scope;
  6687. }
  6688. if (setToFinal && revertedSource) {
  6689. animator.whenWithKeys(0, revertedSource, animationKeys);
  6690. }
  6691. if (sourceClone) {
  6692. animator.whenWithKeys(0, sourceClone, animationKeys);
  6693. }
  6694. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6695. animatable.addAnimator(animator, topKey);
  6696. animators.push(animator);
  6697. }
  6698. }
  6699. var Group = (function (_super) {
  6700. __extends(Group, _super);
  6701. function Group(opts) {
  6702. var _this = _super.call(this) || this;
  6703. _this.isGroup = true;
  6704. _this._children = [];
  6705. _this.attr(opts);
  6706. return _this;
  6707. }
  6708. Group.prototype.childrenRef = function () {
  6709. return this._children;
  6710. };
  6711. Group.prototype.children = function () {
  6712. return this._children.slice();
  6713. };
  6714. Group.prototype.childAt = function (idx) {
  6715. return this._children[idx];
  6716. };
  6717. Group.prototype.childOfName = function (name) {
  6718. var children = this._children;
  6719. for (var i = 0; i < children.length; i++) {
  6720. if (children[i].name === name) {
  6721. return children[i];
  6722. }
  6723. }
  6724. };
  6725. Group.prototype.childCount = function () {
  6726. return this._children.length;
  6727. };
  6728. Group.prototype.add = function (child) {
  6729. if (child) {
  6730. if (child !== this && child.parent !== this) {
  6731. this._children.push(child);
  6732. this._doAdd(child);
  6733. }
  6734. if ("development" !== 'production') {
  6735. if (child.__hostTarget) {
  6736. throw 'This elemenet has been used as an attachment';
  6737. }
  6738. }
  6739. }
  6740. return this;
  6741. };
  6742. Group.prototype.addBefore = function (child, nextSibling) {
  6743. if (child && child !== this && child.parent !== this
  6744. && nextSibling && nextSibling.parent === this) {
  6745. var children = this._children;
  6746. var idx = children.indexOf(nextSibling);
  6747. if (idx >= 0) {
  6748. children.splice(idx, 0, child);
  6749. this._doAdd(child);
  6750. }
  6751. }
  6752. return this;
  6753. };
  6754. Group.prototype.replace = function (oldChild, newChild) {
  6755. var idx = indexOf(this._children, oldChild);
  6756. if (idx >= 0) {
  6757. this.replaceAt(newChild, idx);
  6758. }
  6759. return this;
  6760. };
  6761. Group.prototype.replaceAt = function (child, index) {
  6762. var children = this._children;
  6763. var old = children[index];
  6764. if (child && child !== this && child.parent !== this && child !== old) {
  6765. children[index] = child;
  6766. old.parent = null;
  6767. var zr = this.__zr;
  6768. if (zr) {
  6769. old.removeSelfFromZr(zr);
  6770. }
  6771. this._doAdd(child);
  6772. }
  6773. return this;
  6774. };
  6775. Group.prototype._doAdd = function (child) {
  6776. if (child.parent) {
  6777. child.parent.remove(child);
  6778. }
  6779. child.parent = this;
  6780. var zr = this.__zr;
  6781. if (zr && zr !== child.__zr) {
  6782. child.addSelfToZr(zr);
  6783. }
  6784. zr && zr.refresh();
  6785. };
  6786. Group.prototype.remove = function (child) {
  6787. var zr = this.__zr;
  6788. var children = this._children;
  6789. var idx = indexOf(children, child);
  6790. if (idx < 0) {
  6791. return this;
  6792. }
  6793. children.splice(idx, 1);
  6794. child.parent = null;
  6795. if (zr) {
  6796. child.removeSelfFromZr(zr);
  6797. }
  6798. zr && zr.refresh();
  6799. return this;
  6800. };
  6801. Group.prototype.removeAll = function () {
  6802. var children = this._children;
  6803. var zr = this.__zr;
  6804. for (var i = 0; i < children.length; i++) {
  6805. var child = children[i];
  6806. if (zr) {
  6807. child.removeSelfFromZr(zr);
  6808. }
  6809. child.parent = null;
  6810. }
  6811. children.length = 0;
  6812. return this;
  6813. };
  6814. Group.prototype.eachChild = function (cb, context) {
  6815. var children = this._children;
  6816. for (var i = 0; i < children.length; i++) {
  6817. var child = children[i];
  6818. cb.call(context, child, i);
  6819. }
  6820. return this;
  6821. };
  6822. Group.prototype.traverse = function (cb, context) {
  6823. for (var i = 0; i < this._children.length; i++) {
  6824. var child = this._children[i];
  6825. var stopped = cb.call(context, child);
  6826. if (child.isGroup && !stopped) {
  6827. child.traverse(cb, context);
  6828. }
  6829. }
  6830. return this;
  6831. };
  6832. Group.prototype.addSelfToZr = function (zr) {
  6833. _super.prototype.addSelfToZr.call(this, zr);
  6834. for (var i = 0; i < this._children.length; i++) {
  6835. var child = this._children[i];
  6836. child.addSelfToZr(zr);
  6837. }
  6838. };
  6839. Group.prototype.removeSelfFromZr = function (zr) {
  6840. _super.prototype.removeSelfFromZr.call(this, zr);
  6841. for (var i = 0; i < this._children.length; i++) {
  6842. var child = this._children[i];
  6843. child.removeSelfFromZr(zr);
  6844. }
  6845. };
  6846. Group.prototype.getBoundingRect = function (includeChildren) {
  6847. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6848. var children = includeChildren || this._children;
  6849. var tmpMat = [];
  6850. var rect = null;
  6851. for (var i = 0; i < children.length; i++) {
  6852. var child = children[i];
  6853. if (child.ignore || child.invisible) {
  6854. continue;
  6855. }
  6856. var childRect = child.getBoundingRect();
  6857. var transform = child.getLocalTransform(tmpMat);
  6858. if (transform) {
  6859. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6860. rect = rect || tmpRect.clone();
  6861. rect.union(tmpRect);
  6862. }
  6863. else {
  6864. rect = rect || childRect.clone();
  6865. rect.union(childRect);
  6866. }
  6867. }
  6868. return rect || tmpRect;
  6869. };
  6870. return Group;
  6871. }(Element));
  6872. Group.prototype.type = 'group';
  6873. /*!
  6874. * ZRender, a high performance 2d drawing library.
  6875. *
  6876. * Copyright (c) 2013, Baidu Inc.
  6877. * All rights reserved.
  6878. *
  6879. * LICENSE
  6880. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6881. */
  6882. var painterCtors = {};
  6883. var instances = {};
  6884. function delInstance(id) {
  6885. delete instances[id];
  6886. }
  6887. function isDarkMode(backgroundColor) {
  6888. if (!backgroundColor) {
  6889. return false;
  6890. }
  6891. if (typeof backgroundColor === 'string') {
  6892. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6893. }
  6894. else if (backgroundColor.colorStops) {
  6895. var colorStops = backgroundColor.colorStops;
  6896. var totalLum = 0;
  6897. var len = colorStops.length;
  6898. for (var i = 0; i < len; i++) {
  6899. totalLum += lum(colorStops[i].color, 1);
  6900. }
  6901. totalLum /= len;
  6902. return totalLum < DARK_MODE_THRESHOLD;
  6903. }
  6904. return false;
  6905. }
  6906. var ZRender = (function () {
  6907. function ZRender(id, dom, opts) {
  6908. var _this = this;
  6909. this._sleepAfterStill = 10;
  6910. this._stillFrameAccum = 0;
  6911. this._needsRefresh = true;
  6912. this._needsRefreshHover = true;
  6913. this._darkMode = false;
  6914. opts = opts || {};
  6915. this.dom = dom;
  6916. this.id = id;
  6917. var storage = new Storage();
  6918. var rendererType = opts.renderer || 'canvas';
  6919. if (!painterCtors[rendererType]) {
  6920. rendererType = keys(painterCtors)[0];
  6921. }
  6922. if ("development" !== 'production') {
  6923. if (!painterCtors[rendererType]) {
  6924. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6925. }
  6926. }
  6927. opts.useDirtyRect = opts.useDirtyRect == null
  6928. ? false
  6929. : opts.useDirtyRect;
  6930. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6931. var ssrMode = opts.ssr || painter.ssrOnly;
  6932. this.storage = storage;
  6933. this.painter = painter;
  6934. var handerProxy = (!env.node && !env.worker && !ssrMode)
  6935. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6936. : null;
  6937. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6938. this.animation = new Animation({
  6939. stage: {
  6940. update: ssrMode ? null : function () { return _this._flush(true); }
  6941. }
  6942. });
  6943. if (!ssrMode) {
  6944. this.animation.start();
  6945. }
  6946. }
  6947. ZRender.prototype.add = function (el) {
  6948. if (!el) {
  6949. return;
  6950. }
  6951. this.storage.addRoot(el);
  6952. el.addSelfToZr(this);
  6953. this.refresh();
  6954. };
  6955. ZRender.prototype.remove = function (el) {
  6956. if (!el) {
  6957. return;
  6958. }
  6959. this.storage.delRoot(el);
  6960. el.removeSelfFromZr(this);
  6961. this.refresh();
  6962. };
  6963. ZRender.prototype.configLayer = function (zLevel, config) {
  6964. if (this.painter.configLayer) {
  6965. this.painter.configLayer(zLevel, config);
  6966. }
  6967. this.refresh();
  6968. };
  6969. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6970. if (this.painter.setBackgroundColor) {
  6971. this.painter.setBackgroundColor(backgroundColor);
  6972. }
  6973. this.refresh();
  6974. this._backgroundColor = backgroundColor;
  6975. this._darkMode = isDarkMode(backgroundColor);
  6976. };
  6977. ZRender.prototype.getBackgroundColor = function () {
  6978. return this._backgroundColor;
  6979. };
  6980. ZRender.prototype.setDarkMode = function (darkMode) {
  6981. this._darkMode = darkMode;
  6982. };
  6983. ZRender.prototype.isDarkMode = function () {
  6984. return this._darkMode;
  6985. };
  6986. ZRender.prototype.refreshImmediately = function (fromInside) {
  6987. if (!fromInside) {
  6988. this.animation.update(true);
  6989. }
  6990. this._needsRefresh = false;
  6991. this.painter.refresh();
  6992. this._needsRefresh = false;
  6993. };
  6994. ZRender.prototype.refresh = function () {
  6995. this._needsRefresh = true;
  6996. this.animation.start();
  6997. };
  6998. ZRender.prototype.flush = function () {
  6999. this._flush(false);
  7000. };
  7001. ZRender.prototype._flush = function (fromInside) {
  7002. var triggerRendered;
  7003. var start = getTime();
  7004. if (this._needsRefresh) {
  7005. triggerRendered = true;
  7006. this.refreshImmediately(fromInside);
  7007. }
  7008. if (this._needsRefreshHover) {
  7009. triggerRendered = true;
  7010. this.refreshHoverImmediately();
  7011. }
  7012. var end = getTime();
  7013. if (triggerRendered) {
  7014. this._stillFrameAccum = 0;
  7015. this.trigger('rendered', {
  7016. elapsedTime: end - start
  7017. });
  7018. }
  7019. else if (this._sleepAfterStill > 0) {
  7020. this._stillFrameAccum++;
  7021. if (this._stillFrameAccum > this._sleepAfterStill) {
  7022. this.animation.stop();
  7023. }
  7024. }
  7025. };
  7026. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7027. this._sleepAfterStill = stillFramesCount;
  7028. };
  7029. ZRender.prototype.wakeUp = function () {
  7030. this.animation.start();
  7031. this._stillFrameAccum = 0;
  7032. };
  7033. ZRender.prototype.refreshHover = function () {
  7034. this._needsRefreshHover = true;
  7035. };
  7036. ZRender.prototype.refreshHoverImmediately = function () {
  7037. this._needsRefreshHover = false;
  7038. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7039. this.painter.refreshHover();
  7040. }
  7041. };
  7042. ZRender.prototype.resize = function (opts) {
  7043. opts = opts || {};
  7044. this.painter.resize(opts.width, opts.height);
  7045. this.handler.resize();
  7046. };
  7047. ZRender.prototype.clearAnimation = function () {
  7048. this.animation.clear();
  7049. };
  7050. ZRender.prototype.getWidth = function () {
  7051. return this.painter.getWidth();
  7052. };
  7053. ZRender.prototype.getHeight = function () {
  7054. return this.painter.getHeight();
  7055. };
  7056. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7057. this.handler.setCursorStyle(cursorStyle);
  7058. };
  7059. ZRender.prototype.findHover = function (x, y) {
  7060. return this.handler.findHover(x, y);
  7061. };
  7062. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7063. this.handler.on(eventName, eventHandler, context);
  7064. return this;
  7065. };
  7066. ZRender.prototype.off = function (eventName, eventHandler) {
  7067. this.handler.off(eventName, eventHandler);
  7068. };
  7069. ZRender.prototype.trigger = function (eventName, event) {
  7070. this.handler.trigger(eventName, event);
  7071. };
  7072. ZRender.prototype.clear = function () {
  7073. var roots = this.storage.getRoots();
  7074. for (var i = 0; i < roots.length; i++) {
  7075. if (roots[i] instanceof Group) {
  7076. roots[i].removeSelfFromZr(this);
  7077. }
  7078. }
  7079. this.storage.delAllRoots();
  7080. this.painter.clear();
  7081. };
  7082. ZRender.prototype.dispose = function () {
  7083. this.animation.stop();
  7084. this.clear();
  7085. this.storage.dispose();
  7086. this.painter.dispose();
  7087. this.handler.dispose();
  7088. this.animation =
  7089. this.storage =
  7090. this.painter =
  7091. this.handler = null;
  7092. delInstance(this.id);
  7093. };
  7094. return ZRender;
  7095. }());
  7096. function init(dom, opts) {
  7097. var zr = new ZRender(guid(), dom, opts);
  7098. instances[zr.id] = zr;
  7099. return zr;
  7100. }
  7101. function dispose(zr) {
  7102. zr.dispose();
  7103. }
  7104. function disposeAll() {
  7105. for (var key in instances) {
  7106. if (instances.hasOwnProperty(key)) {
  7107. instances[key].dispose();
  7108. }
  7109. }
  7110. instances = {};
  7111. }
  7112. function getInstance(id) {
  7113. return instances[id];
  7114. }
  7115. function registerPainter(name, Ctor) {
  7116. painterCtors[name] = Ctor;
  7117. }
  7118. var version = '5.3.0';
  7119. var zrender = /*#__PURE__*/Object.freeze({
  7120. __proto__: null,
  7121. init: init,
  7122. dispose: dispose,
  7123. disposeAll: disposeAll,
  7124. getInstance: getInstance,
  7125. registerPainter: registerPainter,
  7126. version: version
  7127. });
  7128. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  7129. // we sill follow the spec for compatibility.
  7130. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7131. function _trim(str) {
  7132. return str.replace(/^\s+|\s+$/g, '');
  7133. }
  7134. /**
  7135. * Linear mapping a value from domain to range
  7136. * @param val
  7137. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7138. * @param range Range extent range[0] can be bigger than range[1]
  7139. * @param clamp Default to be false
  7140. */
  7141. function linearMap(val, domain, range, clamp) {
  7142. var d0 = domain[0];
  7143. var d1 = domain[1];
  7144. var r0 = range[0];
  7145. var r1 = range[1];
  7146. var subDomain = d1 - d0;
  7147. var subRange = r1 - r0;
  7148. if (subDomain === 0) {
  7149. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7150. } // Avoid accuracy problem in edge, such as
  7151. // 146.39 - 62.83 === 83.55999999999999.
  7152. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7153. // It is a little verbose for efficiency considering this method
  7154. // is a hotspot.
  7155. if (clamp) {
  7156. if (subDomain > 0) {
  7157. if (val <= d0) {
  7158. return r0;
  7159. } else if (val >= d1) {
  7160. return r1;
  7161. }
  7162. } else {
  7163. if (val >= d0) {
  7164. return r0;
  7165. } else if (val <= d1) {
  7166. return r1;
  7167. }
  7168. }
  7169. } else {
  7170. if (val === d0) {
  7171. return r0;
  7172. }
  7173. if (val === d1) {
  7174. return r1;
  7175. }
  7176. }
  7177. return (val - d0) / subDomain * subRange + r0;
  7178. }
  7179. /**
  7180. * Convert a percent string to absolute number.
  7181. * Returns NaN if percent is not a valid string or number
  7182. */
  7183. function parsePercent$1(percent, all) {
  7184. switch (percent) {
  7185. case 'center':
  7186. case 'middle':
  7187. percent = '50%';
  7188. break;
  7189. case 'left':
  7190. case 'top':
  7191. percent = '0%';
  7192. break;
  7193. case 'right':
  7194. case 'bottom':
  7195. percent = '100%';
  7196. break;
  7197. }
  7198. if (isString(percent)) {
  7199. if (_trim(percent).match(/%$/)) {
  7200. return parseFloat(percent) / 100 * all;
  7201. }
  7202. return parseFloat(percent);
  7203. }
  7204. return percent == null ? NaN : +percent;
  7205. }
  7206. function round(x, precision, returnStr) {
  7207. if (precision == null) {
  7208. precision = 10;
  7209. } // Avoid range error
  7210. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7211. x = (+x).toFixed(precision);
  7212. return returnStr ? x : +x;
  7213. }
  7214. /**
  7215. * Inplacd asc sort arr.
  7216. * The input arr will be modified.
  7217. */
  7218. function asc(arr) {
  7219. arr.sort(function (a, b) {
  7220. return a - b;
  7221. });
  7222. return arr;
  7223. }
  7224. /**
  7225. * Get precision.
  7226. */
  7227. function getPrecision(val) {
  7228. val = +val;
  7229. if (isNaN(val)) {
  7230. return 0;
  7231. } // It is much faster than methods converting number to string as follows
  7232. // let tmp = val.toString();
  7233. // return tmp.length - 1 - tmp.indexOf('.');
  7234. // especially when precision is low
  7235. // Notice:
  7236. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7237. // (see https://jsbench.me/2vkpcekkvw/1)
  7238. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7239. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7240. if (val > 1e-14) {
  7241. var e = 1;
  7242. for (var i = 0; i < 15; i++, e *= 10) {
  7243. if (Math.round(val * e) / e === val) {
  7244. return i;
  7245. }
  7246. }
  7247. }
  7248. return getPrecisionSafe(val);
  7249. }
  7250. /**
  7251. * Get precision with slow but safe method
  7252. */
  7253. function getPrecisionSafe(val) {
  7254. // toLowerCase for: '3.4E-12'
  7255. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7256. var eIndex = str.indexOf('e');
  7257. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7258. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7259. var dotIndex = str.indexOf('.');
  7260. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7261. return Math.max(0, decimalPartLen - exp);
  7262. }
  7263. /**
  7264. * Minimal dicernible data precisioin according to a single pixel.
  7265. */
  7266. function getPixelPrecision(dataExtent, pixelExtent) {
  7267. var log = Math.log;
  7268. var LN10 = Math.LN10;
  7269. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7270. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7271. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7272. return !isFinite(precision) ? 20 : precision;
  7273. }
  7274. /**
  7275. * Get a data of given precision, assuring the sum of percentages
  7276. * in valueList is 1.
  7277. * The largest remainer method is used.
  7278. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7279. *
  7280. * @param valueList a list of all data
  7281. * @param idx index of the data to be processed in valueList
  7282. * @param precision integer number showing digits of precision
  7283. * @return percent ranging from 0 to 100
  7284. */
  7285. function getPercentWithPrecision(valueList, idx, precision) {
  7286. if (!valueList[idx]) {
  7287. return 0;
  7288. }
  7289. var sum = reduce(valueList, function (acc, val) {
  7290. return acc + (isNaN(val) ? 0 : val);
  7291. }, 0);
  7292. if (sum === 0) {
  7293. return 0;
  7294. }
  7295. var digits = Math.pow(10, precision);
  7296. var votesPerQuota = map(valueList, function (val) {
  7297. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7298. });
  7299. var targetSeats = digits * 100;
  7300. var seats = map(votesPerQuota, function (votes) {
  7301. // Assign automatic seats.
  7302. return Math.floor(votes);
  7303. });
  7304. var currentSum = reduce(seats, function (acc, val) {
  7305. return acc + val;
  7306. }, 0);
  7307. var remainder = map(votesPerQuota, function (votes, idx) {
  7308. return votes - seats[idx];
  7309. }); // Has remainding votes.
  7310. while (currentSum < targetSeats) {
  7311. // Find next largest remainder.
  7312. var max = Number.NEGATIVE_INFINITY;
  7313. var maxId = null;
  7314. for (var i = 0, len = remainder.length; i < len; ++i) {
  7315. if (remainder[i] > max) {
  7316. max = remainder[i];
  7317. maxId = i;
  7318. }
  7319. } // Add a vote to max remainder.
  7320. ++seats[maxId];
  7321. remainder[maxId] = 0;
  7322. ++currentSum;
  7323. }
  7324. return seats[idx] / digits;
  7325. }
  7326. /**
  7327. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7328. * See <http://0.30000000000000004.com/>
  7329. */
  7330. function addSafe(val0, val1) {
  7331. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7332. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7333. var sum = val0 + val1; // // PENDING: support more?
  7334. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7335. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7336. var MAX_SAFE_INTEGER = 9007199254740991;
  7337. /**
  7338. * To 0 - 2 * PI, considering negative radian.
  7339. */
  7340. function remRadian(radian) {
  7341. var pi2 = Math.PI * 2;
  7342. return (radian % pi2 + pi2) % pi2;
  7343. }
  7344. /**
  7345. * @param {type} radian
  7346. * @return {boolean}
  7347. */
  7348. function isRadianAroundZero(val) {
  7349. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7350. } // eslint-disable-next-line
  7351. 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
  7352. /**
  7353. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7354. * These values can be accepted:
  7355. * + An instance of Date, represent a time in its own time zone.
  7356. * + Or string in a subset of ISO 8601, only including:
  7357. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7358. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7359. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7360. * all of which will be treated as local time if time zone is not specified
  7361. * (see <https://momentjs.com/>).
  7362. * + Or other string format, including (all of which will be treated as loacal time):
  7363. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7364. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7365. * + a timestamp, which represent a time in UTC.
  7366. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7367. */
  7368. function parseDate(value) {
  7369. if (value instanceof Date) {
  7370. return value;
  7371. } else if (isString(value)) {
  7372. // Different browsers parse date in different way, so we parse it manually.
  7373. // Some other issues:
  7374. // new Date('1970-01-01') is UTC,
  7375. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7376. // See issue #3623
  7377. var match = TIME_REG.exec(value);
  7378. if (!match) {
  7379. // return Invalid Date.
  7380. return new Date(NaN);
  7381. } // Use local time when no timezone offset specifed.
  7382. if (!match[8]) {
  7383. // match[n] can only be string or undefined.
  7384. // But take care of '12' + 1 => '121'.
  7385. 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);
  7386. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7387. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7388. // For example, system timezone is set as "Time Zone: America/Toronto",
  7389. // then these code will get different result:
  7390. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7391. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7392. // So we should not use `new Date`, but use `Date.UTC`.
  7393. else {
  7394. var hour = +match[4] || 0;
  7395. if (match[8].toUpperCase() !== 'Z') {
  7396. hour -= +match[8].slice(0, 3);
  7397. }
  7398. 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));
  7399. }
  7400. } else if (value == null) {
  7401. return new Date(NaN);
  7402. }
  7403. return new Date(Math.round(value));
  7404. }
  7405. /**
  7406. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7407. *
  7408. * @param val
  7409. * @return
  7410. */
  7411. function quantity(val) {
  7412. return Math.pow(10, quantityExponent(val));
  7413. }
  7414. /**
  7415. * Exponent of the quantity of a number
  7416. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7417. *
  7418. * @param val non-negative value
  7419. * @return
  7420. */
  7421. function quantityExponent(val) {
  7422. if (val === 0) {
  7423. return 0;
  7424. }
  7425. var exp = Math.floor(Math.log(val) / Math.LN10);
  7426. /**
  7427. * exp is expected to be the rounded-down result of the base-10 log of val.
  7428. * But due to the precision loss with Math.log(val), we need to restore it
  7429. * using 10^exp to make sure we can get val back from exp. #11249
  7430. */
  7431. if (val / Math.pow(10, exp) >= 10) {
  7432. exp++;
  7433. }
  7434. return exp;
  7435. }
  7436. /**
  7437. * find a “nice” number approximately equal to x. Round the number if round = true,
  7438. * take ceiling if round = false. The primary observation is that the “nicest”
  7439. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7440. *
  7441. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7442. *
  7443. * @param val Non-negative value.
  7444. * @param round
  7445. * @return Niced number
  7446. */
  7447. function nice(val, round) {
  7448. var exponent = quantityExponent(val);
  7449. var exp10 = Math.pow(10, exponent);
  7450. var f = val / exp10; // 1 <= f < 10
  7451. var nf;
  7452. if (round) {
  7453. if (f < 1.5) {
  7454. nf = 1;
  7455. } else if (f < 2.5) {
  7456. nf = 2;
  7457. } else if (f < 4) {
  7458. nf = 3;
  7459. } else if (f < 7) {
  7460. nf = 5;
  7461. } else {
  7462. nf = 10;
  7463. }
  7464. } else {
  7465. if (f < 1) {
  7466. nf = 1;
  7467. } else if (f < 2) {
  7468. nf = 2;
  7469. } else if (f < 3) {
  7470. nf = 3;
  7471. } else if (f < 5) {
  7472. nf = 5;
  7473. } else {
  7474. nf = 10;
  7475. }
  7476. }
  7477. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7478. // 20 is the uppper bound of toFixed.
  7479. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7480. }
  7481. /**
  7482. * This code was copied from "d3.js"
  7483. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7484. * See the license statement at the head of this file.
  7485. * @param ascArr
  7486. */
  7487. function quantile(ascArr, p) {
  7488. var H = (ascArr.length - 1) * p + 1;
  7489. var h = Math.floor(H);
  7490. var v = +ascArr[h - 1];
  7491. var e = H - h;
  7492. return e ? v + e * (ascArr[h] - v) : v;
  7493. }
  7494. /**
  7495. * Order intervals asc, and split them when overlap.
  7496. * expect(numberUtil.reformIntervals([
  7497. * {interval: [18, 62], close: [1, 1]},
  7498. * {interval: [-Infinity, -70], close: [0, 0]},
  7499. * {interval: [-70, -26], close: [1, 1]},
  7500. * {interval: [-26, 18], close: [1, 1]},
  7501. * {interval: [62, 150], close: [1, 1]},
  7502. * {interval: [106, 150], close: [1, 1]},
  7503. * {interval: [150, Infinity], close: [0, 0]}
  7504. * ])).toEqual([
  7505. * {interval: [-Infinity, -70], close: [0, 0]},
  7506. * {interval: [-70, -26], close: [1, 1]},
  7507. * {interval: [-26, 18], close: [0, 1]},
  7508. * {interval: [18, 62], close: [0, 1]},
  7509. * {interval: [62, 150], close: [0, 1]},
  7510. * {interval: [150, Infinity], close: [0, 0]}
  7511. * ]);
  7512. * @param list, where `close` mean open or close
  7513. * of the interval, and Infinity can be used.
  7514. * @return The origin list, which has been reformed.
  7515. */
  7516. function reformIntervals(list) {
  7517. list.sort(function (a, b) {
  7518. return littleThan(a, b, 0) ? -1 : 1;
  7519. });
  7520. var curr = -Infinity;
  7521. var currClose = 1;
  7522. for (var i = 0; i < list.length;) {
  7523. var interval = list[i].interval;
  7524. var close_1 = list[i].close;
  7525. for (var lg = 0; lg < 2; lg++) {
  7526. if (interval[lg] <= curr) {
  7527. interval[lg] = curr;
  7528. close_1[lg] = !lg ? 1 - currClose : 1;
  7529. }
  7530. curr = interval[lg];
  7531. currClose = close_1[lg];
  7532. }
  7533. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7534. list.splice(i, 1);
  7535. } else {
  7536. i++;
  7537. }
  7538. }
  7539. return list;
  7540. function littleThan(a, b, lg) {
  7541. 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));
  7542. }
  7543. }
  7544. /**
  7545. * [Numberic is defined as]:
  7546. * `parseFloat(val) == val`
  7547. * For example:
  7548. * numeric:
  7549. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7550. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7551. * not-numeric:
  7552. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7553. * empty string, string with only white-spaces or line-terminal (see es spec),
  7554. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7555. * non-string, ...
  7556. *
  7557. * @test See full test cases in `test/ut/spec/util/number.js`.
  7558. * @return Must be a typeof number. If not numeric, return NaN.
  7559. */
  7560. function numericToNumber(val) {
  7561. var valFloat = parseFloat(val);
  7562. return valFloat == val // eslint-disable-line eqeqeq
  7563. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7564. ? valFloat : NaN;
  7565. }
  7566. /**
  7567. * Definition of "numeric": see `numericToNumber`.
  7568. */
  7569. function isNumeric(val) {
  7570. return !isNaN(numericToNumber(val));
  7571. }
  7572. /**
  7573. * Use random base to prevent users hard code depending on
  7574. * this auto generated marker id.
  7575. * @return An positive integer.
  7576. */
  7577. function getRandomIdBase() {
  7578. return Math.round(Math.random() * 9);
  7579. }
  7580. /**
  7581. * Get the greatest common dividor
  7582. *
  7583. * @param {number} a one number
  7584. * @param {number} b the other number
  7585. */
  7586. function getGreatestCommonDividor(a, b) {
  7587. if (b === 0) {
  7588. return a;
  7589. }
  7590. return getGreatestCommonDividor(b, a % b);
  7591. }
  7592. /**
  7593. * Get the least common multiple
  7594. *
  7595. * @param {number} a one number
  7596. * @param {number} b the other number
  7597. */
  7598. function getLeastCommonMultiple(a, b) {
  7599. if (a == null) {
  7600. return b;
  7601. }
  7602. if (b == null) {
  7603. return a;
  7604. }
  7605. return a * b / getGreatestCommonDividor(a, b);
  7606. }
  7607. var ECHARTS_PREFIX = '[ECharts] ';
  7608. var storedLogs = {};
  7609. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7610. && console.warn && console.log;
  7611. function outputLog(type, str, onlyOnce) {
  7612. if (hasConsole) {
  7613. if (onlyOnce) {
  7614. if (storedLogs[str]) {
  7615. return;
  7616. }
  7617. storedLogs[str] = true;
  7618. } // eslint-disable-next-line
  7619. console[type](ECHARTS_PREFIX + str);
  7620. }
  7621. }
  7622. function log(str, onlyOnce) {
  7623. outputLog('log', str, onlyOnce);
  7624. }
  7625. function warn(str, onlyOnce) {
  7626. outputLog('warn', str, onlyOnce);
  7627. }
  7628. function error(str, onlyOnce) {
  7629. outputLog('error', str, onlyOnce);
  7630. }
  7631. function deprecateLog(str) {
  7632. if ("development" !== 'production') {
  7633. // Not display duplicate message.
  7634. outputLog('warn', 'DEPRECATED: ' + str, true);
  7635. }
  7636. }
  7637. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7638. if ("development" !== 'production') {
  7639. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7640. }
  7641. }
  7642. /**
  7643. * If in __DEV__ environment, get console printable message for users hint.
  7644. * Parameters are separated by ' '.
  7645. * @usuage
  7646. * makePrintable('This is an error on', someVar, someObj);
  7647. *
  7648. * @param hintInfo anything about the current execution context to hint users.
  7649. * @throws Error
  7650. */
  7651. function makePrintable() {
  7652. var hintInfo = [];
  7653. for (var _i = 0; _i < arguments.length; _i++) {
  7654. hintInfo[_i] = arguments[_i];
  7655. }
  7656. var msg = '';
  7657. if ("development" !== 'production') {
  7658. // Fuzzy stringify for print.
  7659. // This code only exist in dev environment.
  7660. var makePrintableStringIfPossible_1 = function (val) {
  7661. 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;
  7662. };
  7663. msg = map(hintInfo, function (arg) {
  7664. if (isString(arg)) {
  7665. // Print without quotation mark for some statement.
  7666. return arg;
  7667. } else {
  7668. var printableStr = makePrintableStringIfPossible_1(arg);
  7669. if (printableStr != null) {
  7670. return printableStr;
  7671. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7672. try {
  7673. return JSON.stringify(arg, function (n, val) {
  7674. var printableStr = makePrintableStringIfPossible_1(val);
  7675. return printableStr == null ? val : printableStr;
  7676. }); // In most cases the info object is small, so do not line break.
  7677. } catch (err) {
  7678. return '?';
  7679. }
  7680. } else {
  7681. return '?';
  7682. }
  7683. }
  7684. }).join(' ');
  7685. }
  7686. return msg;
  7687. }
  7688. /**
  7689. * @throws Error
  7690. */
  7691. function throwError(msg) {
  7692. throw new Error(msg);
  7693. }
  7694. function interpolateNumber$1(p0, p1, percent) {
  7695. return (p1 - p0) * percent + p0;
  7696. }
  7697. /**
  7698. * Make the name displayable. But we should
  7699. * make sure it is not duplicated with user
  7700. * specified name, so use '\0';
  7701. */
  7702. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7703. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7704. /**
  7705. * If value is not array, then translate it to array.
  7706. * @param {*} value
  7707. * @return {Array} [value] or value
  7708. */
  7709. function normalizeToArray(value) {
  7710. return value instanceof Array ? value : value == null ? [] : [value];
  7711. }
  7712. /**
  7713. * Sync default option between normal and emphasis like `position` and `show`
  7714. * In case some one will write code like
  7715. * label: {
  7716. * show: false,
  7717. * position: 'outside',
  7718. * fontSize: 18
  7719. * },
  7720. * emphasis: {
  7721. * label: { show: true }
  7722. * }
  7723. */
  7724. function defaultEmphasis(opt, key, subOpts) {
  7725. // Caution: performance sensitive.
  7726. if (opt) {
  7727. opt[key] = opt[key] || {};
  7728. opt.emphasis = opt.emphasis || {};
  7729. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7730. for (var i = 0, len = subOpts.length; i < len; i++) {
  7731. var subOptName = subOpts[i];
  7732. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7733. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7734. }
  7735. }
  7736. }
  7737. }
  7738. 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([
  7739. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7740. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7741. // // FIXME: deprecated, check and remove it.
  7742. // 'textStyle'
  7743. // ]);
  7744. /**
  7745. * The method do not ensure performance.
  7746. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7747. * This helper method retieves value from data.
  7748. */
  7749. function getDataItemValue(dataItem) {
  7750. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7751. }
  7752. /**
  7753. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7754. * This helper method determine if dataItem has extra option besides value
  7755. */
  7756. function isDataItemOption(dataItem) {
  7757. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7758. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7759. }
  7760. /**
  7761. * Mapping to existings for merge.
  7762. *
  7763. * Mode "normalMege":
  7764. * The mapping result (merge result) will keep the order of the existing
  7765. * component, rather than the order of new option. Because we should ensure
  7766. * some specified index reference (like xAxisIndex) keep work.
  7767. * And in most cases, "merge option" is used to update partial option but not
  7768. * be expected to change the order.
  7769. *
  7770. * Mode "replaceMege":
  7771. * (1) Only the id mapped components will be merged.
  7772. * (2) Other existing components (except internal compoonets) will be removed.
  7773. * (3) Other new options will be used to create new component.
  7774. * (4) The index of the existing compoents will not be modified.
  7775. * That means their might be "hole" after the removal.
  7776. * The new components are created first at those available index.
  7777. *
  7778. * Mode "replaceAll":
  7779. * This mode try to support that reproduce an echarts instance from another
  7780. * echarts instance (via `getOption`) in some simple cases.
  7781. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7782. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7783. * the "hole" in `newCmptOptions` will also be kept.
  7784. * On the contrary, other modes try best to eliminate holes.
  7785. * PENDING: This is an experimental mode yet.
  7786. *
  7787. * @return See the comment of <MappingResult>.
  7788. */
  7789. function mappingToExists(existings, newCmptOptions, mode) {
  7790. var isNormalMergeMode = mode === 'normalMerge';
  7791. var isReplaceMergeMode = mode === 'replaceMerge';
  7792. var isReplaceAllMode = mode === 'replaceAll';
  7793. existings = existings || [];
  7794. newCmptOptions = (newCmptOptions || []).slice();
  7795. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7796. each(newCmptOptions, function (cmptOption, index) {
  7797. if (!isObject(cmptOption)) {
  7798. newCmptOptions[index] = null;
  7799. return;
  7800. }
  7801. if ("development" !== 'production') {
  7802. // There is some legacy case that name is set as `false`.
  7803. // But should work normally rather than throw error.
  7804. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7805. warnInvalidateIdOrName(cmptOption.id);
  7806. }
  7807. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7808. warnInvalidateIdOrName(cmptOption.name);
  7809. }
  7810. }
  7811. });
  7812. var result = prepareResult(existings, existingIdIdxMap, mode);
  7813. if (isNormalMergeMode || isReplaceMergeMode) {
  7814. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7815. }
  7816. if (isNormalMergeMode) {
  7817. mappingByName(result, newCmptOptions);
  7818. }
  7819. if (isNormalMergeMode || isReplaceMergeMode) {
  7820. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7821. } else if (isReplaceAllMode) {
  7822. mappingInReplaceAllMode(result, newCmptOptions);
  7823. }
  7824. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7825. // forEach will ommit those items and result in incorrect result.
  7826. return result;
  7827. }
  7828. function prepareResult(existings, existingIdIdxMap, mode) {
  7829. var result = [];
  7830. if (mode === 'replaceAll') {
  7831. return result;
  7832. } // Do not use native `map` to in case that the array `existings`
  7833. // contains elided items, which will be ommited.
  7834. for (var index = 0; index < existings.length; index++) {
  7835. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7836. if (existing && existing.id != null) {
  7837. existingIdIdxMap.set(existing.id, index);
  7838. } // For non-internal-componnets:
  7839. // Mode "normalMerge": all existings kept.
  7840. // Mode "replaceMerge": all existing removed unless mapped by id.
  7841. // For internal-components:
  7842. // go with "replaceMerge" approach in both mode.
  7843. result.push({
  7844. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7845. newOption: null,
  7846. keyInfo: null,
  7847. brandNew: null
  7848. });
  7849. }
  7850. return result;
  7851. }
  7852. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7853. // Mapping by id if specified.
  7854. each(newCmptOptions, function (cmptOption, index) {
  7855. if (!cmptOption || cmptOption.id == null) {
  7856. return;
  7857. }
  7858. var optionId = makeComparableKey(cmptOption.id);
  7859. var existingIdx = existingIdIdxMap.get(optionId);
  7860. if (existingIdx != null) {
  7861. var resultItem = result[existingIdx];
  7862. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7863. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7864. // the existings rather than creating new component model.
  7865. resultItem.existing = existings[existingIdx];
  7866. newCmptOptions[index] = null;
  7867. }
  7868. });
  7869. }
  7870. function mappingByName(result, newCmptOptions) {
  7871. // Mapping by name if specified.
  7872. each(newCmptOptions, function (cmptOption, index) {
  7873. if (!cmptOption || cmptOption.name == null) {
  7874. return;
  7875. }
  7876. for (var i = 0; i < result.length; i++) {
  7877. var existing = result[i].existing;
  7878. if (!result[i].newOption // Consider name: two map to one.
  7879. // Can not match when both ids existing but different.
  7880. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7881. result[i].newOption = cmptOption;
  7882. newCmptOptions[index] = null;
  7883. return;
  7884. }
  7885. }
  7886. });
  7887. }
  7888. function mappingByIndex(result, newCmptOptions, brandNew) {
  7889. each(newCmptOptions, function (cmptOption) {
  7890. if (!cmptOption) {
  7891. return;
  7892. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7893. var resultItem;
  7894. var nextIdx = 0;
  7895. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7896. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7897. // after mapping performed, model will always be assigned with an id if user not given.
  7898. // After that all models have id.
  7899. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7900. // not be merged to the existings with different id. Because id should not be overwritten.
  7901. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7902. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7903. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7904. nextIdx++;
  7905. }
  7906. if (resultItem) {
  7907. resultItem.newOption = cmptOption;
  7908. resultItem.brandNew = brandNew;
  7909. } else {
  7910. result.push({
  7911. newOption: cmptOption,
  7912. brandNew: brandNew,
  7913. existing: null,
  7914. keyInfo: null
  7915. });
  7916. }
  7917. nextIdx++;
  7918. });
  7919. }
  7920. function mappingInReplaceAllMode(result, newCmptOptions) {
  7921. each(newCmptOptions, function (cmptOption) {
  7922. // The feature "reproduce" requires "hole" will also reproduced
  7923. // in case that compoennt index referring are broken.
  7924. result.push({
  7925. newOption: cmptOption,
  7926. brandNew: true,
  7927. existing: null,
  7928. keyInfo: null
  7929. });
  7930. });
  7931. }
  7932. /**
  7933. * Make id and name for mapping result (result of mappingToExists)
  7934. * into `keyInfo` field.
  7935. */
  7936. function makeIdAndName(mapResult) {
  7937. // We use this id to hash component models and view instances
  7938. // in echarts. id can be specified by user, or auto generated.
  7939. // The id generation rule ensures new view instance are able
  7940. // to mapped to old instance when setOption are called in
  7941. // no-merge mode. So we generate model id by name and plus
  7942. // type in view id.
  7943. // name can be duplicated among components, which is convenient
  7944. // to specify multi components (like series) by one name.
  7945. // Ensure that each id is distinct.
  7946. var idMap = createHashMap();
  7947. each(mapResult, function (item) {
  7948. var existing = item.existing;
  7949. existing && idMap.set(existing.id, item);
  7950. });
  7951. each(mapResult, function (item) {
  7952. var opt = item.newOption; // Force ensure id not duplicated.
  7953. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7954. opt && opt.id != null && idMap.set(opt.id, item);
  7955. !item.keyInfo && (item.keyInfo = {});
  7956. }); // Make name and id.
  7957. each(mapResult, function (item, index) {
  7958. var existing = item.existing;
  7959. var opt = item.newOption;
  7960. var keyInfo = item.keyInfo;
  7961. if (!isObject(opt)) {
  7962. return;
  7963. } // name can be overwitten. Consider case: axis.name = '20km'.
  7964. // But id generated by name will not be changed, which affect
  7965. // only in that case: setOption with 'not merge mode' and view
  7966. // instance will be recreated, which can be accepted.
  7967. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7968. // because name may be used like in color pallet.
  7969. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7970. if (existing) {
  7971. keyInfo.id = makeComparableKey(existing.id);
  7972. } else if (opt.id != null) {
  7973. keyInfo.id = makeComparableKey(opt.id);
  7974. } else {
  7975. // Consider this situatoin:
  7976. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7977. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7978. // Series with the same name between optionA and optionB
  7979. // should be mapped.
  7980. var idNum = 0;
  7981. do {
  7982. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7983. } while (idMap.get(keyInfo.id));
  7984. }
  7985. idMap.set(keyInfo.id, item);
  7986. });
  7987. }
  7988. function keyExistAndEqual(attr, obj1, obj2) {
  7989. var key1 = convertOptionIdName(obj1[attr], null);
  7990. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7991. return key1 != null && key2 != null && key1 === key2;
  7992. }
  7993. /**
  7994. * @return return null if not exist.
  7995. */
  7996. function makeComparableKey(val) {
  7997. if ("development" !== 'production') {
  7998. if (val == null) {
  7999. throw new Error();
  8000. }
  8001. }
  8002. return convertOptionIdName(val, '');
  8003. }
  8004. function convertOptionIdName(idOrName, defaultValue) {
  8005. if (idOrName == null) {
  8006. return defaultValue;
  8007. }
  8008. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8009. }
  8010. function warnInvalidateIdOrName(idOrName) {
  8011. if ("development" !== 'production') {
  8012. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8013. }
  8014. }
  8015. function isValidIdOrName(idOrName) {
  8016. return isStringSafe(idOrName) || isNumeric(idOrName);
  8017. }
  8018. function isNameSpecified(componentModel) {
  8019. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  8020. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8021. }
  8022. /**
  8023. * @public
  8024. * @param {Object} cmptOption
  8025. * @return {boolean}
  8026. */
  8027. function isComponentIdInternal(cmptOption) {
  8028. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8029. }
  8030. function makeInternalComponentId(idSuffix) {
  8031. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8032. }
  8033. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8034. // Set mainType and complete subType.
  8035. each(mappingResult, function (item) {
  8036. var newOption = item.newOption;
  8037. if (isObject(newOption)) {
  8038. item.keyInfo.mainType = mainType;
  8039. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8040. }
  8041. });
  8042. }
  8043. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8044. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  8045. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  8046. return subType;
  8047. }
  8048. /**
  8049. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8050. * each of which can be Array or primary type.
  8051. * @return dataIndex If not found, return undefined/null.
  8052. */
  8053. function queryDataIndex(data, payload) {
  8054. if (payload.dataIndexInside != null) {
  8055. return payload.dataIndexInside;
  8056. } else if (payload.dataIndex != null) {
  8057. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8058. return data.indexOfRawIndex(value);
  8059. }) : data.indexOfRawIndex(payload.dataIndex);
  8060. } else if (payload.name != null) {
  8061. return isArray(payload.name) ? map(payload.name, function (value) {
  8062. return data.indexOfName(value);
  8063. }) : data.indexOfName(payload.name);
  8064. }
  8065. }
  8066. /**
  8067. * Enable property storage to any host object.
  8068. * Notice: Serialization is not supported.
  8069. *
  8070. * For example:
  8071. * let inner = zrUitl.makeInner();
  8072. *
  8073. * function some1(hostObj) {
  8074. * inner(hostObj).someProperty = 1212;
  8075. * ...
  8076. * }
  8077. * function some2() {
  8078. * let fields = inner(this);
  8079. * fields.someProperty1 = 1212;
  8080. * fields.someProperty2 = 'xx';
  8081. * ...
  8082. * }
  8083. *
  8084. * @return {Function}
  8085. */
  8086. function makeInner() {
  8087. var key = '__ec_inner_' + innerUniqueIndex++;
  8088. return function (hostObj) {
  8089. return hostObj[key] || (hostObj[key] = {});
  8090. };
  8091. }
  8092. var innerUniqueIndex = getRandomIdBase();
  8093. /**
  8094. * The same behavior as `component.getReferringComponents`.
  8095. */
  8096. function parseFinder(ecModel, finderInput, opt) {
  8097. var _a = preParseFinder(finderInput, opt),
  8098. mainTypeSpecified = _a.mainTypeSpecified,
  8099. queryOptionMap = _a.queryOptionMap,
  8100. others = _a.others;
  8101. var result = others;
  8102. var defaultMainType = opt ? opt.defaultMainType : null;
  8103. if (!mainTypeSpecified && defaultMainType) {
  8104. queryOptionMap.set(defaultMainType, {});
  8105. }
  8106. queryOptionMap.each(function (queryOption, mainType) {
  8107. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8108. useDefault: defaultMainType === mainType,
  8109. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8110. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8111. });
  8112. result[mainType + 'Models'] = queryResult.models;
  8113. result[mainType + 'Model'] = queryResult.models[0];
  8114. });
  8115. return result;
  8116. }
  8117. function preParseFinder(finderInput, opt) {
  8118. var finder;
  8119. if (isString(finderInput)) {
  8120. var obj = {};
  8121. obj[finderInput + 'Index'] = 0;
  8122. finder = obj;
  8123. } else {
  8124. finder = finderInput;
  8125. }
  8126. var queryOptionMap = createHashMap();
  8127. var others = {};
  8128. var mainTypeSpecified = false;
  8129. each(finder, function (value, key) {
  8130. // Exclude 'dataIndex' and other illgal keys.
  8131. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8132. others[key] = value;
  8133. return;
  8134. }
  8135. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8136. var mainType = parsedKey[1];
  8137. var queryType = (parsedKey[2] || '').toLowerCase();
  8138. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8139. return;
  8140. }
  8141. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8142. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8143. queryOption[queryType] = value;
  8144. });
  8145. return {
  8146. mainTypeSpecified: mainTypeSpecified,
  8147. queryOptionMap: queryOptionMap,
  8148. others: others
  8149. };
  8150. }
  8151. var SINGLE_REFERRING = {
  8152. useDefault: true,
  8153. enableAll: false,
  8154. enableNone: false
  8155. };
  8156. var MULTIPLE_REFERRING = {
  8157. useDefault: false,
  8158. enableAll: true,
  8159. enableNone: true
  8160. };
  8161. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8162. opt = opt || SINGLE_REFERRING;
  8163. var indexOption = userOption.index;
  8164. var idOption = userOption.id;
  8165. var nameOption = userOption.name;
  8166. var result = {
  8167. models: null,
  8168. specified: indexOption != null || idOption != null || nameOption != null
  8169. };
  8170. if (!result.specified) {
  8171. // Use the first as default if `useDefault`.
  8172. var firstCmpt = void 0;
  8173. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8174. return result;
  8175. }
  8176. if (indexOption === 'none' || indexOption === false) {
  8177. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8178. result.models = [];
  8179. return result;
  8180. } // `queryComponents` will return all components if
  8181. // both all of index/id/name are null/undefined.
  8182. if (indexOption === 'all') {
  8183. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8184. indexOption = idOption = nameOption = null;
  8185. }
  8186. result.models = ecModel.queryComponents({
  8187. mainType: mainType,
  8188. index: indexOption,
  8189. id: idOption,
  8190. name: nameOption
  8191. });
  8192. return result;
  8193. }
  8194. function setAttribute(dom, key, value) {
  8195. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8196. }
  8197. function getAttribute(dom, key) {
  8198. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8199. }
  8200. function getTooltipRenderMode(renderModeOption) {
  8201. if (renderModeOption === 'auto') {
  8202. // Using html when `document` exists, use richText otherwise
  8203. return env.domSupported ? 'html' : 'richText';
  8204. } else {
  8205. return renderModeOption || 'html';
  8206. }
  8207. }
  8208. /**
  8209. * Interpolate raw values of a series with percent
  8210. *
  8211. * @param data data
  8212. * @param labelModel label model of the text element
  8213. * @param sourceValue start value. May be null/undefined when init.
  8214. * @param targetValue end value
  8215. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8216. * @return interpolated values
  8217. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8218. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8219. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8220. * Other cases do not supported.
  8221. */
  8222. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8223. var isAutoPrecision = precision == null || precision === 'auto';
  8224. if (targetValue == null) {
  8225. return targetValue;
  8226. }
  8227. if (isNumber(targetValue)) {
  8228. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8229. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8230. } else if (isString(targetValue)) {
  8231. return percent < 1 ? sourceValue : targetValue;
  8232. } else {
  8233. var interpolated = [];
  8234. var leftArr = sourceValue;
  8235. var rightArr = targetValue;
  8236. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8237. for (var i = 0; i < length_1; ++i) {
  8238. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8239. if (info && info.type === 'ordinal') {
  8240. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8241. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8242. } else {
  8243. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8244. var rightVal = rightArr[i];
  8245. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8246. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8247. }
  8248. }
  8249. return interpolated;
  8250. }
  8251. }
  8252. var TYPE_DELIMITER = '.';
  8253. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8254. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8255. /**
  8256. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8257. * @public
  8258. */
  8259. function parseClassType(componentType) {
  8260. var ret = {
  8261. main: '',
  8262. sub: ''
  8263. };
  8264. if (componentType) {
  8265. var typeArr = componentType.split(TYPE_DELIMITER);
  8266. ret.main = typeArr[0] || '';
  8267. ret.sub = typeArr[1] || '';
  8268. }
  8269. return ret;
  8270. }
  8271. /**
  8272. * @public
  8273. */
  8274. function checkClassType(componentType) {
  8275. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8276. }
  8277. function isExtendedClass(clz) {
  8278. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8279. }
  8280. /**
  8281. * Implements `ExtendableConstructor` for `rootClz`.
  8282. *
  8283. * @usage
  8284. * ```ts
  8285. * class Xxx {}
  8286. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8287. * enableClassExtend(Xxx as XxxConstructor);
  8288. * ```
  8289. */
  8290. function enableClassExtend(rootClz, mandatoryMethods) {
  8291. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8292. rootClz.extend = function (proto) {
  8293. if ("development" !== 'production') {
  8294. each(mandatoryMethods, function (method) {
  8295. if (!proto[method]) {
  8296. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8297. }
  8298. });
  8299. }
  8300. var superClass = this;
  8301. var ExtendedClass;
  8302. if (isESClass(superClass)) {
  8303. ExtendedClass =
  8304. /** @class */
  8305. function (_super) {
  8306. __extends(class_1, _super);
  8307. function class_1() {
  8308. return _super.apply(this, arguments) || this;
  8309. }
  8310. return class_1;
  8311. }(superClass);
  8312. } else {
  8313. // For backward compat, we both support ts class inheritance and this
  8314. // "extend" approach.
  8315. // The constructor should keep the same behavior as ts class inheritance:
  8316. // If this constructor/$constructor is not declared, auto invoke the super
  8317. // constructor.
  8318. // If this constructor/$constructor is declared, it is responsible for
  8319. // calling the super constructor.
  8320. ExtendedClass = function () {
  8321. (proto.$constructor || superClass).apply(this, arguments);
  8322. };
  8323. inherits(ExtendedClass, this);
  8324. }
  8325. extend(ExtendedClass.prototype, proto);
  8326. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8327. ExtendedClass.extend = this.extend;
  8328. ExtendedClass.superCall = superCall;
  8329. ExtendedClass.superApply = superApply;
  8330. ExtendedClass.superClass = superClass;
  8331. return ExtendedClass;
  8332. };
  8333. }
  8334. function isESClass(fn) {
  8335. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8336. }
  8337. /**
  8338. * A work around to both support ts extend and this extend mechanism.
  8339. * on sub-class.
  8340. * @usage
  8341. * ```ts
  8342. * class Component { ... }
  8343. * classUtil.enableClassExtend(Component);
  8344. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8345. *
  8346. * class Series extends Component { ... }
  8347. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8348. * Component.markExtend(Series);
  8349. * ```
  8350. */
  8351. function mountExtend(SubClz, SupperClz) {
  8352. SubClz.extend = SupperClz.extend;
  8353. } // A random offset.
  8354. var classBase = Math.round(Math.random() * 10);
  8355. /**
  8356. * Implements `CheckableConstructor` for `target`.
  8357. * Can not use instanceof, consider different scope by
  8358. * cross domain or es module import in ec extensions.
  8359. * Mount a method "isInstance()" to Clz.
  8360. *
  8361. * @usage
  8362. * ```ts
  8363. * class Xxx {}
  8364. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8365. * enableClassCheck(Xxx as XxxConstructor)
  8366. * ```
  8367. */
  8368. function enableClassCheck(target) {
  8369. var classAttr = ['__\0is_clz', classBase++].join('_');
  8370. target.prototype[classAttr] = true;
  8371. if ("development" !== 'production') {
  8372. assert(!target.isInstance, 'The method "is" can not be defined.');
  8373. }
  8374. target.isInstance = function (obj) {
  8375. return !!(obj && obj[classAttr]);
  8376. };
  8377. } // superCall should have class info, which can not be fetch from 'this'.
  8378. // Consider this case:
  8379. // class A has method f,
  8380. // class B inherits class A, overrides method f, f call superApply('f'),
  8381. // class C inherits class B, do not overrides method f,
  8382. // then when method of class C is called, dead loop occured.
  8383. function superCall(context, methodName) {
  8384. var args = [];
  8385. for (var _i = 2; _i < arguments.length; _i++) {
  8386. args[_i - 2] = arguments[_i];
  8387. }
  8388. return this.superClass.prototype[methodName].apply(context, args);
  8389. }
  8390. function superApply(context, methodName, args) {
  8391. return this.superClass.prototype[methodName].apply(context, args);
  8392. }
  8393. /**
  8394. * Implements `ClassManager` for `target`
  8395. *
  8396. * @usage
  8397. * ```ts
  8398. * class Xxx {}
  8399. * type XxxConstructor = typeof Xxx & ClassManager
  8400. * enableClassManagement(Xxx as XxxConstructor);
  8401. * ```
  8402. */
  8403. function enableClassManagement(target) {
  8404. /**
  8405. * Component model classes
  8406. * key: componentType,
  8407. * value:
  8408. * componentClass, when componentType is 'xxx'
  8409. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  8410. */
  8411. var storage = {};
  8412. target.registerClass = function (clz) {
  8413. // `type` should not be a "instance memeber".
  8414. // If using TS class, should better declared as `static type = 'series.pie'`.
  8415. // otherwise users have to mount `type` on prototype manually.
  8416. // For backward compat and enable instance visit type via `this.type`,
  8417. // we stil support fetch `type` from prototype.
  8418. var componentFullType = clz.type || clz.prototype.type;
  8419. if (componentFullType) {
  8420. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8421. clz.prototype.type = componentFullType;
  8422. var componentTypeInfo = parseClassType(componentFullType);
  8423. if (!componentTypeInfo.sub) {
  8424. if ("development" !== 'production') {
  8425. if (storage[componentTypeInfo.main]) {
  8426. console.warn(componentTypeInfo.main + ' exists.');
  8427. }
  8428. }
  8429. storage[componentTypeInfo.main] = clz;
  8430. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8431. var container = makeContainer(componentTypeInfo);
  8432. container[componentTypeInfo.sub] = clz;
  8433. }
  8434. }
  8435. return clz;
  8436. };
  8437. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8438. var clz = storage[mainType];
  8439. if (clz && clz[IS_CONTAINER]) {
  8440. clz = subType ? clz[subType] : null;
  8441. }
  8442. if (throwWhenNotFound && !clz) {
  8443. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8444. }
  8445. return clz;
  8446. };
  8447. target.getClassesByMainType = function (componentType) {
  8448. var componentTypeInfo = parseClassType(componentType);
  8449. var result = [];
  8450. var obj = storage[componentTypeInfo.main];
  8451. if (obj && obj[IS_CONTAINER]) {
  8452. each(obj, function (o, type) {
  8453. type !== IS_CONTAINER && result.push(o);
  8454. });
  8455. } else {
  8456. result.push(obj);
  8457. }
  8458. return result;
  8459. };
  8460. target.hasClass = function (componentType) {
  8461. // Just consider componentType.main.
  8462. var componentTypeInfo = parseClassType(componentType);
  8463. return !!storage[componentTypeInfo.main];
  8464. };
  8465. /**
  8466. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8467. */
  8468. target.getAllClassMainTypes = function () {
  8469. var types = [];
  8470. each(storage, function (obj, type) {
  8471. types.push(type);
  8472. });
  8473. return types;
  8474. };
  8475. /**
  8476. * If a main type is container and has sub types
  8477. */
  8478. target.hasSubTypes = function (componentType) {
  8479. var componentTypeInfo = parseClassType(componentType);
  8480. var obj = storage[componentTypeInfo.main];
  8481. return obj && obj[IS_CONTAINER];
  8482. };
  8483. function makeContainer(componentTypeInfo) {
  8484. var container = storage[componentTypeInfo.main];
  8485. if (!container || !container[IS_CONTAINER]) {
  8486. container = storage[componentTypeInfo.main] = {};
  8487. container[IS_CONTAINER] = true;
  8488. }
  8489. return container;
  8490. }
  8491. } // /**
  8492. // * @param {string|Array.<string>} properties
  8493. // */
  8494. // export function setReadOnly(obj, properties) {
  8495. // FIXME It seems broken in IE8 simulation of IE11
  8496. // if (!zrUtil.isArray(properties)) {
  8497. // properties = properties != null ? [properties] : [];
  8498. // }
  8499. // zrUtil.each(properties, function (prop) {
  8500. // let value = obj[prop];
  8501. // Object.defineProperty
  8502. // && Object.defineProperty(obj, prop, {
  8503. // value: value, writable: false
  8504. // });
  8505. // zrUtil.isArray(obj[prop])
  8506. // && Object.freeze
  8507. // && Object.freeze(obj[prop]);
  8508. // });
  8509. // }
  8510. function makeStyleMapper(properties, ignoreParent) {
  8511. // Normalize
  8512. for (var i = 0; i < properties.length; i++) {
  8513. if (!properties[i][1]) {
  8514. properties[i][1] = properties[i][0];
  8515. }
  8516. }
  8517. ignoreParent = ignoreParent || false;
  8518. return function (model, excludes, includes) {
  8519. var style = {};
  8520. for (var i = 0; i < properties.length; i++) {
  8521. var propName = properties[i][1];
  8522. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8523. continue;
  8524. }
  8525. var val = model.getShallow(propName, ignoreParent);
  8526. if (val != null) {
  8527. style[properties[i][0]] = val;
  8528. }
  8529. } // TODO Text or image?
  8530. return style;
  8531. };
  8532. }
  8533. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8534. // So do not transfer decal directly.
  8535. ];
  8536. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8537. var AreaStyleMixin =
  8538. /** @class */
  8539. function () {
  8540. function AreaStyleMixin() {}
  8541. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8542. return getAreaStyle(this, excludes, includes);
  8543. };
  8544. return AreaStyleMixin;
  8545. }();
  8546. var globalImageCache = new LRU(50);
  8547. function findExistImage(newImageOrSrc) {
  8548. if (typeof newImageOrSrc === 'string') {
  8549. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8550. return cachedImgObj && cachedImgObj.image;
  8551. }
  8552. else {
  8553. return newImageOrSrc;
  8554. }
  8555. }
  8556. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8557. if (!newImageOrSrc) {
  8558. return image;
  8559. }
  8560. else if (typeof newImageOrSrc === 'string') {
  8561. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8562. return image;
  8563. }
  8564. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8565. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8566. if (cachedImgObj) {
  8567. image = cachedImgObj.image;
  8568. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8569. }
  8570. else {
  8571. var image_1 = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8572. image_1.__zrImageSrc = newImageOrSrc;
  8573. globalImageCache.put(newImageOrSrc, image_1.__cachedImgObj = {
  8574. image: image_1,
  8575. pending: [pendingWrap]
  8576. });
  8577. }
  8578. return image;
  8579. }
  8580. else {
  8581. return newImageOrSrc;
  8582. }
  8583. }
  8584. function imageOnLoad() {
  8585. var cachedImgObj = this.__cachedImgObj;
  8586. this.onload = this.onerror = this.__cachedImgObj = null;
  8587. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8588. var pendingWrap = cachedImgObj.pending[i];
  8589. var cb = pendingWrap.cb;
  8590. cb && cb(this, pendingWrap.cbPayload);
  8591. pendingWrap.hostEl.dirty();
  8592. }
  8593. cachedImgObj.pending.length = 0;
  8594. }
  8595. function isImageReady(image) {
  8596. return image && image.width && image.height;
  8597. }
  8598. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8599. function truncateText(text, containerWidth, font, ellipsis, options) {
  8600. if (!containerWidth) {
  8601. return '';
  8602. }
  8603. var textLines = (text + '').split('\n');
  8604. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8605. for (var i = 0, len = textLines.length; i < len; i++) {
  8606. textLines[i] = truncateSingleLine(textLines[i], options);
  8607. }
  8608. return textLines.join('\n');
  8609. }
  8610. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8611. options = options || {};
  8612. var preparedOpts = extend({}, options);
  8613. preparedOpts.font = font;
  8614. ellipsis = retrieve2(ellipsis, '...');
  8615. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8616. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8617. preparedOpts.cnCharWidth = getWidth('国', font);
  8618. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8619. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8620. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8621. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8622. contentWidth -= ascCharWidth;
  8623. }
  8624. var ellipsisWidth = getWidth(ellipsis, font);
  8625. if (ellipsisWidth > contentWidth) {
  8626. ellipsis = '';
  8627. ellipsisWidth = 0;
  8628. }
  8629. contentWidth = containerWidth - ellipsisWidth;
  8630. preparedOpts.ellipsis = ellipsis;
  8631. preparedOpts.ellipsisWidth = ellipsisWidth;
  8632. preparedOpts.contentWidth = contentWidth;
  8633. preparedOpts.containerWidth = containerWidth;
  8634. return preparedOpts;
  8635. }
  8636. function truncateSingleLine(textLine, options) {
  8637. var containerWidth = options.containerWidth;
  8638. var font = options.font;
  8639. var contentWidth = options.contentWidth;
  8640. if (!containerWidth) {
  8641. return '';
  8642. }
  8643. var lineWidth = getWidth(textLine, font);
  8644. if (lineWidth <= containerWidth) {
  8645. return textLine;
  8646. }
  8647. for (var j = 0;; j++) {
  8648. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8649. textLine += options.ellipsis;
  8650. break;
  8651. }
  8652. var subLength = j === 0
  8653. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8654. : lineWidth > 0
  8655. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8656. : 0;
  8657. textLine = textLine.substr(0, subLength);
  8658. lineWidth = getWidth(textLine, font);
  8659. }
  8660. if (textLine === '') {
  8661. textLine = options.placeholder;
  8662. }
  8663. return textLine;
  8664. }
  8665. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8666. var width = 0;
  8667. var i = 0;
  8668. for (var len = text.length; i < len && width < contentWidth; i++) {
  8669. var charCode = text.charCodeAt(i);
  8670. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8671. }
  8672. return i;
  8673. }
  8674. function parsePlainText(text, style) {
  8675. text != null && (text += '');
  8676. var overflow = style.overflow;
  8677. var padding = style.padding;
  8678. var font = style.font;
  8679. var truncate = overflow === 'truncate';
  8680. var calculatedLineHeight = getLineHeight(font);
  8681. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8682. var bgColorDrawn = !!(style.backgroundColor);
  8683. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8684. var width = style.width;
  8685. var lines;
  8686. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8687. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8688. }
  8689. else {
  8690. lines = text ? text.split('\n') : [];
  8691. }
  8692. var contentHeight = lines.length * lineHeight;
  8693. var height = retrieve2(style.height, contentHeight);
  8694. if (contentHeight > height && truncateLineOverflow) {
  8695. var lineCount = Math.floor(height / lineHeight);
  8696. lines = lines.slice(0, lineCount);
  8697. }
  8698. if (text && truncate && width != null) {
  8699. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8700. minChar: style.truncateMinChar,
  8701. placeholder: style.placeholder
  8702. });
  8703. for (var i = 0; i < lines.length; i++) {
  8704. lines[i] = truncateSingleLine(lines[i], options);
  8705. }
  8706. }
  8707. var outerHeight = height;
  8708. var contentWidth = 0;
  8709. for (var i = 0; i < lines.length; i++) {
  8710. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8711. }
  8712. if (width == null) {
  8713. width = contentWidth;
  8714. }
  8715. var outerWidth = contentWidth;
  8716. if (padding) {
  8717. outerHeight += padding[0] + padding[2];
  8718. outerWidth += padding[1] + padding[3];
  8719. width += padding[1] + padding[3];
  8720. }
  8721. if (bgColorDrawn) {
  8722. outerWidth = width;
  8723. }
  8724. return {
  8725. lines: lines,
  8726. height: height,
  8727. outerWidth: outerWidth,
  8728. outerHeight: outerHeight,
  8729. lineHeight: lineHeight,
  8730. calculatedLineHeight: calculatedLineHeight,
  8731. contentWidth: contentWidth,
  8732. contentHeight: contentHeight,
  8733. width: width
  8734. };
  8735. }
  8736. var RichTextToken = (function () {
  8737. function RichTextToken() {
  8738. }
  8739. return RichTextToken;
  8740. }());
  8741. var RichTextLine = (function () {
  8742. function RichTextLine(tokens) {
  8743. this.tokens = [];
  8744. if (tokens) {
  8745. this.tokens = tokens;
  8746. }
  8747. }
  8748. return RichTextLine;
  8749. }());
  8750. var RichTextContentBlock = (function () {
  8751. function RichTextContentBlock() {
  8752. this.width = 0;
  8753. this.height = 0;
  8754. this.contentWidth = 0;
  8755. this.contentHeight = 0;
  8756. this.outerWidth = 0;
  8757. this.outerHeight = 0;
  8758. this.lines = [];
  8759. }
  8760. return RichTextContentBlock;
  8761. }());
  8762. function parseRichText(text, style) {
  8763. var contentBlock = new RichTextContentBlock();
  8764. text != null && (text += '');
  8765. if (!text) {
  8766. return contentBlock;
  8767. }
  8768. var topWidth = style.width;
  8769. var topHeight = style.height;
  8770. var overflow = style.overflow;
  8771. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8772. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8773. : null;
  8774. var lastIndex = STYLE_REG.lastIndex = 0;
  8775. var result;
  8776. while ((result = STYLE_REG.exec(text)) != null) {
  8777. var matchedIndex = result.index;
  8778. if (matchedIndex > lastIndex) {
  8779. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8780. }
  8781. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8782. lastIndex = STYLE_REG.lastIndex;
  8783. }
  8784. if (lastIndex < text.length) {
  8785. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8786. }
  8787. var pendingList = [];
  8788. var calculatedHeight = 0;
  8789. var calculatedWidth = 0;
  8790. var stlPadding = style.padding;
  8791. var truncate = overflow === 'truncate';
  8792. var truncateLine = style.lineOverflow === 'truncate';
  8793. function finishLine(line, lineWidth, lineHeight) {
  8794. line.width = lineWidth;
  8795. line.lineHeight = lineHeight;
  8796. calculatedHeight += lineHeight;
  8797. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8798. }
  8799. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8800. var line = contentBlock.lines[i];
  8801. var lineHeight = 0;
  8802. var lineWidth = 0;
  8803. for (var j = 0; j < line.tokens.length; j++) {
  8804. var token = line.tokens[j];
  8805. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8806. var textPadding = token.textPadding = tokenStyle.padding;
  8807. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8808. var font = token.font = tokenStyle.font || style.font;
  8809. token.contentHeight = getLineHeight(font);
  8810. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8811. token.innerHeight = tokenHeight;
  8812. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8813. token.height = tokenHeight;
  8814. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8815. token.align = tokenStyle && tokenStyle.align || style.align;
  8816. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8817. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8818. if (j > 0) {
  8819. line.tokens = line.tokens.slice(0, j);
  8820. finishLine(line, lineWidth, lineHeight);
  8821. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8822. }
  8823. else {
  8824. contentBlock.lines = contentBlock.lines.slice(0, i);
  8825. }
  8826. break outer;
  8827. }
  8828. var styleTokenWidth = tokenStyle.width;
  8829. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8830. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8831. token.percentWidth = styleTokenWidth;
  8832. pendingList.push(token);
  8833. token.contentWidth = getWidth(token.text, font);
  8834. }
  8835. else {
  8836. if (tokenWidthNotSpecified) {
  8837. var textBackgroundColor = tokenStyle.backgroundColor;
  8838. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8839. if (bgImg) {
  8840. bgImg = findExistImage(bgImg);
  8841. if (isImageReady(bgImg)) {
  8842. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8843. }
  8844. }
  8845. }
  8846. var remainTruncWidth = truncate && topWidth != null
  8847. ? topWidth - lineWidth : null;
  8848. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8849. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8850. token.text = '';
  8851. token.width = token.contentWidth = 0;
  8852. }
  8853. else {
  8854. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8855. token.width = token.contentWidth = getWidth(token.text, font);
  8856. }
  8857. }
  8858. else {
  8859. token.contentWidth = getWidth(token.text, font);
  8860. }
  8861. }
  8862. token.width += paddingH;
  8863. lineWidth += token.width;
  8864. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8865. }
  8866. finishLine(line, lineWidth, lineHeight);
  8867. }
  8868. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8869. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8870. contentBlock.contentHeight = calculatedHeight;
  8871. contentBlock.contentWidth = calculatedWidth;
  8872. if (stlPadding) {
  8873. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8874. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8875. }
  8876. for (var i = 0; i < pendingList.length; i++) {
  8877. var token = pendingList[i];
  8878. var percentWidth = token.percentWidth;
  8879. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8880. }
  8881. return contentBlock;
  8882. }
  8883. function pushTokens(block, str, style, wrapInfo, styleName) {
  8884. var isEmptyStr = str === '';
  8885. var tokenStyle = styleName && style.rich[styleName] || {};
  8886. var lines = block.lines;
  8887. var font = tokenStyle.font || style.font;
  8888. var newLine = false;
  8889. var strLines;
  8890. var linesWidths;
  8891. if (wrapInfo) {
  8892. var tokenPadding = tokenStyle.padding;
  8893. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8894. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8895. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8896. if (lines.length > 0) {
  8897. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8898. strLines = str.split('\n');
  8899. newLine = true;
  8900. }
  8901. }
  8902. wrapInfo.accumWidth = outerWidth_1;
  8903. }
  8904. else {
  8905. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8906. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8907. linesWidths = res.linesWidths;
  8908. strLines = res.lines;
  8909. }
  8910. }
  8911. else {
  8912. strLines = str.split('\n');
  8913. }
  8914. for (var i = 0; i < strLines.length; i++) {
  8915. var text = strLines[i];
  8916. var token = new RichTextToken();
  8917. token.styleName = styleName;
  8918. token.text = text;
  8919. token.isLineHolder = !text && !isEmptyStr;
  8920. if (typeof tokenStyle.width === 'number') {
  8921. token.width = tokenStyle.width;
  8922. }
  8923. else {
  8924. token.width = linesWidths
  8925. ? linesWidths[i]
  8926. : getWidth(text, font);
  8927. }
  8928. if (!i && !newLine) {
  8929. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8930. var tokensLen = tokens.length;
  8931. (tokensLen === 1 && tokens[0].isLineHolder)
  8932. ? (tokens[0] = token)
  8933. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8934. }
  8935. else {
  8936. lines.push(new RichTextLine([token]));
  8937. }
  8938. }
  8939. }
  8940. function isLatin(ch) {
  8941. var code = ch.charCodeAt(0);
  8942. return code >= 0x21 && code <= 0x17F;
  8943. }
  8944. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8945. obj[ch] = true;
  8946. return obj;
  8947. }, {});
  8948. function isWordBreakChar(ch) {
  8949. if (isLatin(ch)) {
  8950. if (breakCharMap[ch]) {
  8951. return true;
  8952. }
  8953. return false;
  8954. }
  8955. return true;
  8956. }
  8957. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8958. var lines = [];
  8959. var linesWidths = [];
  8960. var line = '';
  8961. var currentWord = '';
  8962. var currentWordWidth = 0;
  8963. var accumWidth = 0;
  8964. for (var i = 0; i < text.length; i++) {
  8965. var ch = text.charAt(i);
  8966. if (ch === '\n') {
  8967. if (currentWord) {
  8968. line += currentWord;
  8969. accumWidth += currentWordWidth;
  8970. }
  8971. lines.push(line);
  8972. linesWidths.push(accumWidth);
  8973. line = '';
  8974. currentWord = '';
  8975. currentWordWidth = 0;
  8976. accumWidth = 0;
  8977. continue;
  8978. }
  8979. var chWidth = getWidth(ch, font);
  8980. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8981. if (!lines.length
  8982. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8983. : accumWidth + chWidth > lineWidth) {
  8984. if (!accumWidth) {
  8985. if (inWord) {
  8986. lines.push(currentWord);
  8987. linesWidths.push(currentWordWidth);
  8988. currentWord = ch;
  8989. currentWordWidth = chWidth;
  8990. }
  8991. else {
  8992. lines.push(ch);
  8993. linesWidths.push(chWidth);
  8994. }
  8995. }
  8996. else if (line || currentWord) {
  8997. if (inWord) {
  8998. if (!line) {
  8999. line = currentWord;
  9000. currentWord = '';
  9001. currentWordWidth = 0;
  9002. accumWidth = currentWordWidth;
  9003. }
  9004. lines.push(line);
  9005. linesWidths.push(accumWidth - currentWordWidth);
  9006. currentWord += ch;
  9007. currentWordWidth += chWidth;
  9008. line = '';
  9009. accumWidth = currentWordWidth;
  9010. }
  9011. else {
  9012. if (currentWord) {
  9013. line += currentWord;
  9014. currentWord = '';
  9015. currentWordWidth = 0;
  9016. }
  9017. lines.push(line);
  9018. linesWidths.push(accumWidth);
  9019. line = ch;
  9020. accumWidth = chWidth;
  9021. }
  9022. }
  9023. continue;
  9024. }
  9025. accumWidth += chWidth;
  9026. if (inWord) {
  9027. currentWord += ch;
  9028. currentWordWidth += chWidth;
  9029. }
  9030. else {
  9031. if (currentWord) {
  9032. line += currentWord;
  9033. currentWord = '';
  9034. currentWordWidth = 0;
  9035. }
  9036. line += ch;
  9037. }
  9038. }
  9039. if (!lines.length && !line) {
  9040. line = text;
  9041. currentWord = '';
  9042. currentWordWidth = 0;
  9043. }
  9044. if (currentWord) {
  9045. line += currentWord;
  9046. }
  9047. if (line) {
  9048. lines.push(line);
  9049. linesWidths.push(accumWidth);
  9050. }
  9051. if (lines.length === 1) {
  9052. accumWidth += lastAccumWidth;
  9053. }
  9054. return {
  9055. accumWidth: accumWidth,
  9056. lines: lines,
  9057. linesWidths: linesWidths
  9058. };
  9059. }
  9060. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9061. var DEFAULT_COMMON_STYLE = {
  9062. shadowBlur: 0,
  9063. shadowOffsetX: 0,
  9064. shadowOffsetY: 0,
  9065. shadowColor: '#000',
  9066. opacity: 1,
  9067. blend: 'source-over'
  9068. };
  9069. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9070. style: {
  9071. shadowBlur: true,
  9072. shadowOffsetX: true,
  9073. shadowOffsetY: true,
  9074. shadowColor: true,
  9075. opacity: true
  9076. }
  9077. };
  9078. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9079. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9080. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9081. var Displayable = (function (_super) {
  9082. __extends(Displayable, _super);
  9083. function Displayable(props) {
  9084. return _super.call(this, props) || this;
  9085. }
  9086. Displayable.prototype._init = function (props) {
  9087. var keysArr = keys(props);
  9088. for (var i = 0; i < keysArr.length; i++) {
  9089. var key = keysArr[i];
  9090. if (key === 'style') {
  9091. this.useStyle(props[key]);
  9092. }
  9093. else {
  9094. _super.prototype.attrKV.call(this, key, props[key]);
  9095. }
  9096. }
  9097. if (!this.style) {
  9098. this.useStyle({});
  9099. }
  9100. };
  9101. Displayable.prototype.beforeBrush = function () { };
  9102. Displayable.prototype.afterBrush = function () { };
  9103. Displayable.prototype.innerBeforeBrush = function () { };
  9104. Displayable.prototype.innerAfterBrush = function () { };
  9105. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9106. var m = this.transform;
  9107. if (this.ignore
  9108. || this.invisible
  9109. || this.style.opacity === 0
  9110. || (this.culling
  9111. && isDisplayableCulled(this, viewWidth, viewHeight))
  9112. || (m && !m[0] && !m[3])) {
  9113. return false;
  9114. }
  9115. if (considerClipPath && this.__clipPaths) {
  9116. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9117. if (this.__clipPaths[i].isZeroArea()) {
  9118. return false;
  9119. }
  9120. }
  9121. }
  9122. if (considerAncestors && this.parent) {
  9123. var parent_1 = this.parent;
  9124. while (parent_1) {
  9125. if (parent_1.ignore) {
  9126. return false;
  9127. }
  9128. parent_1 = parent_1.parent;
  9129. }
  9130. }
  9131. return true;
  9132. };
  9133. Displayable.prototype.contain = function (x, y) {
  9134. return this.rectContain(x, y);
  9135. };
  9136. Displayable.prototype.traverse = function (cb, context) {
  9137. cb.call(context, this);
  9138. };
  9139. Displayable.prototype.rectContain = function (x, y) {
  9140. var coord = this.transformCoordToLocal(x, y);
  9141. var rect = this.getBoundingRect();
  9142. return rect.contain(coord[0], coord[1]);
  9143. };
  9144. Displayable.prototype.getPaintRect = function () {
  9145. var rect = this._paintRect;
  9146. if (!this._paintRect || this.__dirty) {
  9147. var transform = this.transform;
  9148. var elRect = this.getBoundingRect();
  9149. var style = this.style;
  9150. var shadowSize = style.shadowBlur || 0;
  9151. var shadowOffsetX = style.shadowOffsetX || 0;
  9152. var shadowOffsetY = style.shadowOffsetY || 0;
  9153. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9154. if (transform) {
  9155. BoundingRect.applyTransform(rect, elRect, transform);
  9156. }
  9157. else {
  9158. rect.copy(elRect);
  9159. }
  9160. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9161. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9162. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9163. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9164. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9165. }
  9166. var tolerance = this.dirtyRectTolerance;
  9167. if (!rect.isZero()) {
  9168. rect.x = Math.floor(rect.x - tolerance);
  9169. rect.y = Math.floor(rect.y - tolerance);
  9170. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9171. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9172. }
  9173. }
  9174. return rect;
  9175. };
  9176. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9177. if (paintRect) {
  9178. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9179. this._prevPaintRect.copy(paintRect);
  9180. }
  9181. else {
  9182. this._prevPaintRect = null;
  9183. }
  9184. };
  9185. Displayable.prototype.getPrevPaintRect = function () {
  9186. return this._prevPaintRect;
  9187. };
  9188. Displayable.prototype.animateStyle = function (loop) {
  9189. return this.animate('style', loop);
  9190. };
  9191. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9192. if (targetKey === 'style') {
  9193. this.dirtyStyle();
  9194. }
  9195. else {
  9196. this.markRedraw();
  9197. }
  9198. };
  9199. Displayable.prototype.attrKV = function (key, value) {
  9200. if (key !== 'style') {
  9201. _super.prototype.attrKV.call(this, key, value);
  9202. }
  9203. else {
  9204. if (!this.style) {
  9205. this.useStyle(value);
  9206. }
  9207. else {
  9208. this.setStyle(value);
  9209. }
  9210. }
  9211. };
  9212. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9213. if (typeof keyOrObj === 'string') {
  9214. this.style[keyOrObj] = value;
  9215. }
  9216. else {
  9217. extend(this.style, keyOrObj);
  9218. }
  9219. this.dirtyStyle();
  9220. return this;
  9221. };
  9222. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9223. if (!notRedraw) {
  9224. this.markRedraw();
  9225. }
  9226. this.__dirty |= STYLE_CHANGED_BIT;
  9227. if (this._rect) {
  9228. this._rect = null;
  9229. }
  9230. };
  9231. Displayable.prototype.dirty = function () {
  9232. this.dirtyStyle();
  9233. };
  9234. Displayable.prototype.styleChanged = function () {
  9235. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9236. };
  9237. Displayable.prototype.styleUpdated = function () {
  9238. this.__dirty &= ~STYLE_CHANGED_BIT;
  9239. };
  9240. Displayable.prototype.createStyle = function (obj) {
  9241. return createObject(DEFAULT_COMMON_STYLE, obj);
  9242. };
  9243. Displayable.prototype.useStyle = function (obj) {
  9244. if (!obj[STYLE_MAGIC_KEY]) {
  9245. obj = this.createStyle(obj);
  9246. }
  9247. if (this.__inHover) {
  9248. this.__hoverStyle = obj;
  9249. }
  9250. else {
  9251. this.style = obj;
  9252. }
  9253. this.dirtyStyle();
  9254. };
  9255. Displayable.prototype.isStyleObject = function (obj) {
  9256. return obj[STYLE_MAGIC_KEY];
  9257. };
  9258. Displayable.prototype._innerSaveToNormal = function (toState) {
  9259. _super.prototype._innerSaveToNormal.call(this, toState);
  9260. var normalState = this._normalState;
  9261. if (toState.style && !normalState.style) {
  9262. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9263. }
  9264. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9265. };
  9266. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9267. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9268. var needsRestoreToNormal = !(state && keepCurrentStates);
  9269. var targetStyle;
  9270. if (state && state.style) {
  9271. if (transition) {
  9272. if (keepCurrentStates) {
  9273. targetStyle = state.style;
  9274. }
  9275. else {
  9276. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9277. this._mergeStyle(targetStyle, state.style);
  9278. }
  9279. }
  9280. else {
  9281. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9282. this._mergeStyle(targetStyle, state.style);
  9283. }
  9284. }
  9285. else if (needsRestoreToNormal) {
  9286. targetStyle = normalState.style;
  9287. }
  9288. if (targetStyle) {
  9289. if (transition) {
  9290. var sourceStyle = this.style;
  9291. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9292. if (needsRestoreToNormal) {
  9293. var changedKeys = keys(sourceStyle);
  9294. for (var i = 0; i < changedKeys.length; i++) {
  9295. var key = changedKeys[i];
  9296. if (key in targetStyle) {
  9297. targetStyle[key] = targetStyle[key];
  9298. this.style[key] = sourceStyle[key];
  9299. }
  9300. }
  9301. }
  9302. var targetKeys = keys(targetStyle);
  9303. for (var i = 0; i < targetKeys.length; i++) {
  9304. var key = targetKeys[i];
  9305. this.style[key] = this.style[key];
  9306. }
  9307. this._transitionState(stateName, {
  9308. style: targetStyle
  9309. }, animationCfg, this.getAnimationStyleProps());
  9310. }
  9311. else {
  9312. this.useStyle(targetStyle);
  9313. }
  9314. }
  9315. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9316. for (var i = 0; i < statesKeys.length; i++) {
  9317. var key = statesKeys[i];
  9318. if (state && state[key] != null) {
  9319. this[key] = state[key];
  9320. }
  9321. else if (needsRestoreToNormal) {
  9322. if (normalState[key] != null) {
  9323. this[key] = normalState[key];
  9324. }
  9325. }
  9326. }
  9327. };
  9328. Displayable.prototype._mergeStates = function (states) {
  9329. var mergedState = _super.prototype._mergeStates.call(this, states);
  9330. var mergedStyle;
  9331. for (var i = 0; i < states.length; i++) {
  9332. var state = states[i];
  9333. if (state.style) {
  9334. mergedStyle = mergedStyle || {};
  9335. this._mergeStyle(mergedStyle, state.style);
  9336. }
  9337. }
  9338. if (mergedStyle) {
  9339. mergedState.style = mergedStyle;
  9340. }
  9341. return mergedState;
  9342. };
  9343. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9344. extend(targetStyle, sourceStyle);
  9345. return targetStyle;
  9346. };
  9347. Displayable.prototype.getAnimationStyleProps = function () {
  9348. return DEFAULT_COMMON_ANIMATION_PROPS;
  9349. };
  9350. Displayable.initDefaultProps = (function () {
  9351. var dispProto = Displayable.prototype;
  9352. dispProto.type = 'displayable';
  9353. dispProto.invisible = false;
  9354. dispProto.z = 0;
  9355. dispProto.z2 = 0;
  9356. dispProto.zlevel = 0;
  9357. dispProto.culling = false;
  9358. dispProto.cursor = 'pointer';
  9359. dispProto.rectHover = false;
  9360. dispProto.incremental = false;
  9361. dispProto._rect = null;
  9362. dispProto.dirtyRectTolerance = 0;
  9363. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9364. })();
  9365. return Displayable;
  9366. }(Element));
  9367. var tmpRect = new BoundingRect(0, 0, 0, 0);
  9368. var viewRect = new BoundingRect(0, 0, 0, 0);
  9369. function isDisplayableCulled(el, width, height) {
  9370. tmpRect.copy(el.getBoundingRect());
  9371. if (el.transform) {
  9372. tmpRect.applyTransform(el.transform);
  9373. }
  9374. viewRect.width = width;
  9375. viewRect.height = height;
  9376. return !tmpRect.intersect(viewRect);
  9377. }
  9378. var mathMin$1 = Math.min;
  9379. var mathMax$1 = Math.max;
  9380. var mathSin = Math.sin;
  9381. var mathCos = Math.cos;
  9382. var PI2 = Math.PI * 2;
  9383. var start = create();
  9384. var end = create();
  9385. var extremity = create();
  9386. function fromLine(x0, y0, x1, y1, min, max) {
  9387. min[0] = mathMin$1(x0, x1);
  9388. min[1] = mathMin$1(y0, y1);
  9389. max[0] = mathMax$1(x0, x1);
  9390. max[1] = mathMax$1(y0, y1);
  9391. }
  9392. var xDim = [];
  9393. var yDim = [];
  9394. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9395. var cubicExtrema$1 = cubicExtrema;
  9396. var cubicAt$1 = cubicAt;
  9397. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9398. min[0] = Infinity;
  9399. min[1] = Infinity;
  9400. max[0] = -Infinity;
  9401. max[1] = -Infinity;
  9402. for (var i = 0; i < n; i++) {
  9403. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9404. min[0] = mathMin$1(x, min[0]);
  9405. max[0] = mathMax$1(x, max[0]);
  9406. }
  9407. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9408. for (var i = 0; i < n; i++) {
  9409. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9410. min[1] = mathMin$1(y, min[1]);
  9411. max[1] = mathMax$1(y, max[1]);
  9412. }
  9413. min[0] = mathMin$1(x0, min[0]);
  9414. max[0] = mathMax$1(x0, max[0]);
  9415. min[0] = mathMin$1(x3, min[0]);
  9416. max[0] = mathMax$1(x3, max[0]);
  9417. min[1] = mathMin$1(y0, min[1]);
  9418. max[1] = mathMax$1(y0, max[1]);
  9419. min[1] = mathMin$1(y3, min[1]);
  9420. max[1] = mathMax$1(y3, max[1]);
  9421. }
  9422. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9423. var quadraticExtremum$1 = quadraticExtremum;
  9424. var quadraticAt$1 = quadraticAt;
  9425. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9426. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9427. var x = quadraticAt$1(x0, x1, x2, tx);
  9428. var y = quadraticAt$1(y0, y1, y2, ty);
  9429. min[0] = mathMin$1(x0, x2, x);
  9430. min[1] = mathMin$1(y0, y2, y);
  9431. max[0] = mathMax$1(x0, x2, x);
  9432. max[1] = mathMax$1(y0, y2, y);
  9433. }
  9434. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9435. var vec2Min = min;
  9436. var vec2Max = max;
  9437. var diff = Math.abs(startAngle - endAngle);
  9438. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9439. min$1[0] = x - rx;
  9440. min$1[1] = y - ry;
  9441. max$1[0] = x + rx;
  9442. max$1[1] = y + ry;
  9443. return;
  9444. }
  9445. start[0] = mathCos(startAngle) * rx + x;
  9446. start[1] = mathSin(startAngle) * ry + y;
  9447. end[0] = mathCos(endAngle) * rx + x;
  9448. end[1] = mathSin(endAngle) * ry + y;
  9449. vec2Min(min$1, start, end);
  9450. vec2Max(max$1, start, end);
  9451. startAngle = startAngle % (PI2);
  9452. if (startAngle < 0) {
  9453. startAngle = startAngle + PI2;
  9454. }
  9455. endAngle = endAngle % (PI2);
  9456. if (endAngle < 0) {
  9457. endAngle = endAngle + PI2;
  9458. }
  9459. if (startAngle > endAngle && !anticlockwise) {
  9460. endAngle += PI2;
  9461. }
  9462. else if (startAngle < endAngle && anticlockwise) {
  9463. startAngle += PI2;
  9464. }
  9465. if (anticlockwise) {
  9466. var tmp = endAngle;
  9467. endAngle = startAngle;
  9468. startAngle = tmp;
  9469. }
  9470. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9471. if (angle > startAngle) {
  9472. extremity[0] = mathCos(angle) * rx + x;
  9473. extremity[1] = mathSin(angle) * ry + y;
  9474. vec2Min(min$1, extremity, min$1);
  9475. vec2Max(max$1, extremity, max$1);
  9476. }
  9477. }
  9478. }
  9479. var CMD = {
  9480. M: 1,
  9481. L: 2,
  9482. C: 3,
  9483. Q: 4,
  9484. A: 5,
  9485. Z: 6,
  9486. R: 7
  9487. };
  9488. var tmpOutX = [];
  9489. var tmpOutY = [];
  9490. var min$1 = [];
  9491. var max$1 = [];
  9492. var min2 = [];
  9493. var max2 = [];
  9494. var mathMin$2 = Math.min;
  9495. var mathMax$2 = Math.max;
  9496. var mathCos$1 = Math.cos;
  9497. var mathSin$1 = Math.sin;
  9498. var mathAbs = Math.abs;
  9499. var PI = Math.PI;
  9500. var PI2$1 = PI * 2;
  9501. var hasTypedArray = typeof Float32Array !== 'undefined';
  9502. var tmpAngles = [];
  9503. function modPI2(radian) {
  9504. var n = Math.round(radian / PI * 1e8) / 1e8;
  9505. return (n % 2) * PI;
  9506. }
  9507. function normalizeArcAngles(angles, anticlockwise) {
  9508. var newStartAngle = modPI2(angles[0]);
  9509. if (newStartAngle < 0) {
  9510. newStartAngle += PI2$1;
  9511. }
  9512. var delta = newStartAngle - angles[0];
  9513. var newEndAngle = angles[1];
  9514. newEndAngle += delta;
  9515. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9516. newEndAngle = newStartAngle + PI2$1;
  9517. }
  9518. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9519. newEndAngle = newStartAngle - PI2$1;
  9520. }
  9521. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9522. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9523. }
  9524. else if (anticlockwise && newStartAngle < newEndAngle) {
  9525. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9526. }
  9527. angles[0] = newStartAngle;
  9528. angles[1] = newEndAngle;
  9529. }
  9530. var PathProxy = (function () {
  9531. function PathProxy(notSaveData) {
  9532. this.dpr = 1;
  9533. this._xi = 0;
  9534. this._yi = 0;
  9535. this._x0 = 0;
  9536. this._y0 = 0;
  9537. this._len = 0;
  9538. if (notSaveData) {
  9539. this._saveData = false;
  9540. }
  9541. if (this._saveData) {
  9542. this.data = [];
  9543. }
  9544. }
  9545. PathProxy.prototype.increaseVersion = function () {
  9546. this._version++;
  9547. };
  9548. PathProxy.prototype.getVersion = function () {
  9549. return this._version;
  9550. };
  9551. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9552. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9553. if (segmentIgnoreThreshold > 0) {
  9554. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9555. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9556. }
  9557. };
  9558. PathProxy.prototype.setDPR = function (dpr) {
  9559. this.dpr = dpr;
  9560. };
  9561. PathProxy.prototype.setContext = function (ctx) {
  9562. this._ctx = ctx;
  9563. };
  9564. PathProxy.prototype.getContext = function () {
  9565. return this._ctx;
  9566. };
  9567. PathProxy.prototype.beginPath = function () {
  9568. this._ctx && this._ctx.beginPath();
  9569. this.reset();
  9570. return this;
  9571. };
  9572. PathProxy.prototype.reset = function () {
  9573. if (this._saveData) {
  9574. this._len = 0;
  9575. }
  9576. if (this._pathSegLen) {
  9577. this._pathSegLen = null;
  9578. this._pathLen = 0;
  9579. }
  9580. this._version++;
  9581. };
  9582. PathProxy.prototype.moveTo = function (x, y) {
  9583. this._drawPendingPt();
  9584. this.addData(CMD.M, x, y);
  9585. this._ctx && this._ctx.moveTo(x, y);
  9586. this._x0 = x;
  9587. this._y0 = y;
  9588. this._xi = x;
  9589. this._yi = y;
  9590. return this;
  9591. };
  9592. PathProxy.prototype.lineTo = function (x, y) {
  9593. var dx = mathAbs(x - this._xi);
  9594. var dy = mathAbs(y - this._yi);
  9595. var exceedUnit = dx > this._ux || dy > this._uy;
  9596. this.addData(CMD.L, x, y);
  9597. if (this._ctx && exceedUnit) {
  9598. this._ctx.lineTo(x, y);
  9599. }
  9600. if (exceedUnit) {
  9601. this._xi = x;
  9602. this._yi = y;
  9603. this._pendingPtDist = 0;
  9604. }
  9605. else {
  9606. var d2 = dx * dx + dy * dy;
  9607. if (d2 > this._pendingPtDist) {
  9608. this._pendingPtX = x;
  9609. this._pendingPtY = y;
  9610. this._pendingPtDist = d2;
  9611. }
  9612. }
  9613. return this;
  9614. };
  9615. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9616. this._drawPendingPt();
  9617. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9618. if (this._ctx) {
  9619. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9620. }
  9621. this._xi = x3;
  9622. this._yi = y3;
  9623. return this;
  9624. };
  9625. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9626. this._drawPendingPt();
  9627. this.addData(CMD.Q, x1, y1, x2, y2);
  9628. if (this._ctx) {
  9629. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9630. }
  9631. this._xi = x2;
  9632. this._yi = y2;
  9633. return this;
  9634. };
  9635. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9636. this._drawPendingPt();
  9637. tmpAngles[0] = startAngle;
  9638. tmpAngles[1] = endAngle;
  9639. normalizeArcAngles(tmpAngles, anticlockwise);
  9640. startAngle = tmpAngles[0];
  9641. endAngle = tmpAngles[1];
  9642. var delta = endAngle - startAngle;
  9643. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9644. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9645. this._xi = mathCos$1(endAngle) * r + cx;
  9646. this._yi = mathSin$1(endAngle) * r + cy;
  9647. return this;
  9648. };
  9649. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9650. this._drawPendingPt();
  9651. if (this._ctx) {
  9652. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9653. }
  9654. return this;
  9655. };
  9656. PathProxy.prototype.rect = function (x, y, w, h) {
  9657. this._drawPendingPt();
  9658. this._ctx && this._ctx.rect(x, y, w, h);
  9659. this.addData(CMD.R, x, y, w, h);
  9660. return this;
  9661. };
  9662. PathProxy.prototype.closePath = function () {
  9663. this._drawPendingPt();
  9664. this.addData(CMD.Z);
  9665. var ctx = this._ctx;
  9666. var x0 = this._x0;
  9667. var y0 = this._y0;
  9668. if (ctx) {
  9669. ctx.closePath();
  9670. }
  9671. this._xi = x0;
  9672. this._yi = y0;
  9673. return this;
  9674. };
  9675. PathProxy.prototype.fill = function (ctx) {
  9676. ctx && ctx.fill();
  9677. this.toStatic();
  9678. };
  9679. PathProxy.prototype.stroke = function (ctx) {
  9680. ctx && ctx.stroke();
  9681. this.toStatic();
  9682. };
  9683. PathProxy.prototype.len = function () {
  9684. return this._len;
  9685. };
  9686. PathProxy.prototype.setData = function (data) {
  9687. var len = data.length;
  9688. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9689. this.data = new Float32Array(len);
  9690. }
  9691. for (var i = 0; i < len; i++) {
  9692. this.data[i] = data[i];
  9693. }
  9694. this._len = len;
  9695. };
  9696. PathProxy.prototype.appendPath = function (path) {
  9697. if (!(path instanceof Array)) {
  9698. path = [path];
  9699. }
  9700. var len = path.length;
  9701. var appendSize = 0;
  9702. var offset = this._len;
  9703. for (var i = 0; i < len; i++) {
  9704. appendSize += path[i].len();
  9705. }
  9706. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9707. this.data = new Float32Array(offset + appendSize);
  9708. }
  9709. for (var i = 0; i < len; i++) {
  9710. var appendPathData = path[i].data;
  9711. for (var k = 0; k < appendPathData.length; k++) {
  9712. this.data[offset++] = appendPathData[k];
  9713. }
  9714. }
  9715. this._len = offset;
  9716. };
  9717. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9718. if (!this._saveData) {
  9719. return;
  9720. }
  9721. var data = this.data;
  9722. if (this._len + arguments.length > data.length) {
  9723. this._expandData();
  9724. data = this.data;
  9725. }
  9726. for (var i = 0; i < arguments.length; i++) {
  9727. data[this._len++] = arguments[i];
  9728. }
  9729. };
  9730. PathProxy.prototype._drawPendingPt = function () {
  9731. if (this._pendingPtDist > 0) {
  9732. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9733. this._pendingPtDist = 0;
  9734. }
  9735. };
  9736. PathProxy.prototype._expandData = function () {
  9737. if (!(this.data instanceof Array)) {
  9738. var newData = [];
  9739. for (var i = 0; i < this._len; i++) {
  9740. newData[i] = this.data[i];
  9741. }
  9742. this.data = newData;
  9743. }
  9744. };
  9745. PathProxy.prototype.toStatic = function () {
  9746. if (!this._saveData) {
  9747. return;
  9748. }
  9749. this._drawPendingPt();
  9750. var data = this.data;
  9751. if (data instanceof Array) {
  9752. data.length = this._len;
  9753. if (hasTypedArray && this._len > 11) {
  9754. this.data = new Float32Array(data);
  9755. }
  9756. }
  9757. };
  9758. PathProxy.prototype.getBoundingRect = function () {
  9759. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9760. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9761. var data = this.data;
  9762. var xi = 0;
  9763. var yi = 0;
  9764. var x0 = 0;
  9765. var y0 = 0;
  9766. var i;
  9767. for (i = 0; i < this._len;) {
  9768. var cmd = data[i++];
  9769. var isFirst = i === 1;
  9770. if (isFirst) {
  9771. xi = data[i];
  9772. yi = data[i + 1];
  9773. x0 = xi;
  9774. y0 = yi;
  9775. }
  9776. switch (cmd) {
  9777. case CMD.M:
  9778. xi = x0 = data[i++];
  9779. yi = y0 = data[i++];
  9780. min2[0] = x0;
  9781. min2[1] = y0;
  9782. max2[0] = x0;
  9783. max2[1] = y0;
  9784. break;
  9785. case CMD.L:
  9786. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9787. xi = data[i++];
  9788. yi = data[i++];
  9789. break;
  9790. case CMD.C:
  9791. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9792. xi = data[i++];
  9793. yi = data[i++];
  9794. break;
  9795. case CMD.Q:
  9796. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9797. xi = data[i++];
  9798. yi = data[i++];
  9799. break;
  9800. case CMD.A:
  9801. var cx = data[i++];
  9802. var cy = data[i++];
  9803. var rx = data[i++];
  9804. var ry = data[i++];
  9805. var startAngle = data[i++];
  9806. var endAngle = data[i++] + startAngle;
  9807. i += 1;
  9808. var anticlockwise = !data[i++];
  9809. if (isFirst) {
  9810. x0 = mathCos$1(startAngle) * rx + cx;
  9811. y0 = mathSin$1(startAngle) * ry + cy;
  9812. }
  9813. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9814. xi = mathCos$1(endAngle) * rx + cx;
  9815. yi = mathSin$1(endAngle) * ry + cy;
  9816. break;
  9817. case CMD.R:
  9818. x0 = xi = data[i++];
  9819. y0 = yi = data[i++];
  9820. var width = data[i++];
  9821. var height = data[i++];
  9822. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9823. break;
  9824. case CMD.Z:
  9825. xi = x0;
  9826. yi = y0;
  9827. break;
  9828. }
  9829. min(min$1, min$1, min2);
  9830. max(max$1, max$1, max2);
  9831. }
  9832. if (i === 0) {
  9833. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9834. }
  9835. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9836. };
  9837. PathProxy.prototype._calculateLength = function () {
  9838. var data = this.data;
  9839. var len = this._len;
  9840. var ux = this._ux;
  9841. var uy = this._uy;
  9842. var xi = 0;
  9843. var yi = 0;
  9844. var x0 = 0;
  9845. var y0 = 0;
  9846. if (!this._pathSegLen) {
  9847. this._pathSegLen = [];
  9848. }
  9849. var pathSegLen = this._pathSegLen;
  9850. var pathTotalLen = 0;
  9851. var segCount = 0;
  9852. for (var i = 0; i < len;) {
  9853. var cmd = data[i++];
  9854. var isFirst = i === 1;
  9855. if (isFirst) {
  9856. xi = data[i];
  9857. yi = data[i + 1];
  9858. x0 = xi;
  9859. y0 = yi;
  9860. }
  9861. var l = -1;
  9862. switch (cmd) {
  9863. case CMD.M:
  9864. xi = x0 = data[i++];
  9865. yi = y0 = data[i++];
  9866. break;
  9867. case CMD.L: {
  9868. var x2 = data[i++];
  9869. var y2 = data[i++];
  9870. var dx = x2 - xi;
  9871. var dy = y2 - yi;
  9872. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9873. l = Math.sqrt(dx * dx + dy * dy);
  9874. xi = x2;
  9875. yi = y2;
  9876. }
  9877. break;
  9878. }
  9879. case CMD.C: {
  9880. var x1 = data[i++];
  9881. var y1 = data[i++];
  9882. var x2 = data[i++];
  9883. var y2 = data[i++];
  9884. var x3 = data[i++];
  9885. var y3 = data[i++];
  9886. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9887. xi = x3;
  9888. yi = y3;
  9889. break;
  9890. }
  9891. case CMD.Q: {
  9892. var x1 = data[i++];
  9893. var y1 = data[i++];
  9894. var x2 = data[i++];
  9895. var y2 = data[i++];
  9896. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9897. xi = x2;
  9898. yi = y2;
  9899. break;
  9900. }
  9901. case CMD.A:
  9902. var cx = data[i++];
  9903. var cy = data[i++];
  9904. var rx = data[i++];
  9905. var ry = data[i++];
  9906. var startAngle = data[i++];
  9907. var delta = data[i++];
  9908. var endAngle = delta + startAngle;
  9909. i += 1;
  9910. var anticlockwise = !data[i++];
  9911. if (isFirst) {
  9912. x0 = mathCos$1(startAngle) * rx + cx;
  9913. y0 = mathSin$1(startAngle) * ry + cy;
  9914. }
  9915. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9916. xi = mathCos$1(endAngle) * rx + cx;
  9917. yi = mathSin$1(endAngle) * ry + cy;
  9918. break;
  9919. case CMD.R: {
  9920. x0 = xi = data[i++];
  9921. y0 = yi = data[i++];
  9922. var width = data[i++];
  9923. var height = data[i++];
  9924. l = width * 2 + height * 2;
  9925. break;
  9926. }
  9927. case CMD.Z: {
  9928. var dx = x0 - xi;
  9929. var dy = y0 - yi;
  9930. l = Math.sqrt(dx * dx + dy * dy);
  9931. xi = x0;
  9932. yi = y0;
  9933. break;
  9934. }
  9935. }
  9936. if (l >= 0) {
  9937. pathSegLen[segCount++] = l;
  9938. pathTotalLen += l;
  9939. }
  9940. }
  9941. this._pathLen = pathTotalLen;
  9942. return pathTotalLen;
  9943. };
  9944. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9945. var d = this.data;
  9946. var ux = this._ux;
  9947. var uy = this._uy;
  9948. var len = this._len;
  9949. var x0;
  9950. var y0;
  9951. var xi;
  9952. var yi;
  9953. var x;
  9954. var y;
  9955. var drawPart = percent < 1;
  9956. var pathSegLen;
  9957. var pathTotalLen;
  9958. var accumLength = 0;
  9959. var segCount = 0;
  9960. var displayedLength;
  9961. var pendingPtDist = 0;
  9962. var pendingPtX;
  9963. var pendingPtY;
  9964. if (drawPart) {
  9965. if (!this._pathSegLen) {
  9966. this._calculateLength();
  9967. }
  9968. pathSegLen = this._pathSegLen;
  9969. pathTotalLen = this._pathLen;
  9970. displayedLength = percent * pathTotalLen;
  9971. if (!displayedLength) {
  9972. return;
  9973. }
  9974. }
  9975. lo: for (var i = 0; i < len;) {
  9976. var cmd = d[i++];
  9977. var isFirst = i === 1;
  9978. if (isFirst) {
  9979. xi = d[i];
  9980. yi = d[i + 1];
  9981. x0 = xi;
  9982. y0 = yi;
  9983. }
  9984. if (cmd !== CMD.L && pendingPtDist > 0) {
  9985. ctx.lineTo(pendingPtX, pendingPtY);
  9986. pendingPtDist = 0;
  9987. }
  9988. switch (cmd) {
  9989. case CMD.M:
  9990. x0 = xi = d[i++];
  9991. y0 = yi = d[i++];
  9992. ctx.moveTo(xi, yi);
  9993. break;
  9994. case CMD.L: {
  9995. x = d[i++];
  9996. y = d[i++];
  9997. var dx = mathAbs(x - xi);
  9998. var dy = mathAbs(y - yi);
  9999. if (dx > ux || dy > uy) {
  10000. if (drawPart) {
  10001. var l = pathSegLen[segCount++];
  10002. if (accumLength + l > displayedLength) {
  10003. var t = (displayedLength - accumLength) / l;
  10004. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10005. break lo;
  10006. }
  10007. accumLength += l;
  10008. }
  10009. ctx.lineTo(x, y);
  10010. xi = x;
  10011. yi = y;
  10012. pendingPtDist = 0;
  10013. }
  10014. else {
  10015. var d2 = dx * dx + dy * dy;
  10016. if (d2 > pendingPtDist) {
  10017. pendingPtX = x;
  10018. pendingPtY = y;
  10019. pendingPtDist = d2;
  10020. }
  10021. }
  10022. break;
  10023. }
  10024. case CMD.C: {
  10025. var x1 = d[i++];
  10026. var y1 = d[i++];
  10027. var x2 = d[i++];
  10028. var y2 = d[i++];
  10029. var x3 = d[i++];
  10030. var y3 = d[i++];
  10031. if (drawPart) {
  10032. var l = pathSegLen[segCount++];
  10033. if (accumLength + l > displayedLength) {
  10034. var t = (displayedLength - accumLength) / l;
  10035. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10036. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10037. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10038. break lo;
  10039. }
  10040. accumLength += l;
  10041. }
  10042. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10043. xi = x3;
  10044. yi = y3;
  10045. break;
  10046. }
  10047. case CMD.Q: {
  10048. var x1 = d[i++];
  10049. var y1 = d[i++];
  10050. var x2 = d[i++];
  10051. var y2 = d[i++];
  10052. if (drawPart) {
  10053. var l = pathSegLen[segCount++];
  10054. if (accumLength + l > displayedLength) {
  10055. var t = (displayedLength - accumLength) / l;
  10056. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10057. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10058. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10059. break lo;
  10060. }
  10061. accumLength += l;
  10062. }
  10063. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10064. xi = x2;
  10065. yi = y2;
  10066. break;
  10067. }
  10068. case CMD.A:
  10069. var cx = d[i++];
  10070. var cy = d[i++];
  10071. var rx = d[i++];
  10072. var ry = d[i++];
  10073. var startAngle = d[i++];
  10074. var delta = d[i++];
  10075. var psi = d[i++];
  10076. var anticlockwise = !d[i++];
  10077. var r = (rx > ry) ? rx : ry;
  10078. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10079. var endAngle = startAngle + delta;
  10080. var breakBuild = false;
  10081. if (drawPart) {
  10082. var l = pathSegLen[segCount++];
  10083. if (accumLength + l > displayedLength) {
  10084. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10085. breakBuild = true;
  10086. }
  10087. accumLength += l;
  10088. }
  10089. if (isEllipse && ctx.ellipse) {
  10090. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10091. }
  10092. else {
  10093. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10094. }
  10095. if (breakBuild) {
  10096. break lo;
  10097. }
  10098. if (isFirst) {
  10099. x0 = mathCos$1(startAngle) * rx + cx;
  10100. y0 = mathSin$1(startAngle) * ry + cy;
  10101. }
  10102. xi = mathCos$1(endAngle) * rx + cx;
  10103. yi = mathSin$1(endAngle) * ry + cy;
  10104. break;
  10105. case CMD.R:
  10106. x0 = xi = d[i];
  10107. y0 = yi = d[i + 1];
  10108. x = d[i++];
  10109. y = d[i++];
  10110. var width = d[i++];
  10111. var height = d[i++];
  10112. if (drawPart) {
  10113. var l = pathSegLen[segCount++];
  10114. if (accumLength + l > displayedLength) {
  10115. var d_1 = displayedLength - accumLength;
  10116. ctx.moveTo(x, y);
  10117. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10118. d_1 -= width;
  10119. if (d_1 > 0) {
  10120. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10121. }
  10122. d_1 -= height;
  10123. if (d_1 > 0) {
  10124. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10125. }
  10126. d_1 -= width;
  10127. if (d_1 > 0) {
  10128. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10129. }
  10130. break lo;
  10131. }
  10132. accumLength += l;
  10133. }
  10134. ctx.rect(x, y, width, height);
  10135. break;
  10136. case CMD.Z:
  10137. if (drawPart) {
  10138. var l = pathSegLen[segCount++];
  10139. if (accumLength + l > displayedLength) {
  10140. var t = (displayedLength - accumLength) / l;
  10141. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10142. break lo;
  10143. }
  10144. accumLength += l;
  10145. }
  10146. ctx.closePath();
  10147. xi = x0;
  10148. yi = y0;
  10149. }
  10150. }
  10151. };
  10152. PathProxy.prototype.clone = function () {
  10153. var newProxy = new PathProxy();
  10154. var data = this.data;
  10155. newProxy.data = data.slice ? data.slice()
  10156. : Array.prototype.slice.call(data);
  10157. newProxy._len = this._len;
  10158. return newProxy;
  10159. };
  10160. PathProxy.CMD = CMD;
  10161. PathProxy.initDefaultProps = (function () {
  10162. var proto = PathProxy.prototype;
  10163. proto._saveData = true;
  10164. proto._ux = 0;
  10165. proto._uy = 0;
  10166. proto._pendingPtDist = 0;
  10167. proto._version = 0;
  10168. })();
  10169. return PathProxy;
  10170. }());
  10171. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10172. if (lineWidth === 0) {
  10173. return false;
  10174. }
  10175. var _l = lineWidth;
  10176. var _a = 0;
  10177. var _b = x0;
  10178. if ((y > y0 + _l && y > y1 + _l)
  10179. || (y < y0 - _l && y < y1 - _l)
  10180. || (x > x0 + _l && x > x1 + _l)
  10181. || (x < x0 - _l && x < x1 - _l)) {
  10182. return false;
  10183. }
  10184. if (x0 !== x1) {
  10185. _a = (y0 - y1) / (x0 - x1);
  10186. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10187. }
  10188. else {
  10189. return Math.abs(x - x0) <= _l / 2;
  10190. }
  10191. var tmp = _a * x - y + _b;
  10192. var _s = tmp * tmp / (_a * _a + 1);
  10193. return _s <= _l / 2 * _l / 2;
  10194. }
  10195. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10196. if (lineWidth === 0) {
  10197. return false;
  10198. }
  10199. var _l = lineWidth;
  10200. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10201. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10202. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10203. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10204. return false;
  10205. }
  10206. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10207. return d <= _l / 2;
  10208. }
  10209. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10210. if (lineWidth === 0) {
  10211. return false;
  10212. }
  10213. var _l = lineWidth;
  10214. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10215. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10216. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10217. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10218. return false;
  10219. }
  10220. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10221. return d <= _l / 2;
  10222. }
  10223. var PI2$2 = Math.PI * 2;
  10224. function normalizeRadian(angle) {
  10225. angle %= PI2$2;
  10226. if (angle < 0) {
  10227. angle += PI2$2;
  10228. }
  10229. return angle;
  10230. }
  10231. var PI2$3 = Math.PI * 2;
  10232. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10233. if (lineWidth === 0) {
  10234. return false;
  10235. }
  10236. var _l = lineWidth;
  10237. x -= cx;
  10238. y -= cy;
  10239. var d = Math.sqrt(x * x + y * y);
  10240. if ((d - _l > r) || (d + _l < r)) {
  10241. return false;
  10242. }
  10243. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10244. return true;
  10245. }
  10246. if (anticlockwise) {
  10247. var tmp = startAngle;
  10248. startAngle = normalizeRadian(endAngle);
  10249. endAngle = normalizeRadian(tmp);
  10250. }
  10251. else {
  10252. startAngle = normalizeRadian(startAngle);
  10253. endAngle = normalizeRadian(endAngle);
  10254. }
  10255. if (startAngle > endAngle) {
  10256. endAngle += PI2$3;
  10257. }
  10258. var angle = Math.atan2(y, x);
  10259. if (angle < 0) {
  10260. angle += PI2$3;
  10261. }
  10262. return (angle >= startAngle && angle <= endAngle)
  10263. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10264. }
  10265. function windingLine(x0, y0, x1, y1, x, y) {
  10266. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10267. return 0;
  10268. }
  10269. if (y1 === y0) {
  10270. return 0;
  10271. }
  10272. var t = (y - y0) / (y1 - y0);
  10273. var dir = y1 < y0 ? 1 : -1;
  10274. if (t === 1 || t === 0) {
  10275. dir = y1 < y0 ? 0.5 : -0.5;
  10276. }
  10277. var x_ = t * (x1 - x0) + x0;
  10278. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10279. }
  10280. var CMD$1 = PathProxy.CMD;
  10281. var PI2$4 = Math.PI * 2;
  10282. var EPSILON$3 = 1e-4;
  10283. function isAroundEqual(a, b) {
  10284. return Math.abs(a - b) < EPSILON$3;
  10285. }
  10286. var roots = [-1, -1, -1];
  10287. var extrema = [-1, -1];
  10288. function swapExtrema() {
  10289. var tmp = extrema[0];
  10290. extrema[0] = extrema[1];
  10291. extrema[1] = tmp;
  10292. }
  10293. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10294. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10295. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10296. return 0;
  10297. }
  10298. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10299. if (nRoots === 0) {
  10300. return 0;
  10301. }
  10302. else {
  10303. var w = 0;
  10304. var nExtrema = -1;
  10305. var y0_ = void 0;
  10306. var y1_ = void 0;
  10307. for (var i = 0; i < nRoots; i++) {
  10308. var t = roots[i];
  10309. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10310. var x_ = cubicAt(x0, x1, x2, x3, t);
  10311. if (x_ < x) {
  10312. continue;
  10313. }
  10314. if (nExtrema < 0) {
  10315. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10316. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10317. swapExtrema();
  10318. }
  10319. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10320. if (nExtrema > 1) {
  10321. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10322. }
  10323. }
  10324. if (nExtrema === 2) {
  10325. if (t < extrema[0]) {
  10326. w += y0_ < y0 ? unit : -unit;
  10327. }
  10328. else if (t < extrema[1]) {
  10329. w += y1_ < y0_ ? unit : -unit;
  10330. }
  10331. else {
  10332. w += y3 < y1_ ? unit : -unit;
  10333. }
  10334. }
  10335. else {
  10336. if (t < extrema[0]) {
  10337. w += y0_ < y0 ? unit : -unit;
  10338. }
  10339. else {
  10340. w += y3 < y0_ ? unit : -unit;
  10341. }
  10342. }
  10343. }
  10344. return w;
  10345. }
  10346. }
  10347. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10348. if ((y > y0 && y > y1 && y > y2)
  10349. || (y < y0 && y < y1 && y < y2)) {
  10350. return 0;
  10351. }
  10352. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10353. if (nRoots === 0) {
  10354. return 0;
  10355. }
  10356. else {
  10357. var t = quadraticExtremum(y0, y1, y2);
  10358. if (t >= 0 && t <= 1) {
  10359. var w = 0;
  10360. var y_ = quadraticAt(y0, y1, y2, t);
  10361. for (var i = 0; i < nRoots; i++) {
  10362. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10363. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10364. if (x_ < x) {
  10365. continue;
  10366. }
  10367. if (roots[i] < t) {
  10368. w += y_ < y0 ? unit : -unit;
  10369. }
  10370. else {
  10371. w += y2 < y_ ? unit : -unit;
  10372. }
  10373. }
  10374. return w;
  10375. }
  10376. else {
  10377. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10378. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10379. if (x_ < x) {
  10380. return 0;
  10381. }
  10382. return y2 < y0 ? unit : -unit;
  10383. }
  10384. }
  10385. }
  10386. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10387. y -= cy;
  10388. if (y > r || y < -r) {
  10389. return 0;
  10390. }
  10391. var tmp = Math.sqrt(r * r - y * y);
  10392. roots[0] = -tmp;
  10393. roots[1] = tmp;
  10394. var dTheta = Math.abs(startAngle - endAngle);
  10395. if (dTheta < 1e-4) {
  10396. return 0;
  10397. }
  10398. if (dTheta >= PI2$4 - 1e-4) {
  10399. startAngle = 0;
  10400. endAngle = PI2$4;
  10401. var dir = anticlockwise ? 1 : -1;
  10402. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10403. return dir;
  10404. }
  10405. else {
  10406. return 0;
  10407. }
  10408. }
  10409. if (startAngle > endAngle) {
  10410. var tmp_1 = startAngle;
  10411. startAngle = endAngle;
  10412. endAngle = tmp_1;
  10413. }
  10414. if (startAngle < 0) {
  10415. startAngle += PI2$4;
  10416. endAngle += PI2$4;
  10417. }
  10418. var w = 0;
  10419. for (var i = 0; i < 2; i++) {
  10420. var x_ = roots[i];
  10421. if (x_ + cx > x) {
  10422. var angle = Math.atan2(y, x_);
  10423. var dir = anticlockwise ? 1 : -1;
  10424. if (angle < 0) {
  10425. angle = PI2$4 + angle;
  10426. }
  10427. if ((angle >= startAngle && angle <= endAngle)
  10428. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10429. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10430. dir = -dir;
  10431. }
  10432. w += dir;
  10433. }
  10434. }
  10435. }
  10436. return w;
  10437. }
  10438. function containPath(path, lineWidth, isStroke, x, y) {
  10439. var data = path.data;
  10440. var len = path.len();
  10441. var w = 0;
  10442. var xi = 0;
  10443. var yi = 0;
  10444. var x0 = 0;
  10445. var y0 = 0;
  10446. var x1;
  10447. var y1;
  10448. for (var i = 0; i < len;) {
  10449. var cmd = data[i++];
  10450. var isFirst = i === 1;
  10451. if (cmd === CMD$1.M && i > 1) {
  10452. if (!isStroke) {
  10453. w += windingLine(xi, yi, x0, y0, x, y);
  10454. }
  10455. }
  10456. if (isFirst) {
  10457. xi = data[i];
  10458. yi = data[i + 1];
  10459. x0 = xi;
  10460. y0 = yi;
  10461. }
  10462. switch (cmd) {
  10463. case CMD$1.M:
  10464. x0 = data[i++];
  10465. y0 = data[i++];
  10466. xi = x0;
  10467. yi = y0;
  10468. break;
  10469. case CMD$1.L:
  10470. if (isStroke) {
  10471. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10472. return true;
  10473. }
  10474. }
  10475. else {
  10476. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10477. }
  10478. xi = data[i++];
  10479. yi = data[i++];
  10480. break;
  10481. case CMD$1.C:
  10482. if (isStroke) {
  10483. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10484. return true;
  10485. }
  10486. }
  10487. else {
  10488. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10489. }
  10490. xi = data[i++];
  10491. yi = data[i++];
  10492. break;
  10493. case CMD$1.Q:
  10494. if (isStroke) {
  10495. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10496. return true;
  10497. }
  10498. }
  10499. else {
  10500. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10501. }
  10502. xi = data[i++];
  10503. yi = data[i++];
  10504. break;
  10505. case CMD$1.A:
  10506. var cx = data[i++];
  10507. var cy = data[i++];
  10508. var rx = data[i++];
  10509. var ry = data[i++];
  10510. var theta = data[i++];
  10511. var dTheta = data[i++];
  10512. i += 1;
  10513. var anticlockwise = !!(1 - data[i++]);
  10514. x1 = Math.cos(theta) * rx + cx;
  10515. y1 = Math.sin(theta) * ry + cy;
  10516. if (!isFirst) {
  10517. w += windingLine(xi, yi, x1, y1, x, y);
  10518. }
  10519. else {
  10520. x0 = x1;
  10521. y0 = y1;
  10522. }
  10523. var _x = (x - cx) * ry / rx + cx;
  10524. if (isStroke) {
  10525. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10526. return true;
  10527. }
  10528. }
  10529. else {
  10530. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10531. }
  10532. xi = Math.cos(theta + dTheta) * rx + cx;
  10533. yi = Math.sin(theta + dTheta) * ry + cy;
  10534. break;
  10535. case CMD$1.R:
  10536. x0 = xi = data[i++];
  10537. y0 = yi = data[i++];
  10538. var width = data[i++];
  10539. var height = data[i++];
  10540. x1 = x0 + width;
  10541. y1 = y0 + height;
  10542. if (isStroke) {
  10543. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10544. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10545. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10546. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10547. return true;
  10548. }
  10549. }
  10550. else {
  10551. w += windingLine(x1, y0, x1, y1, x, y);
  10552. w += windingLine(x0, y1, x0, y0, x, y);
  10553. }
  10554. break;
  10555. case CMD$1.Z:
  10556. if (isStroke) {
  10557. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10558. return true;
  10559. }
  10560. }
  10561. else {
  10562. w += windingLine(xi, yi, x0, y0, x, y);
  10563. }
  10564. xi = x0;
  10565. yi = y0;
  10566. break;
  10567. }
  10568. }
  10569. if (!isStroke && !isAroundEqual(yi, y0)) {
  10570. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10571. }
  10572. return w !== 0;
  10573. }
  10574. function contain(pathProxy, x, y) {
  10575. return containPath(pathProxy, 0, false, x, y);
  10576. }
  10577. function containStroke$4(pathProxy, lineWidth, x, y) {
  10578. return containPath(pathProxy, lineWidth, true, x, y);
  10579. }
  10580. var DEFAULT_PATH_STYLE = defaults({
  10581. fill: '#000',
  10582. stroke: null,
  10583. strokePercent: 1,
  10584. fillOpacity: 1,
  10585. strokeOpacity: 1,
  10586. lineDashOffset: 0,
  10587. lineWidth: 1,
  10588. lineCap: 'butt',
  10589. miterLimit: 10,
  10590. strokeNoScale: false,
  10591. strokeFirst: false
  10592. }, DEFAULT_COMMON_STYLE);
  10593. var DEFAULT_PATH_ANIMATION_PROPS = {
  10594. style: defaults({
  10595. fill: true,
  10596. stroke: true,
  10597. strokePercent: true,
  10598. fillOpacity: true,
  10599. strokeOpacity: true,
  10600. lineDashOffset: true,
  10601. lineWidth: true,
  10602. miterLimit: true
  10603. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10604. };
  10605. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10606. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10607. ]);
  10608. var Path = (function (_super) {
  10609. __extends(Path, _super);
  10610. function Path(opts) {
  10611. return _super.call(this, opts) || this;
  10612. }
  10613. Path.prototype.update = function () {
  10614. var _this = this;
  10615. _super.prototype.update.call(this);
  10616. var style = this.style;
  10617. if (style.decal) {
  10618. var decalEl = this._decalEl = this._decalEl || new Path();
  10619. if (decalEl.buildPath === Path.prototype.buildPath) {
  10620. decalEl.buildPath = function (ctx) {
  10621. _this.buildPath(ctx, _this.shape);
  10622. };
  10623. }
  10624. decalEl.silent = true;
  10625. var decalElStyle = decalEl.style;
  10626. for (var key in style) {
  10627. if (decalElStyle[key] !== style[key]) {
  10628. decalElStyle[key] = style[key];
  10629. }
  10630. }
  10631. decalElStyle.fill = style.fill ? style.decal : null;
  10632. decalElStyle.decal = null;
  10633. decalElStyle.shadowColor = null;
  10634. style.strokeFirst && (decalElStyle.stroke = null);
  10635. for (var i = 0; i < pathCopyParams.length; ++i) {
  10636. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10637. }
  10638. decalEl.__dirty |= REDRAW_BIT;
  10639. }
  10640. else if (this._decalEl) {
  10641. this._decalEl = null;
  10642. }
  10643. };
  10644. Path.prototype.getDecalElement = function () {
  10645. return this._decalEl;
  10646. };
  10647. Path.prototype._init = function (props) {
  10648. var keysArr = keys(props);
  10649. this.shape = this.getDefaultShape();
  10650. var defaultStyle = this.getDefaultStyle();
  10651. if (defaultStyle) {
  10652. this.useStyle(defaultStyle);
  10653. }
  10654. for (var i = 0; i < keysArr.length; i++) {
  10655. var key = keysArr[i];
  10656. var value = props[key];
  10657. if (key === 'style') {
  10658. if (!this.style) {
  10659. this.useStyle(value);
  10660. }
  10661. else {
  10662. extend(this.style, value);
  10663. }
  10664. }
  10665. else if (key === 'shape') {
  10666. extend(this.shape, value);
  10667. }
  10668. else {
  10669. _super.prototype.attrKV.call(this, key, value);
  10670. }
  10671. }
  10672. if (!this.style) {
  10673. this.useStyle({});
  10674. }
  10675. };
  10676. Path.prototype.getDefaultStyle = function () {
  10677. return null;
  10678. };
  10679. Path.prototype.getDefaultShape = function () {
  10680. return {};
  10681. };
  10682. Path.prototype.canBeInsideText = function () {
  10683. return this.hasFill();
  10684. };
  10685. Path.prototype.getInsideTextFill = function () {
  10686. var pathFill = this.style.fill;
  10687. if (pathFill !== 'none') {
  10688. if (isString(pathFill)) {
  10689. var fillLum = lum(pathFill, 0);
  10690. if (fillLum > 0.5) {
  10691. return DARK_LABEL_COLOR;
  10692. }
  10693. else if (fillLum > 0.2) {
  10694. return LIGHTER_LABEL_COLOR;
  10695. }
  10696. return LIGHT_LABEL_COLOR;
  10697. }
  10698. else if (pathFill) {
  10699. return LIGHT_LABEL_COLOR;
  10700. }
  10701. }
  10702. return DARK_LABEL_COLOR;
  10703. };
  10704. Path.prototype.getInsideTextStroke = function (textFill) {
  10705. var pathFill = this.style.fill;
  10706. if (isString(pathFill)) {
  10707. var zr = this.__zr;
  10708. var isDarkMode = !!(zr && zr.isDarkMode());
  10709. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10710. if (isDarkMode === isDarkLabel) {
  10711. return pathFill;
  10712. }
  10713. }
  10714. };
  10715. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10716. Path.prototype.pathUpdated = function () {
  10717. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10718. };
  10719. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10720. !this.path && this.createPathProxy();
  10721. this.path.beginPath();
  10722. this.buildPath(this.path, this.shape, inBatch);
  10723. return this.path;
  10724. };
  10725. Path.prototype.createPathProxy = function () {
  10726. this.path = new PathProxy(false);
  10727. };
  10728. Path.prototype.hasStroke = function () {
  10729. var style = this.style;
  10730. var stroke = style.stroke;
  10731. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10732. };
  10733. Path.prototype.hasFill = function () {
  10734. var style = this.style;
  10735. var fill = style.fill;
  10736. return fill != null && fill !== 'none';
  10737. };
  10738. Path.prototype.getBoundingRect = function () {
  10739. var rect = this._rect;
  10740. var style = this.style;
  10741. var needsUpdateRect = !rect;
  10742. if (needsUpdateRect) {
  10743. var firstInvoke = false;
  10744. if (!this.path) {
  10745. firstInvoke = true;
  10746. this.createPathProxy();
  10747. }
  10748. var path = this.path;
  10749. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10750. path.beginPath();
  10751. this.buildPath(path, this.shape, false);
  10752. this.pathUpdated();
  10753. }
  10754. rect = path.getBoundingRect();
  10755. }
  10756. this._rect = rect;
  10757. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10758. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10759. if (this.__dirty || needsUpdateRect) {
  10760. rectStroke.copy(rect);
  10761. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10762. var w = style.lineWidth;
  10763. if (!this.hasFill()) {
  10764. var strokeContainThreshold = this.strokeContainThreshold;
  10765. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10766. }
  10767. if (lineScale > 1e-10) {
  10768. rectStroke.width += w / lineScale;
  10769. rectStroke.height += w / lineScale;
  10770. rectStroke.x -= w / lineScale / 2;
  10771. rectStroke.y -= w / lineScale / 2;
  10772. }
  10773. }
  10774. return rectStroke;
  10775. }
  10776. return rect;
  10777. };
  10778. Path.prototype.contain = function (x, y) {
  10779. var localPos = this.transformCoordToLocal(x, y);
  10780. var rect = this.getBoundingRect();
  10781. var style = this.style;
  10782. x = localPos[0];
  10783. y = localPos[1];
  10784. if (rect.contain(x, y)) {
  10785. var pathProxy = this.path;
  10786. if (this.hasStroke()) {
  10787. var lineWidth = style.lineWidth;
  10788. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10789. if (lineScale > 1e-10) {
  10790. if (!this.hasFill()) {
  10791. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10792. }
  10793. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10794. return true;
  10795. }
  10796. }
  10797. }
  10798. if (this.hasFill()) {
  10799. return contain(pathProxy, x, y);
  10800. }
  10801. }
  10802. return false;
  10803. };
  10804. Path.prototype.dirtyShape = function () {
  10805. this.__dirty |= SHAPE_CHANGED_BIT;
  10806. if (this._rect) {
  10807. this._rect = null;
  10808. }
  10809. if (this._decalEl) {
  10810. this._decalEl.dirtyShape();
  10811. }
  10812. this.markRedraw();
  10813. };
  10814. Path.prototype.dirty = function () {
  10815. this.dirtyStyle();
  10816. this.dirtyShape();
  10817. };
  10818. Path.prototype.animateShape = function (loop) {
  10819. return this.animate('shape', loop);
  10820. };
  10821. Path.prototype.updateDuringAnimation = function (targetKey) {
  10822. if (targetKey === 'style') {
  10823. this.dirtyStyle();
  10824. }
  10825. else if (targetKey === 'shape') {
  10826. this.dirtyShape();
  10827. }
  10828. else {
  10829. this.markRedraw();
  10830. }
  10831. };
  10832. Path.prototype.attrKV = function (key, value) {
  10833. if (key === 'shape') {
  10834. this.setShape(value);
  10835. }
  10836. else {
  10837. _super.prototype.attrKV.call(this, key, value);
  10838. }
  10839. };
  10840. Path.prototype.setShape = function (keyOrObj, value) {
  10841. var shape = this.shape;
  10842. if (!shape) {
  10843. shape = this.shape = {};
  10844. }
  10845. if (typeof keyOrObj === 'string') {
  10846. shape[keyOrObj] = value;
  10847. }
  10848. else {
  10849. extend(shape, keyOrObj);
  10850. }
  10851. this.dirtyShape();
  10852. return this;
  10853. };
  10854. Path.prototype.shapeChanged = function () {
  10855. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  10856. };
  10857. Path.prototype.createStyle = function (obj) {
  10858. return createObject(DEFAULT_PATH_STYLE, obj);
  10859. };
  10860. Path.prototype._innerSaveToNormal = function (toState) {
  10861. _super.prototype._innerSaveToNormal.call(this, toState);
  10862. var normalState = this._normalState;
  10863. if (toState.shape && !normalState.shape) {
  10864. normalState.shape = extend({}, this.shape);
  10865. }
  10866. };
  10867. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10868. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10869. var needsRestoreToNormal = !(state && keepCurrentStates);
  10870. var targetShape;
  10871. if (state && state.shape) {
  10872. if (transition) {
  10873. if (keepCurrentStates) {
  10874. targetShape = state.shape;
  10875. }
  10876. else {
  10877. targetShape = extend({}, normalState.shape);
  10878. extend(targetShape, state.shape);
  10879. }
  10880. }
  10881. else {
  10882. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10883. extend(targetShape, state.shape);
  10884. }
  10885. }
  10886. else if (needsRestoreToNormal) {
  10887. targetShape = normalState.shape;
  10888. }
  10889. if (targetShape) {
  10890. if (transition) {
  10891. this.shape = extend({}, this.shape);
  10892. var targetShapePrimaryProps = {};
  10893. var shapeKeys = keys(targetShape);
  10894. for (var i = 0; i < shapeKeys.length; i++) {
  10895. var key = shapeKeys[i];
  10896. if (typeof targetShape[key] === 'object') {
  10897. this.shape[key] = targetShape[key];
  10898. }
  10899. else {
  10900. targetShapePrimaryProps[key] = targetShape[key];
  10901. }
  10902. }
  10903. this._transitionState(stateName, {
  10904. shape: targetShapePrimaryProps
  10905. }, animationCfg);
  10906. }
  10907. else {
  10908. this.shape = targetShape;
  10909. this.dirtyShape();
  10910. }
  10911. }
  10912. };
  10913. Path.prototype._mergeStates = function (states) {
  10914. var mergedState = _super.prototype._mergeStates.call(this, states);
  10915. var mergedShape;
  10916. for (var i = 0; i < states.length; i++) {
  10917. var state = states[i];
  10918. if (state.shape) {
  10919. mergedShape = mergedShape || {};
  10920. this._mergeStyle(mergedShape, state.shape);
  10921. }
  10922. }
  10923. if (mergedShape) {
  10924. mergedState.shape = mergedShape;
  10925. }
  10926. return mergedState;
  10927. };
  10928. Path.prototype.getAnimationStyleProps = function () {
  10929. return DEFAULT_PATH_ANIMATION_PROPS;
  10930. };
  10931. Path.prototype.isZeroArea = function () {
  10932. return false;
  10933. };
  10934. Path.extend = function (defaultProps) {
  10935. var Sub = (function (_super) {
  10936. __extends(Sub, _super);
  10937. function Sub(opts) {
  10938. var _this = _super.call(this, opts) || this;
  10939. defaultProps.init && defaultProps.init.call(_this, opts);
  10940. return _this;
  10941. }
  10942. Sub.prototype.getDefaultStyle = function () {
  10943. return clone(defaultProps.style);
  10944. };
  10945. Sub.prototype.getDefaultShape = function () {
  10946. return clone(defaultProps.shape);
  10947. };
  10948. return Sub;
  10949. }(Path));
  10950. for (var key in defaultProps) {
  10951. if (typeof defaultProps[key] === 'function') {
  10952. Sub.prototype[key] = defaultProps[key];
  10953. }
  10954. }
  10955. return Sub;
  10956. };
  10957. Path.initDefaultProps = (function () {
  10958. var pathProto = Path.prototype;
  10959. pathProto.type = 'path';
  10960. pathProto.strokeContainThreshold = 5;
  10961. pathProto.segmentIgnoreThreshold = 0;
  10962. pathProto.subPixelOptimize = false;
  10963. pathProto.autoBatch = false;
  10964. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  10965. })();
  10966. return Path;
  10967. }(Displayable));
  10968. var DEFAULT_TSPAN_STYLE = defaults({
  10969. strokeFirst: true,
  10970. font: DEFAULT_FONT,
  10971. x: 0,
  10972. y: 0,
  10973. textAlign: 'left',
  10974. textBaseline: 'top',
  10975. miterLimit: 2
  10976. }, DEFAULT_PATH_STYLE);
  10977. var TSpan = (function (_super) {
  10978. __extends(TSpan, _super);
  10979. function TSpan() {
  10980. return _super !== null && _super.apply(this, arguments) || this;
  10981. }
  10982. TSpan.prototype.hasStroke = function () {
  10983. var style = this.style;
  10984. var stroke = style.stroke;
  10985. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10986. };
  10987. TSpan.prototype.hasFill = function () {
  10988. var style = this.style;
  10989. var fill = style.fill;
  10990. return fill != null && fill !== 'none';
  10991. };
  10992. TSpan.prototype.createStyle = function (obj) {
  10993. return createObject(DEFAULT_TSPAN_STYLE, obj);
  10994. };
  10995. TSpan.prototype.setBoundingRect = function (rect) {
  10996. this._rect = rect;
  10997. };
  10998. TSpan.prototype.getBoundingRect = function () {
  10999. var style = this.style;
  11000. if (!this._rect) {
  11001. var text = style.text;
  11002. text != null ? (text += '') : (text = '');
  11003. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11004. rect.x += style.x || 0;
  11005. rect.y += style.y || 0;
  11006. if (this.hasStroke()) {
  11007. var w = style.lineWidth;
  11008. rect.x -= w / 2;
  11009. rect.y -= w / 2;
  11010. rect.width += w;
  11011. rect.height += w;
  11012. }
  11013. this._rect = rect;
  11014. }
  11015. return this._rect;
  11016. };
  11017. TSpan.initDefaultProps = (function () {
  11018. var tspanProto = TSpan.prototype;
  11019. tspanProto.dirtyRectTolerance = 10;
  11020. })();
  11021. return TSpan;
  11022. }(Displayable));
  11023. TSpan.prototype.type = 'tspan';
  11024. var DEFAULT_IMAGE_STYLE = defaults({
  11025. x: 0,
  11026. y: 0
  11027. }, DEFAULT_COMMON_STYLE);
  11028. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11029. style: defaults({
  11030. x: true,
  11031. y: true,
  11032. width: true,
  11033. height: true,
  11034. sx: true,
  11035. sy: true,
  11036. sWidth: true,
  11037. sHeight: true
  11038. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11039. };
  11040. function isImageLike(source) {
  11041. return !!(source
  11042. && typeof source !== 'string'
  11043. && source.width && source.height);
  11044. }
  11045. var ZRImage = (function (_super) {
  11046. __extends(ZRImage, _super);
  11047. function ZRImage() {
  11048. return _super !== null && _super.apply(this, arguments) || this;
  11049. }
  11050. ZRImage.prototype.createStyle = function (obj) {
  11051. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11052. };
  11053. ZRImage.prototype._getSize = function (dim) {
  11054. var style = this.style;
  11055. var size = style[dim];
  11056. if (size != null) {
  11057. return size;
  11058. }
  11059. var imageSource = isImageLike(style.image)
  11060. ? style.image : this.__image;
  11061. if (!imageSource) {
  11062. return 0;
  11063. }
  11064. var otherDim = dim === 'width' ? 'height' : 'width';
  11065. var otherDimSize = style[otherDim];
  11066. if (otherDimSize == null) {
  11067. return imageSource[dim];
  11068. }
  11069. else {
  11070. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11071. }
  11072. };
  11073. ZRImage.prototype.getWidth = function () {
  11074. return this._getSize('width');
  11075. };
  11076. ZRImage.prototype.getHeight = function () {
  11077. return this._getSize('height');
  11078. };
  11079. ZRImage.prototype.getAnimationStyleProps = function () {
  11080. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11081. };
  11082. ZRImage.prototype.getBoundingRect = function () {
  11083. var style = this.style;
  11084. if (!this._rect) {
  11085. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11086. }
  11087. return this._rect;
  11088. };
  11089. return ZRImage;
  11090. }(Displayable));
  11091. ZRImage.prototype.type = 'image';
  11092. function buildPath(ctx, shape) {
  11093. var x = shape.x;
  11094. var y = shape.y;
  11095. var width = shape.width;
  11096. var height = shape.height;
  11097. var r = shape.r;
  11098. var r1;
  11099. var r2;
  11100. var r3;
  11101. var r4;
  11102. if (width < 0) {
  11103. x = x + width;
  11104. width = -width;
  11105. }
  11106. if (height < 0) {
  11107. y = y + height;
  11108. height = -height;
  11109. }
  11110. if (typeof r === 'number') {
  11111. r1 = r2 = r3 = r4 = r;
  11112. }
  11113. else if (r instanceof Array) {
  11114. if (r.length === 1) {
  11115. r1 = r2 = r3 = r4 = r[0];
  11116. }
  11117. else if (r.length === 2) {
  11118. r1 = r3 = r[0];
  11119. r2 = r4 = r[1];
  11120. }
  11121. else if (r.length === 3) {
  11122. r1 = r[0];
  11123. r2 = r4 = r[1];
  11124. r3 = r[2];
  11125. }
  11126. else {
  11127. r1 = r[0];
  11128. r2 = r[1];
  11129. r3 = r[2];
  11130. r4 = r[3];
  11131. }
  11132. }
  11133. else {
  11134. r1 = r2 = r3 = r4 = 0;
  11135. }
  11136. var total;
  11137. if (r1 + r2 > width) {
  11138. total = r1 + r2;
  11139. r1 *= width / total;
  11140. r2 *= width / total;
  11141. }
  11142. if (r3 + r4 > width) {
  11143. total = r3 + r4;
  11144. r3 *= width / total;
  11145. r4 *= width / total;
  11146. }
  11147. if (r2 + r3 > height) {
  11148. total = r2 + r3;
  11149. r2 *= height / total;
  11150. r3 *= height / total;
  11151. }
  11152. if (r1 + r4 > height) {
  11153. total = r1 + r4;
  11154. r1 *= height / total;
  11155. r4 *= height / total;
  11156. }
  11157. ctx.moveTo(x + r1, y);
  11158. ctx.lineTo(x + width - r2, y);
  11159. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11160. ctx.lineTo(x + width, y + height - r3);
  11161. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11162. ctx.lineTo(x + r4, y + height);
  11163. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11164. ctx.lineTo(x, y + r1);
  11165. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11166. }
  11167. var round$1 = Math.round;
  11168. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11169. if (!inputShape) {
  11170. return;
  11171. }
  11172. var x1 = inputShape.x1;
  11173. var x2 = inputShape.x2;
  11174. var y1 = inputShape.y1;
  11175. var y2 = inputShape.y2;
  11176. outputShape.x1 = x1;
  11177. outputShape.x2 = x2;
  11178. outputShape.y1 = y1;
  11179. outputShape.y2 = y2;
  11180. var lineWidth = style && style.lineWidth;
  11181. if (!lineWidth) {
  11182. return outputShape;
  11183. }
  11184. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11185. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11186. }
  11187. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11188. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11189. }
  11190. return outputShape;
  11191. }
  11192. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11193. if (!inputShape) {
  11194. return;
  11195. }
  11196. var originX = inputShape.x;
  11197. var originY = inputShape.y;
  11198. var originWidth = inputShape.width;
  11199. var originHeight = inputShape.height;
  11200. outputShape.x = originX;
  11201. outputShape.y = originY;
  11202. outputShape.width = originWidth;
  11203. outputShape.height = originHeight;
  11204. var lineWidth = style && style.lineWidth;
  11205. if (!lineWidth) {
  11206. return outputShape;
  11207. }
  11208. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11209. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11210. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11211. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11212. return outputShape;
  11213. }
  11214. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11215. if (!lineWidth) {
  11216. return position;
  11217. }
  11218. var doubledPosition = round$1(position * 2);
  11219. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11220. ? doubledPosition / 2
  11221. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11222. }
  11223. var RectShape = (function () {
  11224. function RectShape() {
  11225. this.x = 0;
  11226. this.y = 0;
  11227. this.width = 0;
  11228. this.height = 0;
  11229. }
  11230. return RectShape;
  11231. }());
  11232. var subPixelOptimizeOutputShape = {};
  11233. var Rect = (function (_super) {
  11234. __extends(Rect, _super);
  11235. function Rect(opts) {
  11236. return _super.call(this, opts) || this;
  11237. }
  11238. Rect.prototype.getDefaultShape = function () {
  11239. return new RectShape();
  11240. };
  11241. Rect.prototype.buildPath = function (ctx, shape) {
  11242. var x;
  11243. var y;
  11244. var width;
  11245. var height;
  11246. if (this.subPixelOptimize) {
  11247. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11248. x = optimizedShape.x;
  11249. y = optimizedShape.y;
  11250. width = optimizedShape.width;
  11251. height = optimizedShape.height;
  11252. optimizedShape.r = shape.r;
  11253. shape = optimizedShape;
  11254. }
  11255. else {
  11256. x = shape.x;
  11257. y = shape.y;
  11258. width = shape.width;
  11259. height = shape.height;
  11260. }
  11261. if (!shape.r) {
  11262. ctx.rect(x, y, width, height);
  11263. }
  11264. else {
  11265. buildPath(ctx, shape);
  11266. }
  11267. };
  11268. Rect.prototype.isZeroArea = function () {
  11269. return !this.shape.width || !this.shape.height;
  11270. };
  11271. return Rect;
  11272. }(Path));
  11273. Rect.prototype.type = 'rect';
  11274. var DEFAULT_RICH_TEXT_COLOR = {
  11275. fill: '#000'
  11276. };
  11277. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11278. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11279. style: defaults({
  11280. fill: true,
  11281. stroke: true,
  11282. fillOpacity: true,
  11283. strokeOpacity: true,
  11284. lineWidth: true,
  11285. fontSize: true,
  11286. lineHeight: true,
  11287. width: true,
  11288. height: true,
  11289. textShadowColor: true,
  11290. textShadowBlur: true,
  11291. textShadowOffsetX: true,
  11292. textShadowOffsetY: true,
  11293. backgroundColor: true,
  11294. padding: true,
  11295. borderColor: true,
  11296. borderWidth: true,
  11297. borderRadius: true
  11298. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11299. };
  11300. var ZRText = (function (_super) {
  11301. __extends(ZRText, _super);
  11302. function ZRText(opts) {
  11303. var _this = _super.call(this) || this;
  11304. _this.type = 'text';
  11305. _this._children = [];
  11306. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11307. _this.attr(opts);
  11308. return _this;
  11309. }
  11310. ZRText.prototype.childrenRef = function () {
  11311. return this._children;
  11312. };
  11313. ZRText.prototype.update = function () {
  11314. _super.prototype.update.call(this);
  11315. if (this.styleChanged()) {
  11316. this._updateSubTexts();
  11317. }
  11318. for (var i = 0; i < this._children.length; i++) {
  11319. var child = this._children[i];
  11320. child.zlevel = this.zlevel;
  11321. child.z = this.z;
  11322. child.z2 = this.z2;
  11323. child.culling = this.culling;
  11324. child.cursor = this.cursor;
  11325. child.invisible = this.invisible;
  11326. }
  11327. };
  11328. ZRText.prototype.updateTransform = function () {
  11329. var innerTransformable = this.innerTransformable;
  11330. if (innerTransformable) {
  11331. innerTransformable.updateTransform();
  11332. if (innerTransformable.transform) {
  11333. this.transform = innerTransformable.transform;
  11334. }
  11335. }
  11336. else {
  11337. _super.prototype.updateTransform.call(this);
  11338. }
  11339. };
  11340. ZRText.prototype.getLocalTransform = function (m) {
  11341. var innerTransformable = this.innerTransformable;
  11342. return innerTransformable
  11343. ? innerTransformable.getLocalTransform(m)
  11344. : _super.prototype.getLocalTransform.call(this, m);
  11345. };
  11346. ZRText.prototype.getComputedTransform = function () {
  11347. if (this.__hostTarget) {
  11348. this.__hostTarget.getComputedTransform();
  11349. this.__hostTarget.updateInnerText(true);
  11350. }
  11351. return _super.prototype.getComputedTransform.call(this);
  11352. };
  11353. ZRText.prototype._updateSubTexts = function () {
  11354. this._childCursor = 0;
  11355. normalizeTextStyle(this.style);
  11356. this.style.rich
  11357. ? this._updateRichTexts()
  11358. : this._updatePlainTexts();
  11359. this._children.length = this._childCursor;
  11360. this.styleUpdated();
  11361. };
  11362. ZRText.prototype.addSelfToZr = function (zr) {
  11363. _super.prototype.addSelfToZr.call(this, zr);
  11364. for (var i = 0; i < this._children.length; i++) {
  11365. this._children[i].__zr = zr;
  11366. }
  11367. };
  11368. ZRText.prototype.removeSelfFromZr = function (zr) {
  11369. _super.prototype.removeSelfFromZr.call(this, zr);
  11370. for (var i = 0; i < this._children.length; i++) {
  11371. this._children[i].__zr = null;
  11372. }
  11373. };
  11374. ZRText.prototype.getBoundingRect = function () {
  11375. if (this.styleChanged()) {
  11376. this._updateSubTexts();
  11377. }
  11378. if (!this._rect) {
  11379. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11380. var children = this._children;
  11381. var tmpMat = [];
  11382. var rect = null;
  11383. for (var i = 0; i < children.length; i++) {
  11384. var child = children[i];
  11385. var childRect = child.getBoundingRect();
  11386. var transform = child.getLocalTransform(tmpMat);
  11387. if (transform) {
  11388. tmpRect.copy(childRect);
  11389. tmpRect.applyTransform(transform);
  11390. rect = rect || tmpRect.clone();
  11391. rect.union(tmpRect);
  11392. }
  11393. else {
  11394. rect = rect || childRect.clone();
  11395. rect.union(childRect);
  11396. }
  11397. }
  11398. this._rect = rect || tmpRect;
  11399. }
  11400. return this._rect;
  11401. };
  11402. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11403. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11404. };
  11405. ZRText.prototype.setTextContent = function (textContent) {
  11406. if ("development" !== 'production') {
  11407. throw new Error('Can\'t attach text on another text');
  11408. }
  11409. };
  11410. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11411. if (!sourceStyle) {
  11412. return targetStyle;
  11413. }
  11414. var sourceRich = sourceStyle.rich;
  11415. var targetRich = targetStyle.rich || (sourceRich && {});
  11416. extend(targetStyle, sourceStyle);
  11417. if (sourceRich && targetRich) {
  11418. this._mergeRich(targetRich, sourceRich);
  11419. targetStyle.rich = targetRich;
  11420. }
  11421. else if (targetRich) {
  11422. targetStyle.rich = targetRich;
  11423. }
  11424. return targetStyle;
  11425. };
  11426. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11427. var richNames = keys(sourceRich);
  11428. for (var i = 0; i < richNames.length; i++) {
  11429. var richName = richNames[i];
  11430. targetRich[richName] = targetRich[richName] || {};
  11431. extend(targetRich[richName], sourceRich[richName]);
  11432. }
  11433. };
  11434. ZRText.prototype.getAnimationStyleProps = function () {
  11435. return DEFAULT_TEXT_ANIMATION_PROPS;
  11436. };
  11437. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11438. var child = this._children[this._childCursor];
  11439. if (!child || !(child instanceof Ctor)) {
  11440. child = new Ctor();
  11441. }
  11442. this._children[this._childCursor++] = child;
  11443. child.__zr = this.__zr;
  11444. child.parent = this;
  11445. return child;
  11446. };
  11447. ZRText.prototype._updatePlainTexts = function () {
  11448. var style = this.style;
  11449. var textFont = style.font || DEFAULT_FONT;
  11450. var textPadding = style.padding;
  11451. var text = getStyleText(style);
  11452. var contentBlock = parsePlainText(text, style);
  11453. var needDrawBg = needDrawBackground(style);
  11454. var bgColorDrawn = !!(style.backgroundColor);
  11455. var outerHeight = contentBlock.outerHeight;
  11456. var outerWidth = contentBlock.outerWidth;
  11457. var contentWidth = contentBlock.contentWidth;
  11458. var textLines = contentBlock.lines;
  11459. var lineHeight = contentBlock.lineHeight;
  11460. var defaultStyle = this._defaultStyle;
  11461. var baseX = style.x || 0;
  11462. var baseY = style.y || 0;
  11463. var textAlign = style.align || defaultStyle.align || 'left';
  11464. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11465. var textX = baseX;
  11466. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11467. if (needDrawBg || textPadding) {
  11468. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11469. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11470. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11471. }
  11472. textY += lineHeight / 2;
  11473. if (textPadding) {
  11474. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11475. if (verticalAlign === 'top') {
  11476. textY += textPadding[0];
  11477. }
  11478. else if (verticalAlign === 'bottom') {
  11479. textY -= textPadding[2];
  11480. }
  11481. }
  11482. var defaultLineWidth = 0;
  11483. var useDefaultFill = false;
  11484. var textFill = getFill('fill' in style
  11485. ? style.fill
  11486. : (useDefaultFill = true, defaultStyle.fill));
  11487. var textStroke = getStroke('stroke' in style
  11488. ? style.stroke
  11489. : (!bgColorDrawn
  11490. && (!defaultStyle.autoStroke || useDefaultFill))
  11491. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11492. : null);
  11493. var hasShadow = style.textShadowBlur > 0;
  11494. var fixedBoundingRect = style.width != null
  11495. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11496. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11497. for (var i = 0; i < textLines.length; i++) {
  11498. var el = this._getOrCreateChild(TSpan);
  11499. var subElStyle = el.createStyle();
  11500. el.useStyle(subElStyle);
  11501. subElStyle.text = textLines[i];
  11502. subElStyle.x = textX;
  11503. subElStyle.y = textY;
  11504. if (textAlign) {
  11505. subElStyle.textAlign = textAlign;
  11506. }
  11507. subElStyle.textBaseline = 'middle';
  11508. subElStyle.opacity = style.opacity;
  11509. subElStyle.strokeFirst = true;
  11510. if (hasShadow) {
  11511. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11512. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11513. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11514. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11515. }
  11516. subElStyle.stroke = textStroke;
  11517. subElStyle.fill = textFill;
  11518. if (textStroke) {
  11519. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11520. subElStyle.lineDash = style.lineDash;
  11521. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11522. }
  11523. subElStyle.font = textFont;
  11524. setSeparateFont(subElStyle, style);
  11525. textY += lineHeight;
  11526. if (fixedBoundingRect) {
  11527. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11528. }
  11529. }
  11530. };
  11531. ZRText.prototype._updateRichTexts = function () {
  11532. var style = this.style;
  11533. var text = getStyleText(style);
  11534. var contentBlock = parseRichText(text, style);
  11535. var contentWidth = contentBlock.width;
  11536. var outerWidth = contentBlock.outerWidth;
  11537. var outerHeight = contentBlock.outerHeight;
  11538. var textPadding = style.padding;
  11539. var baseX = style.x || 0;
  11540. var baseY = style.y || 0;
  11541. var defaultStyle = this._defaultStyle;
  11542. var textAlign = style.align || defaultStyle.align;
  11543. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11544. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11545. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11546. var xLeft = boxX;
  11547. var lineTop = boxY;
  11548. if (textPadding) {
  11549. xLeft += textPadding[3];
  11550. lineTop += textPadding[0];
  11551. }
  11552. var xRight = xLeft + contentWidth;
  11553. if (needDrawBackground(style)) {
  11554. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11555. }
  11556. var bgColorDrawn = !!(style.backgroundColor);
  11557. for (var i = 0; i < contentBlock.lines.length; i++) {
  11558. var line = contentBlock.lines[i];
  11559. var tokens = line.tokens;
  11560. var tokenCount = tokens.length;
  11561. var lineHeight = line.lineHeight;
  11562. var remainedWidth = line.width;
  11563. var leftIndex = 0;
  11564. var lineXLeft = xLeft;
  11565. var lineXRight = xRight;
  11566. var rightIndex = tokenCount - 1;
  11567. var token = void 0;
  11568. while (leftIndex < tokenCount
  11569. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11570. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11571. remainedWidth -= token.width;
  11572. lineXLeft += token.width;
  11573. leftIndex++;
  11574. }
  11575. while (rightIndex >= 0
  11576. && (token = tokens[rightIndex], token.align === 'right')) {
  11577. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11578. remainedWidth -= token.width;
  11579. lineXRight -= token.width;
  11580. rightIndex--;
  11581. }
  11582. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11583. while (leftIndex <= rightIndex) {
  11584. token = tokens[leftIndex];
  11585. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11586. lineXLeft += token.width;
  11587. leftIndex++;
  11588. }
  11589. lineTop += lineHeight;
  11590. }
  11591. };
  11592. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11593. var tokenStyle = style.rich[token.styleName] || {};
  11594. tokenStyle.text = token.text;
  11595. var verticalAlign = token.verticalAlign;
  11596. var y = lineTop + lineHeight / 2;
  11597. if (verticalAlign === 'top') {
  11598. y = lineTop + token.height / 2;
  11599. }
  11600. else if (verticalAlign === 'bottom') {
  11601. y = lineTop + lineHeight - token.height / 2;
  11602. }
  11603. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11604. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11605. ? x - token.width
  11606. : textAlign === 'center'
  11607. ? x - token.width / 2
  11608. : x, y - token.height / 2, token.width, token.height);
  11609. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11610. var textPadding = token.textPadding;
  11611. if (textPadding) {
  11612. x = getTextXForPadding(x, textAlign, textPadding);
  11613. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11614. }
  11615. var el = this._getOrCreateChild(TSpan);
  11616. var subElStyle = el.createStyle();
  11617. el.useStyle(subElStyle);
  11618. var defaultStyle = this._defaultStyle;
  11619. var useDefaultFill = false;
  11620. var defaultLineWidth = 0;
  11621. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11622. : 'fill' in style ? style.fill
  11623. : (useDefaultFill = true, defaultStyle.fill));
  11624. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11625. : 'stroke' in style ? style.stroke
  11626. : (!bgColorDrawn
  11627. && !parentBgColorDrawn
  11628. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11629. : null);
  11630. var hasShadow = tokenStyle.textShadowBlur > 0
  11631. || style.textShadowBlur > 0;
  11632. subElStyle.text = token.text;
  11633. subElStyle.x = x;
  11634. subElStyle.y = y;
  11635. if (hasShadow) {
  11636. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11637. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11638. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11639. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11640. }
  11641. subElStyle.textAlign = textAlign;
  11642. subElStyle.textBaseline = 'middle';
  11643. subElStyle.font = token.font || DEFAULT_FONT;
  11644. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11645. setSeparateFont(subElStyle, tokenStyle);
  11646. if (textStroke) {
  11647. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11648. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11649. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11650. subElStyle.stroke = textStroke;
  11651. }
  11652. if (textFill) {
  11653. subElStyle.fill = textFill;
  11654. }
  11655. var textWidth = token.contentWidth;
  11656. var textHeight = token.contentHeight;
  11657. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11658. };
  11659. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11660. var textBackgroundColor = style.backgroundColor;
  11661. var textBorderWidth = style.borderWidth;
  11662. var textBorderColor = style.borderColor;
  11663. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11664. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11665. var textBorderRadius = style.borderRadius;
  11666. var self = this;
  11667. var rectEl;
  11668. var imgEl;
  11669. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11670. rectEl = this._getOrCreateChild(Rect);
  11671. rectEl.useStyle(rectEl.createStyle());
  11672. rectEl.style.fill = null;
  11673. var rectShape = rectEl.shape;
  11674. rectShape.x = x;
  11675. rectShape.y = y;
  11676. rectShape.width = width;
  11677. rectShape.height = height;
  11678. rectShape.r = textBorderRadius;
  11679. rectEl.dirtyShape();
  11680. }
  11681. if (isPlainOrGradientBg) {
  11682. var rectStyle = rectEl.style;
  11683. rectStyle.fill = textBackgroundColor || null;
  11684. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11685. }
  11686. else if (isImageBg) {
  11687. imgEl = this._getOrCreateChild(ZRImage);
  11688. imgEl.onload = function () {
  11689. self.dirtyStyle();
  11690. };
  11691. var imgStyle = imgEl.style;
  11692. imgStyle.image = textBackgroundColor.image;
  11693. imgStyle.x = x;
  11694. imgStyle.y = y;
  11695. imgStyle.width = width;
  11696. imgStyle.height = height;
  11697. }
  11698. if (textBorderWidth && textBorderColor) {
  11699. var rectStyle = rectEl.style;
  11700. rectStyle.lineWidth = textBorderWidth;
  11701. rectStyle.stroke = textBorderColor;
  11702. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11703. rectStyle.lineDash = style.borderDash;
  11704. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11705. rectEl.strokeContainThreshold = 0;
  11706. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11707. rectStyle.strokeFirst = true;
  11708. rectStyle.lineWidth *= 2;
  11709. }
  11710. }
  11711. var commonStyle = (rectEl || imgEl).style;
  11712. commonStyle.shadowBlur = style.shadowBlur || 0;
  11713. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11714. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11715. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11716. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11717. };
  11718. ZRText.makeFont = function (style) {
  11719. var font = '';
  11720. if (hasSeparateFont(style)) {
  11721. font = [
  11722. style.fontStyle,
  11723. style.fontWeight,
  11724. parseFontSize(style.fontSize),
  11725. style.fontFamily || 'sans-serif'
  11726. ].join(' ');
  11727. }
  11728. return font && trim(font) || style.textFont || style.font;
  11729. };
  11730. return ZRText;
  11731. }(Displayable));
  11732. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11733. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11734. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11735. function parseFontSize(fontSize) {
  11736. if (typeof fontSize === 'string'
  11737. && (fontSize.indexOf('px') !== -1
  11738. || fontSize.indexOf('rem') !== -1
  11739. || fontSize.indexOf('em') !== -1)) {
  11740. return fontSize;
  11741. }
  11742. else if (!isNaN(+fontSize)) {
  11743. return fontSize + 'px';
  11744. }
  11745. else {
  11746. return DEFAULT_FONT_SIZE + 'px';
  11747. }
  11748. }
  11749. function setSeparateFont(targetStyle, sourceStyle) {
  11750. for (var i = 0; i < FONT_PARTS.length; i++) {
  11751. var fontProp = FONT_PARTS[i];
  11752. var val = sourceStyle[fontProp];
  11753. if (val != null) {
  11754. targetStyle[fontProp] = val;
  11755. }
  11756. }
  11757. }
  11758. function hasSeparateFont(style) {
  11759. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11760. }
  11761. function normalizeTextStyle(style) {
  11762. normalizeStyle(style);
  11763. each(style.rich, normalizeStyle);
  11764. return style;
  11765. }
  11766. function normalizeStyle(style) {
  11767. if (style) {
  11768. style.font = ZRText.makeFont(style);
  11769. var textAlign = style.align;
  11770. textAlign === 'middle' && (textAlign = 'center');
  11771. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11772. var verticalAlign = style.verticalAlign;
  11773. verticalAlign === 'center' && (verticalAlign = 'middle');
  11774. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11775. var textPadding = style.padding;
  11776. if (textPadding) {
  11777. style.padding = normalizeCssArray(style.padding);
  11778. }
  11779. }
  11780. }
  11781. function getStroke(stroke, lineWidth) {
  11782. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11783. ? null
  11784. : (stroke.image || stroke.colorStops)
  11785. ? '#000'
  11786. : stroke;
  11787. }
  11788. function getFill(fill) {
  11789. return (fill == null || fill === 'none')
  11790. ? null
  11791. : (fill.image || fill.colorStops)
  11792. ? '#000'
  11793. : fill;
  11794. }
  11795. function getTextXForPadding(x, textAlign, textPadding) {
  11796. return textAlign === 'right'
  11797. ? (x - textPadding[1])
  11798. : textAlign === 'center'
  11799. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11800. : (x + textPadding[3]);
  11801. }
  11802. function getStyleText(style) {
  11803. var text = style.text;
  11804. text != null && (text += '');
  11805. return text;
  11806. }
  11807. function needDrawBackground(style) {
  11808. return !!(style.backgroundColor
  11809. || style.lineHeight
  11810. || (style.borderWidth && style.borderColor));
  11811. }
  11812. var getECData = makeInner();
  11813. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  11814. if (el) {
  11815. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  11816. // Useful in tooltip
  11817. ecData.dataIndex = dataIdx;
  11818. ecData.dataType = dataType;
  11819. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  11820. if (el.type === 'group') {
  11821. el.traverse(function (child) {
  11822. var childECData = getECData(child);
  11823. childECData.seriesIndex = seriesIndex;
  11824. childECData.dataIndex = dataIdx;
  11825. childECData.dataType = dataType;
  11826. });
  11827. }
  11828. }
  11829. };
  11830. var _highlightNextDigit = 1;
  11831. var _highlightKeyMap = {};
  11832. var getSavedStates = makeInner();
  11833. var getComponentStates = makeInner();
  11834. var HOVER_STATE_NORMAL = 0;
  11835. var HOVER_STATE_BLUR = 1;
  11836. var HOVER_STATE_EMPHASIS = 2;
  11837. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11838. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11839. var Z2_EMPHASIS_LIFT = 10;
  11840. var Z2_SELECT_LIFT = 9;
  11841. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11842. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11843. var SELECT_ACTION_TYPE = 'select';
  11844. var UNSELECT_ACTION_TYPE = 'unselect';
  11845. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11846. function hasFillOrStroke(fillOrStroke) {
  11847. return fillOrStroke != null && fillOrStroke !== 'none';
  11848. } // Most lifted color are duplicated.
  11849. var liftedColorCache = new LRU(100);
  11850. function liftColor(color$1) {
  11851. if (isString(color$1)) {
  11852. var liftedColor = liftedColorCache.get(color$1);
  11853. if (!liftedColor) {
  11854. liftedColor = lift(color$1, -0.1);
  11855. liftedColorCache.put(color$1, liftedColor);
  11856. }
  11857. return liftedColor;
  11858. } else if (isGradientObject(color$1)) {
  11859. var ret = extend({}, color$1);
  11860. ret.colorStops = map(color$1.colorStops, function (stop) {
  11861. return {
  11862. offset: stop.offset,
  11863. color: lift(stop.color, -0.1)
  11864. };
  11865. });
  11866. return ret;
  11867. } // Change nothing.
  11868. return color$1;
  11869. }
  11870. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11871. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11872. el.onHoverStateChange(stateName);
  11873. }
  11874. el.hoverState = hoverStateEnum;
  11875. }
  11876. function singleEnterEmphasis(el) {
  11877. // Only mark the flag.
  11878. // States will be applied in the echarts.ts in next frame.
  11879. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11880. }
  11881. function singleLeaveEmphasis(el) {
  11882. // Only mark the flag.
  11883. // States will be applied in the echarts.ts in next frame.
  11884. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11885. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11886. }
  11887. }
  11888. function singleEnterBlur(el) {
  11889. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11890. }
  11891. function singleLeaveBlur(el) {
  11892. if (el.hoverState === HOVER_STATE_BLUR) {
  11893. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11894. }
  11895. }
  11896. function singleEnterSelect(el) {
  11897. el.selected = true;
  11898. }
  11899. function singleLeaveSelect(el) {
  11900. el.selected = false;
  11901. }
  11902. function updateElementState(el, updater, commonParam) {
  11903. updater(el, commonParam);
  11904. }
  11905. function traverseUpdateState(el, updater, commonParam) {
  11906. updateElementState(el, updater, commonParam);
  11907. el.isGroup && el.traverse(function (child) {
  11908. updateElementState(child, updater, commonParam);
  11909. });
  11910. }
  11911. function setStatesFlag(el, stateName) {
  11912. switch (stateName) {
  11913. case 'emphasis':
  11914. el.hoverState = HOVER_STATE_EMPHASIS;
  11915. break;
  11916. case 'normal':
  11917. el.hoverState = HOVER_STATE_NORMAL;
  11918. break;
  11919. case 'blur':
  11920. el.hoverState = HOVER_STATE_BLUR;
  11921. break;
  11922. case 'select':
  11923. el.selected = true;
  11924. }
  11925. }
  11926. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11927. var style = el.style;
  11928. var fromState = {};
  11929. for (var i = 0; i < props.length; i++) {
  11930. var propName = props[i];
  11931. var val = style[propName];
  11932. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11933. }
  11934. for (var i = 0; i < el.animators.length; i++) {
  11935. var animator = el.animators[i];
  11936. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11937. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11938. animator.saveTo(fromState, props);
  11939. }
  11940. }
  11941. return fromState;
  11942. }
  11943. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11944. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11945. var cloned = false;
  11946. if (el instanceof Path) {
  11947. var store = getSavedStates(el);
  11948. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11949. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11950. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11951. state = state || {};
  11952. var emphasisStyle = state.style || {}; // inherit case
  11953. if (emphasisStyle.fill === 'inherit') {
  11954. cloned = true;
  11955. state = extend({}, state);
  11956. emphasisStyle = extend({}, emphasisStyle);
  11957. emphasisStyle.fill = fromFill;
  11958. } // Apply default color lift
  11959. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11960. cloned = true; // Not modify the original value.
  11961. state = extend({}, state);
  11962. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11963. emphasisStyle.fill = liftColor(fromFill);
  11964. } // Not highlight stroke if fill has been highlighted.
  11965. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11966. if (!cloned) {
  11967. state = extend({}, state);
  11968. emphasisStyle = extend({}, emphasisStyle);
  11969. }
  11970. emphasisStyle.stroke = liftColor(fromStroke);
  11971. }
  11972. state.style = emphasisStyle;
  11973. }
  11974. }
  11975. if (state) {
  11976. // TODO Share with textContent?
  11977. if (state.z2 == null) {
  11978. if (!cloned) {
  11979. state = extend({}, state);
  11980. }
  11981. var z2EmphasisLift = el.z2EmphasisLift;
  11982. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11983. }
  11984. }
  11985. return state;
  11986. }
  11987. function createSelectDefaultState(el, stateName, state) {
  11988. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11989. if (state) {
  11990. // TODO Share with textContent?
  11991. if (state.z2 == null) {
  11992. state = extend({}, state);
  11993. var z2SelectLift = el.z2SelectLift;
  11994. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11995. }
  11996. }
  11997. return state;
  11998. }
  11999. function createBlurDefaultState(el, stateName, state) {
  12000. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12001. var currentOpacity = el.style.opacity;
  12002. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12003. opacity: 1
  12004. }) : null;
  12005. state = state || {};
  12006. var blurStyle = state.style || {};
  12007. if (blurStyle.opacity == null) {
  12008. // clone state
  12009. state = extend({}, state);
  12010. blurStyle = extend({
  12011. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12012. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12013. }, blurStyle);
  12014. state.style = blurStyle;
  12015. }
  12016. return state;
  12017. }
  12018. function elementStateProxy(stateName, targetStates) {
  12019. var state = this.states[stateName];
  12020. if (this.style) {
  12021. if (stateName === 'emphasis') {
  12022. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12023. } else if (stateName === 'blur') {
  12024. return createBlurDefaultState(this, stateName, state);
  12025. } else if (stateName === 'select') {
  12026. return createSelectDefaultState(this, stateName, state);
  12027. }
  12028. }
  12029. return state;
  12030. }
  12031. /**FI
  12032. * Set hover style (namely "emphasis style") of element.
  12033. * @param el Should not be `zrender/graphic/Group`.
  12034. * @param focus 'self' | 'selfInSeries' | 'series'
  12035. */
  12036. function setDefaultStateProxy(el) {
  12037. el.stateProxy = elementStateProxy;
  12038. var textContent = el.getTextContent();
  12039. var textGuide = el.getTextGuideLine();
  12040. if (textContent) {
  12041. textContent.stateProxy = elementStateProxy;
  12042. }
  12043. if (textGuide) {
  12044. textGuide.stateProxy = elementStateProxy;
  12045. }
  12046. }
  12047. function enterEmphasisWhenMouseOver(el, e) {
  12048. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12049. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12050. }
  12051. function leaveEmphasisWhenMouseOut(el, e) {
  12052. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12053. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12054. }
  12055. function enterEmphasis(el, highlightDigit) {
  12056. el.__highByOuter |= 1 << (highlightDigit || 0);
  12057. traverseUpdateState(el, singleEnterEmphasis);
  12058. }
  12059. function leaveEmphasis(el, highlightDigit) {
  12060. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12061. }
  12062. function enterBlur(el) {
  12063. traverseUpdateState(el, singleEnterBlur);
  12064. }
  12065. function leaveBlur(el) {
  12066. traverseUpdateState(el, singleLeaveBlur);
  12067. }
  12068. function enterSelect(el) {
  12069. traverseUpdateState(el, singleEnterSelect);
  12070. }
  12071. function leaveSelect(el) {
  12072. traverseUpdateState(el, singleLeaveSelect);
  12073. }
  12074. function shouldSilent(el, e) {
  12075. return el.__highDownSilentOnTouch && e.zrByTouch;
  12076. }
  12077. function allLeaveBlur(api) {
  12078. var model = api.getModel();
  12079. var leaveBlurredSeries = [];
  12080. var allComponentViews = [];
  12081. model.eachComponent(function (componentType, componentModel) {
  12082. var componentStates = getComponentStates(componentModel);
  12083. var isSeries = componentType === 'series';
  12084. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12085. !isSeries && allComponentViews.push(view);
  12086. if (componentStates.isBlured) {
  12087. // Leave blur anyway
  12088. view.group.traverse(function (child) {
  12089. singleLeaveBlur(child);
  12090. });
  12091. isSeries && leaveBlurredSeries.push(componentModel);
  12092. }
  12093. componentStates.isBlured = false;
  12094. });
  12095. each(allComponentViews, function (view) {
  12096. if (view && view.toggleBlurSeries) {
  12097. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12098. }
  12099. });
  12100. }
  12101. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12102. var ecModel = api.getModel();
  12103. blurScope = blurScope || 'coordinateSystem';
  12104. function leaveBlurOfIndices(data, dataIndices) {
  12105. for (var i = 0; i < dataIndices.length; i++) {
  12106. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12107. itemEl && leaveBlur(itemEl);
  12108. }
  12109. }
  12110. if (targetSeriesIndex == null) {
  12111. return;
  12112. }
  12113. if (!focus || focus === 'none') {
  12114. return;
  12115. }
  12116. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12117. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12118. if (targetCoordSys && targetCoordSys.master) {
  12119. targetCoordSys = targetCoordSys.master;
  12120. }
  12121. var blurredSeries = [];
  12122. ecModel.eachSeries(function (seriesModel) {
  12123. var sameSeries = targetSeriesModel === seriesModel;
  12124. var coordSys = seriesModel.coordinateSystem;
  12125. if (coordSys && coordSys.master) {
  12126. coordSys = coordSys.master;
  12127. }
  12128. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12129. if (!( // Not blur other series if blurScope series
  12130. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12131. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12132. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12133. )) {
  12134. var view = api.getViewOfSeriesModel(seriesModel);
  12135. view.group.traverse(function (child) {
  12136. singleEnterBlur(child);
  12137. });
  12138. if (isArrayLike(focus)) {
  12139. leaveBlurOfIndices(seriesModel.getData(), focus);
  12140. } else if (isObject(focus)) {
  12141. var dataTypes = keys(focus);
  12142. for (var d = 0; d < dataTypes.length; d++) {
  12143. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12144. }
  12145. }
  12146. blurredSeries.push(seriesModel);
  12147. getComponentStates(seriesModel).isBlured = true;
  12148. }
  12149. });
  12150. ecModel.eachComponent(function (componentType, componentModel) {
  12151. if (componentType === 'series') {
  12152. return;
  12153. }
  12154. var view = api.getViewOfComponentModel(componentModel);
  12155. if (view && view.toggleBlurSeries) {
  12156. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12157. }
  12158. });
  12159. }
  12160. function blurComponent(componentMainType, componentIndex, api) {
  12161. if (componentMainType == null || componentIndex == null) {
  12162. return;
  12163. }
  12164. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12165. if (!componentModel) {
  12166. return;
  12167. }
  12168. getComponentStates(componentModel).isBlured = true;
  12169. var view = api.getViewOfComponentModel(componentModel);
  12170. if (!view || !view.focusBlurEnabled) {
  12171. return;
  12172. }
  12173. view.group.traverse(function (child) {
  12174. singleEnterBlur(child);
  12175. });
  12176. }
  12177. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12178. var seriesIndex = seriesModel.seriesIndex;
  12179. var data = seriesModel.getData(payload.dataType);
  12180. if (!data) {
  12181. if ("development" !== 'production') {
  12182. error("Unknown dataType " + payload.dataType);
  12183. }
  12184. return;
  12185. }
  12186. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12187. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12188. var el = data.getItemGraphicEl(dataIndex);
  12189. if (!el) {
  12190. var count = data.count();
  12191. var current = 0; // If data on dataIndex is NaN.
  12192. while (!el && current < count) {
  12193. el = data.getItemGraphicEl(current++);
  12194. }
  12195. }
  12196. if (el) {
  12197. var ecData = getECData(el);
  12198. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12199. } else {
  12200. // If there is no element put on the data. Try getting it from raw option
  12201. // TODO Should put it on seriesModel?
  12202. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12203. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12204. if (focus_1 != null) {
  12205. blurSeries(seriesIndex, focus_1, blurScope, api);
  12206. }
  12207. }
  12208. }
  12209. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12210. var ret = {
  12211. focusSelf: false,
  12212. dispatchers: null
  12213. };
  12214. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12215. return ret;
  12216. }
  12217. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12218. if (!componentModel) {
  12219. return ret;
  12220. }
  12221. var view = api.getViewOfComponentModel(componentModel);
  12222. if (!view || !view.findHighDownDispatchers) {
  12223. return ret;
  12224. }
  12225. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12226. // So we do not use `blurScope` in component.
  12227. var focusSelf;
  12228. for (var i = 0; i < dispatchers.length; i++) {
  12229. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12230. error('param should be highDownDispatcher');
  12231. }
  12232. if (getECData(dispatchers[i]).focus === 'self') {
  12233. focusSelf = true;
  12234. break;
  12235. }
  12236. }
  12237. return {
  12238. focusSelf: focusSelf,
  12239. dispatchers: dispatchers
  12240. };
  12241. }
  12242. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12243. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12244. error('param should be highDownDispatcher');
  12245. }
  12246. var ecData = getECData(dispatcher);
  12247. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12248. dispatchers = _a.dispatchers,
  12249. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12250. // highlight/downplay elements with the same name.
  12251. if (dispatchers) {
  12252. if (focusSelf) {
  12253. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12254. }
  12255. each(dispatchers, function (dispatcher) {
  12256. return enterEmphasisWhenMouseOver(dispatcher, e);
  12257. });
  12258. } else {
  12259. // Try blur all in the related series. Then emphasis the hoverred.
  12260. // TODO. progressive mode.
  12261. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12262. if (ecData.focus === 'self') {
  12263. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12264. } // Other than series, component that not support `findHighDownDispatcher` will
  12265. // also use it. But in this case, highlight/downplay are only supported in
  12266. // mouse hover but not in dispatchAction.
  12267. enterEmphasisWhenMouseOver(dispatcher, e);
  12268. }
  12269. }
  12270. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12271. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12272. error('param should be highDownDispatcher');
  12273. }
  12274. allLeaveBlur(api);
  12275. var ecData = getECData(dispatcher);
  12276. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12277. if (dispatchers) {
  12278. each(dispatchers, function (dispatcher) {
  12279. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12280. });
  12281. } else {
  12282. leaveEmphasisWhenMouseOut(dispatcher, e);
  12283. }
  12284. }
  12285. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12286. if (!isSelectChangePayload(payload)) {
  12287. return;
  12288. }
  12289. var dataType = payload.dataType;
  12290. var data = seriesModel.getData(dataType);
  12291. var dataIndex = queryDataIndex(data, payload);
  12292. if (!isArray(dataIndex)) {
  12293. dataIndex = [dataIndex];
  12294. }
  12295. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12296. }
  12297. function updateSeriesElementSelection(seriesModel) {
  12298. var allData = seriesModel.getAllData();
  12299. each(allData, function (_a) {
  12300. var data = _a.data,
  12301. type = _a.type;
  12302. data.eachItemGraphicEl(function (el, idx) {
  12303. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12304. });
  12305. });
  12306. }
  12307. function getAllSelectedIndices(ecModel) {
  12308. var ret = [];
  12309. ecModel.eachSeries(function (seriesModel) {
  12310. var allData = seriesModel.getAllData();
  12311. each(allData, function (_a) {
  12312. var data = _a.data,
  12313. type = _a.type;
  12314. var dataIndices = seriesModel.getSelectedDataIndices();
  12315. if (dataIndices.length > 0) {
  12316. var item = {
  12317. dataIndex: dataIndices,
  12318. seriesIndex: seriesModel.seriesIndex
  12319. };
  12320. if (type != null) {
  12321. item.dataType = type;
  12322. }
  12323. ret.push(item);
  12324. }
  12325. });
  12326. });
  12327. return ret;
  12328. }
  12329. /**
  12330. * Enable the function that mouseover will trigger the emphasis state.
  12331. *
  12332. * NOTE:
  12333. * This function should be used on the element with dataIndex, seriesIndex.
  12334. *
  12335. */
  12336. function enableHoverEmphasis(el, focus, blurScope) {
  12337. setAsHighDownDispatcher(el, true);
  12338. traverseUpdateState(el, setDefaultStateProxy);
  12339. enableHoverFocus(el, focus, blurScope);
  12340. }
  12341. function disableHoverEmphasis(el) {
  12342. setAsHighDownDispatcher(el, false);
  12343. }
  12344. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12345. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12346. }
  12347. function enableHoverFocus(el, focus, blurScope) {
  12348. var ecData = getECData(el);
  12349. if (focus != null) {
  12350. // TODO dataIndex may be set after this function. This check is not useful.
  12351. // if (ecData.dataIndex == null) {
  12352. // if (__DEV__) {
  12353. // console.warn('focus can only been set on element with dataIndex');
  12354. // }
  12355. // }
  12356. // else {
  12357. ecData.focus = focus;
  12358. ecData.blurScope = blurScope; // }
  12359. } else if (ecData.focus) {
  12360. ecData.focus = null;
  12361. }
  12362. }
  12363. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12364. var defaultStyleGetterMap = {
  12365. itemStyle: 'getItemStyle',
  12366. lineStyle: 'getLineStyle',
  12367. areaStyle: 'getAreaStyle'
  12368. };
  12369. /**
  12370. * Set emphasis/blur/selected states of element.
  12371. */
  12372. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12373. getter) {
  12374. styleType = styleType || 'itemStyle';
  12375. for (var i = 0; i < OTHER_STATES.length; i++) {
  12376. var stateName = OTHER_STATES[i];
  12377. var model = itemModel.getModel([stateName, styleType]);
  12378. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12379. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12380. }
  12381. }
  12382. /**
  12383. *
  12384. * Set element as highlight / downplay dispatcher.
  12385. * It will be checked when element recieved mouseover event or from highlight action.
  12386. * It's in change of all highlight/downplay behavior of it's children.
  12387. *
  12388. * @param el
  12389. * @param el.highDownSilentOnTouch
  12390. * In touch device, mouseover event will be trigger on touchstart event
  12391. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12392. * conveniently use hoverStyle when tap on touch screen without additional
  12393. * code for compatibility.
  12394. * But if the chart/component has select feature, which usually also use
  12395. * hoverStyle, there might be conflict between 'select-highlight' and
  12396. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12397. * In this case, `highDownSilentOnTouch` should be used to disable
  12398. * hover-highlight on touch device.
  12399. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12400. */
  12401. function setAsHighDownDispatcher(el, asDispatcher) {
  12402. var disable = asDispatcher === false;
  12403. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12404. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12405. if (el.highDownSilentOnTouch) {
  12406. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12407. } // Simple optimize, since this method might be
  12408. // called for each elements of a group in some cases.
  12409. if (!disable || extendedEl.__highDownDispatcher) {
  12410. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12411. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12412. // Also keep previous record.
  12413. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12414. extendedEl.__highDownDispatcher = !disable;
  12415. }
  12416. }
  12417. function isHighDownDispatcher(el) {
  12418. return !!(el && el.__highDownDispatcher);
  12419. }
  12420. /**
  12421. * Support hightlight/downplay record on each elements.
  12422. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12423. * user triggerred hightlight/downplay should not conflict.
  12424. * Only all of the highlightDigit cleared, return to normal.
  12425. * @param {string} highlightKey
  12426. * @return {number} highlightDigit
  12427. */
  12428. function getHighlightDigit(highlightKey) {
  12429. var highlightDigit = _highlightKeyMap[highlightKey];
  12430. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12431. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12432. }
  12433. return highlightDigit;
  12434. }
  12435. function isSelectChangePayload(payload) {
  12436. var payloadType = payload.type;
  12437. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12438. }
  12439. function isHighDownPayload(payload) {
  12440. var payloadType = payload.type;
  12441. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12442. }
  12443. function savePathStates(el) {
  12444. var store = getSavedStates(el);
  12445. store.normalFill = el.style.fill;
  12446. store.normalStroke = el.style.stroke;
  12447. var selectState = el.states.select || {};
  12448. store.selectFill = selectState.style && selectState.style.fill || null;
  12449. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12450. }
  12451. var CMD$2 = PathProxy.CMD;
  12452. var points = [[], [], []];
  12453. var mathSqrt$1 = Math.sqrt;
  12454. var mathAtan2 = Math.atan2;
  12455. function transformPath(path, m) {
  12456. if (!m) {
  12457. return;
  12458. }
  12459. var data = path.data;
  12460. var len = path.len();
  12461. var cmd;
  12462. var nPoint;
  12463. var i;
  12464. var j;
  12465. var k;
  12466. var p;
  12467. var M = CMD$2.M;
  12468. var C = CMD$2.C;
  12469. var L = CMD$2.L;
  12470. var R = CMD$2.R;
  12471. var A = CMD$2.A;
  12472. var Q = CMD$2.Q;
  12473. for (i = 0, j = 0; i < len;) {
  12474. cmd = data[i++];
  12475. j = i;
  12476. nPoint = 0;
  12477. switch (cmd) {
  12478. case M:
  12479. nPoint = 1;
  12480. break;
  12481. case L:
  12482. nPoint = 1;
  12483. break;
  12484. case C:
  12485. nPoint = 3;
  12486. break;
  12487. case Q:
  12488. nPoint = 2;
  12489. break;
  12490. case A:
  12491. var x = m[4];
  12492. var y = m[5];
  12493. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12494. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12495. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12496. data[i] *= sx;
  12497. data[i++] += x;
  12498. data[i] *= sy;
  12499. data[i++] += y;
  12500. data[i++] *= sx;
  12501. data[i++] *= sy;
  12502. data[i++] += angle;
  12503. data[i++] += angle;
  12504. i += 2;
  12505. j = i;
  12506. break;
  12507. case R:
  12508. p[0] = data[i++];
  12509. p[1] = data[i++];
  12510. applyTransform(p, p, m);
  12511. data[j++] = p[0];
  12512. data[j++] = p[1];
  12513. p[0] += data[i++];
  12514. p[1] += data[i++];
  12515. applyTransform(p, p, m);
  12516. data[j++] = p[0];
  12517. data[j++] = p[1];
  12518. }
  12519. for (k = 0; k < nPoint; k++) {
  12520. var p_1 = points[k];
  12521. p_1[0] = data[i++];
  12522. p_1[1] = data[i++];
  12523. applyTransform(p_1, p_1, m);
  12524. data[j++] = p_1[0];
  12525. data[j++] = p_1[1];
  12526. }
  12527. }
  12528. path.increaseVersion();
  12529. }
  12530. var mathSqrt$2 = Math.sqrt;
  12531. var mathSin$2 = Math.sin;
  12532. var mathCos$2 = Math.cos;
  12533. var PI$1 = Math.PI;
  12534. function vMag(v) {
  12535. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12536. }
  12537. function vRatio(u, v) {
  12538. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12539. }
  12540. function vAngle(u, v) {
  12541. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12542. * Math.acos(vRatio(u, v));
  12543. }
  12544. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12545. var psi = psiDeg * (PI$1 / 180.0);
  12546. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12547. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12548. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12549. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12550. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12551. if (lambda > 1) {
  12552. rx *= mathSqrt$2(lambda);
  12553. ry *= mathSqrt$2(lambda);
  12554. }
  12555. var f = (fa === fs ? -1 : 1)
  12556. * mathSqrt$2((((rx * rx) * (ry * ry))
  12557. - ((rx * rx) * (yp * yp))
  12558. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12559. + (ry * ry) * (xp * xp))) || 0;
  12560. var cxp = f * rx * yp / ry;
  12561. var cyp = f * -ry * xp / rx;
  12562. var cx = (x1 + x2) / 2.0
  12563. + mathCos$2(psi) * cxp
  12564. - mathSin$2(psi) * cyp;
  12565. var cy = (y1 + y2) / 2.0
  12566. + mathSin$2(psi) * cxp
  12567. + mathCos$2(psi) * cyp;
  12568. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12569. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12570. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12571. var dTheta = vAngle(u, v);
  12572. if (vRatio(u, v) <= -1) {
  12573. dTheta = PI$1;
  12574. }
  12575. if (vRatio(u, v) >= 1) {
  12576. dTheta = 0;
  12577. }
  12578. if (dTheta < 0) {
  12579. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12580. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12581. }
  12582. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12583. }
  12584. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12585. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12586. function createPathProxyFromString(data) {
  12587. var path = new PathProxy();
  12588. if (!data) {
  12589. return path;
  12590. }
  12591. var cpx = 0;
  12592. var cpy = 0;
  12593. var subpathX = cpx;
  12594. var subpathY = cpy;
  12595. var prevCmd;
  12596. var CMD = PathProxy.CMD;
  12597. var cmdList = data.match(commandReg);
  12598. if (!cmdList) {
  12599. return path;
  12600. }
  12601. for (var l = 0; l < cmdList.length; l++) {
  12602. var cmdText = cmdList[l];
  12603. var cmdStr = cmdText.charAt(0);
  12604. var cmd = void 0;
  12605. var p = cmdText.match(numberReg) || [];
  12606. var pLen = p.length;
  12607. for (var i = 0; i < pLen; i++) {
  12608. p[i] = parseFloat(p[i]);
  12609. }
  12610. var off = 0;
  12611. while (off < pLen) {
  12612. var ctlPtx = void 0;
  12613. var ctlPty = void 0;
  12614. var rx = void 0;
  12615. var ry = void 0;
  12616. var psi = void 0;
  12617. var fa = void 0;
  12618. var fs = void 0;
  12619. var x1 = cpx;
  12620. var y1 = cpy;
  12621. var len = void 0;
  12622. var pathData = void 0;
  12623. switch (cmdStr) {
  12624. case 'l':
  12625. cpx += p[off++];
  12626. cpy += p[off++];
  12627. cmd = CMD.L;
  12628. path.addData(cmd, cpx, cpy);
  12629. break;
  12630. case 'L':
  12631. cpx = p[off++];
  12632. cpy = p[off++];
  12633. cmd = CMD.L;
  12634. path.addData(cmd, cpx, cpy);
  12635. break;
  12636. case 'm':
  12637. cpx += p[off++];
  12638. cpy += p[off++];
  12639. cmd = CMD.M;
  12640. path.addData(cmd, cpx, cpy);
  12641. subpathX = cpx;
  12642. subpathY = cpy;
  12643. cmdStr = 'l';
  12644. break;
  12645. case 'M':
  12646. cpx = p[off++];
  12647. cpy = p[off++];
  12648. cmd = CMD.M;
  12649. path.addData(cmd, cpx, cpy);
  12650. subpathX = cpx;
  12651. subpathY = cpy;
  12652. cmdStr = 'L';
  12653. break;
  12654. case 'h':
  12655. cpx += p[off++];
  12656. cmd = CMD.L;
  12657. path.addData(cmd, cpx, cpy);
  12658. break;
  12659. case 'H':
  12660. cpx = p[off++];
  12661. cmd = CMD.L;
  12662. path.addData(cmd, cpx, cpy);
  12663. break;
  12664. case 'v':
  12665. cpy += p[off++];
  12666. cmd = CMD.L;
  12667. path.addData(cmd, cpx, cpy);
  12668. break;
  12669. case 'V':
  12670. cpy = p[off++];
  12671. cmd = CMD.L;
  12672. path.addData(cmd, cpx, cpy);
  12673. break;
  12674. case 'C':
  12675. cmd = CMD.C;
  12676. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12677. cpx = p[off - 2];
  12678. cpy = p[off - 1];
  12679. break;
  12680. case 'c':
  12681. cmd = CMD.C;
  12682. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12683. cpx += p[off - 2];
  12684. cpy += p[off - 1];
  12685. break;
  12686. case 'S':
  12687. ctlPtx = cpx;
  12688. ctlPty = cpy;
  12689. len = path.len();
  12690. pathData = path.data;
  12691. if (prevCmd === CMD.C) {
  12692. ctlPtx += cpx - pathData[len - 4];
  12693. ctlPty += cpy - pathData[len - 3];
  12694. }
  12695. cmd = CMD.C;
  12696. x1 = p[off++];
  12697. y1 = p[off++];
  12698. cpx = p[off++];
  12699. cpy = p[off++];
  12700. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12701. break;
  12702. case 's':
  12703. ctlPtx = cpx;
  12704. ctlPty = cpy;
  12705. len = path.len();
  12706. pathData = path.data;
  12707. if (prevCmd === CMD.C) {
  12708. ctlPtx += cpx - pathData[len - 4];
  12709. ctlPty += cpy - pathData[len - 3];
  12710. }
  12711. cmd = CMD.C;
  12712. x1 = cpx + p[off++];
  12713. y1 = cpy + p[off++];
  12714. cpx += p[off++];
  12715. cpy += p[off++];
  12716. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12717. break;
  12718. case 'Q':
  12719. x1 = p[off++];
  12720. y1 = p[off++];
  12721. cpx = p[off++];
  12722. cpy = p[off++];
  12723. cmd = CMD.Q;
  12724. path.addData(cmd, x1, y1, cpx, cpy);
  12725. break;
  12726. case 'q':
  12727. x1 = p[off++] + cpx;
  12728. y1 = p[off++] + cpy;
  12729. cpx += p[off++];
  12730. cpy += p[off++];
  12731. cmd = CMD.Q;
  12732. path.addData(cmd, x1, y1, cpx, cpy);
  12733. break;
  12734. case 'T':
  12735. ctlPtx = cpx;
  12736. ctlPty = cpy;
  12737. len = path.len();
  12738. pathData = path.data;
  12739. if (prevCmd === CMD.Q) {
  12740. ctlPtx += cpx - pathData[len - 4];
  12741. ctlPty += cpy - pathData[len - 3];
  12742. }
  12743. cpx = p[off++];
  12744. cpy = p[off++];
  12745. cmd = CMD.Q;
  12746. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12747. break;
  12748. case 't':
  12749. ctlPtx = cpx;
  12750. ctlPty = cpy;
  12751. len = path.len();
  12752. pathData = path.data;
  12753. if (prevCmd === CMD.Q) {
  12754. ctlPtx += cpx - pathData[len - 4];
  12755. ctlPty += cpy - pathData[len - 3];
  12756. }
  12757. cpx += p[off++];
  12758. cpy += p[off++];
  12759. cmd = CMD.Q;
  12760. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12761. break;
  12762. case 'A':
  12763. rx = p[off++];
  12764. ry = p[off++];
  12765. psi = p[off++];
  12766. fa = p[off++];
  12767. fs = p[off++];
  12768. x1 = cpx, y1 = cpy;
  12769. cpx = p[off++];
  12770. cpy = p[off++];
  12771. cmd = CMD.A;
  12772. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12773. break;
  12774. case 'a':
  12775. rx = p[off++];
  12776. ry = p[off++];
  12777. psi = p[off++];
  12778. fa = p[off++];
  12779. fs = p[off++];
  12780. x1 = cpx, y1 = cpy;
  12781. cpx += p[off++];
  12782. cpy += p[off++];
  12783. cmd = CMD.A;
  12784. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12785. break;
  12786. }
  12787. }
  12788. if (cmdStr === 'z' || cmdStr === 'Z') {
  12789. cmd = CMD.Z;
  12790. path.addData(cmd);
  12791. cpx = subpathX;
  12792. cpy = subpathY;
  12793. }
  12794. prevCmd = cmd;
  12795. }
  12796. path.toStatic();
  12797. return path;
  12798. }
  12799. var SVGPath = (function (_super) {
  12800. __extends(SVGPath, _super);
  12801. function SVGPath() {
  12802. return _super !== null && _super.apply(this, arguments) || this;
  12803. }
  12804. SVGPath.prototype.applyTransform = function (m) { };
  12805. return SVGPath;
  12806. }(Path));
  12807. function isPathProxy(path) {
  12808. return path.setData != null;
  12809. }
  12810. function createPathOptions(str, opts) {
  12811. var pathProxy = createPathProxyFromString(str);
  12812. var innerOpts = extend({}, opts);
  12813. innerOpts.buildPath = function (path) {
  12814. if (isPathProxy(path)) {
  12815. path.setData(pathProxy.data);
  12816. var ctx = path.getContext();
  12817. if (ctx) {
  12818. path.rebuildPath(ctx, 1);
  12819. }
  12820. }
  12821. else {
  12822. var ctx = path;
  12823. pathProxy.rebuildPath(ctx, 1);
  12824. }
  12825. };
  12826. innerOpts.applyTransform = function (m) {
  12827. transformPath(pathProxy, m);
  12828. this.dirtyShape();
  12829. };
  12830. return innerOpts;
  12831. }
  12832. function createFromString(str, opts) {
  12833. return new SVGPath(createPathOptions(str, opts));
  12834. }
  12835. function extendFromString(str, defaultOpts) {
  12836. var innerOpts = createPathOptions(str, defaultOpts);
  12837. var Sub = (function (_super) {
  12838. __extends(Sub, _super);
  12839. function Sub(opts) {
  12840. var _this = _super.call(this, opts) || this;
  12841. _this.applyTransform = innerOpts.applyTransform;
  12842. _this.buildPath = innerOpts.buildPath;
  12843. return _this;
  12844. }
  12845. return Sub;
  12846. }(SVGPath));
  12847. return Sub;
  12848. }
  12849. function mergePath(pathEls, opts) {
  12850. var pathList = [];
  12851. var len = pathEls.length;
  12852. for (var i = 0; i < len; i++) {
  12853. var pathEl = pathEls[i];
  12854. pathList.push(pathEl.getUpdatedPathProxy(true));
  12855. }
  12856. var pathBundle = new Path(opts);
  12857. pathBundle.createPathProxy();
  12858. pathBundle.buildPath = function (path) {
  12859. if (isPathProxy(path)) {
  12860. path.appendPath(pathList);
  12861. var ctx = path.getContext();
  12862. if (ctx) {
  12863. path.rebuildPath(ctx, 1);
  12864. }
  12865. }
  12866. };
  12867. return pathBundle;
  12868. }
  12869. var CircleShape = (function () {
  12870. function CircleShape() {
  12871. this.cx = 0;
  12872. this.cy = 0;
  12873. this.r = 0;
  12874. }
  12875. return CircleShape;
  12876. }());
  12877. var Circle = (function (_super) {
  12878. __extends(Circle, _super);
  12879. function Circle(opts) {
  12880. return _super.call(this, opts) || this;
  12881. }
  12882. Circle.prototype.getDefaultShape = function () {
  12883. return new CircleShape();
  12884. };
  12885. Circle.prototype.buildPath = function (ctx, shape) {
  12886. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12887. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12888. };
  12889. return Circle;
  12890. }(Path));
  12891. Circle.prototype.type = 'circle';
  12892. var EllipseShape = (function () {
  12893. function EllipseShape() {
  12894. this.cx = 0;
  12895. this.cy = 0;
  12896. this.rx = 0;
  12897. this.ry = 0;
  12898. }
  12899. return EllipseShape;
  12900. }());
  12901. var Ellipse = (function (_super) {
  12902. __extends(Ellipse, _super);
  12903. function Ellipse(opts) {
  12904. return _super.call(this, opts) || this;
  12905. }
  12906. Ellipse.prototype.getDefaultShape = function () {
  12907. return new EllipseShape();
  12908. };
  12909. Ellipse.prototype.buildPath = function (ctx, shape) {
  12910. var k = 0.5522848;
  12911. var x = shape.cx;
  12912. var y = shape.cy;
  12913. var a = shape.rx;
  12914. var b = shape.ry;
  12915. var ox = a * k;
  12916. var oy = b * k;
  12917. ctx.moveTo(x - a, y);
  12918. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12919. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12920. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12921. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12922. ctx.closePath();
  12923. };
  12924. return Ellipse;
  12925. }(Path));
  12926. Ellipse.prototype.type = 'ellipse';
  12927. var PI$2 = Math.PI;
  12928. var PI2$5 = PI$2 * 2;
  12929. var mathSin$3 = Math.sin;
  12930. var mathCos$3 = Math.cos;
  12931. var mathACos = Math.acos;
  12932. var mathATan2 = Math.atan2;
  12933. var mathAbs$1 = Math.abs;
  12934. var mathSqrt$3 = Math.sqrt;
  12935. var mathMax$3 = Math.max;
  12936. var mathMin$3 = Math.min;
  12937. var e = 1e-4;
  12938. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12939. var dx10 = x1 - x0;
  12940. var dy10 = y1 - y0;
  12941. var dx32 = x3 - x2;
  12942. var dy32 = y3 - y2;
  12943. var t = dy32 * dx10 - dx32 * dy10;
  12944. if (t * t < e) {
  12945. return;
  12946. }
  12947. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  12948. return [x0 + t * dx10, y0 + t * dy10];
  12949. }
  12950. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12951. var x01 = x0 - x1;
  12952. var y01 = y0 - y1;
  12953. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  12954. var ox = lo * y01;
  12955. var oy = -lo * x01;
  12956. var x11 = x0 + ox;
  12957. var y11 = y0 + oy;
  12958. var x10 = x1 + ox;
  12959. var y10 = y1 + oy;
  12960. var x00 = (x11 + x10) / 2;
  12961. var y00 = (y11 + y10) / 2;
  12962. var dx = x10 - x11;
  12963. var dy = y10 - y11;
  12964. var d2 = dx * dx + dy * dy;
  12965. var r = radius - cr;
  12966. var s = x11 * y10 - x10 * y11;
  12967. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  12968. var cx0 = (s * dy - dx * d) / d2;
  12969. var cy0 = (-s * dx - dy * d) / d2;
  12970. var cx1 = (s * dy + dx * d) / d2;
  12971. var cy1 = (-s * dx + dy * d) / d2;
  12972. var dx0 = cx0 - x00;
  12973. var dy0 = cy0 - y00;
  12974. var dx1 = cx1 - x00;
  12975. var dy1 = cy1 - y00;
  12976. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12977. cx0 = cx1;
  12978. cy0 = cy1;
  12979. }
  12980. return {
  12981. cx: cx0,
  12982. cy: cy0,
  12983. x0: -ox,
  12984. y0: -oy,
  12985. x1: cx0 * (radius / r - 1),
  12986. y1: cy0 * (radius / r - 1)
  12987. };
  12988. }
  12989. function normalizeCornerRadius(cr) {
  12990. var arr;
  12991. if (isArray(cr)) {
  12992. var len = cr.length;
  12993. if (!len) {
  12994. return cr;
  12995. }
  12996. if (len === 1) {
  12997. arr = [cr[0], cr[0], 0, 0];
  12998. }
  12999. else if (len === 2) {
  13000. arr = [cr[0], cr[0], cr[1], cr[1]];
  13001. }
  13002. else if (len === 3) {
  13003. arr = cr.concat(cr[2]);
  13004. }
  13005. else {
  13006. arr = cr;
  13007. }
  13008. }
  13009. else {
  13010. arr = [cr, cr, cr, cr];
  13011. }
  13012. return arr;
  13013. }
  13014. function buildPath$1(ctx, shape) {
  13015. var _a;
  13016. var radius = mathMax$3(shape.r, 0);
  13017. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13018. var hasRadius = radius > 0;
  13019. var hasInnerRadius = innerRadius > 0;
  13020. if (!hasRadius && !hasInnerRadius) {
  13021. return;
  13022. }
  13023. if (!hasRadius) {
  13024. radius = innerRadius;
  13025. innerRadius = 0;
  13026. }
  13027. if (innerRadius > radius) {
  13028. var tmp = radius;
  13029. radius = innerRadius;
  13030. innerRadius = tmp;
  13031. }
  13032. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13033. if (isNaN(startAngle) || isNaN(endAngle)) {
  13034. return;
  13035. }
  13036. var cx = shape.cx, cy = shape.cy;
  13037. var clockwise = !!shape.clockwise;
  13038. var arc = mathAbs$1(endAngle - startAngle);
  13039. var mod = arc > PI2$5 && arc % PI2$5;
  13040. mod > e && (arc = mod);
  13041. if (!(radius > e)) {
  13042. ctx.moveTo(cx, cy);
  13043. }
  13044. else if (arc > PI2$5 - e) {
  13045. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13046. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13047. if (innerRadius > e) {
  13048. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13049. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13050. }
  13051. }
  13052. else {
  13053. var icrStart = void 0;
  13054. var icrEnd = void 0;
  13055. var ocrStart = void 0;
  13056. var ocrEnd = void 0;
  13057. var ocrs = void 0;
  13058. var ocre = void 0;
  13059. var icrs = void 0;
  13060. var icre = void 0;
  13061. var ocrMax = void 0;
  13062. var icrMax = void 0;
  13063. var limitedOcrMax = void 0;
  13064. var limitedIcrMax = void 0;
  13065. var xre = void 0;
  13066. var yre = void 0;
  13067. var xirs = void 0;
  13068. var yirs = void 0;
  13069. var xrs = radius * mathCos$3(startAngle);
  13070. var yrs = radius * mathSin$3(startAngle);
  13071. var xire = innerRadius * mathCos$3(endAngle);
  13072. var yire = innerRadius * mathSin$3(endAngle);
  13073. var hasArc = arc > e;
  13074. if (hasArc) {
  13075. var cornerRadius = shape.cornerRadius;
  13076. if (cornerRadius) {
  13077. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13078. }
  13079. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13080. ocrs = mathMin$3(halfRd, ocrStart);
  13081. ocre = mathMin$3(halfRd, ocrEnd);
  13082. icrs = mathMin$3(halfRd, icrStart);
  13083. icre = mathMin$3(halfRd, icrEnd);
  13084. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13085. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13086. if (ocrMax > e || icrMax > e) {
  13087. xre = radius * mathCos$3(endAngle);
  13088. yre = radius * mathSin$3(endAngle);
  13089. xirs = innerRadius * mathCos$3(startAngle);
  13090. yirs = innerRadius * mathSin$3(startAngle);
  13091. if (arc < PI$2) {
  13092. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13093. if (it_1) {
  13094. var x0 = xrs - it_1[0];
  13095. var y0 = yrs - it_1[1];
  13096. var x1 = xre - it_1[0];
  13097. var y1 = yre - it_1[1];
  13098. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13099. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13100. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13101. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13102. }
  13103. }
  13104. }
  13105. }
  13106. if (!hasArc) {
  13107. ctx.moveTo(cx + xrs, cy + yrs);
  13108. }
  13109. else if (limitedOcrMax > e) {
  13110. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13111. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13112. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13113. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13114. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13115. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13116. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13117. }
  13118. else {
  13119. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13120. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13121. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13122. }
  13123. }
  13124. else {
  13125. ctx.moveTo(cx + xrs, cy + yrs);
  13126. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13127. }
  13128. if (!(innerRadius > e) || !hasArc) {
  13129. ctx.lineTo(cx + xire, cy + yire);
  13130. }
  13131. else if (limitedIcrMax > e) {
  13132. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13133. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13134. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13135. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13136. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13137. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13138. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13139. }
  13140. else {
  13141. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13142. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13143. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13144. }
  13145. }
  13146. else {
  13147. ctx.lineTo(cx + xire, cy + yire);
  13148. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13149. }
  13150. }
  13151. ctx.closePath();
  13152. }
  13153. var SectorShape = (function () {
  13154. function SectorShape() {
  13155. this.cx = 0;
  13156. this.cy = 0;
  13157. this.r0 = 0;
  13158. this.r = 0;
  13159. this.startAngle = 0;
  13160. this.endAngle = Math.PI * 2;
  13161. this.clockwise = true;
  13162. this.cornerRadius = 0;
  13163. }
  13164. return SectorShape;
  13165. }());
  13166. var Sector = (function (_super) {
  13167. __extends(Sector, _super);
  13168. function Sector(opts) {
  13169. return _super.call(this, opts) || this;
  13170. }
  13171. Sector.prototype.getDefaultShape = function () {
  13172. return new SectorShape();
  13173. };
  13174. Sector.prototype.buildPath = function (ctx, shape) {
  13175. buildPath$1(ctx, shape);
  13176. };
  13177. Sector.prototype.isZeroArea = function () {
  13178. return this.shape.startAngle === this.shape.endAngle
  13179. || this.shape.r === this.shape.r0;
  13180. };
  13181. return Sector;
  13182. }(Path));
  13183. Sector.prototype.type = 'sector';
  13184. var RingShape = (function () {
  13185. function RingShape() {
  13186. this.cx = 0;
  13187. this.cy = 0;
  13188. this.r = 0;
  13189. this.r0 = 0;
  13190. }
  13191. return RingShape;
  13192. }());
  13193. var Ring = (function (_super) {
  13194. __extends(Ring, _super);
  13195. function Ring(opts) {
  13196. return _super.call(this, opts) || this;
  13197. }
  13198. Ring.prototype.getDefaultShape = function () {
  13199. return new RingShape();
  13200. };
  13201. Ring.prototype.buildPath = function (ctx, shape) {
  13202. var x = shape.cx;
  13203. var y = shape.cy;
  13204. var PI2 = Math.PI * 2;
  13205. ctx.moveTo(x + shape.r, y);
  13206. ctx.arc(x, y, shape.r, 0, PI2, false);
  13207. ctx.moveTo(x + shape.r0, y);
  13208. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13209. };
  13210. return Ring;
  13211. }(Path));
  13212. Ring.prototype.type = 'ring';
  13213. function smoothBezier(points, smooth, isLoop, constraint) {
  13214. var cps = [];
  13215. var v = [];
  13216. var v1 = [];
  13217. var v2 = [];
  13218. var prevPoint;
  13219. var nextPoint;
  13220. var min$1;
  13221. var max$1;
  13222. if (constraint) {
  13223. min$1 = [Infinity, Infinity];
  13224. max$1 = [-Infinity, -Infinity];
  13225. for (var i = 0, len = points.length; i < len; i++) {
  13226. min(min$1, min$1, points[i]);
  13227. max(max$1, max$1, points[i]);
  13228. }
  13229. min(min$1, min$1, constraint[0]);
  13230. max(max$1, max$1, constraint[1]);
  13231. }
  13232. for (var i = 0, len = points.length; i < len; i++) {
  13233. var point = points[i];
  13234. if (isLoop) {
  13235. prevPoint = points[i ? i - 1 : len - 1];
  13236. nextPoint = points[(i + 1) % len];
  13237. }
  13238. else {
  13239. if (i === 0 || i === len - 1) {
  13240. cps.push(clone$1(points[i]));
  13241. continue;
  13242. }
  13243. else {
  13244. prevPoint = points[i - 1];
  13245. nextPoint = points[i + 1];
  13246. }
  13247. }
  13248. sub(v, nextPoint, prevPoint);
  13249. scale(v, v, smooth);
  13250. var d0 = distance(point, prevPoint);
  13251. var d1 = distance(point, nextPoint);
  13252. var sum = d0 + d1;
  13253. if (sum !== 0) {
  13254. d0 /= sum;
  13255. d1 /= sum;
  13256. }
  13257. scale(v1, v, -d0);
  13258. scale(v2, v, d1);
  13259. var cp0 = add([], point, v1);
  13260. var cp1 = add([], point, v2);
  13261. if (constraint) {
  13262. max(cp0, cp0, min$1);
  13263. min(cp0, cp0, max$1);
  13264. max(cp1, cp1, min$1);
  13265. min(cp1, cp1, max$1);
  13266. }
  13267. cps.push(cp0);
  13268. cps.push(cp1);
  13269. }
  13270. if (isLoop) {
  13271. cps.push(cps.shift());
  13272. }
  13273. return cps;
  13274. }
  13275. function buildPath$2(ctx, shape, closePath) {
  13276. var smooth = shape.smooth;
  13277. var points = shape.points;
  13278. if (points && points.length >= 2) {
  13279. if (smooth) {
  13280. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13281. ctx.moveTo(points[0][0], points[0][1]);
  13282. var len = points.length;
  13283. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13284. var cp1 = controlPoints[i * 2];
  13285. var cp2 = controlPoints[i * 2 + 1];
  13286. var p = points[(i + 1) % len];
  13287. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13288. }
  13289. }
  13290. else {
  13291. ctx.moveTo(points[0][0], points[0][1]);
  13292. for (var i = 1, l = points.length; i < l; i++) {
  13293. ctx.lineTo(points[i][0], points[i][1]);
  13294. }
  13295. }
  13296. closePath && ctx.closePath();
  13297. }
  13298. }
  13299. var PolygonShape = (function () {
  13300. function PolygonShape() {
  13301. this.points = null;
  13302. this.smooth = 0;
  13303. this.smoothConstraint = null;
  13304. }
  13305. return PolygonShape;
  13306. }());
  13307. var Polygon = (function (_super) {
  13308. __extends(Polygon, _super);
  13309. function Polygon(opts) {
  13310. return _super.call(this, opts) || this;
  13311. }
  13312. Polygon.prototype.getDefaultShape = function () {
  13313. return new PolygonShape();
  13314. };
  13315. Polygon.prototype.buildPath = function (ctx, shape) {
  13316. buildPath$2(ctx, shape, true);
  13317. };
  13318. return Polygon;
  13319. }(Path));
  13320. Polygon.prototype.type = 'polygon';
  13321. var PolylineShape = (function () {
  13322. function PolylineShape() {
  13323. this.points = null;
  13324. this.percent = 1;
  13325. this.smooth = 0;
  13326. this.smoothConstraint = null;
  13327. }
  13328. return PolylineShape;
  13329. }());
  13330. var Polyline = (function (_super) {
  13331. __extends(Polyline, _super);
  13332. function Polyline(opts) {
  13333. return _super.call(this, opts) || this;
  13334. }
  13335. Polyline.prototype.getDefaultStyle = function () {
  13336. return {
  13337. stroke: '#000',
  13338. fill: null
  13339. };
  13340. };
  13341. Polyline.prototype.getDefaultShape = function () {
  13342. return new PolylineShape();
  13343. };
  13344. Polyline.prototype.buildPath = function (ctx, shape) {
  13345. buildPath$2(ctx, shape, false);
  13346. };
  13347. return Polyline;
  13348. }(Path));
  13349. Polyline.prototype.type = 'polyline';
  13350. var subPixelOptimizeOutputShape$1 = {};
  13351. var LineShape = (function () {
  13352. function LineShape() {
  13353. this.x1 = 0;
  13354. this.y1 = 0;
  13355. this.x2 = 0;
  13356. this.y2 = 0;
  13357. this.percent = 1;
  13358. }
  13359. return LineShape;
  13360. }());
  13361. var Line = (function (_super) {
  13362. __extends(Line, _super);
  13363. function Line(opts) {
  13364. return _super.call(this, opts) || this;
  13365. }
  13366. Line.prototype.getDefaultStyle = function () {
  13367. return {
  13368. stroke: '#000',
  13369. fill: null
  13370. };
  13371. };
  13372. Line.prototype.getDefaultShape = function () {
  13373. return new LineShape();
  13374. };
  13375. Line.prototype.buildPath = function (ctx, shape) {
  13376. var x1;
  13377. var y1;
  13378. var x2;
  13379. var y2;
  13380. if (this.subPixelOptimize) {
  13381. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13382. x1 = optimizedShape.x1;
  13383. y1 = optimizedShape.y1;
  13384. x2 = optimizedShape.x2;
  13385. y2 = optimizedShape.y2;
  13386. }
  13387. else {
  13388. x1 = shape.x1;
  13389. y1 = shape.y1;
  13390. x2 = shape.x2;
  13391. y2 = shape.y2;
  13392. }
  13393. var percent = shape.percent;
  13394. if (percent === 0) {
  13395. return;
  13396. }
  13397. ctx.moveTo(x1, y1);
  13398. if (percent < 1) {
  13399. x2 = x1 * (1 - percent) + x2 * percent;
  13400. y2 = y1 * (1 - percent) + y2 * percent;
  13401. }
  13402. ctx.lineTo(x2, y2);
  13403. };
  13404. Line.prototype.pointAt = function (p) {
  13405. var shape = this.shape;
  13406. return [
  13407. shape.x1 * (1 - p) + shape.x2 * p,
  13408. shape.y1 * (1 - p) + shape.y2 * p
  13409. ];
  13410. };
  13411. return Line;
  13412. }(Path));
  13413. Line.prototype.type = 'line';
  13414. var out = [];
  13415. var BezierCurveShape = (function () {
  13416. function BezierCurveShape() {
  13417. this.x1 = 0;
  13418. this.y1 = 0;
  13419. this.x2 = 0;
  13420. this.y2 = 0;
  13421. this.cpx1 = 0;
  13422. this.cpy1 = 0;
  13423. this.percent = 1;
  13424. }
  13425. return BezierCurveShape;
  13426. }());
  13427. function someVectorAt(shape, t, isTangent) {
  13428. var cpx2 = shape.cpx2;
  13429. var cpy2 = shape.cpy2;
  13430. if (cpx2 != null || cpy2 != null) {
  13431. return [
  13432. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13433. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13434. ];
  13435. }
  13436. else {
  13437. return [
  13438. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13439. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13440. ];
  13441. }
  13442. }
  13443. var BezierCurve = (function (_super) {
  13444. __extends(BezierCurve, _super);
  13445. function BezierCurve(opts) {
  13446. return _super.call(this, opts) || this;
  13447. }
  13448. BezierCurve.prototype.getDefaultStyle = function () {
  13449. return {
  13450. stroke: '#000',
  13451. fill: null
  13452. };
  13453. };
  13454. BezierCurve.prototype.getDefaultShape = function () {
  13455. return new BezierCurveShape();
  13456. };
  13457. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13458. var x1 = shape.x1;
  13459. var y1 = shape.y1;
  13460. var x2 = shape.x2;
  13461. var y2 = shape.y2;
  13462. var cpx1 = shape.cpx1;
  13463. var cpy1 = shape.cpy1;
  13464. var cpx2 = shape.cpx2;
  13465. var cpy2 = shape.cpy2;
  13466. var percent = shape.percent;
  13467. if (percent === 0) {
  13468. return;
  13469. }
  13470. ctx.moveTo(x1, y1);
  13471. if (cpx2 == null || cpy2 == null) {
  13472. if (percent < 1) {
  13473. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13474. cpx1 = out[1];
  13475. x2 = out[2];
  13476. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13477. cpy1 = out[1];
  13478. y2 = out[2];
  13479. }
  13480. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13481. }
  13482. else {
  13483. if (percent < 1) {
  13484. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13485. cpx1 = out[1];
  13486. cpx2 = out[2];
  13487. x2 = out[3];
  13488. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13489. cpy1 = out[1];
  13490. cpy2 = out[2];
  13491. y2 = out[3];
  13492. }
  13493. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13494. }
  13495. };
  13496. BezierCurve.prototype.pointAt = function (t) {
  13497. return someVectorAt(this.shape, t, false);
  13498. };
  13499. BezierCurve.prototype.tangentAt = function (t) {
  13500. var p = someVectorAt(this.shape, t, true);
  13501. return normalize(p, p);
  13502. };
  13503. return BezierCurve;
  13504. }(Path));
  13505. BezierCurve.prototype.type = 'bezier-curve';
  13506. var ArcShape = (function () {
  13507. function ArcShape() {
  13508. this.cx = 0;
  13509. this.cy = 0;
  13510. this.r = 0;
  13511. this.startAngle = 0;
  13512. this.endAngle = Math.PI * 2;
  13513. this.clockwise = true;
  13514. }
  13515. return ArcShape;
  13516. }());
  13517. var Arc = (function (_super) {
  13518. __extends(Arc, _super);
  13519. function Arc(opts) {
  13520. return _super.call(this, opts) || this;
  13521. }
  13522. Arc.prototype.getDefaultStyle = function () {
  13523. return {
  13524. stroke: '#000',
  13525. fill: null
  13526. };
  13527. };
  13528. Arc.prototype.getDefaultShape = function () {
  13529. return new ArcShape();
  13530. };
  13531. Arc.prototype.buildPath = function (ctx, shape) {
  13532. var x = shape.cx;
  13533. var y = shape.cy;
  13534. var r = Math.max(shape.r, 0);
  13535. var startAngle = shape.startAngle;
  13536. var endAngle = shape.endAngle;
  13537. var clockwise = shape.clockwise;
  13538. var unitX = Math.cos(startAngle);
  13539. var unitY = Math.sin(startAngle);
  13540. ctx.moveTo(unitX * r + x, unitY * r + y);
  13541. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13542. };
  13543. return Arc;
  13544. }(Path));
  13545. Arc.prototype.type = 'arc';
  13546. var CompoundPath = (function (_super) {
  13547. __extends(CompoundPath, _super);
  13548. function CompoundPath() {
  13549. var _this = _super !== null && _super.apply(this, arguments) || this;
  13550. _this.type = 'compound';
  13551. return _this;
  13552. }
  13553. CompoundPath.prototype._updatePathDirty = function () {
  13554. var paths = this.shape.paths;
  13555. var dirtyPath = this.shapeChanged();
  13556. for (var i = 0; i < paths.length; i++) {
  13557. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13558. }
  13559. if (dirtyPath) {
  13560. this.dirtyShape();
  13561. }
  13562. };
  13563. CompoundPath.prototype.beforeBrush = function () {
  13564. this._updatePathDirty();
  13565. var paths = this.shape.paths || [];
  13566. var scale = this.getGlobalScale();
  13567. for (var i = 0; i < paths.length; i++) {
  13568. if (!paths[i].path) {
  13569. paths[i].createPathProxy();
  13570. }
  13571. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13572. }
  13573. };
  13574. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13575. var paths = shape.paths || [];
  13576. for (var i = 0; i < paths.length; i++) {
  13577. paths[i].buildPath(ctx, paths[i].shape, true);
  13578. }
  13579. };
  13580. CompoundPath.prototype.afterBrush = function () {
  13581. var paths = this.shape.paths || [];
  13582. for (var i = 0; i < paths.length; i++) {
  13583. paths[i].pathUpdated();
  13584. }
  13585. };
  13586. CompoundPath.prototype.getBoundingRect = function () {
  13587. this._updatePathDirty.call(this);
  13588. return Path.prototype.getBoundingRect.call(this);
  13589. };
  13590. return CompoundPath;
  13591. }(Path));
  13592. var Gradient = (function () {
  13593. function Gradient(colorStops) {
  13594. this.colorStops = colorStops || [];
  13595. }
  13596. Gradient.prototype.addColorStop = function (offset, color) {
  13597. this.colorStops.push({
  13598. offset: offset,
  13599. color: color
  13600. });
  13601. };
  13602. return Gradient;
  13603. }());
  13604. var LinearGradient = (function (_super) {
  13605. __extends(LinearGradient, _super);
  13606. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13607. var _this = _super.call(this, colorStops) || this;
  13608. _this.x = x == null ? 0 : x;
  13609. _this.y = y == null ? 0 : y;
  13610. _this.x2 = x2 == null ? 1 : x2;
  13611. _this.y2 = y2 == null ? 0 : y2;
  13612. _this.type = 'linear';
  13613. _this.global = globalCoord || false;
  13614. return _this;
  13615. }
  13616. return LinearGradient;
  13617. }(Gradient));
  13618. var RadialGradient = (function (_super) {
  13619. __extends(RadialGradient, _super);
  13620. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13621. var _this = _super.call(this, colorStops) || this;
  13622. _this.x = x == null ? 0.5 : x;
  13623. _this.y = y == null ? 0.5 : y;
  13624. _this.r = r == null ? 0.5 : r;
  13625. _this.type = 'radial';
  13626. _this.global = globalCoord || false;
  13627. return _this;
  13628. }
  13629. return RadialGradient;
  13630. }(Gradient));
  13631. var extent = [0, 0];
  13632. var extent2 = [0, 0];
  13633. var minTv$1 = new Point();
  13634. var maxTv$1 = new Point();
  13635. var OrientedBoundingRect = (function () {
  13636. function OrientedBoundingRect(rect, transform) {
  13637. this._corners = [];
  13638. this._axes = [];
  13639. this._origin = [0, 0];
  13640. for (var i = 0; i < 4; i++) {
  13641. this._corners[i] = new Point();
  13642. }
  13643. for (var i = 0; i < 2; i++) {
  13644. this._axes[i] = new Point();
  13645. }
  13646. if (rect) {
  13647. this.fromBoundingRect(rect, transform);
  13648. }
  13649. }
  13650. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13651. var corners = this._corners;
  13652. var axes = this._axes;
  13653. var x = rect.x;
  13654. var y = rect.y;
  13655. var x2 = x + rect.width;
  13656. var y2 = y + rect.height;
  13657. corners[0].set(x, y);
  13658. corners[1].set(x2, y);
  13659. corners[2].set(x2, y2);
  13660. corners[3].set(x, y2);
  13661. if (transform) {
  13662. for (var i = 0; i < 4; i++) {
  13663. corners[i].transform(transform);
  13664. }
  13665. }
  13666. Point.sub(axes[0], corners[1], corners[0]);
  13667. Point.sub(axes[1], corners[3], corners[0]);
  13668. axes[0].normalize();
  13669. axes[1].normalize();
  13670. for (var i = 0; i < 2; i++) {
  13671. this._origin[i] = axes[i].dot(corners[0]);
  13672. }
  13673. };
  13674. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13675. var overlapped = true;
  13676. var noMtv = !mtv;
  13677. minTv$1.set(Infinity, Infinity);
  13678. maxTv$1.set(0, 0);
  13679. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13680. overlapped = false;
  13681. if (noMtv) {
  13682. return overlapped;
  13683. }
  13684. }
  13685. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13686. overlapped = false;
  13687. if (noMtv) {
  13688. return overlapped;
  13689. }
  13690. }
  13691. if (!noMtv) {
  13692. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13693. }
  13694. return overlapped;
  13695. };
  13696. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13697. var overlapped = true;
  13698. for (var i = 0; i < 2; i++) {
  13699. var axis = this._axes[i];
  13700. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13701. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13702. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13703. overlapped = false;
  13704. if (noMtv) {
  13705. return overlapped;
  13706. }
  13707. var dist0 = Math.abs(extent2[0] - extent[1]);
  13708. var dist1 = Math.abs(extent[0] - extent2[1]);
  13709. if (Math.min(dist0, dist1) > maxTv.len()) {
  13710. if (dist0 < dist1) {
  13711. Point.scale(maxTv, axis, -dist0 * inverse);
  13712. }
  13713. else {
  13714. Point.scale(maxTv, axis, dist1 * inverse);
  13715. }
  13716. }
  13717. }
  13718. else if (minTv) {
  13719. var dist0 = Math.abs(extent2[0] - extent[1]);
  13720. var dist1 = Math.abs(extent[0] - extent2[1]);
  13721. if (Math.min(dist0, dist1) < minTv.len()) {
  13722. if (dist0 < dist1) {
  13723. Point.scale(minTv, axis, dist0 * inverse);
  13724. }
  13725. else {
  13726. Point.scale(minTv, axis, -dist1 * inverse);
  13727. }
  13728. }
  13729. }
  13730. }
  13731. return overlapped;
  13732. };
  13733. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13734. var axis = this._axes[dim];
  13735. var origin = this._origin;
  13736. var proj = corners[0].dot(axis) + origin[dim];
  13737. var min = proj;
  13738. var max = proj;
  13739. for (var i = 1; i < corners.length; i++) {
  13740. var proj_1 = corners[i].dot(axis) + origin[dim];
  13741. min = Math.min(proj_1, min);
  13742. max = Math.max(proj_1, max);
  13743. }
  13744. out[0] = min;
  13745. out[1] = max;
  13746. };
  13747. return OrientedBoundingRect;
  13748. }());
  13749. var m = [];
  13750. var IncrementalDisplayable = (function (_super) {
  13751. __extends(IncrementalDisplayable, _super);
  13752. function IncrementalDisplayable() {
  13753. var _this = _super !== null && _super.apply(this, arguments) || this;
  13754. _this.notClear = true;
  13755. _this.incremental = true;
  13756. _this._displayables = [];
  13757. _this._temporaryDisplayables = [];
  13758. _this._cursor = 0;
  13759. return _this;
  13760. }
  13761. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13762. cb.call(context, this);
  13763. };
  13764. IncrementalDisplayable.prototype.useStyle = function () {
  13765. this.style = {};
  13766. };
  13767. IncrementalDisplayable.prototype.getCursor = function () {
  13768. return this._cursor;
  13769. };
  13770. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13771. this._cursor = this._displayables.length;
  13772. };
  13773. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13774. this._displayables = [];
  13775. this._temporaryDisplayables = [];
  13776. this._cursor = 0;
  13777. this.markRedraw();
  13778. this.notClear = false;
  13779. };
  13780. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13781. this._temporaryDisplayables = [];
  13782. };
  13783. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13784. if (notPersistent) {
  13785. this._temporaryDisplayables.push(displayable);
  13786. }
  13787. else {
  13788. this._displayables.push(displayable);
  13789. }
  13790. this.markRedraw();
  13791. };
  13792. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13793. notPersistent = notPersistent || false;
  13794. for (var i = 0; i < displayables.length; i++) {
  13795. this.addDisplayable(displayables[i], notPersistent);
  13796. }
  13797. };
  13798. IncrementalDisplayable.prototype.getDisplayables = function () {
  13799. return this._displayables;
  13800. };
  13801. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13802. return this._temporaryDisplayables;
  13803. };
  13804. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13805. for (var i = this._cursor; i < this._displayables.length; i++) {
  13806. cb && cb(this._displayables[i]);
  13807. }
  13808. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13809. cb && cb(this._temporaryDisplayables[i]);
  13810. }
  13811. };
  13812. IncrementalDisplayable.prototype.update = function () {
  13813. this.updateTransform();
  13814. for (var i = this._cursor; i < this._displayables.length; i++) {
  13815. var displayable = this._displayables[i];
  13816. displayable.parent = this;
  13817. displayable.update();
  13818. displayable.parent = null;
  13819. }
  13820. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13821. var displayable = this._temporaryDisplayables[i];
  13822. displayable.parent = this;
  13823. displayable.update();
  13824. displayable.parent = null;
  13825. }
  13826. };
  13827. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13828. if (!this._rect) {
  13829. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13830. for (var i = 0; i < this._displayables.length; i++) {
  13831. var displayable = this._displayables[i];
  13832. var childRect = displayable.getBoundingRect().clone();
  13833. if (displayable.needLocalTransform()) {
  13834. childRect.applyTransform(displayable.getLocalTransform(m));
  13835. }
  13836. rect.union(childRect);
  13837. }
  13838. this._rect = rect;
  13839. }
  13840. return this._rect;
  13841. };
  13842. IncrementalDisplayable.prototype.contain = function (x, y) {
  13843. var localPos = this.transformCoordToLocal(x, y);
  13844. var rect = this.getBoundingRect();
  13845. if (rect.contain(localPos[0], localPos[1])) {
  13846. for (var i = 0; i < this._displayables.length; i++) {
  13847. var displayable = this._displayables[i];
  13848. if (displayable.contain(x, y)) {
  13849. return true;
  13850. }
  13851. }
  13852. }
  13853. return false;
  13854. };
  13855. return IncrementalDisplayable;
  13856. }(Displayable));
  13857. var transitionStore = makeInner();
  13858. /**
  13859. * Return null if animation is disabled.
  13860. */
  13861. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  13862. extraOpts, // TODO It's only for pictorial bar now.
  13863. extraDelayParams) {
  13864. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13865. // If animation is enabled. Will use this animation config in payload.
  13866. // If animation is disabled. Just ignore it.
  13867. if (animatableModel && animatableModel.ecModel) {
  13868. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13869. animationPayload = updatePayload && updatePayload.animation;
  13870. }
  13871. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13872. var isUpdate = animationType === 'update';
  13873. if (animationEnabled) {
  13874. var duration = void 0;
  13875. var easing = void 0;
  13876. var delay = void 0;
  13877. if (extraOpts) {
  13878. duration = retrieve2(extraOpts.duration, 200);
  13879. easing = retrieve2(extraOpts.easing, 'cubicOut');
  13880. delay = 0;
  13881. } else {
  13882. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13883. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13884. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13885. } // animation from payload has highest priority.
  13886. if (animationPayload) {
  13887. animationPayload.duration != null && (duration = animationPayload.duration);
  13888. animationPayload.easing != null && (easing = animationPayload.easing);
  13889. animationPayload.delay != null && (delay = animationPayload.delay);
  13890. }
  13891. if (isFunction(delay)) {
  13892. delay = delay(dataIndex, extraDelayParams);
  13893. }
  13894. if (isFunction(duration)) {
  13895. duration = duration(dataIndex);
  13896. }
  13897. var config = {
  13898. duration: duration || 0,
  13899. delay: delay,
  13900. easing: easing
  13901. };
  13902. return config;
  13903. } else {
  13904. return null;
  13905. }
  13906. }
  13907. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13908. var isFrom = false;
  13909. var removeOpt;
  13910. if (isFunction(dataIndex)) {
  13911. during = cb;
  13912. cb = dataIndex;
  13913. dataIndex = null;
  13914. } else if (isObject(dataIndex)) {
  13915. cb = dataIndex.cb;
  13916. during = dataIndex.during;
  13917. isFrom = dataIndex.isFrom;
  13918. removeOpt = dataIndex.removeOpt;
  13919. dataIndex = dataIndex.dataIndex;
  13920. }
  13921. var isRemove = animationType === 'leave';
  13922. if (!isRemove) {
  13923. // Must stop the remove animation.
  13924. el.stopAnimation('leave');
  13925. }
  13926. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13927. if (animationConfig && animationConfig.duration > 0) {
  13928. var duration = animationConfig.duration;
  13929. var animationDelay = animationConfig.delay;
  13930. var animationEasing = animationConfig.easing;
  13931. var animateConfig = {
  13932. duration: duration,
  13933. delay: animationDelay || 0,
  13934. easing: animationEasing,
  13935. done: cb,
  13936. force: !!cb || !!during,
  13937. // Set to final state in update/init animation.
  13938. // So the post processing based on the path shape can be done correctly.
  13939. setToFinal: !isRemove,
  13940. scope: animationType,
  13941. during: during
  13942. };
  13943. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  13944. } else {
  13945. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  13946. !isFrom && el.attr(props); // Call during at least once.
  13947. during && during(1);
  13948. cb && cb();
  13949. }
  13950. }
  13951. /**
  13952. * Update graphic element properties with or without animation according to the
  13953. * configuration in series.
  13954. *
  13955. * Caution: this method will stop previous animation.
  13956. * So do not use this method to one element twice before
  13957. * animation starts, unless you know what you are doing.
  13958. * @example
  13959. * graphic.updateProps(el, {
  13960. * position: [100, 100]
  13961. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13962. * // Or
  13963. * graphic.updateProps(el, {
  13964. * position: [100, 100]
  13965. * }, seriesModel, function () { console.log('Animation done!'); });
  13966. */
  13967. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13968. animatableModel, dataIndex, cb, during) {
  13969. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13970. }
  13971. /**
  13972. * Init graphic element properties with or without animation according to the
  13973. * configuration in series.
  13974. *
  13975. * Caution: this method will stop previous animation.
  13976. * So do not use this method to one element twice before
  13977. * animation starts, unless you know what you are doing.
  13978. */
  13979. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13980. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  13981. }
  13982. /**
  13983. * If element is removed.
  13984. * It can determine if element is having remove animation.
  13985. */
  13986. function isElementRemoved(el) {
  13987. if (!el.__zr) {
  13988. return true;
  13989. }
  13990. for (var i = 0; i < el.animators.length; i++) {
  13991. var animator = el.animators[i];
  13992. if (animator.scope === 'leave') {
  13993. return true;
  13994. }
  13995. }
  13996. return false;
  13997. }
  13998. /**
  13999. * Remove graphic element
  14000. */
  14001. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14002. // Don't do remove animation twice.
  14003. if (isElementRemoved(el)) {
  14004. return;
  14005. }
  14006. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14007. }
  14008. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14009. el.removeTextContent();
  14010. el.removeTextGuideLine();
  14011. removeElement(el, {
  14012. style: {
  14013. opacity: 0
  14014. }
  14015. }, animatableModel, dataIndex, done);
  14016. }
  14017. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14018. function doRemove() {
  14019. el.parent && el.parent.remove(el);
  14020. } // Hide label and labelLine first
  14021. // TODO Also use fade out animation?
  14022. if (!el.isGroup) {
  14023. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14024. } else {
  14025. el.traverse(function (disp) {
  14026. if (!disp.isGroup) {
  14027. // Can invoke doRemove multiple times.
  14028. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14029. }
  14030. });
  14031. }
  14032. }
  14033. /**
  14034. * Save old style for style transition in universalTransition module.
  14035. * It's used when element will be reused in each render.
  14036. * For chart like map, heatmap, which will always create new element.
  14037. * We don't need to save this because universalTransition can get old style from the old element
  14038. */
  14039. function saveOldStyle(el) {
  14040. transitionStore(el).oldStyle = el.style;
  14041. }
  14042. var mathMax$4 = Math.max;
  14043. var mathMin$4 = Math.min;
  14044. var _customShapeMap = {};
  14045. /**
  14046. * Extend shape with parameters
  14047. */
  14048. function extendShape(opts) {
  14049. return Path.extend(opts);
  14050. }
  14051. var extendPathFromString = extendFromString;
  14052. /**
  14053. * Extend path
  14054. */
  14055. function extendPath(pathData, opts) {
  14056. return extendPathFromString(pathData, opts);
  14057. }
  14058. /**
  14059. * Register a user defined shape.
  14060. * The shape class can be fetched by `getShapeClass`
  14061. * This method will overwrite the registered shapes, including
  14062. * the registered built-in shapes, if using the same `name`.
  14063. * The shape can be used in `custom series` and
  14064. * `graphic component` by declaring `{type: name}`.
  14065. *
  14066. * @param name
  14067. * @param ShapeClass Can be generated by `extendShape`.
  14068. */
  14069. function registerShape(name, ShapeClass) {
  14070. _customShapeMap[name] = ShapeClass;
  14071. }
  14072. /**
  14073. * Find shape class registered by `registerShape`. Usually used in
  14074. * fetching user defined shape.
  14075. *
  14076. * [Caution]:
  14077. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14078. * to use user registered shapes.
  14079. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14080. * `registerShape` by default. That enables users to get both built-in
  14081. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14082. * the built-in shapes by using names like 'circle', 'rect' via calling
  14083. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14084. * in case that it is overwritten by users, except that some features, like
  14085. * `custom series`, `graphic component`, do it deliberately.
  14086. *
  14087. * (2) In the features like `custom series`, `graphic component`, the user input
  14088. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14089. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14090. * are reserved names, that is, if some user register a shape named `'image'`,
  14091. * the shape will not be used. If we intending to add some more reserved names
  14092. * in feature, that might bring break changes (disable some existing user shape
  14093. * names). But that case probably rearly happen. So we dont make more mechanism
  14094. * to resolve this issue here.
  14095. *
  14096. * @param name
  14097. * @return The shape class. If not found, return nothing.
  14098. */
  14099. function getShapeClass(name) {
  14100. if (_customShapeMap.hasOwnProperty(name)) {
  14101. return _customShapeMap[name];
  14102. }
  14103. }
  14104. /**
  14105. * Create a path element from path data string
  14106. * @param pathData
  14107. * @param opts
  14108. * @param rect
  14109. * @param layout 'center' or 'cover' default to be cover
  14110. */
  14111. function makePath(pathData, opts, rect, layout) {
  14112. var path = createFromString(pathData, opts);
  14113. if (rect) {
  14114. if (layout === 'center') {
  14115. rect = centerGraphic(rect, path.getBoundingRect());
  14116. }
  14117. resizePath(path, rect);
  14118. }
  14119. return path;
  14120. }
  14121. /**
  14122. * Create a image element from image url
  14123. * @param imageUrl image url
  14124. * @param opts options
  14125. * @param rect constrain rect
  14126. * @param layout 'center' or 'cover'. Default to be 'cover'
  14127. */
  14128. function makeImage(imageUrl, rect, layout) {
  14129. var zrImg = new ZRImage({
  14130. style: {
  14131. image: imageUrl,
  14132. x: rect.x,
  14133. y: rect.y,
  14134. width: rect.width,
  14135. height: rect.height
  14136. },
  14137. onload: function (img) {
  14138. if (layout === 'center') {
  14139. var boundingRect = {
  14140. width: img.width,
  14141. height: img.height
  14142. };
  14143. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14144. }
  14145. }
  14146. });
  14147. return zrImg;
  14148. }
  14149. /**
  14150. * Get position of centered element in bounding box.
  14151. *
  14152. * @param rect element local bounding box
  14153. * @param boundingRect constraint bounding box
  14154. * @return element position containing x, y, width, and height
  14155. */
  14156. function centerGraphic(rect, boundingRect) {
  14157. // Set rect to center, keep width / height ratio.
  14158. var aspect = boundingRect.width / boundingRect.height;
  14159. var width = rect.height * aspect;
  14160. var height;
  14161. if (width <= rect.width) {
  14162. height = rect.height;
  14163. } else {
  14164. width = rect.width;
  14165. height = width / aspect;
  14166. }
  14167. var cx = rect.x + rect.width / 2;
  14168. var cy = rect.y + rect.height / 2;
  14169. return {
  14170. x: cx - width / 2,
  14171. y: cy - height / 2,
  14172. width: width,
  14173. height: height
  14174. };
  14175. }
  14176. var mergePath$1 = mergePath;
  14177. /**
  14178. * Resize a path to fit the rect
  14179. * @param path
  14180. * @param rect
  14181. */
  14182. function resizePath(path, rect) {
  14183. if (!path.applyTransform) {
  14184. return;
  14185. }
  14186. var pathRect = path.getBoundingRect();
  14187. var m = pathRect.calculateTransform(rect);
  14188. path.applyTransform(m);
  14189. }
  14190. /**
  14191. * Sub pixel optimize line for canvas
  14192. */
  14193. function subPixelOptimizeLine$1(param) {
  14194. subPixelOptimizeLine(param.shape, param.shape, param.style);
  14195. return param;
  14196. }
  14197. /**
  14198. * Sub pixel optimize rect for canvas
  14199. */
  14200. function subPixelOptimizeRect$1(param) {
  14201. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14202. return param;
  14203. }
  14204. /**
  14205. * Sub pixel optimize for canvas
  14206. *
  14207. * @param position Coordinate, such as x, y
  14208. * @param lineWidth Should be nonnegative integer.
  14209. * @param positiveOrNegative Default false (negative).
  14210. * @return Optimized position.
  14211. */
  14212. var subPixelOptimize$1 = subPixelOptimize;
  14213. /**
  14214. * Get transform matrix of target (param target),
  14215. * in coordinate of its ancestor (param ancestor)
  14216. *
  14217. * @param target
  14218. * @param [ancestor]
  14219. */
  14220. function getTransform(target, ancestor) {
  14221. var mat = identity([]);
  14222. while (target && target !== ancestor) {
  14223. mul$1(mat, target.getLocalTransform(), mat);
  14224. target = target.parent;
  14225. }
  14226. return mat;
  14227. }
  14228. /**
  14229. * Apply transform to an vertex.
  14230. * @param target [x, y]
  14231. * @param transform Can be:
  14232. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14233. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14234. * @param invert Whether use invert matrix.
  14235. * @return [x, y]
  14236. */
  14237. function applyTransform$1(target, transform, invert$1) {
  14238. if (transform && !isArrayLike(transform)) {
  14239. transform = Transformable.getLocalTransform(transform);
  14240. }
  14241. if (invert$1) {
  14242. transform = invert([], transform);
  14243. }
  14244. return applyTransform([], target, transform);
  14245. }
  14246. /**
  14247. * @param direction 'left' 'right' 'top' 'bottom'
  14248. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14249. * @param invert Whether use invert matrix.
  14250. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14251. */
  14252. function transformDirection(direction, transform, invert) {
  14253. // Pick a base, ensure that transform result will not be (0, 0).
  14254. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14255. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14256. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14257. vertex = applyTransform$1(vertex, transform, invert);
  14258. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14259. }
  14260. function isNotGroup(el) {
  14261. return !el.isGroup;
  14262. }
  14263. function isPath(el) {
  14264. return el.shape != null;
  14265. }
  14266. /**
  14267. * Apply group transition animation from g1 to g2.
  14268. * If no animatableModel, no animation.
  14269. */
  14270. function groupTransition(g1, g2, animatableModel) {
  14271. if (!g1 || !g2) {
  14272. return;
  14273. }
  14274. function getElMap(g) {
  14275. var elMap = {};
  14276. g.traverse(function (el) {
  14277. if (isNotGroup(el) && el.anid) {
  14278. elMap[el.anid] = el;
  14279. }
  14280. });
  14281. return elMap;
  14282. }
  14283. function getAnimatableProps(el) {
  14284. var obj = {
  14285. x: el.x,
  14286. y: el.y,
  14287. rotation: el.rotation
  14288. };
  14289. if (isPath(el)) {
  14290. obj.shape = extend({}, el.shape);
  14291. }
  14292. return obj;
  14293. }
  14294. var elMap1 = getElMap(g1);
  14295. g2.traverse(function (el) {
  14296. if (isNotGroup(el) && el.anid) {
  14297. var oldEl = elMap1[el.anid];
  14298. if (oldEl) {
  14299. var newProp = getAnimatableProps(el);
  14300. el.attr(getAnimatableProps(oldEl));
  14301. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14302. }
  14303. }
  14304. });
  14305. }
  14306. function clipPointsByRect(points, rect) {
  14307. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14308. // and when element have border.
  14309. return map(points, function (point) {
  14310. var x = point[0];
  14311. x = mathMax$4(x, rect.x);
  14312. x = mathMin$4(x, rect.x + rect.width);
  14313. var y = point[1];
  14314. y = mathMax$4(y, rect.y);
  14315. y = mathMin$4(y, rect.y + rect.height);
  14316. return [x, y];
  14317. });
  14318. }
  14319. /**
  14320. * Return a new clipped rect. If rect size are negative, return undefined.
  14321. */
  14322. function clipRectByRect(targetRect, rect) {
  14323. var x = mathMax$4(targetRect.x, rect.x);
  14324. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14325. var y = mathMax$4(targetRect.y, rect.y);
  14326. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14327. // should be painted. So return undefined.
  14328. if (x2 >= x && y2 >= y) {
  14329. return {
  14330. x: x,
  14331. y: y,
  14332. width: x2 - x,
  14333. height: y2 - y
  14334. };
  14335. }
  14336. }
  14337. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14338. opt, rect) {
  14339. var innerOpts = extend({
  14340. rectHover: true
  14341. }, opt);
  14342. var style = innerOpts.style = {
  14343. strokeNoScale: true
  14344. };
  14345. rect = rect || {
  14346. x: -1,
  14347. y: -1,
  14348. width: 2,
  14349. height: 2
  14350. };
  14351. if (iconStr) {
  14352. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14353. }
  14354. }
  14355. /**
  14356. * Return `true` if the given line (line `a`) and the given polygon
  14357. * are intersect.
  14358. * Note that we do not count colinear as intersect here because no
  14359. * requirement for that. We could do that if required in future.
  14360. */
  14361. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14362. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14363. var p = points[i];
  14364. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14365. return true;
  14366. }
  14367. p2 = p;
  14368. }
  14369. }
  14370. /**
  14371. * Return `true` if the given two lines (line `a` and line `b`)
  14372. * are intersect.
  14373. * Note that we do not count colinear as intersect here because no
  14374. * requirement for that. We could do that if required in future.
  14375. */
  14376. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14377. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14378. var mx = a2x - a1x;
  14379. var my = a2y - a1y;
  14380. var nx = b2x - b1x;
  14381. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14382. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14383. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14384. if (nearZero(nmCrossProduct)) {
  14385. return false;
  14386. } // `vec_m` and `vec_n` are intersect iff
  14387. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14388. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14389. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14390. var b1a1x = a1x - b1x;
  14391. var b1a1y = a1y - b1y;
  14392. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14393. if (q < 0 || q > 1) {
  14394. return false;
  14395. }
  14396. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14397. if (p < 0 || p > 1) {
  14398. return false;
  14399. }
  14400. return true;
  14401. }
  14402. /**
  14403. * Cross product of 2-dimension vector.
  14404. */
  14405. function crossProduct2d(x1, y1, x2, y2) {
  14406. return x1 * y2 - x2 * y1;
  14407. }
  14408. function nearZero(val) {
  14409. return val <= 1e-6 && val >= -1e-6;
  14410. }
  14411. function setTooltipConfig(opt) {
  14412. var itemTooltipOption = opt.itemTooltipOption;
  14413. var componentModel = opt.componentModel;
  14414. var itemName = opt.itemName;
  14415. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14416. formatter: itemTooltipOption
  14417. } : itemTooltipOption;
  14418. var mainType = componentModel.mainType;
  14419. var componentIndex = componentModel.componentIndex;
  14420. var formatterParams = {
  14421. componentType: mainType,
  14422. name: itemName,
  14423. $vars: ['name']
  14424. };
  14425. formatterParams[mainType + 'Index'] = componentIndex;
  14426. var formatterParamsExtra = opt.formatterParamsExtra;
  14427. if (formatterParamsExtra) {
  14428. each(keys(formatterParamsExtra), function (key) {
  14429. if (!hasOwn(formatterParams, key)) {
  14430. formatterParams[key] = formatterParamsExtra[key];
  14431. formatterParams.$vars.push(key);
  14432. }
  14433. });
  14434. }
  14435. var ecData = getECData(opt.el);
  14436. ecData.componentMainType = mainType;
  14437. ecData.componentIndex = componentIndex;
  14438. ecData.tooltipConfig = {
  14439. name: itemName,
  14440. option: defaults({
  14441. content: itemName,
  14442. formatterParams: formatterParams
  14443. }, itemTooltipOptionObj)
  14444. };
  14445. }
  14446. function traverseElement(el, cb) {
  14447. var stopped; // TODO
  14448. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14449. if (el.isGroup) {
  14450. stopped = cb(el);
  14451. }
  14452. if (!stopped) {
  14453. el.traverse(cb);
  14454. }
  14455. }
  14456. function traverseElements(els, cb) {
  14457. if (els) {
  14458. if (isArray(els)) {
  14459. for (var i = 0; i < els.length; i++) {
  14460. traverseElement(els[i], cb);
  14461. }
  14462. } else {
  14463. traverseElement(els, cb);
  14464. }
  14465. }
  14466. } // Register built-in shapes. These shapes might be overwirtten
  14467. // by users, although we do not recommend that.
  14468. registerShape('circle', Circle);
  14469. registerShape('ellipse', Ellipse);
  14470. registerShape('sector', Sector);
  14471. registerShape('ring', Ring);
  14472. registerShape('polygon', Polygon);
  14473. registerShape('polyline', Polyline);
  14474. registerShape('rect', Rect);
  14475. registerShape('line', Line);
  14476. registerShape('bezierCurve', BezierCurve);
  14477. registerShape('arc', Arc);
  14478. var graphic = /*#__PURE__*/Object.freeze({
  14479. __proto__: null,
  14480. updateProps: updateProps,
  14481. initProps: initProps,
  14482. removeElement: removeElement,
  14483. removeElementWithFadeOut: removeElementWithFadeOut,
  14484. isElementRemoved: isElementRemoved,
  14485. extendShape: extendShape,
  14486. extendPath: extendPath,
  14487. registerShape: registerShape,
  14488. getShapeClass: getShapeClass,
  14489. makePath: makePath,
  14490. makeImage: makeImage,
  14491. mergePath: mergePath$1,
  14492. resizePath: resizePath,
  14493. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14494. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14495. subPixelOptimize: subPixelOptimize$1,
  14496. getTransform: getTransform,
  14497. applyTransform: applyTransform$1,
  14498. transformDirection: transformDirection,
  14499. groupTransition: groupTransition,
  14500. clipPointsByRect: clipPointsByRect,
  14501. clipRectByRect: clipRectByRect,
  14502. createIcon: createIcon,
  14503. linePolygonIntersect: linePolygonIntersect,
  14504. lineLineIntersect: lineLineIntersect,
  14505. setTooltipConfig: setTooltipConfig,
  14506. traverseElements: traverseElements,
  14507. Group: Group,
  14508. Image: ZRImage,
  14509. Text: ZRText,
  14510. Circle: Circle,
  14511. Ellipse: Ellipse,
  14512. Sector: Sector,
  14513. Ring: Ring,
  14514. Polygon: Polygon,
  14515. Polyline: Polyline,
  14516. Rect: Rect,
  14517. Line: Line,
  14518. BezierCurve: BezierCurve,
  14519. Arc: Arc,
  14520. IncrementalDisplayable: IncrementalDisplayable,
  14521. CompoundPath: CompoundPath,
  14522. LinearGradient: LinearGradient,
  14523. RadialGradient: RadialGradient,
  14524. BoundingRect: BoundingRect,
  14525. OrientedBoundingRect: OrientedBoundingRect,
  14526. Point: Point,
  14527. Path: Path
  14528. });
  14529. var EMPTY_OBJ = {};
  14530. function setLabelText(label, labelTexts) {
  14531. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14532. var stateName = SPECIAL_STATES[i];
  14533. var text = labelTexts[stateName];
  14534. var state = label.ensureState(stateName);
  14535. state.style = state.style || {};
  14536. state.style.text = text;
  14537. }
  14538. var oldStates = label.currentStates.slice();
  14539. label.clearStates(true);
  14540. label.setStyle({
  14541. text: labelTexts.normal
  14542. });
  14543. label.useStates(oldStates, true);
  14544. }
  14545. function getLabelText(opt, stateModels, interpolatedValue) {
  14546. var labelFetcher = opt.labelFetcher;
  14547. var labelDataIndex = opt.labelDataIndex;
  14548. var labelDimIndex = opt.labelDimIndex;
  14549. var normalModel = stateModels.normal;
  14550. var baseText;
  14551. if (labelFetcher) {
  14552. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14553. interpolatedValue: interpolatedValue
  14554. } : null);
  14555. }
  14556. if (baseText == null) {
  14557. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14558. }
  14559. var statesText = {
  14560. normal: baseText
  14561. };
  14562. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14563. var stateName = SPECIAL_STATES[i];
  14564. var stateModel = stateModels[stateName];
  14565. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14566. }
  14567. return statesText;
  14568. }
  14569. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14570. ) {
  14571. opt = opt || EMPTY_OBJ;
  14572. var isSetOnText = targetEl instanceof ZRText;
  14573. var needsCreateText = false;
  14574. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14575. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14576. if (stateModel && stateModel.getShallow('show')) {
  14577. needsCreateText = true;
  14578. break;
  14579. }
  14580. }
  14581. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14582. if (needsCreateText) {
  14583. if (!isSetOnText) {
  14584. // Reuse the previous
  14585. if (!textContent) {
  14586. textContent = new ZRText();
  14587. targetEl.setTextContent(textContent);
  14588. } // Use same state proxy
  14589. if (targetEl.stateProxy) {
  14590. textContent.stateProxy = targetEl.stateProxy;
  14591. }
  14592. }
  14593. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14594. var normalModel = labelStatesModels.normal;
  14595. var showNormal = !!normalModel.getShallow('show');
  14596. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14597. normalStyle.text = labelStatesTexts.normal;
  14598. if (!isSetOnText) {
  14599. // Always create new
  14600. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14601. }
  14602. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14603. var stateName = SPECIAL_STATES[i];
  14604. var stateModel = labelStatesModels[stateName];
  14605. if (stateModel) {
  14606. var stateObj = textContent.ensureState(stateName);
  14607. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14608. if (stateShow !== showNormal) {
  14609. stateObj.ignore = !stateShow;
  14610. }
  14611. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14612. stateObj.style.text = labelStatesTexts[stateName];
  14613. if (!isSetOnText) {
  14614. var targetElEmphasisState = targetEl.ensureState(stateName);
  14615. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14616. }
  14617. }
  14618. } // PENDING: if there is many requirements that emphasis position
  14619. // need to be different from normal position, we might consider
  14620. // auto slient is those cases.
  14621. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14622. if (textContent.style.x != null) {
  14623. normalStyle.x = textContent.style.x;
  14624. }
  14625. if (textContent.style.y != null) {
  14626. normalStyle.y = textContent.style.y;
  14627. }
  14628. textContent.ignore = !showNormal; // Always create new style.
  14629. textContent.useStyle(normalStyle);
  14630. textContent.dirty();
  14631. if (opt.enableTextSetter) {
  14632. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14633. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14634. setLabelText(textContent, labelStatesTexts);
  14635. };
  14636. }
  14637. } else if (textContent) {
  14638. // Not display rich text.
  14639. textContent.ignore = true;
  14640. }
  14641. targetEl.dirty();
  14642. }
  14643. function getLabelStatesModels(itemModel, labelName) {
  14644. labelName = labelName || 'label';
  14645. var statesModels = {
  14646. normal: itemModel.getModel(labelName)
  14647. };
  14648. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14649. var stateName = SPECIAL_STATES[i];
  14650. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14651. }
  14652. return statesModels;
  14653. }
  14654. /**
  14655. * Set basic textStyle properties.
  14656. */
  14657. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14658. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14659. ) {
  14660. var textStyle = {};
  14661. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14662. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14663. return textStyle;
  14664. }
  14665. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14666. opt = opt || {};
  14667. var textConfig = {};
  14668. var labelPosition;
  14669. var labelRotate = textStyleModel.getShallow('rotate');
  14670. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14671. var labelOffset = textStyleModel.getShallow('offset');
  14672. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14673. // in bar series, and magric type should be considered.
  14674. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14675. if (labelPosition != null) {
  14676. textConfig.position = labelPosition;
  14677. }
  14678. if (labelOffset != null) {
  14679. textConfig.offset = labelOffset;
  14680. }
  14681. if (labelRotate != null) {
  14682. labelRotate *= Math.PI / 180;
  14683. textConfig.rotation = labelRotate;
  14684. }
  14685. if (labelDistance != null) {
  14686. textConfig.distance = labelDistance;
  14687. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14688. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14689. return textConfig;
  14690. }
  14691. /**
  14692. * The uniform entry of set text style, that is, retrieve style definitions
  14693. * from `model` and set to `textStyle` object.
  14694. *
  14695. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14696. * properties will be set. (Consider the states of normal and emphasis and
  14697. * default value can be adopted, merge would make the logic too complicated
  14698. * to manage.)
  14699. */
  14700. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14701. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14702. opt = opt || EMPTY_OBJ;
  14703. var ecModel = textStyleModel.ecModel;
  14704. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14705. // {
  14706. // data: [{
  14707. // value: 12,
  14708. // label: {
  14709. // rich: {
  14710. // // no 'a' here but using parent 'a'.
  14711. // }
  14712. // }
  14713. // }],
  14714. // rich: {
  14715. // a: { ... }
  14716. // }
  14717. // }
  14718. var richItemNames = getRichItemNames(textStyleModel);
  14719. var richResult;
  14720. if (richItemNames) {
  14721. richResult = {};
  14722. for (var name_1 in richItemNames) {
  14723. if (richItemNames.hasOwnProperty(name_1)) {
  14724. // Cascade is supported in rich.
  14725. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14726. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14727. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14728. // That might confuses users. So probably we should put `textStyleModel` as the
  14729. // root ancestor of the `richTextStyle`. But that would be a break change.
  14730. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14731. }
  14732. }
  14733. }
  14734. if (richResult) {
  14735. textStyle.rich = richResult;
  14736. }
  14737. var overflow = textStyleModel.get('overflow');
  14738. if (overflow) {
  14739. textStyle.overflow = overflow;
  14740. }
  14741. var margin = textStyleModel.get('minMargin');
  14742. if (margin != null) {
  14743. textStyle.margin = margin;
  14744. }
  14745. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14746. } // Consider case:
  14747. // {
  14748. // data: [{
  14749. // value: 12,
  14750. // label: {
  14751. // rich: {
  14752. // // no 'a' here but using parent 'a'.
  14753. // }
  14754. // }
  14755. // }],
  14756. // rich: {
  14757. // a: { ... }
  14758. // }
  14759. // }
  14760. // TODO TextStyleModel
  14761. function getRichItemNames(textStyleModel) {
  14762. // Use object to remove duplicated names.
  14763. var richItemNameMap;
  14764. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14765. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14766. if (rich) {
  14767. richItemNameMap = richItemNameMap || {};
  14768. var richKeys = keys(rich);
  14769. for (var i = 0; i < richKeys.length; i++) {
  14770. var richKey = richKeys[i];
  14771. richItemNameMap[richKey] = 1;
  14772. }
  14773. }
  14774. textStyleModel = textStyleModel.parentModel;
  14775. }
  14776. return richItemNameMap;
  14777. }
  14778. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14779. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14780. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14781. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14782. // In merge mode, default value should not be given.
  14783. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14784. var inheritColor = opt && opt.inheritColor;
  14785. var fillColor = textStyleModel.getShallow('color');
  14786. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14787. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14788. if (fillColor === 'inherit' || fillColor === 'auto') {
  14789. if ("development" !== 'production') {
  14790. if (fillColor === 'auto') {
  14791. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14792. }
  14793. }
  14794. if (inheritColor) {
  14795. fillColor = inheritColor;
  14796. } else {
  14797. fillColor = null;
  14798. }
  14799. }
  14800. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14801. if ("development" !== 'production') {
  14802. if (strokeColor === 'auto') {
  14803. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14804. }
  14805. }
  14806. if (inheritColor) {
  14807. strokeColor = inheritColor;
  14808. } else {
  14809. strokeColor = null;
  14810. }
  14811. }
  14812. if (!isAttached) {
  14813. // Only use default global textStyle.color if text is individual.
  14814. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14815. fillColor = fillColor || globalTextStyle.color;
  14816. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14817. }
  14818. if (fillColor != null) {
  14819. textStyle.fill = fillColor;
  14820. }
  14821. if (strokeColor != null) {
  14822. textStyle.stroke = strokeColor;
  14823. }
  14824. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14825. if (textBorderWidth != null) {
  14826. textStyle.lineWidth = textBorderWidth;
  14827. }
  14828. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14829. if (textBorderType != null) {
  14830. textStyle.lineDash = textBorderType;
  14831. }
  14832. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14833. if (textBorderDashOffset != null) {
  14834. textStyle.lineDashOffset = textBorderDashOffset;
  14835. }
  14836. if (!isNotNormal && opacity == null && !inRich) {
  14837. opacity = opt && opt.defaultOpacity;
  14838. }
  14839. if (opacity != null) {
  14840. textStyle.opacity = opacity;
  14841. } // TODO
  14842. if (!isNotNormal && !isAttached) {
  14843. // Set default finally.
  14844. if (textStyle.fill == null && opt.inheritColor) {
  14845. textStyle.fill = opt.inheritColor;
  14846. }
  14847. } // Do not use `getFont` here, because merge should be supported, where
  14848. // part of these properties may be changed in emphasis style, and the
  14849. // others should remain their original value got from normal style.
  14850. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14851. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14852. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14853. if (val != null) {
  14854. textStyle[key] = val;
  14855. }
  14856. }
  14857. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14858. var key = TEXT_PROPS_SELF[i];
  14859. var val = textStyleModel.getShallow(key);
  14860. if (val != null) {
  14861. textStyle[key] = val;
  14862. }
  14863. }
  14864. if (textStyle.verticalAlign == null) {
  14865. var baseline = textStyleModel.getShallow('baseline');
  14866. if (baseline != null) {
  14867. textStyle.verticalAlign = baseline;
  14868. }
  14869. }
  14870. if (!isBlock || !opt.disableBox) {
  14871. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14872. var key = TEXT_PROPS_BOX[i];
  14873. var val = textStyleModel.getShallow(key);
  14874. if (val != null) {
  14875. textStyle[key] = val;
  14876. }
  14877. }
  14878. var borderType = textStyleModel.getShallow('borderType');
  14879. if (borderType != null) {
  14880. textStyle.borderDash = borderType;
  14881. }
  14882. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14883. if ("development" !== 'production') {
  14884. if (textStyle.backgroundColor === 'auto') {
  14885. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14886. }
  14887. }
  14888. textStyle.backgroundColor = inheritColor;
  14889. }
  14890. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14891. if ("development" !== 'production') {
  14892. if (textStyle.borderColor === 'auto') {
  14893. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14894. }
  14895. }
  14896. textStyle.borderColor = inheritColor;
  14897. }
  14898. }
  14899. }
  14900. function getFont(opt, ecModel) {
  14901. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14902. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14903. 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(' '));
  14904. }
  14905. var labelInner = makeInner();
  14906. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14907. if (!label) {
  14908. return;
  14909. }
  14910. var obj = labelInner(label);
  14911. obj.prevValue = obj.value;
  14912. obj.value = value;
  14913. var normalLabelModel = labelStatesModels.normal;
  14914. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14915. if (obj.valueAnimation) {
  14916. obj.precision = normalLabelModel.get('precision');
  14917. obj.defaultInterpolatedText = getDefaultText;
  14918. obj.statesModels = labelStatesModels;
  14919. }
  14920. }
  14921. var PATH_COLOR = ['textStyle', 'color'];
  14922. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  14923. var tmpText = new ZRText();
  14924. var TextStyleMixin =
  14925. /** @class */
  14926. function () {
  14927. function TextStyleMixin() {}
  14928. /**
  14929. * Get color property or get color from option.textStyle.color
  14930. */
  14931. // TODO Callback
  14932. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14933. var ecModel = this.ecModel;
  14934. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14935. };
  14936. /**
  14937. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14938. * @return {string}
  14939. */
  14940. TextStyleMixin.prototype.getFont = function () {
  14941. return getFont({
  14942. fontStyle: this.getShallow('fontStyle'),
  14943. fontWeight: this.getShallow('fontWeight'),
  14944. fontSize: this.getShallow('fontSize'),
  14945. fontFamily: this.getShallow('fontFamily')
  14946. }, this.ecModel);
  14947. };
  14948. TextStyleMixin.prototype.getTextRect = function (text) {
  14949. var style = {
  14950. text: text,
  14951. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  14952. };
  14953. for (var i = 0; i < textStyleParams.length; i++) {
  14954. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  14955. }
  14956. tmpText.useStyle(style);
  14957. tmpText.update();
  14958. return tmpText.getBoundingRect();
  14959. };
  14960. return TextStyleMixin;
  14961. }();
  14962. 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`.
  14963. // So do not transfer decal directly.
  14964. ];
  14965. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14966. var LineStyleMixin =
  14967. /** @class */
  14968. function () {
  14969. function LineStyleMixin() {}
  14970. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14971. return getLineStyle(this, excludes);
  14972. };
  14973. return LineStyleMixin;
  14974. }();
  14975. 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`.
  14976. // So do not transfer decal directly.
  14977. ];
  14978. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14979. var ItemStyleMixin =
  14980. /** @class */
  14981. function () {
  14982. function ItemStyleMixin() {}
  14983. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14984. return getItemStyle(this, excludes, includes);
  14985. };
  14986. return ItemStyleMixin;
  14987. }();
  14988. var Model =
  14989. /** @class */
  14990. function () {
  14991. function Model(option, parentModel, ecModel) {
  14992. this.parentModel = parentModel;
  14993. this.ecModel = ecModel;
  14994. this.option = option; // Simple optimization
  14995. // if (this.init) {
  14996. // if (arguments.length <= 4) {
  14997. // this.init(option, parentModel, ecModel, extraOpt);
  14998. // }
  14999. // else {
  15000. // this.init.apply(this, arguments);
  15001. // }
  15002. // }
  15003. }
  15004. Model.prototype.init = function (option, parentModel, ecModel) {
  15005. var rest = [];
  15006. for (var _i = 3; _i < arguments.length; _i++) {
  15007. rest[_i - 3] = arguments[_i];
  15008. }
  15009. };
  15010. /**
  15011. * Merge the input option to me.
  15012. */
  15013. Model.prototype.mergeOption = function (option, ecModel) {
  15014. merge(this.option, option, true);
  15015. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `ModelOption`
  15016. // TODO: TYPE strict key check?
  15017. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15018. Model.prototype.get = function (path, ignoreParent) {
  15019. if (path == null) {
  15020. return this.option;
  15021. }
  15022. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15023. };
  15024. Model.prototype.getShallow = function (key, ignoreParent) {
  15025. var option = this.option;
  15026. var val = option == null ? option : option[key];
  15027. if (val == null && !ignoreParent) {
  15028. var parentModel = this.parentModel;
  15029. if (parentModel) {
  15030. // FIXME:TS do not know how to make it works
  15031. val = parentModel.getShallow(key);
  15032. }
  15033. }
  15034. return val;
  15035. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `Model<ModelOption>`
  15036. // getModel(path: string | string[], parentModel?: Model): Model;
  15037. // TODO 'xxx.yyy.zzz' is deprecated
  15038. Model.prototype.getModel = function (path, parentModel) {
  15039. var hasPath = path != null;
  15040. var pathFinal = hasPath ? this.parsePath(path) : null;
  15041. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15042. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15043. return new Model(obj, parentModel, this.ecModel);
  15044. };
  15045. /**
  15046. * If model has option
  15047. */
  15048. Model.prototype.isEmpty = function () {
  15049. return this.option == null;
  15050. };
  15051. Model.prototype.restoreData = function () {}; // Pending
  15052. Model.prototype.clone = function () {
  15053. var Ctor = this.constructor;
  15054. return new Ctor(clone(this.option));
  15055. }; // setReadOnly(properties): void {
  15056. // clazzUtil.setReadOnly(this, properties);
  15057. // }
  15058. // If path is null/undefined, return null/undefined.
  15059. Model.prototype.parsePath = function (path) {
  15060. if (typeof path === 'string') {
  15061. return path.split('.');
  15062. }
  15063. return path;
  15064. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15065. // Default to be a identity resolver.
  15066. // Can be modified to a different resolver.
  15067. Model.prototype.resolveParentPath = function (path) {
  15068. return path;
  15069. }; // FIXME:TS check whether put this method here
  15070. Model.prototype.isAnimationEnabled = function () {
  15071. if (!env.node && this.option) {
  15072. if (this.option.animation != null) {
  15073. return !!this.option.animation;
  15074. } else if (this.parentModel) {
  15075. return this.parentModel.isAnimationEnabled();
  15076. }
  15077. }
  15078. };
  15079. Model.prototype._doGet = function (pathArr, parentModel) {
  15080. var obj = this.option;
  15081. if (!pathArr) {
  15082. return obj;
  15083. }
  15084. for (var i = 0; i < pathArr.length; i++) {
  15085. // Ignore empty
  15086. if (!pathArr[i]) {
  15087. continue;
  15088. } // obj could be number/string/... (like 0)
  15089. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15090. if (obj == null) {
  15091. break;
  15092. }
  15093. }
  15094. if (obj == null && parentModel) {
  15095. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15096. }
  15097. return obj;
  15098. };
  15099. return Model;
  15100. }();
  15101. enableClassExtend(Model);
  15102. enableClassCheck(Model);
  15103. mixin(Model, LineStyleMixin);
  15104. mixin(Model, ItemStyleMixin);
  15105. mixin(Model, AreaStyleMixin);
  15106. mixin(Model, TextStyleMixin);
  15107. var base = Math.round(Math.random() * 10);
  15108. /**
  15109. * @public
  15110. * @param {string} type
  15111. * @return {string}
  15112. */
  15113. function getUID(type) {
  15114. // Considering the case of crossing js context,
  15115. // use Math.random to make id as unique as possible.
  15116. return [type || '', base++].join('_');
  15117. }
  15118. /**
  15119. * Implements `SubTypeDefaulterManager` for `target`.
  15120. */
  15121. function enableSubTypeDefaulter(target) {
  15122. var subTypeDefaulters = {};
  15123. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15124. var componentTypeInfo = parseClassType(componentType);
  15125. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15126. };
  15127. target.determineSubType = function (componentType, option) {
  15128. var type = option.type;
  15129. if (!type) {
  15130. var componentTypeMain = parseClassType(componentType).main;
  15131. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15132. type = subTypeDefaulters[componentTypeMain](option);
  15133. }
  15134. }
  15135. return type;
  15136. };
  15137. }
  15138. /**
  15139. * Implements `TopologicalTravelable<any>` for `entity`.
  15140. *
  15141. * Topological travel on Activity Network (Activity On Vertices).
  15142. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15143. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15144. * If there is circular dependencey, Error will be thrown.
  15145. */
  15146. function enableTopologicalTravel(entity, dependencyGetter) {
  15147. /**
  15148. * @param targetNameList Target Component type list.
  15149. * Can be ['aa', 'bb', 'aa.xx']
  15150. * @param fullNameList By which we can build dependency graph.
  15151. * @param callback Params: componentType, dependencies.
  15152. * @param context Scope of callback.
  15153. */
  15154. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15155. if (!targetNameList.length) {
  15156. return;
  15157. }
  15158. var result = makeDepndencyGraph(fullNameList);
  15159. var graph = result.graph;
  15160. var noEntryList = result.noEntryList;
  15161. var targetNameSet = {};
  15162. each(targetNameList, function (name) {
  15163. targetNameSet[name] = true;
  15164. });
  15165. while (noEntryList.length) {
  15166. var currComponentType = noEntryList.pop();
  15167. var currVertex = graph[currComponentType];
  15168. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15169. if (isInTargetNameSet) {
  15170. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15171. delete targetNameSet[currComponentType];
  15172. }
  15173. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15174. }
  15175. each(targetNameSet, function () {
  15176. var errMsg = '';
  15177. if ("development" !== 'production') {
  15178. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15179. }
  15180. throw new Error(errMsg);
  15181. });
  15182. function removeEdge(succComponentType) {
  15183. graph[succComponentType].entryCount--;
  15184. if (graph[succComponentType].entryCount === 0) {
  15185. noEntryList.push(succComponentType);
  15186. }
  15187. } // Consider this case: legend depends on series, and we call
  15188. // chart.setOption({series: [...]}), where only series is in option.
  15189. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15190. // not be called, but only sereis.mergeOption is called. Thus legend
  15191. // have no chance to update its local record about series (like which
  15192. // name of series is available in legend).
  15193. function removeEdgeAndAdd(succComponentType) {
  15194. targetNameSet[succComponentType] = true;
  15195. removeEdge(succComponentType);
  15196. }
  15197. };
  15198. function makeDepndencyGraph(fullNameList) {
  15199. var graph = {};
  15200. var noEntryList = [];
  15201. each(fullNameList, function (name) {
  15202. var thisItem = createDependencyGraphItem(graph, name);
  15203. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15204. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15205. thisItem.entryCount = availableDeps.length;
  15206. if (thisItem.entryCount === 0) {
  15207. noEntryList.push(name);
  15208. }
  15209. each(availableDeps, function (dependentName) {
  15210. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15211. thisItem.predecessor.push(dependentName);
  15212. }
  15213. var thatItem = createDependencyGraphItem(graph, dependentName);
  15214. if (indexOf(thatItem.successor, dependentName) < 0) {
  15215. thatItem.successor.push(name);
  15216. }
  15217. });
  15218. });
  15219. return {
  15220. graph: graph,
  15221. noEntryList: noEntryList
  15222. };
  15223. }
  15224. function createDependencyGraphItem(graph, name) {
  15225. if (!graph[name]) {
  15226. graph[name] = {
  15227. predecessor: [],
  15228. successor: []
  15229. };
  15230. }
  15231. return graph[name];
  15232. }
  15233. function getAvailableDependencies(originalDeps, fullNameList) {
  15234. var availableDeps = [];
  15235. each(originalDeps, function (dep) {
  15236. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15237. });
  15238. return availableDeps;
  15239. }
  15240. }
  15241. function inheritDefaultOption(superOption, subOption) {
  15242. // See also `model/Component.ts#getDefaultOption`
  15243. return merge(merge({}, superOption, true), subOption, true);
  15244. }
  15245. /*
  15246. * Licensed to the Apache Software Foundation (ASF) under one
  15247. * or more contributor license agreements. See the NOTICE file
  15248. * distributed with this work for additional information
  15249. * regarding copyright ownership. The ASF licenses this file
  15250. * to you under the Apache License, Version 2.0 (the
  15251. * "License"); you may not use this file except in compliance
  15252. * with the License. You may obtain a copy of the License at
  15253. *
  15254. * http://www.apache.org/licenses/LICENSE-2.0
  15255. *
  15256. * Unless required by applicable law or agreed to in writing,
  15257. * software distributed under the License is distributed on an
  15258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15259. * KIND, either express or implied. See the License for the
  15260. * specific language governing permissions and limitations
  15261. * under the License.
  15262. */
  15263. /**
  15264. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15265. */
  15266. /*
  15267. * Licensed to the Apache Software Foundation (ASF) under one
  15268. * or more contributor license agreements. See the NOTICE file
  15269. * distributed with this work for additional information
  15270. * regarding copyright ownership. The ASF licenses this file
  15271. * to you under the Apache License, Version 2.0 (the
  15272. * "License"); you may not use this file except in compliance
  15273. * with the License. You may obtain a copy of the License at
  15274. *
  15275. * http://www.apache.org/licenses/LICENSE-2.0
  15276. *
  15277. * Unless required by applicable law or agreed to in writing,
  15278. * software distributed under the License is distributed on an
  15279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15280. * KIND, either express or implied. See the License for the
  15281. * specific language governing permissions and limitations
  15282. * under the License.
  15283. */
  15284. /**
  15285. * Language: English.
  15286. */
  15287. var langEN = {
  15288. time: {
  15289. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15290. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15291. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15292. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15293. },
  15294. legend: {
  15295. selector: {
  15296. all: 'All',
  15297. inverse: 'Inv'
  15298. }
  15299. },
  15300. toolbox: {
  15301. brush: {
  15302. title: {
  15303. rect: 'Box Select',
  15304. polygon: 'Lasso Select',
  15305. lineX: 'Horizontally Select',
  15306. lineY: 'Vertically Select',
  15307. keep: 'Keep Selections',
  15308. clear: 'Clear Selections'
  15309. }
  15310. },
  15311. dataView: {
  15312. title: 'Data View',
  15313. lang: ['Data View', 'Close', 'Refresh']
  15314. },
  15315. dataZoom: {
  15316. title: {
  15317. zoom: 'Zoom',
  15318. back: 'Zoom Reset'
  15319. }
  15320. },
  15321. magicType: {
  15322. title: {
  15323. line: 'Switch to Line Chart',
  15324. bar: 'Switch to Bar Chart',
  15325. stack: 'Stack',
  15326. tiled: 'Tile'
  15327. }
  15328. },
  15329. restore: {
  15330. title: 'Restore'
  15331. },
  15332. saveAsImage: {
  15333. title: 'Save as Image',
  15334. lang: ['Right Click to Save Image']
  15335. }
  15336. },
  15337. series: {
  15338. typeNames: {
  15339. pie: 'Pie chart',
  15340. bar: 'Bar chart',
  15341. line: 'Line chart',
  15342. scatter: 'Scatter plot',
  15343. effectScatter: 'Ripple scatter plot',
  15344. radar: 'Radar chart',
  15345. tree: 'Tree',
  15346. treemap: 'Treemap',
  15347. boxplot: 'Boxplot',
  15348. candlestick: 'Candlestick',
  15349. k: 'K line chart',
  15350. heatmap: 'Heat map',
  15351. map: 'Map',
  15352. parallel: 'Parallel coordinate map',
  15353. lines: 'Line graph',
  15354. graph: 'Relationship graph',
  15355. sankey: 'Sankey diagram',
  15356. funnel: 'Funnel chart',
  15357. gauge: 'Gauge',
  15358. pictorialBar: 'Pictorial bar',
  15359. themeRiver: 'Theme River Map',
  15360. sunburst: 'Sunburst'
  15361. }
  15362. },
  15363. aria: {
  15364. general: {
  15365. withTitle: 'This is a chart about "{title}"',
  15366. withoutTitle: 'This is a chart'
  15367. },
  15368. series: {
  15369. single: {
  15370. prefix: '',
  15371. withName: ' with type {seriesType} named {seriesName}.',
  15372. withoutName: ' with type {seriesType}.'
  15373. },
  15374. multiple: {
  15375. prefix: '. It consists of {seriesCount} series count.',
  15376. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15377. withoutName: ' The {seriesId} series is a {seriesType}.',
  15378. separator: {
  15379. middle: '',
  15380. end: ''
  15381. }
  15382. }
  15383. },
  15384. data: {
  15385. allData: 'The data is as follows: ',
  15386. partialData: 'The first {displayCnt} items are: ',
  15387. withName: 'the data for {name} is {value}',
  15388. withoutName: '{value}',
  15389. separator: {
  15390. middle: ', ',
  15391. end: '. '
  15392. }
  15393. }
  15394. }
  15395. };
  15396. /*
  15397. * Licensed to the Apache Software Foundation (ASF) under one
  15398. * or more contributor license agreements. See the NOTICE file
  15399. * distributed with this work for additional information
  15400. * regarding copyright ownership. The ASF licenses this file
  15401. * to you under the Apache License, Version 2.0 (the
  15402. * "License"); you may not use this file except in compliance
  15403. * with the License. You may obtain a copy of the License at
  15404. *
  15405. * http://www.apache.org/licenses/LICENSE-2.0
  15406. *
  15407. * Unless required by applicable law or agreed to in writing,
  15408. * software distributed under the License is distributed on an
  15409. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15410. * KIND, either express or implied. See the License for the
  15411. * specific language governing permissions and limitations
  15412. * under the License.
  15413. */
  15414. /**
  15415. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15416. */
  15417. /*
  15418. * Licensed to the Apache Software Foundation (ASF) under one
  15419. * or more contributor license agreements. See the NOTICE file
  15420. * distributed with this work for additional information
  15421. * regarding copyright ownership. The ASF licenses this file
  15422. * to you under the Apache License, Version 2.0 (the
  15423. * "License"); you may not use this file except in compliance
  15424. * with the License. You may obtain a copy of the License at
  15425. *
  15426. * http://www.apache.org/licenses/LICENSE-2.0
  15427. *
  15428. * Unless required by applicable law or agreed to in writing,
  15429. * software distributed under the License is distributed on an
  15430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15431. * KIND, either express or implied. See the License for the
  15432. * specific language governing permissions and limitations
  15433. * under the License.
  15434. */
  15435. var langZH = {
  15436. time: {
  15437. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15438. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15439. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15440. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15441. },
  15442. legend: {
  15443. selector: {
  15444. all: '全选',
  15445. inverse: '反选'
  15446. }
  15447. },
  15448. toolbox: {
  15449. brush: {
  15450. title: {
  15451. rect: '矩形选择',
  15452. polygon: '圈选',
  15453. lineX: '横向选择',
  15454. lineY: '纵向选择',
  15455. keep: '保持选择',
  15456. clear: '清除选择'
  15457. }
  15458. },
  15459. dataView: {
  15460. title: '数据视图',
  15461. lang: ['数据视图', '关闭', '刷新']
  15462. },
  15463. dataZoom: {
  15464. title: {
  15465. zoom: '区域缩放',
  15466. back: '区域缩放还原'
  15467. }
  15468. },
  15469. magicType: {
  15470. title: {
  15471. line: '切换为折线图',
  15472. bar: '切换为柱状图',
  15473. stack: '切换为堆叠',
  15474. tiled: '切换为平铺'
  15475. }
  15476. },
  15477. restore: {
  15478. title: '还原'
  15479. },
  15480. saveAsImage: {
  15481. title: '保存为图片',
  15482. lang: ['右键另存为图片']
  15483. }
  15484. },
  15485. series: {
  15486. typeNames: {
  15487. pie: '饼图',
  15488. bar: '柱状图',
  15489. line: '折线图',
  15490. scatter: '散点图',
  15491. effectScatter: '涟漪散点图',
  15492. radar: '雷达图',
  15493. tree: '树图',
  15494. treemap: '矩形树图',
  15495. boxplot: '箱型图',
  15496. candlestick: 'K线图',
  15497. k: 'K线图',
  15498. heatmap: '热力图',
  15499. map: '地图',
  15500. parallel: '平行坐标图',
  15501. lines: '线图',
  15502. graph: '关系图',
  15503. sankey: '桑基图',
  15504. funnel: '漏斗图',
  15505. gauge: '仪表盘图',
  15506. pictorialBar: '象形柱图',
  15507. themeRiver: '主题河流图',
  15508. sunburst: '旭日图'
  15509. }
  15510. },
  15511. aria: {
  15512. general: {
  15513. withTitle: '这是一个关于“{title}”的图表。',
  15514. withoutTitle: '这是一个图表,'
  15515. },
  15516. series: {
  15517. single: {
  15518. prefix: '',
  15519. withName: '图表类型是{seriesType},表示{seriesName}。',
  15520. withoutName: '图表类型是{seriesType}。'
  15521. },
  15522. multiple: {
  15523. prefix: '它由{seriesCount}个图表系列组成。',
  15524. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15525. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15526. separator: {
  15527. middle: ';',
  15528. end: '。'
  15529. }
  15530. }
  15531. },
  15532. data: {
  15533. allData: '其数据是——',
  15534. partialData: '其中,前{displayCnt}项是——',
  15535. withName: '{name}的数据是{value}',
  15536. withoutName: '{value}',
  15537. separator: {
  15538. middle: ',',
  15539. end: ''
  15540. }
  15541. }
  15542. }
  15543. };
  15544. var LOCALE_ZH = 'ZH';
  15545. var LOCALE_EN = 'EN';
  15546. var DEFAULT_LOCALE = LOCALE_EN;
  15547. var localeStorage = {};
  15548. var localeModels = {};
  15549. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15550. var langStr = (
  15551. /* eslint-disable-next-line */
  15552. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15553. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15554. }();
  15555. function registerLocale(locale, localeObj) {
  15556. locale = locale.toUpperCase();
  15557. localeModels[locale] = new Model(localeObj);
  15558. localeStorage[locale] = localeObj;
  15559. } // export function getLocale(locale: string) {
  15560. // return localeStorage[locale];
  15561. // }
  15562. function createLocaleObject(locale) {
  15563. if (isString(locale)) {
  15564. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15565. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15566. return clone(localeObj);
  15567. } else {
  15568. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15569. }
  15570. } else {
  15571. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15572. }
  15573. }
  15574. function getLocaleModel(lang) {
  15575. return localeModels[lang];
  15576. }
  15577. function getDefaultLocaleModel() {
  15578. return localeModels[DEFAULT_LOCALE];
  15579. } // Default locale
  15580. registerLocale(LOCALE_EN, langEN);
  15581. registerLocale(LOCALE_ZH, langZH);
  15582. var ONE_SECOND = 1000;
  15583. var ONE_MINUTE = ONE_SECOND * 60;
  15584. var ONE_HOUR = ONE_MINUTE * 60;
  15585. var ONE_DAY = ONE_HOUR * 24;
  15586. var ONE_YEAR = ONE_DAY * 365;
  15587. var defaultLeveledFormatter = {
  15588. year: '{yyyy}',
  15589. month: '{MMM}',
  15590. day: '{d}',
  15591. hour: '{HH}:{mm}',
  15592. minute: '{HH}:{mm}',
  15593. second: '{HH}:{mm}:{ss}',
  15594. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15595. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15596. };
  15597. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15598. var fullLeveledFormatter = {
  15599. year: '{yyyy}',
  15600. month: '{yyyy}-{MM}',
  15601. day: fullDayFormatter,
  15602. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15603. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15604. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15605. millisecond: defaultLeveledFormatter.none
  15606. };
  15607. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15608. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15609. function pad(str, len) {
  15610. str += '';
  15611. return '0000'.substr(0, len - str.length) + str;
  15612. }
  15613. function getPrimaryTimeUnit(timeUnit) {
  15614. switch (timeUnit) {
  15615. case 'half-year':
  15616. case 'quarter':
  15617. return 'month';
  15618. case 'week':
  15619. case 'half-week':
  15620. return 'day';
  15621. case 'half-day':
  15622. case 'quarter-day':
  15623. return 'hour';
  15624. default:
  15625. // year, minutes, second, milliseconds
  15626. return timeUnit;
  15627. }
  15628. }
  15629. function isPrimaryTimeUnit(timeUnit) {
  15630. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15631. }
  15632. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15633. switch (timeUnit) {
  15634. case 'year':
  15635. case 'month':
  15636. return 'day';
  15637. case 'millisecond':
  15638. return 'millisecond';
  15639. default:
  15640. // Also for day, hour, minute, second
  15641. return 'second';
  15642. }
  15643. }
  15644. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15645. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15646. time, template, isUTC, lang) {
  15647. var date = parseDate(time);
  15648. var y = date[fullYearGetterName(isUTC)]();
  15649. var M = date[monthGetterName(isUTC)]() + 1;
  15650. var q = Math.floor((M - 1) / 4) + 1;
  15651. var d = date[dateGetterName(isUTC)]();
  15652. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15653. var H = date[hoursGetterName(isUTC)]();
  15654. var h = (H - 1) % 12 + 1;
  15655. var m = date[minutesGetterName(isUTC)]();
  15656. var s = date[secondsGetterName(isUTC)]();
  15657. var S = date[millisecondsGetterName(isUTC)]();
  15658. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15659. var timeModel = localeModel.getModel('time');
  15660. var month = timeModel.get('month');
  15661. var monthAbbr = timeModel.get('monthAbbr');
  15662. var dayOfWeek = timeModel.get('dayOfWeek');
  15663. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15664. 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 + '');
  15665. }
  15666. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15667. var template = null;
  15668. if (isString(formatter)) {
  15669. // Single formatter for all units at all levels
  15670. template = formatter;
  15671. } else if (isFunction(formatter)) {
  15672. // Callback formatter
  15673. template = formatter(tick.value, idx, {
  15674. level: tick.level
  15675. });
  15676. } else {
  15677. var defaults$1 = extend({}, defaultLeveledFormatter);
  15678. if (tick.level > 0) {
  15679. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15680. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15681. }
  15682. }
  15683. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15684. : defaults(formatter, defaults$1) : defaults$1;
  15685. var unit = getUnitFromValue(tick.value, isUTC);
  15686. if (mergedFormatter[unit]) {
  15687. template = mergedFormatter[unit];
  15688. } else if (mergedFormatter.inherit) {
  15689. // Unit formatter is not defined and should inherit from bigger units
  15690. var targetId = timeUnits.indexOf(unit);
  15691. for (var i = targetId - 1; i >= 0; --i) {
  15692. if (mergedFormatter[unit]) {
  15693. template = mergedFormatter[unit];
  15694. break;
  15695. }
  15696. }
  15697. template = template || defaults$1.none;
  15698. }
  15699. if (isArray(template)) {
  15700. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15701. levelId = Math.min(levelId, template.length - 1);
  15702. template = template[levelId];
  15703. }
  15704. }
  15705. return format(new Date(tick.value), template, isUTC, lang);
  15706. }
  15707. function getUnitFromValue(value, isUTC) {
  15708. var date = parseDate(value);
  15709. var M = date[monthGetterName(isUTC)]() + 1;
  15710. var d = date[dateGetterName(isUTC)]();
  15711. var h = date[hoursGetterName(isUTC)]();
  15712. var m = date[minutesGetterName(isUTC)]();
  15713. var s = date[secondsGetterName(isUTC)]();
  15714. var S = date[millisecondsGetterName(isUTC)]();
  15715. var isSecond = S === 0;
  15716. var isMinute = isSecond && s === 0;
  15717. var isHour = isMinute && m === 0;
  15718. var isDay = isHour && h === 0;
  15719. var isMonth = isDay && d === 1;
  15720. var isYear = isMonth && M === 1;
  15721. if (isYear) {
  15722. return 'year';
  15723. } else if (isMonth) {
  15724. return 'month';
  15725. } else if (isDay) {
  15726. return 'day';
  15727. } else if (isHour) {
  15728. return 'hour';
  15729. } else if (isMinute) {
  15730. return 'minute';
  15731. } else if (isSecond) {
  15732. return 'second';
  15733. } else {
  15734. return 'millisecond';
  15735. }
  15736. }
  15737. function getUnitValue(value, unit, isUTC) {
  15738. var date = isNumber(value) ? parseDate(value) : value;
  15739. unit = unit || getUnitFromValue(value, isUTC);
  15740. switch (unit) {
  15741. case 'year':
  15742. return date[fullYearGetterName(isUTC)]();
  15743. case 'half-year':
  15744. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15745. case 'quarter':
  15746. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15747. case 'month':
  15748. return date[monthGetterName(isUTC)]();
  15749. case 'day':
  15750. return date[dateGetterName(isUTC)]();
  15751. case 'half-day':
  15752. return date[hoursGetterName(isUTC)]() / 24;
  15753. case 'hour':
  15754. return date[hoursGetterName(isUTC)]();
  15755. case 'minute':
  15756. return date[minutesGetterName(isUTC)]();
  15757. case 'second':
  15758. return date[secondsGetterName(isUTC)]();
  15759. case 'millisecond':
  15760. return date[millisecondsGetterName(isUTC)]();
  15761. }
  15762. }
  15763. function fullYearGetterName(isUTC) {
  15764. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15765. }
  15766. function monthGetterName(isUTC) {
  15767. return isUTC ? 'getUTCMonth' : 'getMonth';
  15768. }
  15769. function dateGetterName(isUTC) {
  15770. return isUTC ? 'getUTCDate' : 'getDate';
  15771. }
  15772. function hoursGetterName(isUTC) {
  15773. return isUTC ? 'getUTCHours' : 'getHours';
  15774. }
  15775. function minutesGetterName(isUTC) {
  15776. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15777. }
  15778. function secondsGetterName(isUTC) {
  15779. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15780. }
  15781. function millisecondsGetterName(isUTC) {
  15782. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  15783. }
  15784. function fullYearSetterName(isUTC) {
  15785. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15786. }
  15787. function monthSetterName(isUTC) {
  15788. return isUTC ? 'setUTCMonth' : 'setMonth';
  15789. }
  15790. function dateSetterName(isUTC) {
  15791. return isUTC ? 'setUTCDate' : 'setDate';
  15792. }
  15793. function hoursSetterName(isUTC) {
  15794. return isUTC ? 'setUTCHours' : 'setHours';
  15795. }
  15796. function minutesSetterName(isUTC) {
  15797. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15798. }
  15799. function secondsSetterName(isUTC) {
  15800. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15801. }
  15802. function millisecondsSetterName(isUTC) {
  15803. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  15804. }
  15805. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15806. var textEl = new ZRText({
  15807. style: {
  15808. text: text,
  15809. font: font,
  15810. align: align,
  15811. verticalAlign: verticalAlign,
  15812. padding: padding,
  15813. rich: rich,
  15814. overflow: truncate ? 'truncate' : null,
  15815. lineHeight: lineHeight
  15816. }
  15817. });
  15818. return textEl.getBoundingRect();
  15819. }
  15820. /**
  15821. * Add a comma each three digit.
  15822. */
  15823. function addCommas(x) {
  15824. if (!isNumeric(x)) {
  15825. return isString(x) ? x : '-';
  15826. }
  15827. var parts = (x + '').split('.');
  15828. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15829. }
  15830. function toCamelCase(str, upperCaseFirst) {
  15831. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15832. return group1.toUpperCase();
  15833. });
  15834. if (upperCaseFirst && str) {
  15835. str = str.charAt(0).toUpperCase() + str.slice(1);
  15836. }
  15837. return str;
  15838. }
  15839. var normalizeCssArray$1 = normalizeCssArray;
  15840. var replaceReg = /([&<>"'])/g;
  15841. var replaceMap = {
  15842. '&': '&amp;',
  15843. '<': '&lt;',
  15844. '>': '&gt;',
  15845. '"': '&quot;',
  15846. '\'': '&#39;'
  15847. };
  15848. function encodeHTML(source) {
  15849. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15850. return replaceMap[c];
  15851. });
  15852. }
  15853. /**
  15854. * Make value user readable for tooltip and label.
  15855. * "User readable":
  15856. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  15857. * Avoid to display an empty string, which users can not recognize there is
  15858. * a value and it might look like a bug.
  15859. */
  15860. function makeValueReadable(value, valueType, useUTC) {
  15861. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  15862. function stringToUserReadable(str) {
  15863. return str && trim(str) ? str : '-';
  15864. }
  15865. function isNumberUserReadable(num) {
  15866. return !!(num != null && !isNaN(num) && isFinite(num));
  15867. }
  15868. var isTypeTime = valueType === 'time';
  15869. var isValueDate = value instanceof Date;
  15870. if (isTypeTime || isValueDate) {
  15871. var date = isTypeTime ? parseDate(value) : value;
  15872. if (!isNaN(+date)) {
  15873. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  15874. } else if (isValueDate) {
  15875. return '-';
  15876. } // In other cases, continue to try to display the value in the following code.
  15877. }
  15878. if (valueType === 'ordinal') {
  15879. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  15880. } // By default.
  15881. var numericResult = numericToNumber(value);
  15882. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  15883. }
  15884. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15885. var wrapVar = function (varName, seriesIdx) {
  15886. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15887. };
  15888. /**
  15889. * Template formatter
  15890. * @param {Array.<Object>|Object} paramsList
  15891. */
  15892. function formatTpl(tpl, paramsList, encode) {
  15893. if (!isArray(paramsList)) {
  15894. paramsList = [paramsList];
  15895. }
  15896. var seriesLen = paramsList.length;
  15897. if (!seriesLen) {
  15898. return '';
  15899. }
  15900. var $vars = paramsList[0].$vars || [];
  15901. for (var i = 0; i < $vars.length; i++) {
  15902. var alias = TPL_VAR_ALIAS[i];
  15903. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15904. }
  15905. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15906. for (var k = 0; k < $vars.length; k++) {
  15907. var val = paramsList[seriesIdx][$vars[k]];
  15908. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15909. }
  15910. }
  15911. return tpl;
  15912. }
  15913. function getTooltipMarker(inOpt, extraCssText) {
  15914. var opt = isString(inOpt) ? {
  15915. color: inOpt,
  15916. extraCssText: extraCssText
  15917. } : inOpt || {};
  15918. var color = opt.color;
  15919. var type = opt.type;
  15920. extraCssText = opt.extraCssText;
  15921. var renderMode = opt.renderMode || 'html';
  15922. if (!color) {
  15923. return '';
  15924. }
  15925. if (renderMode === 'html') {
  15926. 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
  15927. + 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>';
  15928. } else {
  15929. // Should better not to auto generate style name by auto-increment number here.
  15930. // Because this util is usually called in tooltip formatter, which is probably
  15931. // called repeatly when mouse move and the auto-increment number increases fast.
  15932. // Users can make their own style name by theirselves, make it unique and readable.
  15933. var markerId = opt.markerId || 'markerX';
  15934. return {
  15935. renderMode: renderMode,
  15936. content: '{' + markerId + '|} ',
  15937. style: type === 'subItem' ? {
  15938. width: 4,
  15939. height: 4,
  15940. borderRadius: 2,
  15941. backgroundColor: color
  15942. } : {
  15943. width: 10,
  15944. height: 10,
  15945. borderRadius: 5,
  15946. backgroundColor: color
  15947. }
  15948. };
  15949. }
  15950. }
  15951. /**
  15952. * @deprecated Use `time/format` instead.
  15953. * ISO Date format
  15954. * @param {string} tpl
  15955. * @param {number} value
  15956. * @param {boolean} [isUTC=false] Default in local time.
  15957. * see `module:echarts/scale/Time`
  15958. * and `module:echarts/util/number#parseDate`.
  15959. * @inner
  15960. */
  15961. function formatTime(tpl, value, isUTC) {
  15962. if ("development" !== 'production') {
  15963. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15964. }
  15965. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15966. tpl = 'MM-dd\nyyyy';
  15967. }
  15968. var date = parseDate(value);
  15969. var getUTC = isUTC ? 'getUTC' : 'get';
  15970. var y = date[getUTC + 'FullYear']();
  15971. var M = date[getUTC + 'Month']() + 1;
  15972. var d = date[getUTC + 'Date']();
  15973. var h = date[getUTC + 'Hours']();
  15974. var m = date[getUTC + 'Minutes']();
  15975. var s = date[getUTC + 'Seconds']();
  15976. var S = date[getUTC + 'Milliseconds']();
  15977. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').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));
  15978. return tpl;
  15979. }
  15980. /**
  15981. * Capital first
  15982. * @param {string} str
  15983. * @return {string}
  15984. */
  15985. function capitalFirst(str) {
  15986. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15987. }
  15988. /**
  15989. * @return Never be null/undefined.
  15990. */
  15991. function convertToColorString(color, defaultColor) {
  15992. defaultColor = defaultColor || 'transparent';
  15993. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15994. }
  15995. /**
  15996. * open new tab
  15997. * @param link url
  15998. * @param target blank or self
  15999. */
  16000. function windowOpen(link, target) {
  16001. /* global window */
  16002. if (target === '_blank' || target === 'blank') {
  16003. var blank = window.open();
  16004. blank.opener = null;
  16005. blank.location.href = link;
  16006. } else {
  16007. window.open(link, target);
  16008. }
  16009. }
  16010. var each$1 = each;
  16011. /**
  16012. * @public
  16013. */
  16014. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16015. /**
  16016. * @public
  16017. */
  16018. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16019. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16020. var x = 0;
  16021. var y = 0;
  16022. if (maxWidth == null) {
  16023. maxWidth = Infinity;
  16024. }
  16025. if (maxHeight == null) {
  16026. maxHeight = Infinity;
  16027. }
  16028. var currentLineMaxSize = 0;
  16029. group.eachChild(function (child, idx) {
  16030. var rect = child.getBoundingRect();
  16031. var nextChild = group.childAt(idx + 1);
  16032. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16033. var nextX;
  16034. var nextY;
  16035. if (orient === 'horizontal') {
  16036. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16037. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16038. // FIXME compare before adding gap?
  16039. if (nextX > maxWidth || child.newline) {
  16040. x = 0;
  16041. nextX = moveX;
  16042. y += currentLineMaxSize + gap;
  16043. currentLineMaxSize = rect.height;
  16044. } else {
  16045. // FIXME: consider rect.y is not `0`?
  16046. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16047. }
  16048. } else {
  16049. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16050. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16051. if (nextY > maxHeight || child.newline) {
  16052. x += currentLineMaxSize + gap;
  16053. y = 0;
  16054. nextY = moveY;
  16055. currentLineMaxSize = rect.width;
  16056. } else {
  16057. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16058. }
  16059. }
  16060. if (child.newline) {
  16061. return;
  16062. }
  16063. child.x = x;
  16064. child.y = y;
  16065. child.markRedraw();
  16066. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16067. });
  16068. }
  16069. /**
  16070. * VBox or HBox layouting
  16071. * @param {string} orient
  16072. * @param {module:zrender/graphic/Group} group
  16073. * @param {number} gap
  16074. * @param {number} [width=Infinity]
  16075. * @param {number} [height=Infinity]
  16076. */
  16077. var box = boxLayout;
  16078. /**
  16079. * VBox layouting
  16080. * @param {module:zrender/graphic/Group} group
  16081. * @param {number} gap
  16082. * @param {number} [width=Infinity]
  16083. * @param {number} [height=Infinity]
  16084. */
  16085. var vbox = curry(boxLayout, 'vertical');
  16086. /**
  16087. * HBox layouting
  16088. * @param {module:zrender/graphic/Group} group
  16089. * @param {number} gap
  16090. * @param {number} [width=Infinity]
  16091. * @param {number} [height=Infinity]
  16092. */
  16093. var hbox = curry(boxLayout, 'horizontal');
  16094. /**
  16095. * Parse position info.
  16096. */
  16097. function getLayoutRect(positionInfo, containerRect, margin) {
  16098. margin = normalizeCssArray$1(margin || 0);
  16099. var containerWidth = containerRect.width;
  16100. var containerHeight = containerRect.height;
  16101. var left = parsePercent$1(positionInfo.left, containerWidth);
  16102. var top = parsePercent$1(positionInfo.top, containerHeight);
  16103. var right = parsePercent$1(positionInfo.right, containerWidth);
  16104. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16105. var width = parsePercent$1(positionInfo.width, containerWidth);
  16106. var height = parsePercent$1(positionInfo.height, containerHeight);
  16107. var verticalMargin = margin[2] + margin[0];
  16108. var horizontalMargin = margin[1] + margin[3];
  16109. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16110. if (isNaN(width)) {
  16111. width = containerWidth - right - horizontalMargin - left;
  16112. }
  16113. if (isNaN(height)) {
  16114. height = containerHeight - bottom - verticalMargin - top;
  16115. }
  16116. if (aspect != null) {
  16117. // If width and height are not given
  16118. // 1. Graph should not exceeds the container
  16119. // 2. Aspect must be keeped
  16120. // 3. Graph should take the space as more as possible
  16121. // FIXME
  16122. // Margin is not considered, because there is no case that both
  16123. // using margin and aspect so far.
  16124. if (isNaN(width) && isNaN(height)) {
  16125. if (aspect > containerWidth / containerHeight) {
  16126. width = containerWidth * 0.8;
  16127. } else {
  16128. height = containerHeight * 0.8;
  16129. }
  16130. } // Calculate width or height with given aspect
  16131. if (isNaN(width)) {
  16132. width = aspect * height;
  16133. }
  16134. if (isNaN(height)) {
  16135. height = width / aspect;
  16136. }
  16137. } // If left is not specified, calculate left from right and width
  16138. if (isNaN(left)) {
  16139. left = containerWidth - right - width - horizontalMargin;
  16140. }
  16141. if (isNaN(top)) {
  16142. top = containerHeight - bottom - height - verticalMargin;
  16143. } // Align left and top
  16144. switch (positionInfo.left || positionInfo.right) {
  16145. case 'center':
  16146. left = containerWidth / 2 - width / 2 - margin[3];
  16147. break;
  16148. case 'right':
  16149. left = containerWidth - width - horizontalMargin;
  16150. break;
  16151. }
  16152. switch (positionInfo.top || positionInfo.bottom) {
  16153. case 'middle':
  16154. case 'center':
  16155. top = containerHeight / 2 - height / 2 - margin[0];
  16156. break;
  16157. case 'bottom':
  16158. top = containerHeight - height - verticalMargin;
  16159. break;
  16160. } // If something is wrong and left, top, width, height are calculated as NaN
  16161. left = left || 0;
  16162. top = top || 0;
  16163. if (isNaN(width)) {
  16164. // Width may be NaN if only one value is given except width
  16165. width = containerWidth - horizontalMargin - left - (right || 0);
  16166. }
  16167. if (isNaN(height)) {
  16168. // Height may be NaN if only one value is given except height
  16169. height = containerHeight - verticalMargin - top - (bottom || 0);
  16170. }
  16171. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16172. rect.margin = margin;
  16173. return rect;
  16174. }
  16175. /**
  16176. * Position a zr element in viewport
  16177. * Group position is specified by either
  16178. * {left, top}, {right, bottom}
  16179. * If all properties exists, right and bottom will be igonred.
  16180. *
  16181. * Logic:
  16182. * 1. Scale (against origin point in parent coord)
  16183. * 2. Rotate (against origin point in parent coord)
  16184. * 3. Traslate (with el.position by this method)
  16185. * So this method only fixes the last step 'Traslate', which does not affect
  16186. * scaling and rotating.
  16187. *
  16188. * If be called repeatly with the same input el, the same result will be gotten.
  16189. *
  16190. * Return true if the layout happend.
  16191. *
  16192. * @param el Should have `getBoundingRect` method.
  16193. * @param positionInfo
  16194. * @param positionInfo.left
  16195. * @param positionInfo.top
  16196. * @param positionInfo.right
  16197. * @param positionInfo.bottom
  16198. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16199. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16200. * @param containerRect
  16201. * @param margin
  16202. * @param opt
  16203. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16204. * @param opt.boundingMode
  16205. * Specify how to calculate boundingRect when locating.
  16206. * 'all': Position the boundingRect that is transformed and uioned
  16207. * both itself and its descendants.
  16208. * This mode simplies confine the elements in the bounding
  16209. * of their container (e.g., using 'right: 0').
  16210. * 'raw': Position the boundingRect that is not transformed and only itself.
  16211. * This mode is useful when you want a element can overflow its
  16212. * container. (Consider a rotated circle needs to be located in a corner.)
  16213. * In this mode positionInfo.width/height can only be number.
  16214. */
  16215. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16216. var h = !opt || !opt.hv || opt.hv[0];
  16217. var v = !opt || !opt.hv || opt.hv[1];
  16218. var boundingMode = opt && opt.boundingMode || 'all';
  16219. out = out || el;
  16220. out.x = el.x;
  16221. out.y = el.y;
  16222. if (!h && !v) {
  16223. return false;
  16224. }
  16225. var rect;
  16226. if (boundingMode === 'raw') {
  16227. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16228. } else {
  16229. rect = el.getBoundingRect();
  16230. if (el.needLocalTransform()) {
  16231. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16232. // which should not be modified.
  16233. rect = rect.clone();
  16234. rect.applyTransform(transform);
  16235. }
  16236. } // The real width and height can not be specified but calculated by the given el.
  16237. var layoutRect = getLayoutRect(defaults({
  16238. width: rect.width,
  16239. height: rect.height
  16240. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16241. // (see zrender/core/Transformable#getLocalTransform),
  16242. // we can just only modify el.position to get final result.
  16243. var dx = h ? layoutRect.x - rect.x : 0;
  16244. var dy = v ? layoutRect.y - rect.y : 0;
  16245. if (boundingMode === 'raw') {
  16246. out.x = dx;
  16247. out.y = dy;
  16248. } else {
  16249. out.x += dx;
  16250. out.y += dy;
  16251. }
  16252. if (out === el) {
  16253. el.markRedraw();
  16254. }
  16255. return true;
  16256. }
  16257. function fetchLayoutMode(ins) {
  16258. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16259. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16260. type: layoutMode
  16261. } : null;
  16262. }
  16263. /**
  16264. * Consider Case:
  16265. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16266. * through setOption or media query, using normal zrUtil.merge will cause
  16267. * {right: 0} does not take effect.
  16268. *
  16269. * @example
  16270. * ComponentModel.extend({
  16271. * init: function () {
  16272. * ...
  16273. * let inputPositionParams = layout.getLayoutParams(option);
  16274. * this.mergeOption(inputPositionParams);
  16275. * },
  16276. * mergeOption: function (newOption) {
  16277. * newOption && zrUtil.merge(thisOption, newOption, true);
  16278. * layout.mergeLayoutParam(thisOption, newOption);
  16279. * }
  16280. * });
  16281. *
  16282. * @param targetOption
  16283. * @param newOption
  16284. * @param opt
  16285. */
  16286. function mergeLayoutParam(targetOption, newOption, opt) {
  16287. var ignoreSize = opt && opt.ignoreSize;
  16288. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16289. var hResult = merge(HV_NAMES[0], 0);
  16290. var vResult = merge(HV_NAMES[1], 1);
  16291. copy(HV_NAMES[0], targetOption, hResult);
  16292. copy(HV_NAMES[1], targetOption, vResult);
  16293. function merge(names, hvIdx) {
  16294. var newParams = {};
  16295. var newValueCount = 0;
  16296. var merged = {};
  16297. var mergedValueCount = 0;
  16298. var enoughParamNumber = 2;
  16299. each$1(names, function (name) {
  16300. merged[name] = targetOption[name];
  16301. });
  16302. each$1(names, function (name) {
  16303. // Consider case: newOption.width is null, which is
  16304. // set by user for removing width setting.
  16305. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16306. hasValue(newParams, name) && newValueCount++;
  16307. hasValue(merged, name) && mergedValueCount++;
  16308. });
  16309. if (ignoreSize[hvIdx]) {
  16310. // Only one of left/right is premitted to exist.
  16311. if (hasValue(newOption, names[1])) {
  16312. merged[names[2]] = null;
  16313. } else if (hasValue(newOption, names[2])) {
  16314. merged[names[1]] = null;
  16315. }
  16316. return merged;
  16317. } // Case: newOption: {width: ..., right: ...},
  16318. // or targetOption: {right: ...} and newOption: {width: ...},
  16319. // There is no conflict when merged only has params count
  16320. // little than enoughParamNumber.
  16321. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16322. return merged;
  16323. } // Case: newOption: {width: ..., right: ...},
  16324. // Than we can make sure user only want those two, and ignore
  16325. // all origin params in targetOption.
  16326. else if (newValueCount >= enoughParamNumber) {
  16327. return newParams;
  16328. } else {
  16329. // Chose another param from targetOption by priority.
  16330. for (var i = 0; i < names.length; i++) {
  16331. var name_1 = names[i];
  16332. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16333. newParams[name_1] = targetOption[name_1];
  16334. break;
  16335. }
  16336. }
  16337. return newParams;
  16338. }
  16339. }
  16340. function hasProp(obj, name) {
  16341. return obj.hasOwnProperty(name);
  16342. }
  16343. function hasValue(obj, name) {
  16344. return obj[name] != null && obj[name] !== 'auto';
  16345. }
  16346. function copy(names, target, source) {
  16347. each$1(names, function (name) {
  16348. target[name] = source[name];
  16349. });
  16350. }
  16351. }
  16352. /**
  16353. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16354. */
  16355. function getLayoutParams(source) {
  16356. return copyLayoutParams({}, source);
  16357. }
  16358. /**
  16359. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16360. * @param {Object} source
  16361. * @return {Object} Result contains those props.
  16362. */
  16363. function copyLayoutParams(target, source) {
  16364. source && target && each$1(LOCATION_PARAMS, function (name) {
  16365. source.hasOwnProperty(name) && (target[name] = source[name]);
  16366. });
  16367. return target;
  16368. }
  16369. var inner = makeInner();
  16370. var ComponentModel =
  16371. /** @class */
  16372. function (_super) {
  16373. __extends(ComponentModel, _super);
  16374. function ComponentModel(option, parentModel, ecModel) {
  16375. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16376. _this.uid = getUID('ec_cpt_model');
  16377. return _this;
  16378. }
  16379. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16380. this.mergeDefaultAndTheme(option, ecModel);
  16381. };
  16382. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16383. var layoutMode = fetchLayoutMode(this);
  16384. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16385. var themeModel = ecModel.getTheme();
  16386. merge(option, themeModel.get(this.mainType));
  16387. merge(option, this.getDefaultOption());
  16388. if (layoutMode) {
  16389. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16390. }
  16391. };
  16392. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16393. merge(this.option, option, true);
  16394. var layoutMode = fetchLayoutMode(this);
  16395. if (layoutMode) {
  16396. mergeLayoutParam(this.option, option, layoutMode);
  16397. }
  16398. };
  16399. /**
  16400. * Called immediately after `init` or `mergeOption` of this instance called.
  16401. */
  16402. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16403. /**
  16404. * [How to declare defaultOption]:
  16405. *
  16406. * (A) If using class declaration in typescript (since echarts 5):
  16407. * ```ts
  16408. * import {ComponentOption} from '../model/option.js';
  16409. * export interface XxxOption extends ComponentOption {
  16410. * aaa: number
  16411. * }
  16412. * export class XxxModel extends Component {
  16413. * static type = 'xxx';
  16414. * static defaultOption: XxxOption = {
  16415. * aaa: 123
  16416. * }
  16417. * }
  16418. * Component.registerClass(XxxModel);
  16419. * ```
  16420. * ```ts
  16421. * import {inheritDefaultOption} from '../util/component.js';
  16422. * import {XxxModel, XxxOption} from './XxxModel.js';
  16423. * export interface XxxSubOption extends XxxOption {
  16424. * bbb: number
  16425. * }
  16426. * class XxxSubModel extends XxxModel {
  16427. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16428. * bbb: 456
  16429. * })
  16430. * fn() {
  16431. * let opt = this.getDefaultOption();
  16432. * // opt is {aaa: 123, bbb: 456}
  16433. * }
  16434. * }
  16435. * ```
  16436. *
  16437. * (B) If using class extend (previous approach in echarts 3 & 4):
  16438. * ```js
  16439. * let XxxComponent = Component.extend({
  16440. * defaultOption: {
  16441. * xx: 123
  16442. * }
  16443. * })
  16444. * ```
  16445. * ```js
  16446. * let XxxSubComponent = XxxComponent.extend({
  16447. * defaultOption: {
  16448. * yy: 456
  16449. * },
  16450. * fn: function () {
  16451. * let opt = this.getDefaultOption();
  16452. * // opt is {xx: 123, yy: 456}
  16453. * }
  16454. * })
  16455. * ```
  16456. */
  16457. ComponentModel.prototype.getDefaultOption = function () {
  16458. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16459. // in legacy env and auto merge defaultOption. So if using class
  16460. // declaration, defaultOption should be merged manually.
  16461. if (!isExtendedClass(ctor)) {
  16462. // When using ts class, defaultOption must be declared as static.
  16463. return ctor.defaultOption;
  16464. } // FIXME: remove this approach?
  16465. var fields = inner(this);
  16466. if (!fields.defaultOption) {
  16467. var optList = [];
  16468. var clz = ctor;
  16469. while (clz) {
  16470. var opt = clz.prototype.defaultOption;
  16471. opt && optList.push(opt);
  16472. clz = clz.superClass;
  16473. }
  16474. var defaultOption = {};
  16475. for (var i = optList.length - 1; i >= 0; i--) {
  16476. defaultOption = merge(defaultOption, optList[i], true);
  16477. }
  16478. fields.defaultOption = defaultOption;
  16479. }
  16480. return fields.defaultOption;
  16481. };
  16482. /**
  16483. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16484. * The same behavior as `modelUtil.parseFinder`.
  16485. *
  16486. * @param useDefault In many cases like series refer axis and axis refer grid,
  16487. * If axis index / axis id not specified, use the first target as default.
  16488. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16489. */
  16490. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16491. var indexKey = mainType + 'Index';
  16492. var idKey = mainType + 'Id';
  16493. return queryReferringComponents(this.ecModel, mainType, {
  16494. index: this.get(indexKey, true),
  16495. id: this.get(idKey, true)
  16496. }, opt);
  16497. };
  16498. ComponentModel.prototype.getBoxLayoutParams = function () {
  16499. // Consider itself having box layout configs.
  16500. var boxLayoutModel = this;
  16501. return {
  16502. left: boxLayoutModel.get('left'),
  16503. top: boxLayoutModel.get('top'),
  16504. right: boxLayoutModel.get('right'),
  16505. bottom: boxLayoutModel.get('bottom'),
  16506. width: boxLayoutModel.get('width'),
  16507. height: boxLayoutModel.get('height')
  16508. };
  16509. };
  16510. /**
  16511. * Get key for zlevel.
  16512. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16513. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16514. */
  16515. ComponentModel.prototype.getZLevelKey = function () {
  16516. return '';
  16517. };
  16518. ComponentModel.prototype.setZLevel = function (zlevel) {
  16519. this.option.zlevel = zlevel;
  16520. };
  16521. ComponentModel.protoInitialize = function () {
  16522. var proto = ComponentModel.prototype;
  16523. proto.type = 'component';
  16524. proto.id = '';
  16525. proto.name = '';
  16526. proto.mainType = '';
  16527. proto.subType = '';
  16528. proto.componentIndex = 0;
  16529. }();
  16530. return ComponentModel;
  16531. }(Model);
  16532. mountExtend(ComponentModel, Model);
  16533. enableClassManagement(ComponentModel);
  16534. enableSubTypeDefaulter(ComponentModel);
  16535. enableTopologicalTravel(ComponentModel, getDependencies);
  16536. function getDependencies(componentType) {
  16537. var deps = [];
  16538. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16539. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16540. }); // Ensure main type.
  16541. deps = map(deps, function (type) {
  16542. return parseClassType(type).main;
  16543. }); // Hack dataset for convenience.
  16544. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16545. deps.unshift('dataset');
  16546. }
  16547. return deps;
  16548. }
  16549. /*
  16550. * Licensed to the Apache Software Foundation (ASF) under one
  16551. * or more contributor license agreements. See the NOTICE file
  16552. * distributed with this work for additional information
  16553. * regarding copyright ownership. The ASF licenses this file
  16554. * to you under the Apache License, Version 2.0 (the
  16555. * "License"); you may not use this file except in compliance
  16556. * with the License. You may obtain a copy of the License at
  16557. *
  16558. * http://www.apache.org/licenses/LICENSE-2.0
  16559. *
  16560. * Unless required by applicable law or agreed to in writing,
  16561. * software distributed under the License is distributed on an
  16562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16563. * KIND, either express or implied. See the License for the
  16564. * specific language governing permissions and limitations
  16565. * under the License.
  16566. */
  16567. /**
  16568. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16569. */
  16570. /*
  16571. * Licensed to the Apache Software Foundation (ASF) under one
  16572. * or more contributor license agreements. See the NOTICE file
  16573. * distributed with this work for additional information
  16574. * regarding copyright ownership. The ASF licenses this file
  16575. * to you under the Apache License, Version 2.0 (the
  16576. * "License"); you may not use this file except in compliance
  16577. * with the License. You may obtain a copy of the License at
  16578. *
  16579. * http://www.apache.org/licenses/LICENSE-2.0
  16580. *
  16581. * Unless required by applicable law or agreed to in writing,
  16582. * software distributed under the License is distributed on an
  16583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16584. * KIND, either express or implied. See the License for the
  16585. * specific language governing permissions and limitations
  16586. * under the License.
  16587. */
  16588. var platform = ''; // Navigator not exists in node
  16589. if (typeof navigator !== 'undefined') {
  16590. /* global navigator */
  16591. platform = navigator.platform || '';
  16592. }
  16593. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16594. var globalDefault = {
  16595. darkMode: 'auto',
  16596. // backgroundColor: 'rgba(0,0,0,0)',
  16597. colorBy: 'series',
  16598. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16599. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16600. aria: {
  16601. decal: {
  16602. decals: [{
  16603. color: decalColor,
  16604. dashArrayX: [1, 0],
  16605. dashArrayY: [2, 5],
  16606. symbolSize: 1,
  16607. rotation: Math.PI / 6
  16608. }, {
  16609. color: decalColor,
  16610. symbol: 'circle',
  16611. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16612. dashArrayY: [6, 0],
  16613. symbolSize: 0.8
  16614. }, {
  16615. color: decalColor,
  16616. dashArrayX: [1, 0],
  16617. dashArrayY: [4, 3],
  16618. rotation: -Math.PI / 4
  16619. }, {
  16620. color: decalColor,
  16621. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16622. dashArrayY: [6, 0]
  16623. }, {
  16624. color: decalColor,
  16625. dashArrayX: [[1, 0], [1, 6]],
  16626. dashArrayY: [1, 0, 6, 0],
  16627. rotation: Math.PI / 4
  16628. }, {
  16629. color: decalColor,
  16630. symbol: 'triangle',
  16631. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16632. dashArrayY: [7, 2],
  16633. symbolSize: 0.75
  16634. }]
  16635. }
  16636. },
  16637. // If xAxis and yAxis declared, grid is created by default.
  16638. // grid: {},
  16639. textStyle: {
  16640. // color: '#000',
  16641. // decoration: 'none',
  16642. // PENDING
  16643. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16644. // fontFamily: 'Arial, Verdana, sans-serif',
  16645. fontSize: 12,
  16646. fontStyle: 'normal',
  16647. fontWeight: 'normal'
  16648. },
  16649. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16650. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16651. // Default is source-over
  16652. blendMode: null,
  16653. stateAnimation: {
  16654. duration: 300,
  16655. easing: 'cubicOut'
  16656. },
  16657. animation: 'auto',
  16658. animationDuration: 1000,
  16659. animationDurationUpdate: 500,
  16660. animationEasing: 'cubicInOut',
  16661. animationEasingUpdate: 'cubicInOut',
  16662. animationThreshold: 2000,
  16663. // Configuration for progressive/incremental rendering
  16664. progressiveThreshold: 3000,
  16665. progressive: 400,
  16666. // Threshold of if use single hover layer to optimize.
  16667. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16668. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16669. // which is unexpected.
  16670. // see example <echarts/test/heatmap-large.html>.
  16671. hoverLayerThreshold: 3000,
  16672. // See: module:echarts/scale/Time
  16673. useUTC: false
  16674. };
  16675. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16676. var SOURCE_FORMAT_ORIGINAL = 'original';
  16677. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16678. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16679. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16680. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16681. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16682. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16683. var SERIES_LAYOUT_BY_ROW = 'row';
  16684. var BE_ORDINAL = {
  16685. Must: 1,
  16686. Might: 2,
  16687. Not: 3 // Other cases
  16688. };
  16689. var innerGlobalModel = makeInner();
  16690. /**
  16691. * MUST be called before mergeOption of all series.
  16692. */
  16693. function resetSourceDefaulter(ecModel) {
  16694. // `datasetMap` is used to make default encode.
  16695. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16696. }
  16697. /**
  16698. * [The strategy of the arrengment of data dimensions for dataset]:
  16699. * "value way": all axes are non-category axes. So series one by one take
  16700. * several (the number is coordSysDims.length) dimensions from dataset.
  16701. * The result of data arrengment of data dimensions like:
  16702. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16703. * "category way": at least one axis is category axis. So the the first data
  16704. * dimension is always mapped to the first category axis and shared by
  16705. * all of the series. The other data dimensions are taken by series like
  16706. * "value way" does.
  16707. * The result of data arrengment of data dimensions like:
  16708. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16709. *
  16710. * @return encode Never be `null/undefined`.
  16711. */
  16712. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16713. var encode = {};
  16714. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16715. if (!datasetModel || !coordDimensions) {
  16716. return encode;
  16717. }
  16718. var encodeItemName = [];
  16719. var encodeSeriesName = [];
  16720. var ecModel = seriesModel.ecModel;
  16721. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16722. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16723. var baseCategoryDimIndex;
  16724. var categoryWayValueDimStart;
  16725. coordDimensions = coordDimensions.slice();
  16726. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16727. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16728. name: coordDimInfoLoose
  16729. };
  16730. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16731. baseCategoryDimIndex = coordDimIdx;
  16732. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16733. }
  16734. encode[coordDimInfo.name] = [];
  16735. });
  16736. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16737. categoryWayDim: categoryWayValueDimStart,
  16738. valueWayDim: 0
  16739. }); // TODO
  16740. // Auto detect first time axis and do arrangement.
  16741. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16742. var coordDimName = coordDimInfo.name;
  16743. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16744. if (baseCategoryDimIndex == null) {
  16745. var start = datasetRecord.valueWayDim;
  16746. pushDim(encode[coordDimName], start, count);
  16747. pushDim(encodeSeriesName, start, count);
  16748. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16749. // especially when encode x y specified.
  16750. // consider: when mutiple series share one dimension
  16751. // category axis, series name should better use
  16752. // the other dimsion name. On the other hand, use
  16753. // both dimensions name.
  16754. } // In category way, the first category axis.
  16755. else if (baseCategoryDimIndex === coordDimIdx) {
  16756. pushDim(encode[coordDimName], 0, count);
  16757. pushDim(encodeItemName, 0, count);
  16758. } // In category way, the other axis.
  16759. else {
  16760. var start = datasetRecord.categoryWayDim;
  16761. pushDim(encode[coordDimName], start, count);
  16762. pushDim(encodeSeriesName, start, count);
  16763. datasetRecord.categoryWayDim += count;
  16764. }
  16765. });
  16766. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16767. for (var i = 0; i < idxCount; i++) {
  16768. dimIdxArr.push(idxFrom + i);
  16769. }
  16770. }
  16771. function getDataDimCountOnCoordDim(coordDimInfo) {
  16772. var dimsDef = coordDimInfo.dimsDef;
  16773. return dimsDef ? dimsDef.length : 1;
  16774. }
  16775. encodeItemName.length && (encode.itemName = encodeItemName);
  16776. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16777. return encode;
  16778. }
  16779. /**
  16780. * Work for data like [{name: ..., value: ...}, ...].
  16781. *
  16782. * @return encode Never be `null/undefined`.
  16783. */
  16784. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16785. var encode = {};
  16786. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16787. if (!datasetModel) {
  16788. return encode;
  16789. }
  16790. var sourceFormat = source.sourceFormat;
  16791. var dimensionsDefine = source.dimensionsDefine;
  16792. var potentialNameDimIndex;
  16793. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16794. each(dimensionsDefine, function (dim, idx) {
  16795. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16796. potentialNameDimIndex = idx;
  16797. }
  16798. });
  16799. }
  16800. var idxResult = function () {
  16801. var idxRes0 = {};
  16802. var idxRes1 = {};
  16803. var guessRecords = []; // 5 is an experience value.
  16804. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16805. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16806. guessRecords.push(guessResult);
  16807. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16808. // and then find a name dim with the priority:
  16809. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16810. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16811. idxRes0.v = i;
  16812. }
  16813. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16814. idxRes0.n = i;
  16815. }
  16816. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16817. return idxRes0;
  16818. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16819. // find the first BE_ORDINAL.Might as the value dim,
  16820. // and then find a name dim with the priority:
  16821. // "other dim" > "the value dim itself".
  16822. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16823. // treated as number.
  16824. if (!isPureNumber) {
  16825. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16826. idxRes1.v = i;
  16827. }
  16828. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16829. idxRes1.n = i;
  16830. }
  16831. }
  16832. }
  16833. function fulfilled(idxResult) {
  16834. return idxResult.v != null && idxResult.n != null;
  16835. }
  16836. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16837. }();
  16838. if (idxResult) {
  16839. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16840. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16841. // So we dont set encodeLabel here.
  16842. encode.itemName = [nameDimIndex];
  16843. encode.seriesName = [nameDimIndex];
  16844. }
  16845. return encode;
  16846. }
  16847. /**
  16848. * @return If return null/undefined, indicate that should not use datasetModel.
  16849. */
  16850. function querySeriesUpstreamDatasetModel(seriesModel) {
  16851. // Caution: consider the scenario:
  16852. // A dataset is declared and a series is not expected to use the dataset,
  16853. // and at the beginning `setOption({series: { noData })` (just prepare other
  16854. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16855. // the user should set an empty array to avoid that dataset is used by default.
  16856. var thisData = seriesModel.get('data', true);
  16857. if (!thisData) {
  16858. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16859. index: seriesModel.get('datasetIndex', true),
  16860. id: seriesModel.get('datasetId', true)
  16861. }, SINGLE_REFERRING).models[0];
  16862. }
  16863. }
  16864. /**
  16865. * @return Always return an array event empty.
  16866. */
  16867. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16868. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16869. // Otherwise, no reference.
  16870. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16871. return [];
  16872. }
  16873. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16874. index: datasetModel.get('fromDatasetIndex', true),
  16875. id: datasetModel.get('fromDatasetId', true)
  16876. }, SINGLE_REFERRING).models;
  16877. }
  16878. /**
  16879. * The rule should not be complex, otherwise user might not
  16880. * be able to known where the data is wrong.
  16881. * The code is ugly, but how to make it neat?
  16882. */
  16883. function guessOrdinal(source, dimIndex) {
  16884. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16885. } // dimIndex may be overflow source data.
  16886. // return {BE_ORDINAL}
  16887. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16888. var result; // Experience value.
  16889. var maxLoop = 5;
  16890. if (isTypedArray(data)) {
  16891. return BE_ORDINAL.Not;
  16892. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16893. // always exists in source.
  16894. var dimName;
  16895. var dimType;
  16896. if (dimensionsDefine) {
  16897. var dimDefItem = dimensionsDefine[dimIndex];
  16898. if (isObject(dimDefItem)) {
  16899. dimName = dimDefItem.name;
  16900. dimType = dimDefItem.type;
  16901. } else if (isString(dimDefItem)) {
  16902. dimName = dimDefItem;
  16903. }
  16904. }
  16905. if (dimType != null) {
  16906. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16907. }
  16908. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16909. var dataArrayRows = data;
  16910. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16911. var sample = dataArrayRows[dimIndex];
  16912. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16913. if ((result = detectValue(sample[startIndex + i])) != null) {
  16914. return result;
  16915. }
  16916. }
  16917. } else {
  16918. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16919. var row = dataArrayRows[startIndex + i];
  16920. if (row && (result = detectValue(row[dimIndex])) != null) {
  16921. return result;
  16922. }
  16923. }
  16924. }
  16925. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16926. var dataObjectRows = data;
  16927. if (!dimName) {
  16928. return BE_ORDINAL.Not;
  16929. }
  16930. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16931. var item = dataObjectRows[i];
  16932. if (item && (result = detectValue(item[dimName])) != null) {
  16933. return result;
  16934. }
  16935. }
  16936. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16937. var dataKeyedColumns = data;
  16938. if (!dimName) {
  16939. return BE_ORDINAL.Not;
  16940. }
  16941. var sample = dataKeyedColumns[dimName];
  16942. if (!sample || isTypedArray(sample)) {
  16943. return BE_ORDINAL.Not;
  16944. }
  16945. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16946. if ((result = detectValue(sample[i])) != null) {
  16947. return result;
  16948. }
  16949. }
  16950. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16951. var dataOriginal = data;
  16952. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16953. var item = dataOriginal[i];
  16954. var val = getDataItemValue(item);
  16955. if (!isArray(val)) {
  16956. return BE_ORDINAL.Not;
  16957. }
  16958. if ((result = detectValue(val[dimIndex])) != null) {
  16959. return result;
  16960. }
  16961. }
  16962. }
  16963. function detectValue(val) {
  16964. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  16965. // `isFinit('')` get `true`.
  16966. if (val != null && isFinite(val) && val !== '') {
  16967. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16968. } else if (beStr && val !== '-') {
  16969. return BE_ORDINAL.Must;
  16970. }
  16971. }
  16972. return BE_ORDINAL.Not;
  16973. }
  16974. var internalOptionCreatorMap = createHashMap();
  16975. function registerInternalOptionCreator(mainType, creator) {
  16976. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  16977. internalOptionCreatorMap.set(mainType, creator);
  16978. }
  16979. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16980. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16981. if (!internalOptionCreator) {
  16982. return newCmptOptionList;
  16983. }
  16984. var internalOptions = internalOptionCreator(ecModel);
  16985. if (!internalOptions) {
  16986. return newCmptOptionList;
  16987. }
  16988. if ("development" !== 'production') {
  16989. for (var i = 0; i < internalOptions.length; i++) {
  16990. assert(isComponentIdInternal(internalOptions[i]));
  16991. }
  16992. }
  16993. return newCmptOptionList.concat(internalOptions);
  16994. }
  16995. var innerColor = makeInner();
  16996. var innerDecal = makeInner();
  16997. var PaletteMixin =
  16998. /** @class */
  16999. function () {
  17000. function PaletteMixin() {}
  17001. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17002. var defaultPalette = normalizeToArray(this.get('color', true));
  17003. var layeredPalette = this.get('colorLayer', true);
  17004. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17005. };
  17006. PaletteMixin.prototype.clearColorPalette = function () {
  17007. clearPalette(this, innerColor);
  17008. };
  17009. return PaletteMixin;
  17010. }();
  17011. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17012. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17013. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17014. }
  17015. function getNearestPalette(palettes, requestColorNum) {
  17016. var paletteNum = palettes.length; // TODO palettes must be in order
  17017. for (var i = 0; i < paletteNum; i++) {
  17018. if (palettes[i].length > requestColorNum) {
  17019. return palettes[i];
  17020. }
  17021. }
  17022. return palettes[paletteNum - 1];
  17023. }
  17024. /**
  17025. * @param name MUST NOT be null/undefined. Otherwise call this function
  17026. * twise with the same parameters will get different result.
  17027. * @param scope default this.
  17028. * @return Can be null/undefined
  17029. */
  17030. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17031. scope = scope || that;
  17032. var scopeFields = inner(scope);
  17033. var paletteIdx = scopeFields.paletteIdx || 0;
  17034. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17035. if (paletteNameMap.hasOwnProperty(name)) {
  17036. return paletteNameMap[name];
  17037. }
  17038. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17039. palette = palette || defaultPalette;
  17040. if (!palette || !palette.length) {
  17041. return;
  17042. }
  17043. var pickedPaletteItem = palette[paletteIdx];
  17044. if (name) {
  17045. paletteNameMap[name] = pickedPaletteItem;
  17046. }
  17047. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17048. return pickedPaletteItem;
  17049. }
  17050. function clearPalette(that, inner) {
  17051. inner(that).paletteIdx = 0;
  17052. inner(that).paletteNameMap = {};
  17053. }
  17054. // Internal method names:
  17055. // -----------------------
  17056. var reCreateSeriesIndices;
  17057. var assertSeriesInitialized;
  17058. var initBase;
  17059. var OPTION_INNER_KEY = '\0_ec_inner';
  17060. var OPTION_INNER_VALUE = 1;
  17061. var BUITIN_COMPONENTS_MAP = {
  17062. grid: 'GridComponent',
  17063. polar: 'PolarComponent',
  17064. geo: 'GeoComponent',
  17065. singleAxis: 'SingleAxisComponent',
  17066. parallel: 'ParallelComponent',
  17067. calendar: 'CalendarComponent',
  17068. graphic: 'GraphicComponent',
  17069. toolbox: 'ToolboxComponent',
  17070. tooltip: 'TooltipComponent',
  17071. axisPointer: 'AxisPointerComponent',
  17072. brush: 'BrushComponent',
  17073. title: 'TitleComponent',
  17074. timeline: 'TimelineComponent',
  17075. markPoint: 'MarkPointComponent',
  17076. markLine: 'MarkLineComponent',
  17077. markArea: 'MarkAreaComponent',
  17078. legend: 'LegendComponent',
  17079. dataZoom: 'DataZoomComponent',
  17080. visualMap: 'VisualMapComponent',
  17081. // aria: 'AriaComponent',
  17082. // dataset: 'DatasetComponent',
  17083. // Dependencies
  17084. xAxis: 'GridComponent',
  17085. yAxis: 'GridComponent',
  17086. angleAxis: 'PolarComponent',
  17087. radiusAxis: 'PolarComponent'
  17088. };
  17089. var BUILTIN_CHARTS_MAP = {
  17090. line: 'LineChart',
  17091. bar: 'BarChart',
  17092. pie: 'PieChart',
  17093. scatter: 'ScatterChart',
  17094. radar: 'RadarChart',
  17095. map: 'MapChart',
  17096. tree: 'TreeChart',
  17097. treemap: 'TreemapChart',
  17098. graph: 'GraphChart',
  17099. gauge: 'GaugeChart',
  17100. funnel: 'FunnelChart',
  17101. parallel: 'ParallelChart',
  17102. sankey: 'SankeyChart',
  17103. boxplot: 'BoxplotChart',
  17104. candlestick: 'CandlestickChart',
  17105. effectScatter: 'EffectScatterChart',
  17106. lines: 'LinesChart',
  17107. heatmap: 'HeatmapChart',
  17108. pictorialBar: 'PictorialBarChart',
  17109. themeRiver: 'ThemeRiverChart',
  17110. sunburst: 'SunburstChart',
  17111. custom: 'CustomChart'
  17112. };
  17113. var componetsMissingLogPrinted = {};
  17114. function checkMissingComponents(option) {
  17115. each(option, function (componentOption, mainType) {
  17116. if (!ComponentModel.hasClass(mainType)) {
  17117. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17118. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17119. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17120. componetsMissingLogPrinted[componentImportName] = true;
  17121. }
  17122. }
  17123. });
  17124. }
  17125. var GlobalModel =
  17126. /** @class */
  17127. function (_super) {
  17128. __extends(GlobalModel, _super);
  17129. function GlobalModel() {
  17130. return _super !== null && _super.apply(this, arguments) || this;
  17131. }
  17132. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17133. theme = theme || {};
  17134. this.option = null; // Mark as not initialized.
  17135. this._theme = new Model(theme);
  17136. this._locale = new Model(locale);
  17137. this._optionManager = optionManager;
  17138. };
  17139. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17140. if ("development" !== 'production') {
  17141. assert(option != null, 'option is null/undefined');
  17142. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17143. }
  17144. var innerOpt = normalizeSetOptionInput(opts);
  17145. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17146. this._resetOption(null, innerOpt);
  17147. };
  17148. /**
  17149. * @param type null/undefined: reset all.
  17150. * 'recreate': force recreate all.
  17151. * 'timeline': only reset timeline option
  17152. * 'media': only reset media query option
  17153. * @return Whether option changed.
  17154. */
  17155. GlobalModel.prototype.resetOption = function (type, opt) {
  17156. return this._resetOption(type, normalizeSetOptionInput(opt));
  17157. };
  17158. GlobalModel.prototype._resetOption = function (type, opt) {
  17159. var optionChanged = false;
  17160. var optionManager = this._optionManager;
  17161. if (!type || type === 'recreate') {
  17162. var baseOption = optionManager.mountOption(type === 'recreate');
  17163. if ("development" !== 'production') {
  17164. checkMissingComponents(baseOption);
  17165. }
  17166. if (!this.option || type === 'recreate') {
  17167. initBase(this, baseOption);
  17168. } else {
  17169. this.restoreData();
  17170. this._mergeOption(baseOption, opt);
  17171. }
  17172. optionChanged = true;
  17173. }
  17174. if (type === 'timeline' || type === 'media') {
  17175. this.restoreData();
  17176. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17177. // it should better not have the same props with `MediaUnit['option']`.
  17178. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17179. // rather than original "baseOption". If they both override a prop, the result might be
  17180. // unexpected when media state changed after `setOption` called.
  17181. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17182. // (`{baseOption, media}`) in `setOption`.
  17183. // For `timeline`, the case is the same.
  17184. if (!type || type === 'recreate' || type === 'timeline') {
  17185. var timelineOption = optionManager.getTimelineOption(this);
  17186. if (timelineOption) {
  17187. optionChanged = true;
  17188. this._mergeOption(timelineOption, opt);
  17189. }
  17190. }
  17191. if (!type || type === 'recreate' || type === 'media') {
  17192. var mediaOptions = optionManager.getMediaOption(this);
  17193. if (mediaOptions.length) {
  17194. each(mediaOptions, function (mediaOption) {
  17195. optionChanged = true;
  17196. this._mergeOption(mediaOption, opt);
  17197. }, this);
  17198. }
  17199. }
  17200. return optionChanged;
  17201. };
  17202. GlobalModel.prototype.mergeOption = function (option) {
  17203. this._mergeOption(option, null);
  17204. };
  17205. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17206. var option = this.option;
  17207. var componentsMap = this._componentsMap;
  17208. var componentsCount = this._componentsCount;
  17209. var newCmptTypes = [];
  17210. var newCmptTypeMap = createHashMap();
  17211. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17212. resetSourceDefaulter(this); // If no component class, merge directly.
  17213. // For example: color, animaiton options, etc.
  17214. each(newOption, function (componentOption, mainType) {
  17215. if (componentOption == null) {
  17216. return;
  17217. }
  17218. if (!ComponentModel.hasClass(mainType)) {
  17219. // globalSettingTask.dirty();
  17220. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17221. } else if (mainType) {
  17222. newCmptTypes.push(mainType);
  17223. newCmptTypeMap.set(mainType, true);
  17224. }
  17225. });
  17226. if (replaceMergeMainTypeMap) {
  17227. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17228. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17229. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17230. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17231. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17232. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17233. newCmptTypes.push(mainTypeInReplaceMerge);
  17234. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17235. }
  17236. });
  17237. }
  17238. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17239. function visitComponent(mainType) {
  17240. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17241. var oldCmptList = componentsMap.get(mainType);
  17242. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17243. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17244. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17245. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17246. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17247. // components, which is probably incorrect logic.
  17248. option[mainType] = null;
  17249. componentsMap.set(mainType, null);
  17250. componentsCount.set(mainType, 0);
  17251. var optionsByMainType = [];
  17252. var cmptsByMainType = [];
  17253. var cmptsCountByMainType = 0;
  17254. var tooltipExists;
  17255. var tooltipWarningLogged;
  17256. each(mappingResult, function (resultItem, index) {
  17257. var componentModel = resultItem.existing;
  17258. var newCmptOption = resultItem.newOption;
  17259. if (!newCmptOption) {
  17260. if (componentModel) {
  17261. // Consider where is no new option and should be merged using {},
  17262. // see removeEdgeAndAdd in topologicalTravel and
  17263. // ComponentModel.getAllClassMainTypes.
  17264. componentModel.mergeOption({}, this);
  17265. componentModel.optionUpdated({}, false);
  17266. } // If no both `resultItem.exist` and `resultItem.option`,
  17267. // either it is in `replaceMerge` and not matched by any id,
  17268. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17269. } else {
  17270. var isSeriesType = mainType === 'series';
  17271. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17272. );
  17273. if (!ComponentModelClass) {
  17274. if ("development" !== 'production') {
  17275. var subType = resultItem.keyInfo.subType;
  17276. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17277. if (!componetsMissingLogPrinted[subType]) {
  17278. componetsMissingLogPrinted[subType] = true;
  17279. if (seriesImportName) {
  17280. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17281. } else {
  17282. error("Unkown series " + subType);
  17283. }
  17284. }
  17285. }
  17286. return;
  17287. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17288. if (mainType === 'tooltip') {
  17289. if (tooltipExists) {
  17290. if ("development" !== 'production') {
  17291. if (!tooltipWarningLogged) {
  17292. warn('Currently only one tooltip component is allowed.');
  17293. tooltipWarningLogged = true;
  17294. }
  17295. }
  17296. return;
  17297. }
  17298. tooltipExists = true;
  17299. }
  17300. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17301. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17302. componentModel.mergeOption(newCmptOption, this);
  17303. componentModel.optionUpdated(newCmptOption, false);
  17304. } else {
  17305. // PENDING Global as parent ?
  17306. var extraOpt = extend({
  17307. componentIndex: index
  17308. }, resultItem.keyInfo);
  17309. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17310. extend(componentModel, extraOpt);
  17311. if (resultItem.brandNew) {
  17312. componentModel.__requireNewView = true;
  17313. }
  17314. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17315. // newCmptOption has been used as componentModel.option
  17316. // and may be merged with theme and default, so pass null
  17317. // to avoid confusion.
  17318. componentModel.optionUpdated(null, true);
  17319. }
  17320. }
  17321. if (componentModel) {
  17322. optionsByMainType.push(componentModel.option);
  17323. cmptsByMainType.push(componentModel);
  17324. cmptsCountByMainType++;
  17325. } else {
  17326. // Always do assign to avoid elided item in array.
  17327. optionsByMainType.push(void 0);
  17328. cmptsByMainType.push(void 0);
  17329. }
  17330. }, this);
  17331. option[mainType] = optionsByMainType;
  17332. componentsMap.set(mainType, cmptsByMainType);
  17333. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17334. if (mainType === 'series') {
  17335. reCreateSeriesIndices(this);
  17336. }
  17337. } // If no series declared, ensure `_seriesIndices` initialized.
  17338. if (!this._seriesIndices) {
  17339. reCreateSeriesIndices(this);
  17340. }
  17341. };
  17342. /**
  17343. * Get option for output (cloned option and inner info removed)
  17344. */
  17345. GlobalModel.prototype.getOption = function () {
  17346. var option = clone(this.option);
  17347. each(option, function (optInMainType, mainType) {
  17348. if (ComponentModel.hasClass(mainType)) {
  17349. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17350. // Inner cmpts might not be at last since ec5.0, but still
  17351. // compatible for users: if inner cmpt at last, splice the returned array.
  17352. var realLen = opts.length;
  17353. var metNonInner = false;
  17354. for (var i = realLen - 1; i >= 0; i--) {
  17355. // Remove options with inner id.
  17356. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17357. metNonInner = true;
  17358. } else {
  17359. opts[i] = null;
  17360. !metNonInner && realLen--;
  17361. }
  17362. }
  17363. opts.length = realLen;
  17364. option[mainType] = opts;
  17365. }
  17366. });
  17367. delete option[OPTION_INNER_KEY];
  17368. return option;
  17369. };
  17370. GlobalModel.prototype.getTheme = function () {
  17371. return this._theme;
  17372. };
  17373. GlobalModel.prototype.getLocaleModel = function () {
  17374. return this._locale;
  17375. };
  17376. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17377. this._payload = payload;
  17378. };
  17379. GlobalModel.prototype.getUpdatePayload = function () {
  17380. return this._payload;
  17381. };
  17382. /**
  17383. * @param idx If not specified, return the first one.
  17384. */
  17385. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17386. var list = this._componentsMap.get(mainType);
  17387. if (list) {
  17388. var cmpt = list[idx || 0];
  17389. if (cmpt) {
  17390. return cmpt;
  17391. } else if (idx == null) {
  17392. for (var i = 0; i < list.length; i++) {
  17393. if (list[i]) {
  17394. return list[i];
  17395. }
  17396. }
  17397. }
  17398. }
  17399. };
  17400. /**
  17401. * @return Never be null/undefined.
  17402. */
  17403. GlobalModel.prototype.queryComponents = function (condition) {
  17404. var mainType = condition.mainType;
  17405. if (!mainType) {
  17406. return [];
  17407. }
  17408. var index = condition.index;
  17409. var id = condition.id;
  17410. var name = condition.name;
  17411. var cmpts = this._componentsMap.get(mainType);
  17412. if (!cmpts || !cmpts.length) {
  17413. return [];
  17414. }
  17415. var result;
  17416. if (index != null) {
  17417. result = [];
  17418. each(normalizeToArray(index), function (idx) {
  17419. cmpts[idx] && result.push(cmpts[idx]);
  17420. });
  17421. } else if (id != null) {
  17422. result = queryByIdOrName('id', id, cmpts);
  17423. } else if (name != null) {
  17424. result = queryByIdOrName('name', name, cmpts);
  17425. } else {
  17426. // Return all non-empty components in that mainType
  17427. result = filter(cmpts, function (cmpt) {
  17428. return !!cmpt;
  17429. });
  17430. }
  17431. return filterBySubType(result, condition);
  17432. };
  17433. /**
  17434. * The interface is different from queryComponents,
  17435. * which is convenient for inner usage.
  17436. *
  17437. * @usage
  17438. * let result = findComponents(
  17439. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17440. * );
  17441. * let result = findComponents(
  17442. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17443. * );
  17444. * let result = findComponents(
  17445. * {mainType: 'series',
  17446. * filter: function (model, index) {...}}
  17447. * );
  17448. * // result like [component0, componnet1, ...]
  17449. */
  17450. GlobalModel.prototype.findComponents = function (condition) {
  17451. var query = condition.query;
  17452. var mainType = condition.mainType;
  17453. var queryCond = getQueryCond(query);
  17454. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17455. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17456. return !!cmpt;
  17457. });
  17458. return doFilter(filterBySubType(result, condition));
  17459. function getQueryCond(q) {
  17460. var indexAttr = mainType + 'Index';
  17461. var idAttr = mainType + 'Id';
  17462. var nameAttr = mainType + 'Name';
  17463. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17464. mainType: mainType,
  17465. // subType will be filtered finally.
  17466. index: q[indexAttr],
  17467. id: q[idAttr],
  17468. name: q[nameAttr]
  17469. } : null;
  17470. }
  17471. function doFilter(res) {
  17472. return condition.filter ? filter(res, condition.filter) : res;
  17473. }
  17474. };
  17475. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17476. var componentsMap = this._componentsMap;
  17477. if (isFunction(mainType)) {
  17478. var ctxForAll_1 = cb;
  17479. var cbForAll_1 = mainType;
  17480. componentsMap.each(function (cmpts, componentType) {
  17481. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17482. var cmpt = cmpts[i];
  17483. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17484. }
  17485. });
  17486. } else {
  17487. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17488. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17489. var cmpt = cmpts[i];
  17490. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17491. }
  17492. }
  17493. };
  17494. /**
  17495. * Get series list before filtered by name.
  17496. */
  17497. GlobalModel.prototype.getSeriesByName = function (name) {
  17498. var nameStr = convertOptionIdName(name, null);
  17499. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17500. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17501. });
  17502. };
  17503. /**
  17504. * Get series list before filtered by index.
  17505. */
  17506. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17507. return this._componentsMap.get('series')[seriesIndex];
  17508. };
  17509. /**
  17510. * Get series list before filtered by type.
  17511. * FIXME: rename to getRawSeriesByType?
  17512. */
  17513. GlobalModel.prototype.getSeriesByType = function (subType) {
  17514. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17515. return !!oneSeries && oneSeries.subType === subType;
  17516. });
  17517. };
  17518. /**
  17519. * Get all series before filtered.
  17520. */
  17521. GlobalModel.prototype.getSeries = function () {
  17522. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17523. return !!oneSeries;
  17524. });
  17525. };
  17526. /**
  17527. * Count series before filtered.
  17528. */
  17529. GlobalModel.prototype.getSeriesCount = function () {
  17530. return this._componentsCount.get('series');
  17531. };
  17532. /**
  17533. * After filtering, series may be different
  17534. * frome raw series.
  17535. */
  17536. GlobalModel.prototype.eachSeries = function (cb, context) {
  17537. assertSeriesInitialized(this);
  17538. each(this._seriesIndices, function (rawSeriesIndex) {
  17539. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17540. cb.call(context, series, rawSeriesIndex);
  17541. }, this);
  17542. };
  17543. /**
  17544. * Iterate raw series before filtered.
  17545. *
  17546. * @param {Function} cb
  17547. * @param {*} context
  17548. */
  17549. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17550. each(this._componentsMap.get('series'), function (series) {
  17551. series && cb.call(context, series, series.componentIndex);
  17552. });
  17553. };
  17554. /**
  17555. * After filtering, series may be different.
  17556. * frome raw series.
  17557. */
  17558. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17559. assertSeriesInitialized(this);
  17560. each(this._seriesIndices, function (rawSeriesIndex) {
  17561. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17562. if (series.subType === subType) {
  17563. cb.call(context, series, rawSeriesIndex);
  17564. }
  17565. }, this);
  17566. };
  17567. /**
  17568. * Iterate raw series before filtered of given type.
  17569. */
  17570. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17571. return each(this.getSeriesByType(subType), cb, context);
  17572. };
  17573. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17574. assertSeriesInitialized(this);
  17575. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17576. };
  17577. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17578. return (this._seriesIndices || []).slice();
  17579. };
  17580. GlobalModel.prototype.filterSeries = function (cb, context) {
  17581. assertSeriesInitialized(this);
  17582. var newSeriesIndices = [];
  17583. each(this._seriesIndices, function (seriesRawIdx) {
  17584. var series = this._componentsMap.get('series')[seriesRawIdx];
  17585. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17586. }, this);
  17587. this._seriesIndices = newSeriesIndices;
  17588. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17589. };
  17590. GlobalModel.prototype.restoreData = function (payload) {
  17591. reCreateSeriesIndices(this);
  17592. var componentsMap = this._componentsMap;
  17593. var componentTypes = [];
  17594. componentsMap.each(function (components, componentType) {
  17595. if (ComponentModel.hasClass(componentType)) {
  17596. componentTypes.push(componentType);
  17597. }
  17598. });
  17599. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17600. each(componentsMap.get(componentType), function (component) {
  17601. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17602. component.restoreData();
  17603. }
  17604. });
  17605. });
  17606. };
  17607. GlobalModel.internalField = function () {
  17608. reCreateSeriesIndices = function (ecModel) {
  17609. var seriesIndices = ecModel._seriesIndices = [];
  17610. each(ecModel._componentsMap.get('series'), function (series) {
  17611. // series may have been removed by `replaceMerge`.
  17612. series && seriesIndices.push(series.componentIndex);
  17613. });
  17614. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17615. };
  17616. assertSeriesInitialized = function (ecModel) {
  17617. // Components that use _seriesIndices should depends on series component,
  17618. // which make sure that their initialization is after series.
  17619. if ("development" !== 'production') {
  17620. if (!ecModel._seriesIndices) {
  17621. throw new Error('Option should contains series.');
  17622. }
  17623. }
  17624. };
  17625. initBase = function (ecModel, baseOption) {
  17626. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17627. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17628. ecModel.option = {};
  17629. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17630. // before series initialized.
  17631. ecModel._componentsMap = createHashMap({
  17632. series: []
  17633. });
  17634. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17635. // performed before theme and globalDefault merge.
  17636. var airaOption = baseOption.aria;
  17637. if (isObject(airaOption) && airaOption.enabled == null) {
  17638. airaOption.enabled = true;
  17639. }
  17640. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17641. merge(baseOption, globalDefault, false);
  17642. ecModel._mergeOption(baseOption, null);
  17643. };
  17644. }();
  17645. return GlobalModel;
  17646. }(Model);
  17647. function isNotTargetSeries(seriesModel, payload) {
  17648. if (payload) {
  17649. var index = payload.seriesIndex;
  17650. var id = payload.seriesId;
  17651. var name_1 = payload.seriesName;
  17652. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17653. }
  17654. }
  17655. function mergeTheme(option, theme) {
  17656. // PENDING
  17657. // NOT use `colorLayer` in theme if option has `color`
  17658. var notMergeColorLayer = option.color && !option.colorLayer;
  17659. each(theme, function (themeItem, name) {
  17660. if (name === 'colorLayer' && notMergeColorLayer) {
  17661. return;
  17662. } // If it is component model mainType, the model handles that merge later.
  17663. // otherwise, merge them here.
  17664. if (!ComponentModel.hasClass(name)) {
  17665. if (typeof themeItem === 'object') {
  17666. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17667. } else {
  17668. if (option[name] == null) {
  17669. option[name] = themeItem;
  17670. }
  17671. }
  17672. }
  17673. });
  17674. }
  17675. function queryByIdOrName(attr, idOrName, cmpts) {
  17676. // Here is a break from echarts4: string and number are
  17677. // treated as equal.
  17678. if (isArray(idOrName)) {
  17679. var keyMap_1 = createHashMap();
  17680. each(idOrName, function (idOrNameItem) {
  17681. if (idOrNameItem != null) {
  17682. var idName = convertOptionIdName(idOrNameItem, null);
  17683. idName != null && keyMap_1.set(idOrNameItem, true);
  17684. }
  17685. });
  17686. return filter(cmpts, function (cmpt) {
  17687. return cmpt && keyMap_1.get(cmpt[attr]);
  17688. });
  17689. } else {
  17690. var idName_1 = convertOptionIdName(idOrName, null);
  17691. return filter(cmpts, function (cmpt) {
  17692. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17693. });
  17694. }
  17695. }
  17696. function filterBySubType(components, condition) {
  17697. // Using hasOwnProperty for restrict. Consider
  17698. // subType is undefined in user payload.
  17699. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17700. return cmpt && cmpt.subType === condition.subType;
  17701. }) : components;
  17702. }
  17703. function normalizeSetOptionInput(opts) {
  17704. var replaceMergeMainTypeMap = createHashMap();
  17705. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17706. if ("development" !== 'production') {
  17707. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17708. }
  17709. replaceMergeMainTypeMap.set(mainType, true);
  17710. });
  17711. return {
  17712. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17713. };
  17714. }
  17715. mixin(GlobalModel, PaletteMixin);
  17716. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17717. 'getOption', // 'getViewOfComponentModel',
  17718. // 'getViewOfSeriesModel',
  17719. 'getId', 'updateLabelLayout'];
  17720. var ExtensionAPI =
  17721. /** @class */
  17722. function () {
  17723. function ExtensionAPI(ecInstance) {
  17724. each(availableMethods, function (methodName) {
  17725. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17726. }, this);
  17727. }
  17728. return ExtensionAPI;
  17729. }();
  17730. var coordinateSystemCreators = {};
  17731. var CoordinateSystemManager =
  17732. /** @class */
  17733. function () {
  17734. function CoordinateSystemManager() {
  17735. this._coordinateSystems = [];
  17736. }
  17737. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17738. var coordinateSystems = [];
  17739. each(coordinateSystemCreators, function (creater, type) {
  17740. var list = creater.create(ecModel, api);
  17741. coordinateSystems = coordinateSystems.concat(list || []);
  17742. });
  17743. this._coordinateSystems = coordinateSystems;
  17744. };
  17745. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17746. each(this._coordinateSystems, function (coordSys) {
  17747. coordSys.update && coordSys.update(ecModel, api);
  17748. });
  17749. };
  17750. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17751. return this._coordinateSystems.slice();
  17752. };
  17753. CoordinateSystemManager.register = function (type, creator) {
  17754. coordinateSystemCreators[type] = creator;
  17755. };
  17756. CoordinateSystemManager.get = function (type) {
  17757. return coordinateSystemCreators[type];
  17758. };
  17759. return CoordinateSystemManager;
  17760. }();
  17761. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17762. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17763. /**
  17764. * TERM EXPLANATIONS:
  17765. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17766. */
  17767. var OptionManager =
  17768. /** @class */
  17769. function () {
  17770. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17771. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17772. // rawOption cloned and backuped when timeline changed, which does no
  17773. // good to performance. What's more, that both timeline and setOption
  17774. // method supply 'notMerge' brings complex and some problems.
  17775. // Consider this case:
  17776. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17777. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17778. function OptionManager(api) {
  17779. this._timelineOptions = [];
  17780. this._mediaList = [];
  17781. /**
  17782. * -1, means default.
  17783. * empty means no media.
  17784. */
  17785. this._currentMediaIndices = [];
  17786. this._api = api;
  17787. }
  17788. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17789. if (rawOption) {
  17790. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17791. each(normalizeToArray(rawOption.series), function (series) {
  17792. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17793. });
  17794. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17795. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17796. });
  17797. } // Caution: some series modify option data, if do not clone,
  17798. // it should ensure that the repeat modify correctly
  17799. // (create a new object when modify itself).
  17800. rawOption = clone(rawOption); // FIXME
  17801. // If some property is set in timeline options or media option but
  17802. // not set in baseOption, a warning should be given.
  17803. var optionBackup = this._optionBackup;
  17804. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17805. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17806. if (optionBackup) {
  17807. // FIXME
  17808. // the restore merge solution is essentially incorrect.
  17809. // the mapping can not be 100% consistent with ecModel, which probably brings
  17810. // potential bug!
  17811. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17812. // let fakeCmptsMap = this._fakeCmptsMap;
  17813. // if (!fakeCmptsMap) {
  17814. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17815. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17816. // }
  17817. // mergeToBackupOption(
  17818. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17819. // );
  17820. // For simplicity, timeline options and media options do not support merge,
  17821. // that is, if you `setOption` twice and both has timeline options, the latter
  17822. // timeline opitons will not be merged to the formers, but just substitude them.
  17823. if (newParsedOption.timelineOptions.length) {
  17824. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17825. }
  17826. if (newParsedOption.mediaList.length) {
  17827. optionBackup.mediaList = newParsedOption.mediaList;
  17828. }
  17829. if (newParsedOption.mediaDefault) {
  17830. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17831. }
  17832. } else {
  17833. this._optionBackup = newParsedOption;
  17834. }
  17835. };
  17836. OptionManager.prototype.mountOption = function (isRecreate) {
  17837. var optionBackup = this._optionBackup;
  17838. this._timelineOptions = optionBackup.timelineOptions;
  17839. this._mediaList = optionBackup.mediaList;
  17840. this._mediaDefault = optionBackup.mediaDefault;
  17841. this._currentMediaIndices = [];
  17842. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17843. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17844. // each time `setOption` called, can be only used in `isRecreate`, because
  17845. // its reliability is under suspicion. In other cases option merge is
  17846. // performed by `model.mergeOption`.
  17847. ? optionBackup.baseOption : this._newBaseOption);
  17848. };
  17849. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17850. var option;
  17851. var timelineOptions = this._timelineOptions;
  17852. if (timelineOptions.length) {
  17853. // getTimelineOption can only be called after ecModel inited,
  17854. // so we can get currentIndex from timelineModel.
  17855. var timelineModel = ecModel.getComponent('timeline');
  17856. if (timelineModel) {
  17857. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17858. timelineOptions[timelineModel.getCurrentIndex()]);
  17859. }
  17860. }
  17861. return option;
  17862. };
  17863. OptionManager.prototype.getMediaOption = function (ecModel) {
  17864. var ecWidth = this._api.getWidth();
  17865. var ecHeight = this._api.getHeight();
  17866. var mediaList = this._mediaList;
  17867. var mediaDefault = this._mediaDefault;
  17868. var indices = [];
  17869. var result = []; // No media defined.
  17870. if (!mediaList.length && !mediaDefault) {
  17871. return result;
  17872. } // Multi media may be applied, the latter defined media has higher priority.
  17873. for (var i = 0, len = mediaList.length; i < len; i++) {
  17874. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17875. indices.push(i);
  17876. }
  17877. } // FIXME
  17878. // Whether mediaDefault should force users to provide? Otherwise
  17879. // the change by media query can not be recorvered.
  17880. if (!indices.length && mediaDefault) {
  17881. indices = [-1];
  17882. }
  17883. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17884. result = map(indices, function (index) {
  17885. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17886. });
  17887. } // Otherwise return nothing.
  17888. this._currentMediaIndices = indices;
  17889. return result;
  17890. };
  17891. return OptionManager;
  17892. }();
  17893. /**
  17894. * [RAW_OPTION_PATTERNS]
  17895. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17896. *
  17897. * (1) No prop "baseOption" declared:
  17898. * Root option is used as "baseOption" (except prop "options" and "media").
  17899. * ```js
  17900. * option = {
  17901. * series: [],
  17902. * timeline: {},
  17903. * options: [],
  17904. * };
  17905. * option = {
  17906. * series: [],
  17907. * media: {},
  17908. * };
  17909. * option = {
  17910. * series: [],
  17911. * timeline: {},
  17912. * options: [],
  17913. * media: {},
  17914. * }
  17915. * ```
  17916. *
  17917. * (2) Prop "baseOption" declared:
  17918. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17919. * inside "baseOption" except prop "timeline" (compat ec2).
  17920. * ```js
  17921. * option = {
  17922. * baseOption: {
  17923. * timeline: {},
  17924. * series: [],
  17925. * },
  17926. * options: []
  17927. * };
  17928. * option = {
  17929. * baseOption: {
  17930. * series: [],
  17931. * },
  17932. * media: []
  17933. * };
  17934. * option = {
  17935. * baseOption: {
  17936. * timeline: {},
  17937. * series: [],
  17938. * },
  17939. * options: []
  17940. * media: []
  17941. * };
  17942. * option = {
  17943. * // ec3 compat ec2: allow (only) `timeline` declared
  17944. * // outside baseOption. Keep this setting for compat.
  17945. * timeline: {},
  17946. * baseOption: {
  17947. * series: [],
  17948. * },
  17949. * options: [],
  17950. * media: []
  17951. * };
  17952. * ```
  17953. */
  17954. function parseRawOption( // `rawOption` May be modified
  17955. rawOption, optionPreprocessorFuncs, isNew) {
  17956. var mediaList = [];
  17957. var mediaDefault;
  17958. var baseOption;
  17959. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17960. var timelineOnRoot = rawOption.timeline;
  17961. var timelineOptionsOnRoot = rawOption.options;
  17962. var mediaOnRoot = rawOption.media;
  17963. var hasMedia = !!rawOption.media;
  17964. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17965. if (declaredBaseOption) {
  17966. baseOption = declaredBaseOption; // For merge option.
  17967. if (!baseOption.timeline) {
  17968. baseOption.timeline = timelineOnRoot;
  17969. }
  17970. } // For convenience, enable to use the root option as the `baseOption`:
  17971. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17972. else {
  17973. if (hasTimeline || hasMedia) {
  17974. rawOption.options = rawOption.media = null;
  17975. }
  17976. baseOption = rawOption;
  17977. }
  17978. if (hasMedia) {
  17979. if (isArray(mediaOnRoot)) {
  17980. each(mediaOnRoot, function (singleMedia) {
  17981. if ("development" !== 'production') {
  17982. // Real case of wrong config.
  17983. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17984. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17985. }
  17986. }
  17987. if (singleMedia && singleMedia.option) {
  17988. if (singleMedia.query) {
  17989. mediaList.push(singleMedia);
  17990. } else if (!mediaDefault) {
  17991. // Use the first media default.
  17992. mediaDefault = singleMedia;
  17993. }
  17994. }
  17995. });
  17996. } else {
  17997. if ("development" !== 'production') {
  17998. // Real case of wrong config.
  17999. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18000. }
  18001. }
  18002. }
  18003. doPreprocess(baseOption);
  18004. each(timelineOptionsOnRoot, function (option) {
  18005. return doPreprocess(option);
  18006. });
  18007. each(mediaList, function (media) {
  18008. return doPreprocess(media.option);
  18009. });
  18010. function doPreprocess(option) {
  18011. each(optionPreprocessorFuncs, function (preProcess) {
  18012. preProcess(option, isNew);
  18013. });
  18014. }
  18015. return {
  18016. baseOption: baseOption,
  18017. timelineOptions: timelineOptionsOnRoot || [],
  18018. mediaDefault: mediaDefault,
  18019. mediaList: mediaList
  18020. };
  18021. }
  18022. /**
  18023. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18024. * Support: width, height, aspectRatio
  18025. * Can use max or min as prefix.
  18026. */
  18027. function applyMediaQuery(query, ecWidth, ecHeight) {
  18028. var realMap = {
  18029. width: ecWidth,
  18030. height: ecHeight,
  18031. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18032. };
  18033. var applicatable = true;
  18034. each(query, function (value, attr) {
  18035. var matched = attr.match(QUERY_REG);
  18036. if (!matched || !matched[1] || !matched[2]) {
  18037. return;
  18038. }
  18039. var operator = matched[1];
  18040. var realAttr = matched[2].toLowerCase();
  18041. if (!compare(realMap[realAttr], value, operator)) {
  18042. applicatable = false;
  18043. }
  18044. });
  18045. return applicatable;
  18046. }
  18047. function compare(real, expect, operator) {
  18048. if (operator === 'min') {
  18049. return real >= expect;
  18050. } else if (operator === 'max') {
  18051. return real <= expect;
  18052. } else {
  18053. // Equals
  18054. return real === expect;
  18055. }
  18056. }
  18057. function indicesEquals(indices1, indices2) {
  18058. // indices is always order by asc and has only finite number.
  18059. return indices1.join(',') === indices2.join(',');
  18060. }
  18061. var each$2 = each;
  18062. var isObject$1 = isObject;
  18063. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18064. function compatEC2ItemStyle(opt) {
  18065. var itemStyleOpt = opt && opt.itemStyle;
  18066. if (!itemStyleOpt) {
  18067. return;
  18068. }
  18069. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18070. var styleName = POSSIBLE_STYLES[i];
  18071. var normalItemStyleOpt = itemStyleOpt.normal;
  18072. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18073. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18074. if ("development" !== 'production') {
  18075. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18076. }
  18077. opt[styleName] = opt[styleName] || {};
  18078. if (!opt[styleName].normal) {
  18079. opt[styleName].normal = normalItemStyleOpt[styleName];
  18080. } else {
  18081. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18082. }
  18083. normalItemStyleOpt[styleName] = null;
  18084. }
  18085. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18086. if ("development" !== 'production') {
  18087. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18088. }
  18089. opt[styleName] = opt[styleName] || {};
  18090. if (!opt[styleName].emphasis) {
  18091. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18092. } else {
  18093. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18094. }
  18095. emphasisItemStyleOpt[styleName] = null;
  18096. }
  18097. }
  18098. }
  18099. function convertNormalEmphasis(opt, optType, useExtend) {
  18100. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18101. var normalOpt = opt[optType].normal;
  18102. var emphasisOpt = opt[optType].emphasis;
  18103. if (normalOpt) {
  18104. if ("development" !== 'production') {
  18105. // eslint-disable-next-line max-len
  18106. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18107. } // Timeline controlStyle has other properties besides normal and emphasis
  18108. if (useExtend) {
  18109. opt[optType].normal = opt[optType].emphasis = null;
  18110. defaults(opt[optType], normalOpt);
  18111. } else {
  18112. opt[optType] = normalOpt;
  18113. }
  18114. }
  18115. if (emphasisOpt) {
  18116. if ("development" !== 'production') {
  18117. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18118. }
  18119. opt.emphasis = opt.emphasis || {};
  18120. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18121. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18122. if (emphasisOpt.focus) {
  18123. opt.emphasis.focus = emphasisOpt.focus;
  18124. }
  18125. if (emphasisOpt.blurScope) {
  18126. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18127. }
  18128. }
  18129. }
  18130. }
  18131. function removeEC3NormalStatus(opt) {
  18132. convertNormalEmphasis(opt, 'itemStyle');
  18133. convertNormalEmphasis(opt, 'lineStyle');
  18134. convertNormalEmphasis(opt, 'areaStyle');
  18135. convertNormalEmphasis(opt, 'label');
  18136. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18137. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18138. convertNormalEmphasis(opt, 'edgeLabel');
  18139. }
  18140. function compatTextStyle(opt, propName) {
  18141. // Check whether is not object (string\null\undefined ...)
  18142. var labelOptSingle = isObject$1(opt) && opt[propName];
  18143. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18144. if (textStyle) {
  18145. if ("development" !== 'production') {
  18146. // eslint-disable-next-line max-len
  18147. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18148. }
  18149. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18150. var textPropName = TEXT_STYLE_OPTIONS[i];
  18151. if (textStyle.hasOwnProperty(textPropName)) {
  18152. labelOptSingle[textPropName] = textStyle[textPropName];
  18153. }
  18154. }
  18155. }
  18156. }
  18157. function compatEC3CommonStyles(opt) {
  18158. if (opt) {
  18159. removeEC3NormalStatus(opt);
  18160. compatTextStyle(opt, 'label');
  18161. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18162. }
  18163. }
  18164. function processSeries(seriesOpt) {
  18165. if (!isObject$1(seriesOpt)) {
  18166. return;
  18167. }
  18168. compatEC2ItemStyle(seriesOpt);
  18169. removeEC3NormalStatus(seriesOpt);
  18170. compatTextStyle(seriesOpt, 'label'); // treemap
  18171. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18172. compatTextStyle(seriesOpt, 'edgeLabel');
  18173. if (seriesOpt.emphasis) {
  18174. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18175. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18176. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18177. }
  18178. var markPoint = seriesOpt.markPoint;
  18179. if (markPoint) {
  18180. compatEC2ItemStyle(markPoint);
  18181. compatEC3CommonStyles(markPoint);
  18182. }
  18183. var markLine = seriesOpt.markLine;
  18184. if (markLine) {
  18185. compatEC2ItemStyle(markLine);
  18186. compatEC3CommonStyles(markLine);
  18187. }
  18188. var markArea = seriesOpt.markArea;
  18189. if (markArea) {
  18190. compatEC3CommonStyles(markArea);
  18191. }
  18192. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18193. // then the backward compat based on option type will not be performed.
  18194. if (seriesOpt.type === 'graph') {
  18195. data = data || seriesOpt.nodes;
  18196. var edgeData = seriesOpt.links || seriesOpt.edges;
  18197. if (edgeData && !isTypedArray(edgeData)) {
  18198. for (var i = 0; i < edgeData.length; i++) {
  18199. compatEC3CommonStyles(edgeData[i]);
  18200. }
  18201. }
  18202. each(seriesOpt.categories, function (opt) {
  18203. removeEC3NormalStatus(opt);
  18204. });
  18205. }
  18206. if (data && !isTypedArray(data)) {
  18207. for (var i = 0; i < data.length; i++) {
  18208. compatEC3CommonStyles(data[i]);
  18209. }
  18210. } // mark point data
  18211. markPoint = seriesOpt.markPoint;
  18212. if (markPoint && markPoint.data) {
  18213. var mpData = markPoint.data;
  18214. for (var i = 0; i < mpData.length; i++) {
  18215. compatEC3CommonStyles(mpData[i]);
  18216. }
  18217. } // mark line data
  18218. markLine = seriesOpt.markLine;
  18219. if (markLine && markLine.data) {
  18220. var mlData = markLine.data;
  18221. for (var i = 0; i < mlData.length; i++) {
  18222. if (isArray(mlData[i])) {
  18223. compatEC3CommonStyles(mlData[i][0]);
  18224. compatEC3CommonStyles(mlData[i][1]);
  18225. } else {
  18226. compatEC3CommonStyles(mlData[i]);
  18227. }
  18228. }
  18229. } // Series
  18230. if (seriesOpt.type === 'gauge') {
  18231. compatTextStyle(seriesOpt, 'axisLabel');
  18232. compatTextStyle(seriesOpt, 'title');
  18233. compatTextStyle(seriesOpt, 'detail');
  18234. } else if (seriesOpt.type === 'treemap') {
  18235. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18236. each(seriesOpt.levels, function (opt) {
  18237. removeEC3NormalStatus(opt);
  18238. });
  18239. } else if (seriesOpt.type === 'tree') {
  18240. removeEC3NormalStatus(seriesOpt.leaves);
  18241. } // sunburst starts from ec4, so it does not need to compat levels.
  18242. }
  18243. function toArr(o) {
  18244. return isArray(o) ? o : o ? [o] : [];
  18245. }
  18246. function toObj(o) {
  18247. return (isArray(o) ? o[0] : o) || {};
  18248. }
  18249. function globalCompatStyle(option, isTheme) {
  18250. each$2(toArr(option.series), function (seriesOpt) {
  18251. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18252. });
  18253. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18254. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18255. each$2(axes, function (axisName) {
  18256. each$2(toArr(option[axisName]), function (axisOpt) {
  18257. if (axisOpt) {
  18258. compatTextStyle(axisOpt, 'axisLabel');
  18259. compatTextStyle(axisOpt.axisPointer, 'label');
  18260. }
  18261. });
  18262. });
  18263. each$2(toArr(option.parallel), function (parallelOpt) {
  18264. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18265. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18266. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18267. });
  18268. each$2(toArr(option.calendar), function (calendarOpt) {
  18269. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18270. compatTextStyle(calendarOpt, 'dayLabel');
  18271. compatTextStyle(calendarOpt, 'monthLabel');
  18272. compatTextStyle(calendarOpt, 'yearLabel');
  18273. }); // radar.name.textStyle
  18274. each$2(toArr(option.radar), function (radarOpt) {
  18275. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18276. if (radarOpt.name && radarOpt.axisName == null) {
  18277. radarOpt.axisName = radarOpt.name;
  18278. delete radarOpt.name;
  18279. if ("development" !== 'production') {
  18280. deprecateLog('name property in radar component has been changed to axisName');
  18281. }
  18282. }
  18283. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18284. radarOpt.axisNameGap = radarOpt.nameGap;
  18285. delete radarOpt.nameGap;
  18286. if ("development" !== 'production') {
  18287. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18288. }
  18289. }
  18290. if ("development" !== 'production') {
  18291. each$2(radarOpt.indicator, function (indicatorOpt) {
  18292. if (indicatorOpt.text) {
  18293. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18294. }
  18295. });
  18296. }
  18297. });
  18298. each$2(toArr(option.geo), function (geoOpt) {
  18299. if (isObject$1(geoOpt)) {
  18300. compatEC3CommonStyles(geoOpt);
  18301. each$2(toArr(geoOpt.regions), function (regionObj) {
  18302. compatEC3CommonStyles(regionObj);
  18303. });
  18304. }
  18305. });
  18306. each$2(toArr(option.timeline), function (timelineOpt) {
  18307. compatEC3CommonStyles(timelineOpt);
  18308. convertNormalEmphasis(timelineOpt, 'label');
  18309. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18310. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18311. var data = timelineOpt.data;
  18312. isArray(data) && each(data, function (item) {
  18313. if (isObject(item)) {
  18314. convertNormalEmphasis(item, 'label');
  18315. convertNormalEmphasis(item, 'itemStyle');
  18316. }
  18317. });
  18318. });
  18319. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18320. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18321. each$2(toolboxOpt.feature, function (featureOpt) {
  18322. convertNormalEmphasis(featureOpt, 'iconStyle');
  18323. });
  18324. });
  18325. compatTextStyle(toObj(option.axisPointer), 'label');
  18326. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18327. // storedLogs = {};
  18328. }
  18329. function get(opt, path) {
  18330. var pathArr = path.split(',');
  18331. var obj = opt;
  18332. for (var i = 0; i < pathArr.length; i++) {
  18333. obj = obj && obj[pathArr[i]];
  18334. if (obj == null) {
  18335. break;
  18336. }
  18337. }
  18338. return obj;
  18339. }
  18340. function set$1(opt, path, val, overwrite) {
  18341. var pathArr = path.split(',');
  18342. var obj = opt;
  18343. var key;
  18344. var i = 0;
  18345. for (; i < pathArr.length - 1; i++) {
  18346. key = pathArr[i];
  18347. if (obj[key] == null) {
  18348. obj[key] = {};
  18349. }
  18350. obj = obj[key];
  18351. }
  18352. if (overwrite || obj[pathArr[i]] == null) {
  18353. obj[pathArr[i]] = val;
  18354. }
  18355. }
  18356. function compatLayoutProperties(option) {
  18357. option && each(LAYOUT_PROPERTIES, function (prop) {
  18358. if (prop[0] in option && !(prop[1] in option)) {
  18359. option[prop[1]] = option[prop[0]];
  18360. }
  18361. });
  18362. }
  18363. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18364. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18365. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18366. function compatBarItemStyle(option) {
  18367. var itemStyle = option && option.itemStyle;
  18368. if (itemStyle) {
  18369. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18370. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18371. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18372. if (itemStyle[oldName] != null) {
  18373. itemStyle[newName] = itemStyle[oldName];
  18374. if ("development" !== 'production') {
  18375. deprecateReplaceLog(oldName, newName);
  18376. }
  18377. }
  18378. }
  18379. }
  18380. }
  18381. function compatPieLabel(option) {
  18382. if (!option) {
  18383. return;
  18384. }
  18385. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18386. if ("development" !== 'production') {
  18387. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18388. }
  18389. option.edgeDistance = option.margin;
  18390. }
  18391. }
  18392. function compatSunburstState(option) {
  18393. if (!option) {
  18394. return;
  18395. }
  18396. if (option.downplay && !option.blur) {
  18397. option.blur = option.downplay;
  18398. if ("development" !== 'production') {
  18399. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18400. }
  18401. }
  18402. }
  18403. function compatGraphFocus(option) {
  18404. if (!option) {
  18405. return;
  18406. }
  18407. if (option.focusNodeAdjacency != null) {
  18408. option.emphasis = option.emphasis || {};
  18409. if (option.emphasis.focus == null) {
  18410. if ("development" !== 'production') {
  18411. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18412. }
  18413. option.emphasis.focus = 'adjacency';
  18414. }
  18415. }
  18416. }
  18417. function traverseTree(data, cb) {
  18418. if (data) {
  18419. for (var i = 0; i < data.length; i++) {
  18420. cb(data[i]);
  18421. data[i] && traverseTree(data[i].children, cb);
  18422. }
  18423. }
  18424. }
  18425. function globalBackwardCompat(option, isTheme) {
  18426. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18427. option.series = normalizeToArray(option.series);
  18428. each(option.series, function (seriesOpt) {
  18429. if (!isObject(seriesOpt)) {
  18430. return;
  18431. }
  18432. var seriesType = seriesOpt.type;
  18433. if (seriesType === 'line') {
  18434. if (seriesOpt.clipOverflow != null) {
  18435. seriesOpt.clip = seriesOpt.clipOverflow;
  18436. if ("development" !== 'production') {
  18437. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18438. }
  18439. }
  18440. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18441. if (seriesOpt.clockWise != null) {
  18442. seriesOpt.clockwise = seriesOpt.clockWise;
  18443. if ("development" !== 'production') {
  18444. deprecateReplaceLog('clockWise', 'clockwise');
  18445. }
  18446. }
  18447. compatPieLabel(seriesOpt.label);
  18448. var data = seriesOpt.data;
  18449. if (data && !isTypedArray(data)) {
  18450. for (var i = 0; i < data.length; i++) {
  18451. compatPieLabel(data[i]);
  18452. }
  18453. }
  18454. if (seriesOpt.hoverOffset != null) {
  18455. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18456. if (seriesOpt.emphasis.scaleSize = null) {
  18457. if ("development" !== 'production') {
  18458. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18459. }
  18460. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18461. }
  18462. }
  18463. } else if (seriesType === 'gauge') {
  18464. var pointerColor = get(seriesOpt, 'pointer.color');
  18465. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18466. } else if (seriesType === 'bar') {
  18467. compatBarItemStyle(seriesOpt);
  18468. compatBarItemStyle(seriesOpt.backgroundStyle);
  18469. compatBarItemStyle(seriesOpt.emphasis);
  18470. var data = seriesOpt.data;
  18471. if (data && !isTypedArray(data)) {
  18472. for (var i = 0; i < data.length; i++) {
  18473. if (typeof data[i] === 'object') {
  18474. compatBarItemStyle(data[i]);
  18475. compatBarItemStyle(data[i] && data[i].emphasis);
  18476. }
  18477. }
  18478. }
  18479. } else if (seriesType === 'sunburst') {
  18480. var highlightPolicy = seriesOpt.highlightPolicy;
  18481. if (highlightPolicy) {
  18482. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18483. if (!seriesOpt.emphasis.focus) {
  18484. seriesOpt.emphasis.focus = highlightPolicy;
  18485. if ("development" !== 'production') {
  18486. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18487. }
  18488. }
  18489. }
  18490. compatSunburstState(seriesOpt);
  18491. traverseTree(seriesOpt.data, compatSunburstState);
  18492. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18493. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18494. } else if (seriesType === 'map') {
  18495. if (seriesOpt.mapType && !seriesOpt.map) {
  18496. if ("development" !== 'production') {
  18497. deprecateReplaceLog('mapType', 'map', 'map');
  18498. }
  18499. seriesOpt.map = seriesOpt.mapType;
  18500. }
  18501. if (seriesOpt.mapLocation) {
  18502. if ("development" !== 'production') {
  18503. deprecateLog('`mapLocation` is not used anymore.');
  18504. }
  18505. defaults(seriesOpt, seriesOpt.mapLocation);
  18506. }
  18507. }
  18508. if (seriesOpt.hoverAnimation != null) {
  18509. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18510. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18511. if ("development" !== 'production') {
  18512. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18513. }
  18514. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18515. }
  18516. }
  18517. compatLayoutProperties(seriesOpt);
  18518. }); // dataRange has changed to visualMap
  18519. if (option.dataRange) {
  18520. option.visualMap = option.dataRange;
  18521. }
  18522. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18523. var options = option[componentName];
  18524. if (options) {
  18525. if (!isArray(options)) {
  18526. options = [options];
  18527. }
  18528. each(options, function (option) {
  18529. compatLayoutProperties(option);
  18530. });
  18531. }
  18532. });
  18533. }
  18534. // data processing stage is blocked in stream.
  18535. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18536. // (2) Only register once when import repeatly.
  18537. // Should be executed after series filtered and before stack calculation.
  18538. function dataStack(ecModel) {
  18539. var stackInfoMap = createHashMap();
  18540. ecModel.eachSeries(function (seriesModel) {
  18541. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18542. if (stack) {
  18543. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18544. var data = seriesModel.getData();
  18545. var stackInfo = {
  18546. // Used for calculate axis extent automatically.
  18547. // TODO: Type getCalculationInfo return more specific type?
  18548. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18549. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18550. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18551. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18552. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18553. data: data,
  18554. seriesModel: seriesModel
  18555. }; // If stacked on axis that do not support data stack.
  18556. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18557. return;
  18558. }
  18559. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18560. stackInfoList.push(stackInfo);
  18561. }
  18562. });
  18563. stackInfoMap.each(calculateStack);
  18564. }
  18565. function calculateStack(stackInfoList) {
  18566. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18567. var resultVal = [];
  18568. var resultNaN = [NaN, NaN];
  18569. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18570. var targetData = targetStackInfo.data;
  18571. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  18572. // depending on legend selection.
  18573. targetData.modify(dims, function (v0, v1, dataIndex) {
  18574. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18575. // should also be NaN, to draw a appropriate belt area.
  18576. if (isNaN(sum)) {
  18577. return resultNaN;
  18578. }
  18579. var byValue;
  18580. var stackedDataRawIndex;
  18581. if (isStackedByIndex) {
  18582. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18583. } else {
  18584. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18585. } // If stackOver is NaN, chart view will render point on value start.
  18586. var stackedOver = NaN;
  18587. for (var j = idxInStack - 1; j >= 0; j--) {
  18588. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18589. if (!isStackedByIndex) {
  18590. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18591. }
  18592. if (stackedDataRawIndex >= 0) {
  18593. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18594. if (sum >= 0 && val > 0 || // Positive stack
  18595. sum <= 0 && val < 0 // Negative stack
  18596. ) {
  18597. // The sum should be as less as possible to be effected
  18598. // by floating arithmetic problem. A wrong result probably
  18599. // filtered incorrectly by axis min/max.
  18600. sum = addSafe(sum, val);
  18601. stackedOver = val;
  18602. break;
  18603. }
  18604. }
  18605. }
  18606. resultVal[0] = sum;
  18607. resultVal[1] = stackedOver;
  18608. return resultVal;
  18609. });
  18610. });
  18611. }
  18612. var SourceImpl =
  18613. /** @class */
  18614. function () {
  18615. function SourceImpl(fields) {
  18616. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18617. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18618. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18619. this.startIndex = fields.startIndex || 0;
  18620. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18621. this.metaRawOption = fields.metaRawOption;
  18622. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18623. if (dimensionsDefine) {
  18624. for (var i = 0; i < dimensionsDefine.length; i++) {
  18625. var dim = dimensionsDefine[i];
  18626. if (dim.type == null) {
  18627. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18628. dim.type = 'ordinal';
  18629. }
  18630. }
  18631. }
  18632. }
  18633. }
  18634. return SourceImpl;
  18635. }();
  18636. function isSourceInstance(val) {
  18637. return val instanceof SourceImpl;
  18638. }
  18639. /**
  18640. * Create a source from option.
  18641. * NOTE: Created source is immutable. Don't change any properties in it.
  18642. */
  18643. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18644. sourceFormat) {
  18645. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18646. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18647. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18648. var source = new SourceImpl({
  18649. data: sourceData,
  18650. sourceFormat: sourceFormat,
  18651. seriesLayoutBy: seriesLayoutBy,
  18652. dimensionsDefine: determined.dimensionsDefine,
  18653. startIndex: determined.startIndex,
  18654. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18655. metaRawOption: clone(thisMetaRawOption)
  18656. });
  18657. return source;
  18658. }
  18659. /**
  18660. * Wrap original series data for some compatibility cases.
  18661. */
  18662. function createSourceFromSeriesDataOption(data) {
  18663. return new SourceImpl({
  18664. data: data,
  18665. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18666. });
  18667. }
  18668. /**
  18669. * Clone source but excludes source data.
  18670. */
  18671. function cloneSourceShallow(source) {
  18672. return new SourceImpl({
  18673. data: source.data,
  18674. sourceFormat: source.sourceFormat,
  18675. seriesLayoutBy: source.seriesLayoutBy,
  18676. dimensionsDefine: clone(source.dimensionsDefine),
  18677. startIndex: source.startIndex,
  18678. dimensionsDetectedCount: source.dimensionsDetectedCount
  18679. });
  18680. }
  18681. /**
  18682. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18683. */
  18684. function detectSourceFormat(data) {
  18685. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18686. if (isTypedArray(data)) {
  18687. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18688. } else if (isArray(data)) {
  18689. // FIXME Whether tolerate null in top level array?
  18690. if (data.length === 0) {
  18691. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18692. }
  18693. for (var i = 0, len = data.length; i < len; i++) {
  18694. var item = data[i];
  18695. if (item == null) {
  18696. continue;
  18697. } else if (isArray(item)) {
  18698. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18699. break;
  18700. } else if (isObject(item)) {
  18701. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18702. break;
  18703. }
  18704. }
  18705. } else if (isObject(data)) {
  18706. for (var key in data) {
  18707. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18708. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18709. break;
  18710. }
  18711. }
  18712. }
  18713. return sourceFormat;
  18714. }
  18715. /**
  18716. * Determine the source definitions from data standalone dimensions definitions
  18717. * are not specified.
  18718. */
  18719. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18720. // {
  18721. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18722. // }
  18723. // in `dataset` or `series`
  18724. dimensionsDefine) {
  18725. var dimensionsDetectedCount;
  18726. var startIndex; // PEDING: could data be null/undefined here?
  18727. // currently, if `dataset.source` not specified, error thrown.
  18728. // if `series.data` not specified, nothing rendered without error thrown.
  18729. // Should test these cases.
  18730. if (!data) {
  18731. return {
  18732. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18733. startIndex: startIndex,
  18734. dimensionsDetectedCount: dimensionsDetectedCount
  18735. };
  18736. }
  18737. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18738. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18739. // Caution: consider a line with 5 string and 1 number,
  18740. // it still can not be sure it is a head, because the
  18741. // 5 string may be 5 values of category columns.
  18742. if (sourceHeader === 'auto' || sourceHeader == null) {
  18743. arrayRowsTravelFirst(function (val) {
  18744. // '-' is regarded as null/undefined.
  18745. if (val != null && val !== '-') {
  18746. if (isString(val)) {
  18747. startIndex == null && (startIndex = 1);
  18748. } else {
  18749. startIndex = 0;
  18750. }
  18751. } // 10 is an experience number, avoid long loop.
  18752. }, seriesLayoutBy, dataArrayRows, 10);
  18753. } else {
  18754. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18755. }
  18756. if (!dimensionsDefine && startIndex === 1) {
  18757. dimensionsDefine = [];
  18758. arrayRowsTravelFirst(function (val, index) {
  18759. dimensionsDefine[index] = val != null ? val + '' : '';
  18760. }, seriesLayoutBy, dataArrayRows, Infinity);
  18761. }
  18762. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18763. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18764. if (!dimensionsDefine) {
  18765. dimensionsDefine = objectRowsCollectDimensions(data);
  18766. }
  18767. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18768. if (!dimensionsDefine) {
  18769. dimensionsDefine = [];
  18770. each(data, function (colArr, key) {
  18771. dimensionsDefine.push(key);
  18772. });
  18773. }
  18774. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18775. var value0 = getDataItemValue(data[0]);
  18776. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18777. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18778. if ("development" !== 'production') {
  18779. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18780. }
  18781. }
  18782. return {
  18783. startIndex: startIndex,
  18784. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18785. dimensionsDetectedCount: dimensionsDetectedCount
  18786. };
  18787. }
  18788. function objectRowsCollectDimensions(data) {
  18789. var firstIndex = 0;
  18790. var obj;
  18791. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18792. if (obj) {
  18793. var dimensions_1 = [];
  18794. each(obj, function (value, key) {
  18795. dimensions_1.push(key);
  18796. });
  18797. return dimensions_1;
  18798. }
  18799. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18800. // which is reasonable. But dimension name is duplicated.
  18801. // Returns undefined or an array contains only object without null/undefiend or string.
  18802. function normalizeDimensionsOption(dimensionsDefine) {
  18803. if (!dimensionsDefine) {
  18804. // The meaning of null/undefined is different from empty array.
  18805. return;
  18806. }
  18807. var nameMap = createHashMap();
  18808. return map(dimensionsDefine, function (rawItem, index) {
  18809. rawItem = isObject(rawItem) ? rawItem : {
  18810. name: rawItem
  18811. }; // Other fields will be discarded.
  18812. var item = {
  18813. name: rawItem.name,
  18814. displayName: rawItem.displayName,
  18815. type: rawItem.type
  18816. }; // User can set null in dimensions.
  18817. // We dont auto specify name, othewise a given name may
  18818. // cause it be refered unexpectedly.
  18819. if (item.name == null) {
  18820. return item;
  18821. } // Also consider number form like 2012.
  18822. item.name += ''; // User may also specify displayName.
  18823. // displayName will always exists except user not
  18824. // specified or dim name is not specified or detected.
  18825. // (A auto generated dim name will not be used as
  18826. // displayName).
  18827. if (item.displayName == null) {
  18828. item.displayName = item.name;
  18829. }
  18830. var exist = nameMap.get(item.name);
  18831. if (!exist) {
  18832. nameMap.set(item.name, {
  18833. count: 1
  18834. });
  18835. } else {
  18836. item.name += '-' + exist.count++;
  18837. }
  18838. return item;
  18839. });
  18840. }
  18841. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18842. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18843. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18844. cb(data[i] ? data[i][0] : null, i);
  18845. }
  18846. } else {
  18847. var value0 = data[0] || [];
  18848. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18849. cb(value0[i], i);
  18850. }
  18851. }
  18852. }
  18853. function shouldRetrieveDataByName(source) {
  18854. var sourceFormat = source.sourceFormat;
  18855. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  18856. }
  18857. /*
  18858. * Licensed to the Apache Software Foundation (ASF) under one
  18859. * or more contributor license agreements. See the NOTICE file
  18860. * distributed with this work for additional information
  18861. * regarding copyright ownership. The ASF licenses this file
  18862. * to you under the Apache License, Version 2.0 (the
  18863. * "License"); you may not use this file except in compliance
  18864. * with the License. You may obtain a copy of the License at
  18865. *
  18866. * http://www.apache.org/licenses/LICENSE-2.0
  18867. *
  18868. * Unless required by applicable law or agreed to in writing,
  18869. * software distributed under the License is distributed on an
  18870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18871. * KIND, either express or implied. See the License for the
  18872. * specific language governing permissions and limitations
  18873. * under the License.
  18874. */
  18875. /**
  18876. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18877. */
  18878. /*
  18879. * Licensed to the Apache Software Foundation (ASF) under one
  18880. * or more contributor license agreements. See the NOTICE file
  18881. * distributed with this work for additional information
  18882. * regarding copyright ownership. The ASF licenses this file
  18883. * to you under the Apache License, Version 2.0 (the
  18884. * "License"); you may not use this file except in compliance
  18885. * with the License. You may obtain a copy of the License at
  18886. *
  18887. * http://www.apache.org/licenses/LICENSE-2.0
  18888. *
  18889. * Unless required by applicable law or agreed to in writing,
  18890. * software distributed under the License is distributed on an
  18891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18892. * KIND, either express or implied. See the License for the
  18893. * specific language governing permissions and limitations
  18894. * under the License.
  18895. */
  18896. var _a, _b, _c; // TODO
  18897. var providerMethods;
  18898. var mountMethods;
  18899. /**
  18900. * If normal array used, mutable chunk size is supported.
  18901. * If typed array used, chunk size must be fixed.
  18902. */
  18903. var DefaultDataProvider =
  18904. /** @class */
  18905. function () {
  18906. function DefaultDataProvider(sourceParam, dimSize) {
  18907. // let source: Source;
  18908. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18909. this._source = source;
  18910. var data = this._data = source.data; // Typed array. TODO IE10+?
  18911. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18912. if ("development" !== 'production') {
  18913. if (dimSize == null) {
  18914. throw new Error('Typed array data must specify dimension size');
  18915. }
  18916. }
  18917. this._offset = 0;
  18918. this._dimSize = dimSize;
  18919. this._data = data;
  18920. }
  18921. mountMethods(this, data, source);
  18922. }
  18923. DefaultDataProvider.prototype.getSource = function () {
  18924. return this._source;
  18925. };
  18926. DefaultDataProvider.prototype.count = function () {
  18927. return 0;
  18928. };
  18929. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18930. return;
  18931. };
  18932. DefaultDataProvider.prototype.appendData = function (newData) {};
  18933. DefaultDataProvider.prototype.clean = function () {};
  18934. DefaultDataProvider.protoInitialize = function () {
  18935. // PENDING: To avoid potential incompat (e.g., prototype
  18936. // is visited somewhere), still init them on prototype.
  18937. var proto = DefaultDataProvider.prototype;
  18938. proto.pure = false;
  18939. proto.persistent = true;
  18940. }();
  18941. DefaultDataProvider.internalField = function () {
  18942. var _a;
  18943. mountMethods = function (provider, data, source) {
  18944. var sourceFormat = source.sourceFormat;
  18945. var seriesLayoutBy = source.seriesLayoutBy;
  18946. var startIndex = source.startIndex;
  18947. var dimsDef = source.dimensionsDefine;
  18948. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18949. if ("development" !== 'production') {
  18950. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18951. }
  18952. extend(provider, methods);
  18953. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18954. provider.getItem = getItemForTypedArray;
  18955. provider.count = countForTypedArray;
  18956. provider.fillStorage = fillStorageForTypedArray;
  18957. } else {
  18958. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18959. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18960. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18961. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18962. }
  18963. };
  18964. var getItemForTypedArray = function (idx, out) {
  18965. idx = idx - this._offset;
  18966. out = out || [];
  18967. var data = this._data;
  18968. var dimSize = this._dimSize;
  18969. var offset = dimSize * idx;
  18970. for (var i = 0; i < dimSize; i++) {
  18971. out[i] = data[offset + i];
  18972. }
  18973. return out;
  18974. };
  18975. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18976. var data = this._data;
  18977. var dimSize = this._dimSize;
  18978. for (var dim = 0; dim < dimSize; dim++) {
  18979. var dimExtent = extent[dim];
  18980. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18981. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18982. var count = end - start;
  18983. var arr = storage[dim];
  18984. for (var i = 0; i < count; i++) {
  18985. // appendData with TypedArray will always do replace in provider.
  18986. var val = data[i * dimSize + dim];
  18987. arr[start + i] = val;
  18988. val < min && (min = val);
  18989. val > max && (max = val);
  18990. }
  18991. dimExtent[0] = min;
  18992. dimExtent[1] = max;
  18993. }
  18994. };
  18995. var countForTypedArray = function () {
  18996. return this._data ? this._data.length / this._dimSize : 0;
  18997. };
  18998. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18999. pure: true,
  19000. appendData: appendDataSimply
  19001. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19002. pure: true,
  19003. appendData: function () {
  19004. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19005. }
  19006. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19007. pure: true,
  19008. appendData: appendDataSimply
  19009. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19010. pure: true,
  19011. appendData: function (newData) {
  19012. var data = this._data;
  19013. each(newData, function (newCol, key) {
  19014. var oldCol = data[key] || (data[key] = []);
  19015. for (var i = 0; i < (newCol || []).length; i++) {
  19016. oldCol.push(newCol[i]);
  19017. }
  19018. });
  19019. }
  19020. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19021. appendData: appendDataSimply
  19022. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19023. persistent: false,
  19024. pure: true,
  19025. appendData: function (newData) {
  19026. if ("development" !== 'production') {
  19027. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19028. }
  19029. this._data = newData;
  19030. },
  19031. // Clean self if data is already used.
  19032. clean: function () {
  19033. // PENDING
  19034. this._offset += this.count();
  19035. this._data = null;
  19036. }
  19037. }, _a);
  19038. function appendDataSimply(newData) {
  19039. for (var i = 0; i < newData.length; i++) {
  19040. this._data.push(newData[i]);
  19041. }
  19042. }
  19043. }();
  19044. return DefaultDataProvider;
  19045. }();
  19046. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19047. return rawData[idx];
  19048. };
  19049. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19050. return rawData[idx + startIndex];
  19051. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19052. idx += startIndex;
  19053. var item = out || [];
  19054. var data = rawData;
  19055. for (var i = 0; i < data.length; i++) {
  19056. var row = data[i];
  19057. item[i] = row ? row[idx] : null;
  19058. }
  19059. return item;
  19060. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19061. var item = out || [];
  19062. for (var i = 0; i < dimsDef.length; i++) {
  19063. var dimName = dimsDef[i].name;
  19064. if ("development" !== 'production') {
  19065. if (dimName == null) {
  19066. throw new Error();
  19067. }
  19068. }
  19069. var col = rawData[dimName];
  19070. item[i] = col ? col[idx] : null;
  19071. }
  19072. return item;
  19073. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19074. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19075. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19076. if ("development" !== 'production') {
  19077. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19078. }
  19079. return method;
  19080. }
  19081. var countSimply = function (rawData, startIndex, dimsDef) {
  19082. return rawData.length;
  19083. };
  19084. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19085. return Math.max(0, rawData.length - startIndex);
  19086. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19087. var row = rawData[0];
  19088. return row ? Math.max(0, row.length - startIndex) : 0;
  19089. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19090. var dimName = dimsDef[0].name;
  19091. if ("development" !== 'production') {
  19092. if (dimName == null) {
  19093. throw new Error();
  19094. }
  19095. }
  19096. var col = rawData[dimName];
  19097. return col ? col.length : 0;
  19098. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19099. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19100. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19101. if ("development" !== 'production') {
  19102. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19103. }
  19104. return method;
  19105. }
  19106. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19107. return dataItem[dimIndex];
  19108. };
  19109. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19110. return dataItem[property];
  19111. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19112. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19113. // dataItem is {coord: [...]}
  19114. var value = getDataItemValue(dataItem);
  19115. return !(value instanceof Array) ? value : value[dimIndex];
  19116. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19117. function getRawSourceValueGetter(sourceFormat) {
  19118. var method = rawSourceValueGetterMap[sourceFormat];
  19119. if ("development" !== 'production') {
  19120. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  19121. }
  19122. return method;
  19123. }
  19124. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19125. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19126. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19127. // Consider persistent.
  19128. // Caution: why use raw value to display on label or tooltip?
  19129. // A reason is to avoid format. For example time value we do not know
  19130. // how to format is expected. More over, if stack is used, calculated
  19131. // value may be 0.91000000001, which have brings trouble to display.
  19132. // TODO: consider how to treat null/undefined/NaN when display?
  19133. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19134. // Otherwise, return OptionDataValue.
  19135. dim) {
  19136. if (!data) {
  19137. return;
  19138. } // Consider data may be not persistent.
  19139. var dataItem = data.getRawDataItem(dataIndex);
  19140. if (dataItem == null) {
  19141. return;
  19142. }
  19143. var store = data.getStore();
  19144. var sourceFormat = store.getSource().sourceFormat;
  19145. if (dim != null) {
  19146. var dimIndex = data.getDimensionIndex(dim);
  19147. var property = store.getDimensionProperty(dimIndex);
  19148. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19149. } else {
  19150. var result = dataItem;
  19151. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19152. result = getDataItemValue(dataItem);
  19153. }
  19154. return result;
  19155. }
  19156. }
  19157. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19158. var DataFormatMixin =
  19159. /** @class */
  19160. function () {
  19161. function DataFormatMixin() {}
  19162. /**
  19163. * Get params for formatter
  19164. */
  19165. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19166. var data = this.getData(dataType);
  19167. var rawValue = this.getRawValue(dataIndex, dataType);
  19168. var rawDataIndex = data.getRawIndex(dataIndex);
  19169. var name = data.getName(dataIndex);
  19170. var itemOpt = data.getRawDataItem(dataIndex);
  19171. var style = data.getItemVisual(dataIndex, 'style');
  19172. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19173. var borderColor = style && style.stroke;
  19174. var mainType = this.mainType;
  19175. var isSeries = mainType === 'series';
  19176. var userOutput = data.userOutput && data.userOutput.get();
  19177. return {
  19178. componentType: mainType,
  19179. componentSubType: this.subType,
  19180. componentIndex: this.componentIndex,
  19181. seriesType: isSeries ? this.subType : null,
  19182. seriesIndex: this.seriesIndex,
  19183. seriesId: isSeries ? this.id : null,
  19184. seriesName: isSeries ? this.name : null,
  19185. name: name,
  19186. dataIndex: rawDataIndex,
  19187. data: itemOpt,
  19188. dataType: dataType,
  19189. value: rawValue,
  19190. color: color,
  19191. borderColor: borderColor,
  19192. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19193. encode: userOutput ? userOutput.encode : null,
  19194. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19195. $vars: ['seriesName', 'name', 'value']
  19196. };
  19197. };
  19198. /**
  19199. * Format label
  19200. * @param dataIndex
  19201. * @param status 'normal' by default
  19202. * @param dataType
  19203. * @param labelDimIndex Only used in some chart that
  19204. * use formatter in different dimensions, like radar.
  19205. * @param formatter Formatter given outside.
  19206. * @return return null/undefined if no formatter
  19207. */
  19208. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19209. status = status || 'normal';
  19210. var data = this.getData(dataType);
  19211. var params = this.getDataParams(dataIndex, dataType);
  19212. if (extendParams) {
  19213. params.value = extendParams.interpolatedValue;
  19214. }
  19215. if (labelDimIndex != null && isArray(params.value)) {
  19216. params.value = params.value[labelDimIndex];
  19217. }
  19218. if (!formatter) {
  19219. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19220. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19221. }
  19222. if (isFunction(formatter)) {
  19223. params.status = status;
  19224. params.dimensionIndex = labelDimIndex;
  19225. return formatter(params);
  19226. } else if (isString(formatter)) {
  19227. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19228. // Do not support '}' in dim name util have to.
  19229. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19230. var len = dimStr.length;
  19231. var dimLoose = dimStr;
  19232. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19233. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19234. if ("development" !== 'production') {
  19235. if (isNaN(dimLoose)) {
  19236. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19237. }
  19238. }
  19239. }
  19240. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19241. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19242. var dimIndex = data.getDimensionIndex(dimLoose);
  19243. if (dimIndex >= 0) {
  19244. val = extendParams.interpolatedValue[dimIndex];
  19245. }
  19246. }
  19247. return val != null ? val + '' : '';
  19248. });
  19249. }
  19250. };
  19251. /**
  19252. * Get raw value in option
  19253. */
  19254. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19255. return retrieveRawValue(this.getData(dataType), idx);
  19256. };
  19257. /**
  19258. * Should be implemented.
  19259. * @param {number} dataIndex
  19260. * @param {boolean} [multipleSeries=false]
  19261. * @param {string} [dataType]
  19262. */
  19263. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19264. // Empty function
  19265. return;
  19266. };
  19267. return DataFormatMixin;
  19268. }();
  19269. // but guess little chance has been used outside. Do we need to backward
  19270. // compat it?
  19271. // type TooltipFormatResultLegacyObject = {
  19272. // // `html` means the markup language text, either in 'html' or 'richText'.
  19273. // // The name `html` is not appropriate becuase in 'richText' it is not a HTML
  19274. // // string. But still support it for backward compat.
  19275. // html: string;
  19276. // markers: Dictionary<ColorString>;
  19277. // };
  19278. /**
  19279. * For backward compat, normalize the return from `formatTooltip`.
  19280. */
  19281. function normalizeTooltipFormatResult(result) {
  19282. var markupText; // let markers: Dictionary<ColorString>;
  19283. var markupFragment;
  19284. if (isObject(result)) {
  19285. if (result.type) {
  19286. markupFragment = result;
  19287. } else {
  19288. if ("development" !== 'production') {
  19289. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19290. }
  19291. } // else {
  19292. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19293. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19294. // if (markersExisting) {
  19295. // markers = zrUtil.merge(markersExisting, markers);
  19296. // }
  19297. // }
  19298. } else {
  19299. markupText = result;
  19300. }
  19301. return {
  19302. text: markupText,
  19303. // markers: markers || markersExisting,
  19304. frag: markupFragment
  19305. };
  19306. }
  19307. /**
  19308. * @param {Object} define
  19309. * @return See the return of `createTask`.
  19310. */
  19311. function createTask(define) {
  19312. return new Task(define);
  19313. }
  19314. var Task =
  19315. /** @class */
  19316. function () {
  19317. function Task(define) {
  19318. define = define || {};
  19319. this._reset = define.reset;
  19320. this._plan = define.plan;
  19321. this._count = define.count;
  19322. this._onDirty = define.onDirty;
  19323. this._dirty = true;
  19324. }
  19325. /**
  19326. * @param step Specified step.
  19327. * @param skip Skip customer perform call.
  19328. * @param modBy Sampling window size.
  19329. * @param modDataCount Sampling count.
  19330. * @return whether unfinished.
  19331. */
  19332. Task.prototype.perform = function (performArgs) {
  19333. var upTask = this._upstream;
  19334. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19335. // Pull data. Must pull data each time, because context.data
  19336. // may be updated by Series.setData.
  19337. if (this._dirty && upTask) {
  19338. var context = this.context;
  19339. context.data = context.outputData = upTask.context.outputData;
  19340. }
  19341. if (this.__pipeline) {
  19342. this.__pipeline.currentTask = this;
  19343. }
  19344. var planResult;
  19345. if (this._plan && !skip) {
  19346. planResult = this._plan(this.context);
  19347. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19348. // elements uniformed distributed when progress, especially when moving or zooming.
  19349. var lastModBy = normalizeModBy(this._modBy);
  19350. var lastModDataCount = this._modDataCount || 0;
  19351. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19352. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19353. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19354. planResult = 'reset';
  19355. }
  19356. function normalizeModBy(val) {
  19357. !(val >= 1) && (val = 1); // jshint ignore:line
  19358. return val;
  19359. }
  19360. var forceFirstProgress;
  19361. if (this._dirty || planResult === 'reset') {
  19362. this._dirty = false;
  19363. forceFirstProgress = this._doReset(skip);
  19364. }
  19365. this._modBy = modBy;
  19366. this._modDataCount = modDataCount;
  19367. var step = performArgs && performArgs.step;
  19368. if (upTask) {
  19369. if ("development" !== 'production') {
  19370. assert(upTask._outputDueEnd != null);
  19371. }
  19372. this._dueEnd = upTask._outputDueEnd;
  19373. } // DataTask or overallTask
  19374. else {
  19375. if ("development" !== 'production') {
  19376. assert(!this._progress || this._count);
  19377. }
  19378. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19379. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19380. // If no progress, pass index from upstream to downstream each time plan called.
  19381. if (this._progress) {
  19382. var start = this._dueIndex;
  19383. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19384. if (!skip && (forceFirstProgress || start < end)) {
  19385. var progress = this._progress;
  19386. if (isArray(progress)) {
  19387. for (var i = 0; i < progress.length; i++) {
  19388. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19389. }
  19390. } else {
  19391. this._doProgress(progress, start, end, modBy, modDataCount);
  19392. }
  19393. }
  19394. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19395. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19396. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19397. if ("development" !== 'production') {
  19398. // ??? Can not rollback.
  19399. assert(outputDueEnd >= this._outputDueEnd);
  19400. }
  19401. this._outputDueEnd = outputDueEnd;
  19402. } else {
  19403. // (1) Some overall task has no progress.
  19404. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19405. // This should always be performed so it can be passed to downstream.
  19406. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19407. }
  19408. return this.unfinished();
  19409. };
  19410. Task.prototype.dirty = function () {
  19411. this._dirty = true;
  19412. this._onDirty && this._onDirty(this.context);
  19413. };
  19414. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19415. iterator.reset(start, end, modBy, modDataCount);
  19416. this._callingProgress = progress;
  19417. this._callingProgress({
  19418. start: start,
  19419. end: end,
  19420. count: end - start,
  19421. next: iterator.next
  19422. }, this.context);
  19423. };
  19424. Task.prototype._doReset = function (skip) {
  19425. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19426. this._settedOutputEnd = null;
  19427. var progress;
  19428. var forceFirstProgress;
  19429. if (!skip && this._reset) {
  19430. progress = this._reset(this.context);
  19431. if (progress && progress.progress) {
  19432. forceFirstProgress = progress.forceFirstProgress;
  19433. progress = progress.progress;
  19434. } // To simplify no progress checking, array must has item.
  19435. if (isArray(progress) && !progress.length) {
  19436. progress = null;
  19437. }
  19438. }
  19439. this._progress = progress;
  19440. this._modBy = this._modDataCount = null;
  19441. var downstream = this._downstream;
  19442. downstream && downstream.dirty();
  19443. return forceFirstProgress;
  19444. };
  19445. Task.prototype.unfinished = function () {
  19446. return this._progress && this._dueIndex < this._dueEnd;
  19447. };
  19448. /**
  19449. * @param downTask The downstream task.
  19450. * @return The downstream task.
  19451. */
  19452. Task.prototype.pipe = function (downTask) {
  19453. if ("development" !== 'production') {
  19454. assert(downTask && !downTask._disposed && downTask !== this);
  19455. } // If already downstream, do not dirty downTask.
  19456. if (this._downstream !== downTask || this._dirty) {
  19457. this._downstream = downTask;
  19458. downTask._upstream = this;
  19459. downTask.dirty();
  19460. }
  19461. };
  19462. Task.prototype.dispose = function () {
  19463. if (this._disposed) {
  19464. return;
  19465. }
  19466. this._upstream && (this._upstream._downstream = null);
  19467. this._downstream && (this._downstream._upstream = null);
  19468. this._dirty = false;
  19469. this._disposed = true;
  19470. };
  19471. Task.prototype.getUpstream = function () {
  19472. return this._upstream;
  19473. };
  19474. Task.prototype.getDownstream = function () {
  19475. return this._downstream;
  19476. };
  19477. Task.prototype.setOutputEnd = function (end) {
  19478. // This only happend in dataTask, dataZoom, map, currently.
  19479. // where dataZoom do not set end each time, but only set
  19480. // when reset. So we should record the setted end, in case
  19481. // that the stub of dataZoom perform again and earse the
  19482. // setted end by upstream.
  19483. this._outputDueEnd = this._settedOutputEnd = end;
  19484. };
  19485. return Task;
  19486. }();
  19487. var iterator = function () {
  19488. var end;
  19489. var current;
  19490. var modBy;
  19491. var modDataCount;
  19492. var winCount;
  19493. var it = {
  19494. reset: function (s, e, sStep, sCount) {
  19495. current = s;
  19496. end = e;
  19497. modBy = sStep;
  19498. modDataCount = sCount;
  19499. winCount = Math.ceil(modDataCount / modBy);
  19500. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19501. }
  19502. };
  19503. return it;
  19504. function sequentialNext() {
  19505. return current < end ? current++ : null;
  19506. }
  19507. function modNext() {
  19508. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19509. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19510. // Use normal linear rendering mode.
  19511. : current;
  19512. current++;
  19513. return result;
  19514. }
  19515. }(); ///////////////////////////////////////////////////////////
  19516. // For stream debug (Should be commented out after used!)
  19517. // @usage: printTask(this, 'begin');
  19518. // @usage: printTask(this, null, {someExtraProp});
  19519. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19520. //
  19521. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19522. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19523. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19524. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19525. // let props = [];
  19526. // if (task.__pipeline) {
  19527. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19528. // props.push({text: '__idxInPipeline/total', value: val});
  19529. // } else {
  19530. // let stubCount = 0;
  19531. // task.agentStubMap.each(() => stubCount++);
  19532. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19533. // }
  19534. // props.push({text: 'uid', value: task.uidDebug});
  19535. // if (task.__pipeline) {
  19536. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19537. // task.agent && props.push(
  19538. // {text: 'stubFor', value: task.agent.uidDebug}
  19539. // );
  19540. // }
  19541. // props.push(
  19542. // {text: 'dirty', value: task._dirty},
  19543. // {text: 'dueIndex', value: task._dueIndex},
  19544. // {text: 'dueEnd', value: task._dueEnd},
  19545. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19546. // );
  19547. // if (extra) {
  19548. // Object.keys(extra).forEach(key => {
  19549. // props.push({text: key, value: extra[key]});
  19550. // });
  19551. // }
  19552. // let args = ['color: blue'];
  19553. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19554. // args.push('color: green', 'color: red'),
  19555. // `${item.text}: %c${item.value}`
  19556. // )).join('%c, ');
  19557. // console.log.apply(console, [msg].concat(args));
  19558. // // console.log(this);
  19559. // };
  19560. // window.printPipeline = function (task: any, prefix: string) {
  19561. // const pipeline = task.__pipeline;
  19562. // let currTask = pipeline.head;
  19563. // while (currTask) {
  19564. // window.printTask(currTask, prefix);
  19565. // currTask = currTask._downstream;
  19566. // }
  19567. // };
  19568. // window.showChain = function (chainHeadTask) {
  19569. // var chain = [];
  19570. // var task = chainHeadTask;
  19571. // while (task) {
  19572. // chain.push({
  19573. // task: task,
  19574. // up: task._upstream,
  19575. // down: task._downstream,
  19576. // idxInPipeline: task.__idxInPipeline
  19577. // });
  19578. // task = task._downstream;
  19579. // }
  19580. // return chain;
  19581. // };
  19582. // window.findTaskInChain = function (task, chainHeadTask) {
  19583. // let chain = window.showChain(chainHeadTask);
  19584. // let result = [];
  19585. // for (let i = 0; i < chain.length; i++) {
  19586. // let chainItem = chain[i];
  19587. // if (chainItem.task === task) {
  19588. // result.push(i);
  19589. // }
  19590. // }
  19591. // return result;
  19592. // };
  19593. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19594. // let chainA = window.showChain(chainHeadTaskA);
  19595. // for (let i = 0; i < chainA.length; i++) {
  19596. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19597. // }
  19598. // };
  19599. /**
  19600. * Convert raw the value in to inner value in List.
  19601. *
  19602. * [Performance sensitive]
  19603. *
  19604. * [Caution]: this is the key logic of user value parser.
  19605. * For backward compatibiliy, do not modify it until have to!
  19606. */
  19607. function parseDataValue(value, // For high performance, do not omit the second param.
  19608. opt) {
  19609. // Performance sensitive.
  19610. var dimType = opt && opt.type;
  19611. if (dimType === 'ordinal') {
  19612. // If given value is a category string
  19613. return value;
  19614. }
  19615. if (dimType === 'time' // spead up when using timestamp
  19616. && !isNumber(value) && value != null && value !== '-') {
  19617. value = +parseDate(value);
  19618. } // dimType defaults 'number'.
  19619. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19620. // parse to NaN.
  19621. // number-like string (like ' 123 ') can be converted to a number.
  19622. // where null/undefined or other string will be converted to NaN.
  19623. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19624. // If object, also parse to NaN
  19625. : +value;
  19626. }
  19627. var valueParserMap = createHashMap({
  19628. 'number': function (val) {
  19629. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  19630. // Here the number parser can have loose rule:
  19631. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19632. return parseFloat(val);
  19633. },
  19634. 'time': function (val) {
  19635. // return timestamp.
  19636. return +parseDate(val);
  19637. },
  19638. 'trim': function (val) {
  19639. return isString(val) ? trim(val) : val;
  19640. }
  19641. });
  19642. var SortOrderComparator =
  19643. /** @class */
  19644. function () {
  19645. /**
  19646. * @param order by defualt: 'asc'
  19647. * @param incomparable by defualt: Always on the tail.
  19648. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19649. * See the definition of "incomparable" in [SORT_COMPARISON_RULE]
  19650. */
  19651. function SortOrderComparator(order, incomparable) {
  19652. var isDesc = order === 'desc';
  19653. this._resultLT = isDesc ? 1 : -1;
  19654. if (incomparable == null) {
  19655. incomparable = isDesc ? 'min' : 'max';
  19656. }
  19657. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19658. } // See [SORT_COMPARISON_RULE].
  19659. // Performance sensitive.
  19660. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  19661. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19662. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  19663. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  19664. var lvalNotNumeric = isNaN(lvalFloat);
  19665. var rvalNotNumeric = isNaN(rvalFloat);
  19666. if (lvalNotNumeric) {
  19667. lvalFloat = this._incomparable;
  19668. }
  19669. if (rvalNotNumeric) {
  19670. rvalFloat = this._incomparable;
  19671. }
  19672. if (lvalNotNumeric && rvalNotNumeric) {
  19673. var lvalIsStr = isString(lval);
  19674. var rvalIsStr = isString(rval);
  19675. if (lvalIsStr) {
  19676. lvalFloat = rvalIsStr ? lval : 0;
  19677. }
  19678. if (rvalIsStr) {
  19679. rvalFloat = lvalIsStr ? rval : 0;
  19680. }
  19681. }
  19682. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  19683. };
  19684. return SortOrderComparator;
  19685. }();
  19686. /**
  19687. * TODO: disable writable.
  19688. * This structure will be exposed to users.
  19689. */
  19690. var ExternalSource =
  19691. /** @class */
  19692. function () {
  19693. function ExternalSource() {}
  19694. ExternalSource.prototype.getRawData = function () {
  19695. // Only built-in transform available.
  19696. throw new Error('not supported');
  19697. };
  19698. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19699. // Only built-in transform available.
  19700. throw new Error('not supported');
  19701. };
  19702. ExternalSource.prototype.cloneRawData = function () {
  19703. return;
  19704. };
  19705. /**
  19706. * @return If dimension not found, return null/undefined.
  19707. */
  19708. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19709. return;
  19710. };
  19711. /**
  19712. * dimensions defined if and only if either:
  19713. * (a) dataset.dimensions are declared.
  19714. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19715. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19716. * the defined dimensions.
  19717. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19718. * @return Always return an array (even empty array).
  19719. */
  19720. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19721. return;
  19722. };
  19723. ExternalSource.prototype.count = function () {
  19724. return;
  19725. };
  19726. /**
  19727. * Only support by dimension index.
  19728. * No need to support by dimension name in transform function,
  19729. * becuase transform function is not case-specific, no need to use name literally.
  19730. */
  19731. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19732. return;
  19733. };
  19734. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19735. return;
  19736. };
  19737. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19738. return parseDataValue(rawVal, dimInfo);
  19739. };
  19740. return ExternalSource;
  19741. }();
  19742. function createExternalSource(internalSource, externalTransform) {
  19743. var extSource = new ExternalSource();
  19744. var data = internalSource.data;
  19745. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19746. var sourceHeaderCount = internalSource.startIndex;
  19747. var errMsg = '';
  19748. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19749. // For the logic simplicity in transformer, only 'culumn' is
  19750. // supported in data transform. Otherwise, the `dimensionsDefine`
  19751. // might be detected by 'row', which probably confuses users.
  19752. if ("development" !== 'production') {
  19753. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19754. }
  19755. throwError(errMsg);
  19756. } // [MEMO]
  19757. // Create a new dimensions structure for exposing.
  19758. // Do not expose all dimension info to users directly.
  19759. // Becuase the dimension is probably auto detected from data and not might reliable.
  19760. // Should not lead the transformers to think that is relialbe and return it.
  19761. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19762. var dimensions = [];
  19763. var dimsByName = {};
  19764. var dimsDef = internalSource.dimensionsDefine;
  19765. if (dimsDef) {
  19766. each(dimsDef, function (dimDef, idx) {
  19767. var name = dimDef.name;
  19768. var dimDefExt = {
  19769. index: idx,
  19770. name: name,
  19771. displayName: dimDef.displayName
  19772. };
  19773. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  19774. // do not generate dimension name.
  19775. if (name != null) {
  19776. // Dimension name should not be duplicated.
  19777. // For simplicity, data transform forbid name duplication, do not generate
  19778. // new name like module `completeDimensions.ts` did, but just tell users.
  19779. var errMsg_1 = '';
  19780. if (hasOwn(dimsByName, name)) {
  19781. if ("development" !== 'production') {
  19782. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19783. }
  19784. throwError(errMsg_1);
  19785. }
  19786. dimsByName[name] = dimDefExt;
  19787. }
  19788. });
  19789. } // If dimension definitions are not defined and can not be detected.
  19790. // e.g., pure data `[[11, 22], ...]`.
  19791. else {
  19792. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19793. // Do not generete name or anything others. The consequence process in
  19794. // `transform` or `series` probably have there own name generation strategry.
  19795. dimensions.push({
  19796. index: i
  19797. });
  19798. }
  19799. } // Implement public methods:
  19800. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19801. if (externalTransform.__isBuiltIn) {
  19802. extSource.getRawDataItem = function (dataIndex) {
  19803. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19804. };
  19805. extSource.getRawData = bind(getRawData, null, internalSource);
  19806. }
  19807. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19808. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19809. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19810. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19811. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19812. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19813. return retrieveValueFromItem(rawItem, dimIndex);
  19814. };
  19815. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19816. if (dataItem == null) {
  19817. return;
  19818. }
  19819. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19820. if (dimDef) {
  19821. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19822. }
  19823. };
  19824. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19825. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19826. return extSource;
  19827. }
  19828. function getRawData(upstream) {
  19829. var sourceFormat = upstream.sourceFormat;
  19830. if (!isSupportedSourceFormat(sourceFormat)) {
  19831. var errMsg = '';
  19832. if ("development" !== 'production') {
  19833. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19834. }
  19835. throwError(errMsg);
  19836. }
  19837. return upstream.data;
  19838. }
  19839. function cloneRawData(upstream) {
  19840. var sourceFormat = upstream.sourceFormat;
  19841. var data = upstream.data;
  19842. if (!isSupportedSourceFormat(sourceFormat)) {
  19843. var errMsg = '';
  19844. if ("development" !== 'production') {
  19845. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19846. }
  19847. throwError(errMsg);
  19848. }
  19849. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19850. var result = [];
  19851. for (var i = 0, len = data.length; i < len; i++) {
  19852. // Not strictly clone for performance
  19853. result.push(data[i].slice());
  19854. }
  19855. return result;
  19856. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19857. var result = [];
  19858. for (var i = 0, len = data.length; i < len; i++) {
  19859. // Not strictly clone for performance
  19860. result.push(extend({}, data[i]));
  19861. }
  19862. return result;
  19863. }
  19864. }
  19865. function getDimensionInfo(dimensions, dimsByName, dim) {
  19866. if (dim == null) {
  19867. return;
  19868. } // Keep the same logic as `List::getDimension` did.
  19869. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  19870. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19871. return dimensions[dim];
  19872. } else if (hasOwn(dimsByName, dim)) {
  19873. return dimsByName[dim];
  19874. }
  19875. }
  19876. function cloneAllDimensionInfo(dimensions) {
  19877. return clone(dimensions);
  19878. }
  19879. var externalTransformMap = createHashMap();
  19880. function registerExternalTransform(externalTransform) {
  19881. externalTransform = clone(externalTransform);
  19882. var type = externalTransform.type;
  19883. var errMsg = '';
  19884. if (!type) {
  19885. if ("development" !== 'production') {
  19886. errMsg = 'Must have a `type` when `registerTransform`.';
  19887. }
  19888. throwError(errMsg);
  19889. }
  19890. var typeParsed = type.split(':');
  19891. if (typeParsed.length !== 2) {
  19892. if ("development" !== 'production') {
  19893. errMsg = 'Name must include namespace like "ns:regression".';
  19894. }
  19895. throwError(errMsg);
  19896. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19897. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19898. var isBuiltIn = false;
  19899. if (typeParsed[0] === 'echarts') {
  19900. type = typeParsed[1];
  19901. isBuiltIn = true;
  19902. }
  19903. externalTransform.__isBuiltIn = isBuiltIn;
  19904. externalTransformMap.set(type, externalTransform);
  19905. }
  19906. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19907. var pipedTransOption = normalizeToArray(rawTransOption);
  19908. var pipeLen = pipedTransOption.length;
  19909. var errMsg = '';
  19910. if (!pipeLen) {
  19911. if ("development" !== 'production') {
  19912. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19913. }
  19914. throwError(errMsg);
  19915. }
  19916. for (var i = 0, len = pipeLen; i < len; i++) {
  19917. var transOption = pipedTransOption[i];
  19918. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  19919. // piped transform only support single output, except the last one.
  19920. if (i !== len - 1) {
  19921. sourceList.length = Math.max(sourceList.length, 1);
  19922. }
  19923. }
  19924. return sourceList;
  19925. }
  19926. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  19927. pipeIndex) {
  19928. var errMsg = '';
  19929. if (!upSourceList.length) {
  19930. if ("development" !== 'production') {
  19931. errMsg = 'Must have at least one upstream dataset.';
  19932. }
  19933. throwError(errMsg);
  19934. }
  19935. if (!isObject(transOption)) {
  19936. if ("development" !== 'production') {
  19937. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19938. }
  19939. throwError(errMsg);
  19940. }
  19941. var transType = transOption.type;
  19942. var externalTransform = externalTransformMap.get(transType);
  19943. if (!externalTransform) {
  19944. if ("development" !== 'production') {
  19945. errMsg = 'Can not find transform on type "' + transType + '".';
  19946. }
  19947. throwError(errMsg);
  19948. } // Prepare source
  19949. var extUpSourceList = map(upSourceList, function (upSource) {
  19950. return createExternalSource(upSource, externalTransform);
  19951. });
  19952. var resultList = normalizeToArray(externalTransform.transform({
  19953. upstream: extUpSourceList[0],
  19954. upstreamList: extUpSourceList,
  19955. config: clone(transOption.config)
  19956. }));
  19957. if ("development" !== 'production') {
  19958. if (transOption.print) {
  19959. var printStrArr = map(resultList, function (extSource) {
  19960. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19961. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19962. }).join('\n');
  19963. log(printStrArr);
  19964. }
  19965. }
  19966. return map(resultList, function (result, resultIndex) {
  19967. var errMsg = '';
  19968. if (!isObject(result)) {
  19969. if ("development" !== 'production') {
  19970. errMsg = 'A transform should not return some empty results.';
  19971. }
  19972. throwError(errMsg);
  19973. }
  19974. if (!result.data) {
  19975. if ("development" !== 'production') {
  19976. errMsg = 'Transform result data should be not be null or undefined';
  19977. }
  19978. throwError(errMsg);
  19979. }
  19980. var sourceFormat = detectSourceFormat(result.data);
  19981. if (!isSupportedSourceFormat(sourceFormat)) {
  19982. if ("development" !== 'production') {
  19983. errMsg = 'Transform result data should be array rows or object rows.';
  19984. }
  19985. throwError(errMsg);
  19986. }
  19987. var resultMetaRawOption;
  19988. var firstUpSource = upSourceList[0];
  19989. /**
  19990. * Intuitively, the end users known the content of the original `dataset.source`,
  19991. * calucating the transform result in mind.
  19992. * Suppose the original `dataset.source` is:
  19993. * ```js
  19994. * [
  19995. * ['product', '2012', '2013', '2014', '2015'],
  19996. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19997. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19998. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19999. * ]
  20000. * ```
  20001. * The dimension info have to be detected from the source data.
  20002. * Some of the transformers (like filter, sort) will follow the dimension info
  20003. * of upstream, while others use new dimensions (like aggregate).
  20004. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20005. * We also allow transformers to ignore the output `dimensions` field, and
  20006. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20007. * dimensions in transformers.
  20008. *
  20009. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20010. */
  20011. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20012. // dimensions definitions. We do not inherit anything from upstream.
  20013. && !result.dimensions) {
  20014. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  20015. // (1) The returned data always does not contain header line and can not be used
  20016. // as dimension-detection. In this case we can not use "detected dimensions" of
  20017. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20018. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20019. // So the original detected header should be add to the result, otherwise they can not be read.
  20020. if (startIndex) {
  20021. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20022. }
  20023. resultMetaRawOption = {
  20024. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20025. sourceHeader: startIndex,
  20026. dimensions: firstUpSource.metaRawOption.dimensions
  20027. };
  20028. } else {
  20029. resultMetaRawOption = {
  20030. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20031. sourceHeader: 0,
  20032. dimensions: result.dimensions
  20033. };
  20034. }
  20035. return createSource(result.data, resultMetaRawOption, null);
  20036. });
  20037. }
  20038. function isSupportedSourceFormat(sourceFormat) {
  20039. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20040. }
  20041. var UNDEFINED = 'undefined';
  20042. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20043. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20044. // different from the Ctor of typed array.
  20045. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20046. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20047. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20048. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20049. /**
  20050. * Multi dimensional data store
  20051. */
  20052. var dataCtors = {
  20053. 'float': CtorFloat64Array,
  20054. 'int': CtorInt32Array,
  20055. // Ordinal data type can be string or int
  20056. 'ordinal': Array,
  20057. 'number': Array,
  20058. 'time': CtorFloat64Array
  20059. };
  20060. var defaultDimValueGetters;
  20061. function getIndicesCtor(rawCount) {
  20062. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20063. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20064. }
  20065. function getInitialExtent() {
  20066. return [Infinity, -Infinity];
  20067. }
  20068. function cloneChunk(originalChunk) {
  20069. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20070. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20071. }
  20072. function prepareStore(store, dimIdx, dimType, end, append) {
  20073. var DataCtor = dataCtors[dimType || 'float'];
  20074. if (append) {
  20075. var oldStore = store[dimIdx];
  20076. var oldLen = oldStore && oldStore.length;
  20077. if (!(oldLen === end)) {
  20078. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20079. // within the initial chunkSize.
  20080. for (var j = 0; j < oldLen; j++) {
  20081. newStore[j] = oldStore[j];
  20082. }
  20083. store[dimIdx] = newStore;
  20084. }
  20085. } else {
  20086. store[dimIdx] = new DataCtor(end);
  20087. }
  20088. }
  20089. /**
  20090. * Basically, DataStore API keep immutable.
  20091. */
  20092. var DataStore =
  20093. /** @class */
  20094. function () {
  20095. function DataStore() {
  20096. this._chunks = []; // It will not be calculated util needed.
  20097. this._rawExtent = [];
  20098. this._extent = [];
  20099. this._count = 0;
  20100. this._rawCount = 0;
  20101. this._calcDimNameToIdx = createHashMap();
  20102. }
  20103. /**
  20104. * Initialize from data
  20105. */
  20106. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20107. if ("development" !== 'production') {
  20108. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.');
  20109. }
  20110. this._provider = provider; // Clear
  20111. this._chunks = [];
  20112. this._indices = null;
  20113. this.getRawIndex = this._getRawIdxIdentity;
  20114. var source = provider.getSource();
  20115. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20116. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20117. this._rawExtent = [];
  20118. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20119. this._dimensions = map(inputDimensions, function (dim) {
  20120. if ("development" !== 'production') {
  20121. if (willRetrieveDataByName) {
  20122. assert(dim.property != null);
  20123. }
  20124. }
  20125. return {
  20126. // Only pick these two props. Not leak other properties like orderMeta.
  20127. type: dim.type,
  20128. property: dim.property
  20129. };
  20130. });
  20131. this._initDataFromProvider(0, provider.count());
  20132. };
  20133. DataStore.prototype.getProvider = function () {
  20134. return this._provider;
  20135. };
  20136. /**
  20137. * Caution: even when a `source` instance owned by a series, the created data store
  20138. * may still be shared by different sereis (the source hash does not use all `source`
  20139. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20140. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20141. * thus should not be fetch here.
  20142. */
  20143. DataStore.prototype.getSource = function () {
  20144. return this._provider.getSource();
  20145. };
  20146. /**
  20147. * @caution Only used in dataStack.
  20148. */
  20149. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20150. var calcDimNameToIdx = this._calcDimNameToIdx;
  20151. var dimensions = this._dimensions;
  20152. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20153. if (calcDimIdx != null) {
  20154. if (dimensions[calcDimIdx].type === type) {
  20155. return calcDimIdx;
  20156. }
  20157. } else {
  20158. calcDimIdx = dimensions.length;
  20159. }
  20160. dimensions[calcDimIdx] = {
  20161. type: type
  20162. };
  20163. calcDimNameToIdx.set(dimName, calcDimIdx);
  20164. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20165. this._rawExtent[calcDimIdx] = getInitialExtent();
  20166. return calcDimIdx;
  20167. };
  20168. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20169. var chunk = this._chunks[dimIdx];
  20170. var dim = this._dimensions[dimIdx];
  20171. var rawExtents = this._rawExtent;
  20172. var offset = dim.ordinalOffset || 0;
  20173. var len = chunk.length;
  20174. if (offset === 0) {
  20175. // We need to reset the rawExtent if collect is from start.
  20176. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20177. rawExtents[dimIdx] = getInitialExtent();
  20178. }
  20179. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20180. for (var i = offset; i < len; i++) {
  20181. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20182. if (!isNaN(val)) {
  20183. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20184. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20185. }
  20186. }
  20187. dim.ordinalMeta = ordinalMeta;
  20188. dim.ordinalOffset = len;
  20189. dim.type = 'ordinal'; // Force to be ordinal
  20190. };
  20191. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20192. var dimInfo = this._dimensions[dimIdx];
  20193. var ordinalMeta = dimInfo.ordinalMeta;
  20194. return ordinalMeta;
  20195. };
  20196. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20197. var item = this._dimensions[dimIndex];
  20198. return item && item.property;
  20199. };
  20200. /**
  20201. * Caution: Can be only called on raw data (before `this._indices` created).
  20202. */
  20203. DataStore.prototype.appendData = function (data) {
  20204. if ("development" !== 'production') {
  20205. assert(!this._indices, 'appendData can only be called on raw data.');
  20206. }
  20207. var provider = this._provider;
  20208. var start = this.count();
  20209. provider.appendData(data);
  20210. var end = provider.count();
  20211. if (!provider.persistent) {
  20212. end += start;
  20213. }
  20214. if (start < end) {
  20215. this._initDataFromProvider(start, end, true);
  20216. }
  20217. return [start, end];
  20218. };
  20219. DataStore.prototype.appendValues = function (values, minFillLen) {
  20220. var chunks = this._chunks;
  20221. var dimensions = this._dimensions;
  20222. var dimLen = dimensions.length;
  20223. var rawExtent = this._rawExtent;
  20224. var start = this.count();
  20225. var end = start + Math.max(values.length, minFillLen || 0);
  20226. for (var i = 0; i < dimLen; i++) {
  20227. var dim = dimensions[i];
  20228. prepareStore(chunks, i, dim.type, end, true);
  20229. }
  20230. var emptyDataItem = [];
  20231. for (var idx = start; idx < end; idx++) {
  20232. var sourceIdx = idx - start; // Store the data by dimensions
  20233. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20234. var dim = dimensions[dimIdx];
  20235. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20236. chunks[dimIdx][idx] = val;
  20237. var dimRawExtent = rawExtent[dimIdx];
  20238. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20239. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20240. }
  20241. }
  20242. this._rawCount = this._count = end;
  20243. return {
  20244. start: start,
  20245. end: end
  20246. };
  20247. };
  20248. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20249. var provider = this._provider;
  20250. var chunks = this._chunks;
  20251. var dimensions = this._dimensions;
  20252. var dimLen = dimensions.length;
  20253. var rawExtent = this._rawExtent;
  20254. var dimNames = map(dimensions, function (dim) {
  20255. return dim.property;
  20256. });
  20257. for (var i = 0; i < dimLen; i++) {
  20258. var dim = dimensions[i];
  20259. if (!rawExtent[i]) {
  20260. rawExtent[i] = getInitialExtent();
  20261. }
  20262. prepareStore(chunks, i, dim.type, end, append);
  20263. }
  20264. if (provider.fillStorage) {
  20265. provider.fillStorage(start, end, chunks, rawExtent);
  20266. } else {
  20267. var dataItem = [];
  20268. for (var idx = start; idx < end; idx++) {
  20269. // NOTICE: Try not to write things into dataItem
  20270. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20271. // [1, 2]
  20272. // 2
  20273. // Bar chart, line chart which uses category axis
  20274. // only gives the 'y' value. 'x' value is the indices of category
  20275. // Use a tempValue to normalize the value to be a (x, y) value
  20276. // Store the data by dimensions
  20277. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20278. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20279. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20280. dimStorage[idx] = val;
  20281. var dimRawExtent = rawExtent[dimIdx];
  20282. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20283. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20284. }
  20285. }
  20286. }
  20287. if (!provider.persistent && provider.clean) {
  20288. // Clean unused data if data source is typed array.
  20289. provider.clean();
  20290. }
  20291. this._rawCount = this._count = end; // Reset data extent
  20292. this._extent = [];
  20293. };
  20294. DataStore.prototype.count = function () {
  20295. return this._count;
  20296. };
  20297. /**
  20298. * Get value. Return NaN if idx is out of range.
  20299. */
  20300. DataStore.prototype.get = function (dim, idx) {
  20301. if (!(idx >= 0 && idx < this._count)) {
  20302. return NaN;
  20303. }
  20304. var dimStore = this._chunks[dim];
  20305. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20306. };
  20307. DataStore.prototype.getValues = function (dimensions, idx) {
  20308. var values = [];
  20309. var dimArr = [];
  20310. if (idx == null) {
  20311. idx = dimensions; // TODO get all from store?
  20312. dimensions = []; // All dimensions
  20313. for (var i = 0; i < this._dimensions.length; i++) {
  20314. dimArr.push(i);
  20315. }
  20316. } else {
  20317. dimArr = dimensions;
  20318. }
  20319. for (var i = 0, len = dimArr.length; i < len; i++) {
  20320. values.push(this.get(dimArr[i], idx));
  20321. }
  20322. return values;
  20323. };
  20324. /**
  20325. * @param dim concrete dim
  20326. */
  20327. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20328. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20329. return NaN;
  20330. }
  20331. var dimStore = this._chunks[dim];
  20332. return dimStore ? dimStore[rawIdx] : NaN;
  20333. };
  20334. /**
  20335. * Get sum of data in one dimension
  20336. */
  20337. DataStore.prototype.getSum = function (dim) {
  20338. var dimData = this._chunks[dim];
  20339. var sum = 0;
  20340. if (dimData) {
  20341. for (var i = 0, len = this.count(); i < len; i++) {
  20342. var value = this.get(dim, i);
  20343. if (!isNaN(value)) {
  20344. sum += value;
  20345. }
  20346. }
  20347. }
  20348. return sum;
  20349. };
  20350. /**
  20351. * Get median of data in one dimension
  20352. */
  20353. DataStore.prototype.getMedian = function (dim) {
  20354. var dimDataArray = []; // map all data of one dimension
  20355. this.each([dim], function (val) {
  20356. if (!isNaN(val)) {
  20357. dimDataArray.push(val);
  20358. }
  20359. }); // TODO
  20360. // Use quick select?
  20361. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20362. return a - b;
  20363. });
  20364. var len = this.count(); // calculate median
  20365. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20366. };
  20367. /**
  20368. * Retreive the index with given raw data index
  20369. */
  20370. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20371. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20372. return -1;
  20373. }
  20374. if (!this._indices) {
  20375. return rawIndex;
  20376. } // Indices are ascending
  20377. var indices = this._indices; // If rawIndex === dataIndex
  20378. var rawDataIndex = indices[rawIndex];
  20379. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20380. return rawIndex;
  20381. }
  20382. var left = 0;
  20383. var right = this._count - 1;
  20384. while (left <= right) {
  20385. var mid = (left + right) / 2 | 0;
  20386. if (indices[mid] < rawIndex) {
  20387. left = mid + 1;
  20388. } else if (indices[mid] > rawIndex) {
  20389. right = mid - 1;
  20390. } else {
  20391. return mid;
  20392. }
  20393. }
  20394. return -1;
  20395. };
  20396. /**
  20397. * Retreive the index of nearest value
  20398. * @param dim
  20399. * @param value
  20400. * @param [maxDistance=Infinity]
  20401. * @return If and only if multiple indices has
  20402. * the same value, they are put to the result.
  20403. */
  20404. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20405. var chunks = this._chunks;
  20406. var dimData = chunks[dim];
  20407. var nearestIndices = [];
  20408. if (!dimData) {
  20409. return nearestIndices;
  20410. }
  20411. if (maxDistance == null) {
  20412. maxDistance = Infinity;
  20413. }
  20414. var minDist = Infinity;
  20415. var minDiff = -1;
  20416. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20417. for (var i = 0, len = this.count(); i < len; i++) {
  20418. var dataIndex = this.getRawIndex(i);
  20419. var diff = value - dimData[dataIndex];
  20420. var dist = Math.abs(diff);
  20421. if (dist <= maxDistance) {
  20422. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20423. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20424. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20425. // So we chose the one that `diff >= 0` in this csae.
  20426. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20427. // should be push to `nearestIndices`.
  20428. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20429. minDist = dist;
  20430. minDiff = diff;
  20431. nearestIndicesLen = 0;
  20432. }
  20433. if (diff === minDiff) {
  20434. nearestIndices[nearestIndicesLen++] = i;
  20435. }
  20436. }
  20437. }
  20438. nearestIndices.length = nearestIndicesLen;
  20439. return nearestIndices;
  20440. };
  20441. DataStore.prototype.getIndices = function () {
  20442. var newIndices;
  20443. var indices = this._indices;
  20444. if (indices) {
  20445. var Ctor = indices.constructor;
  20446. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20447. if (Ctor === Array) {
  20448. newIndices = new Ctor(thisCount);
  20449. for (var i = 0; i < thisCount; i++) {
  20450. newIndices[i] = indices[i];
  20451. }
  20452. } else {
  20453. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20454. }
  20455. } else {
  20456. var Ctor = getIndicesCtor(this._rawCount);
  20457. newIndices = new Ctor(this.count());
  20458. for (var i = 0; i < newIndices.length; i++) {
  20459. newIndices[i] = i;
  20460. }
  20461. }
  20462. return newIndices;
  20463. };
  20464. /**
  20465. * Data filter.
  20466. */
  20467. DataStore.prototype.filter = function (dims, cb) {
  20468. if (!this._count) {
  20469. return this;
  20470. }
  20471. var newStore = this.clone();
  20472. var count = newStore.count();
  20473. var Ctor = getIndicesCtor(newStore._rawCount);
  20474. var newIndices = new Ctor(count);
  20475. var value = [];
  20476. var dimSize = dims.length;
  20477. var offset = 0;
  20478. var dim0 = dims[0];
  20479. var chunks = newStore._chunks;
  20480. for (var i = 0; i < count; i++) {
  20481. var keep = void 0;
  20482. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20483. if (dimSize === 0) {
  20484. keep = cb(i);
  20485. } else if (dimSize === 1) {
  20486. var val = chunks[dim0][rawIdx];
  20487. keep = cb(val, i);
  20488. } else {
  20489. var k = 0;
  20490. for (; k < dimSize; k++) {
  20491. value[k] = chunks[dims[k]][rawIdx];
  20492. }
  20493. value[k] = i;
  20494. keep = cb.apply(null, value);
  20495. }
  20496. if (keep) {
  20497. newIndices[offset++] = rawIdx;
  20498. }
  20499. } // Set indices after filtered.
  20500. if (offset < count) {
  20501. newStore._indices = newIndices;
  20502. }
  20503. newStore._count = offset; // Reset data extent
  20504. newStore._extent = [];
  20505. newStore._updateGetRawIdx();
  20506. return newStore;
  20507. };
  20508. /**
  20509. * Select data in range. (For optimization of filter)
  20510. * (Manually inline code, support 5 million data filtering in data zoom.)
  20511. */
  20512. DataStore.prototype.selectRange = function (range) {
  20513. var newStore = this.clone();
  20514. var len = newStore._count;
  20515. if (!len) {
  20516. return this;
  20517. }
  20518. var dims = keys(range);
  20519. var dimSize = dims.length;
  20520. if (!dimSize) {
  20521. return this;
  20522. }
  20523. var originalCount = newStore.count();
  20524. var Ctor = getIndicesCtor(newStore._rawCount);
  20525. var newIndices = new Ctor(originalCount);
  20526. var offset = 0;
  20527. var dim0 = dims[0];
  20528. var min = range[dim0][0];
  20529. var max = range[dim0][1];
  20530. var storeArr = newStore._chunks;
  20531. var quickFinished = false;
  20532. if (!newStore._indices) {
  20533. // Extreme optimization for common case. About 2x faster in chrome.
  20534. var idx = 0;
  20535. if (dimSize === 1) {
  20536. var dimStorage = storeArr[dims[0]];
  20537. for (var i = 0; i < len; i++) {
  20538. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20539. // value indicates the line should be broken. But for the case like
  20540. // scatter plot, a data item with empty value will not be rendered,
  20541. // but the axis extent may be effected if some other dim of the data
  20542. // item has value. Fortunately it is not a significant negative effect.
  20543. if (val >= min && val <= max || isNaN(val)) {
  20544. newIndices[offset++] = idx;
  20545. }
  20546. idx++;
  20547. }
  20548. quickFinished = true;
  20549. } else if (dimSize === 2) {
  20550. var dimStorage = storeArr[dims[0]];
  20551. var dimStorage2 = storeArr[dims[1]];
  20552. var min2 = range[dims[1]][0];
  20553. var max2 = range[dims[1]][1];
  20554. for (var i = 0; i < len; i++) {
  20555. var val = dimStorage[i];
  20556. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20557. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20558. newIndices[offset++] = idx;
  20559. }
  20560. idx++;
  20561. }
  20562. quickFinished = true;
  20563. }
  20564. }
  20565. if (!quickFinished) {
  20566. if (dimSize === 1) {
  20567. for (var i = 0; i < originalCount; i++) {
  20568. var rawIndex = newStore.getRawIndex(i);
  20569. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20570. if (val >= min && val <= max || isNaN(val)) {
  20571. newIndices[offset++] = rawIndex;
  20572. }
  20573. }
  20574. } else {
  20575. for (var i = 0; i < originalCount; i++) {
  20576. var keep = true;
  20577. var rawIndex = newStore.getRawIndex(i);
  20578. for (var k = 0; k < dimSize; k++) {
  20579. var dimk = dims[k];
  20580. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20581. if (val < range[dimk][0] || val > range[dimk][1]) {
  20582. keep = false;
  20583. }
  20584. }
  20585. if (keep) {
  20586. newIndices[offset++] = newStore.getRawIndex(i);
  20587. }
  20588. }
  20589. }
  20590. } // Set indices after filtered.
  20591. if (offset < originalCount) {
  20592. newStore._indices = newIndices;
  20593. }
  20594. newStore._count = offset; // Reset data extent
  20595. newStore._extent = [];
  20596. newStore._updateGetRawIdx();
  20597. return newStore;
  20598. }; // /**
  20599. // * Data mapping to a plain array
  20600. // */
  20601. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  20602. // const result: any[] = [];
  20603. // this.each(dims, function () {
  20604. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  20605. // });
  20606. // return result;
  20607. // }
  20608. /**
  20609. * Data mapping to a new List with given dimensions
  20610. */
  20611. DataStore.prototype.map = function (dims, cb) {
  20612. // TODO only clone picked chunks.
  20613. var target = this.clone(dims);
  20614. this._updateDims(target, dims, cb);
  20615. return target;
  20616. };
  20617. /**
  20618. * @caution Danger!! Only used in dataStack.
  20619. */
  20620. DataStore.prototype.modify = function (dims, cb) {
  20621. this._updateDims(this, dims, cb);
  20622. };
  20623. DataStore.prototype._updateDims = function (target, dims, cb) {
  20624. var targetChunks = target._chunks;
  20625. var tmpRetValue = [];
  20626. var dimSize = dims.length;
  20627. var dataCount = target.count();
  20628. var values = [];
  20629. var rawExtent = target._rawExtent;
  20630. for (var i = 0; i < dims.length; i++) {
  20631. rawExtent[dims[i]] = getInitialExtent();
  20632. }
  20633. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  20634. var rawIndex = target.getRawIndex(dataIndex);
  20635. for (var k = 0; k < dimSize; k++) {
  20636. values[k] = targetChunks[dims[k]][rawIndex];
  20637. }
  20638. values[dimSize] = dataIndex;
  20639. var retValue = cb && cb.apply(null, values);
  20640. if (retValue != null) {
  20641. // a number or string (in oridinal dimension)?
  20642. if (typeof retValue !== 'object') {
  20643. tmpRetValue[0] = retValue;
  20644. retValue = tmpRetValue;
  20645. }
  20646. for (var i = 0; i < retValue.length; i++) {
  20647. var dim = dims[i];
  20648. var val = retValue[i];
  20649. var rawExtentOnDim = rawExtent[dim];
  20650. var dimStore = targetChunks[dim];
  20651. if (dimStore) {
  20652. dimStore[rawIndex] = val;
  20653. }
  20654. if (val < rawExtentOnDim[0]) {
  20655. rawExtentOnDim[0] = val;
  20656. }
  20657. if (val > rawExtentOnDim[1]) {
  20658. rawExtentOnDim[1] = val;
  20659. }
  20660. }
  20661. }
  20662. }
  20663. };
  20664. /**
  20665. * Large data down sampling using largest-triangle-three-buckets
  20666. * @param {string} valueDimension
  20667. * @param {number} targetCount
  20668. */
  20669. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  20670. var target = this.clone([valueDimension], true);
  20671. var targetStorage = target._chunks;
  20672. var dimStore = targetStorage[valueDimension];
  20673. var len = this.count();
  20674. var sampledIndex = 0;
  20675. var frameSize = Math.floor(1 / rate);
  20676. var currentRawIndex = this.getRawIndex(0);
  20677. var maxArea;
  20678. var area;
  20679. var nextRawIndex;
  20680. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  20681. newIndices[sampledIndex++] = currentRawIndex;
  20682. for (var i = 1; i < len - 1; i += frameSize) {
  20683. var nextFrameStart = Math.min(i + frameSize, len - 1);
  20684. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  20685. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  20686. var avgY = 0;
  20687. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  20688. var rawIndex = this.getRawIndex(idx);
  20689. var y = dimStore[rawIndex];
  20690. if (isNaN(y)) {
  20691. continue;
  20692. }
  20693. avgY += y;
  20694. }
  20695. avgY /= nextFrameEnd - nextFrameStart;
  20696. var frameStart = i;
  20697. var frameEnd = Math.min(i + frameSize, len);
  20698. var pointAX = i - 1;
  20699. var pointAY = dimStore[currentRawIndex];
  20700. maxArea = -1;
  20701. nextRawIndex = frameStart;
  20702. var firstNaNIndex = -1;
  20703. var countNaN = 0; // Find a point from current frame that construct a triangel with largest area with previous selected point
  20704. // And the average of next frame.
  20705. for (var idx = frameStart; idx < frameEnd; idx++) {
  20706. var rawIndex = this.getRawIndex(idx);
  20707. var y = dimStore[rawIndex];
  20708. if (isNaN(y)) {
  20709. countNaN++;
  20710. if (firstNaNIndex < 0) {
  20711. firstNaNIndex = rawIndex;
  20712. }
  20713. continue;
  20714. } // Calculate triangle area over three buckets
  20715. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  20716. if (area > maxArea) {
  20717. maxArea = area;
  20718. nextRawIndex = rawIndex; // Next a is this b
  20719. }
  20720. }
  20721. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  20722. // Append first NaN point in every bucket.
  20723. // It is necessary to ensure the correct order of indices.
  20724. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  20725. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  20726. }
  20727. newIndices[sampledIndex++] = nextRawIndex;
  20728. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  20729. } // First frame use the last data.
  20730. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  20731. target._count = sampledIndex;
  20732. target._indices = newIndices;
  20733. target.getRawIndex = this._getRawIdx;
  20734. return target;
  20735. };
  20736. /**
  20737. * Large data down sampling on given dimension
  20738. * @param sampleIndex Sample index for name and id
  20739. */
  20740. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20741. var target = this.clone([dimension], true);
  20742. var targetStorage = target._chunks;
  20743. var frameValues = [];
  20744. var frameSize = Math.floor(1 / rate);
  20745. var dimStore = targetStorage[dimension];
  20746. var len = this.count();
  20747. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  20748. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  20749. var offset = 0;
  20750. for (var i = 0; i < len; i += frameSize) {
  20751. // Last frame
  20752. if (frameSize > len - i) {
  20753. frameSize = len - i;
  20754. frameValues.length = frameSize;
  20755. }
  20756. for (var k = 0; k < frameSize; k++) {
  20757. var dataIdx = this.getRawIndex(i + k);
  20758. frameValues[k] = dimStore[dataIdx];
  20759. }
  20760. var value = sampleValue(frameValues);
  20761. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  20762. dimStore[sampleFrameIdx] = value;
  20763. if (value < rawExtentOnDim[0]) {
  20764. rawExtentOnDim[0] = value;
  20765. }
  20766. if (value > rawExtentOnDim[1]) {
  20767. rawExtentOnDim[1] = value;
  20768. }
  20769. newIndices[offset++] = sampleFrameIdx;
  20770. }
  20771. target._count = offset;
  20772. target._indices = newIndices;
  20773. target._updateGetRawIdx();
  20774. return target;
  20775. };
  20776. /**
  20777. * Data iteration
  20778. * @param ctx default this
  20779. * @example
  20780. * list.each('x', function (x, idx) {});
  20781. * list.each(['x', 'y'], function (x, y, idx) {});
  20782. * list.each(function (idx) {})
  20783. */
  20784. DataStore.prototype.each = function (dims, cb) {
  20785. if (!this._count) {
  20786. return;
  20787. }
  20788. var dimSize = dims.length;
  20789. var chunks = this._chunks;
  20790. for (var i = 0, len = this.count(); i < len; i++) {
  20791. var rawIdx = this.getRawIndex(i); // Simple optimization
  20792. switch (dimSize) {
  20793. case 0:
  20794. cb(i);
  20795. break;
  20796. case 1:
  20797. cb(chunks[dims[0]][rawIdx], i);
  20798. break;
  20799. case 2:
  20800. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  20801. break;
  20802. default:
  20803. var k = 0;
  20804. var value = [];
  20805. for (; k < dimSize; k++) {
  20806. value[k] = chunks[dims[k]][rawIdx];
  20807. } // Index
  20808. value[k] = i;
  20809. cb.apply(null, value);
  20810. }
  20811. }
  20812. };
  20813. /**
  20814. * Get extent of data in one dimension
  20815. */
  20816. DataStore.prototype.getDataExtent = function (dim) {
  20817. // Make sure use concrete dim as cache name.
  20818. var dimData = this._chunks[dim];
  20819. var initialExtent = getInitialExtent();
  20820. if (!dimData) {
  20821. return initialExtent;
  20822. } // Make more strict checkings to ensure hitting cache.
  20823. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  20824. // happened before filtering. We cache raw extent, which is not
  20825. // necessary to be cleared and recalculated when restore data.
  20826. var useRaw = !this._indices;
  20827. var dimExtent;
  20828. if (useRaw) {
  20829. return this._rawExtent[dim].slice();
  20830. }
  20831. dimExtent = this._extent[dim];
  20832. if (dimExtent) {
  20833. return dimExtent.slice();
  20834. }
  20835. dimExtent = initialExtent;
  20836. var min = dimExtent[0];
  20837. var max = dimExtent[1];
  20838. for (var i = 0; i < currEnd; i++) {
  20839. var rawIdx = this.getRawIndex(i);
  20840. var value = dimData[rawIdx];
  20841. value < min && (min = value);
  20842. value > max && (max = value);
  20843. }
  20844. dimExtent = [min, max];
  20845. this._extent[dim] = dimExtent;
  20846. return dimExtent;
  20847. };
  20848. /**
  20849. * Get raw data item
  20850. */
  20851. DataStore.prototype.getRawDataItem = function (idx) {
  20852. var rawIdx = this.getRawIndex(idx);
  20853. if (!this._provider.persistent) {
  20854. var val = [];
  20855. var chunks = this._chunks;
  20856. for (var i = 0; i < chunks.length; i++) {
  20857. val.push(chunks[i][rawIdx]);
  20858. }
  20859. return val;
  20860. } else {
  20861. return this._provider.getItem(rawIdx);
  20862. }
  20863. };
  20864. /**
  20865. * Clone shallow.
  20866. *
  20867. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  20868. */
  20869. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  20870. var target = new DataStore();
  20871. var chunks = this._chunks;
  20872. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  20873. obj[dimIdx] = true;
  20874. return obj;
  20875. }, {});
  20876. if (clonedDimsMap) {
  20877. for (var i = 0; i < chunks.length; i++) {
  20878. // Not clone if dim is not picked.
  20879. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  20880. }
  20881. } else {
  20882. target._chunks = chunks;
  20883. }
  20884. this._copyCommonProps(target);
  20885. if (!ignoreIndices) {
  20886. target._indices = this._cloneIndices();
  20887. }
  20888. target._updateGetRawIdx();
  20889. return target;
  20890. };
  20891. DataStore.prototype._copyCommonProps = function (target) {
  20892. target._count = this._count;
  20893. target._rawCount = this._rawCount;
  20894. target._provider = this._provider;
  20895. target._dimensions = this._dimensions;
  20896. target._extent = clone(this._extent);
  20897. target._rawExtent = clone(this._rawExtent);
  20898. };
  20899. DataStore.prototype._cloneIndices = function () {
  20900. if (this._indices) {
  20901. var Ctor = this._indices.constructor;
  20902. var indices = void 0;
  20903. if (Ctor === Array) {
  20904. var thisCount = this._indices.length;
  20905. indices = new Ctor(thisCount);
  20906. for (var i = 0; i < thisCount; i++) {
  20907. indices[i] = this._indices[i];
  20908. }
  20909. } else {
  20910. indices = new Ctor(this._indices);
  20911. }
  20912. return indices;
  20913. }
  20914. return null;
  20915. };
  20916. DataStore.prototype._getRawIdxIdentity = function (idx) {
  20917. return idx;
  20918. };
  20919. DataStore.prototype._getRawIdx = function (idx) {
  20920. if (idx < this._count && idx >= 0) {
  20921. return this._indices[idx];
  20922. }
  20923. return -1;
  20924. };
  20925. DataStore.prototype._updateGetRawIdx = function () {
  20926. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  20927. };
  20928. DataStore.internalField = function () {
  20929. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  20930. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  20931. }
  20932. defaultDimValueGetters = {
  20933. arrayRows: getDimValueSimply,
  20934. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  20935. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  20936. },
  20937. keyedColumns: getDimValueSimply,
  20938. original: function (dataItem, property, dataIndex, dimIndex) {
  20939. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20940. // If dataItem is an plain object with no value field, the let `value`
  20941. // will be assigned with the object, but it will be tread correctly
  20942. // in the `convertValue`.
  20943. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20944. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  20945. : value, this._dimensions[dimIndex]);
  20946. },
  20947. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  20948. return dataItem[dimIndex];
  20949. }
  20950. };
  20951. }();
  20952. return DataStore;
  20953. }();
  20954. /**
  20955. * [REQUIREMENT_MEMO]:
  20956. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  20957. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  20958. * `root-dataset`. Them on `series` has higher priority.
  20959. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  20960. * confuse users: whether those props indicate how to visit the upstream source or visit
  20961. * the transform result source, and some transforms has nothing to do with these props,
  20962. * and some transforms might have multiple upstream.
  20963. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  20964. * declared in `root-dataset`.
  20965. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  20966. * That is for reducing complexity in transfroms.
  20967. * PENDING: Whether to provide transposition transform?
  20968. *
  20969. * [IMPLEMENTAION_MEMO]:
  20970. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  20971. * They will not be calculated until `source` is about to be visited (to prevent from
  20972. * duplicate calcuation). `source` is visited only in series and input to transforms.
  20973. *
  20974. * [DIMENSION_INHERIT_RULE]:
  20975. * By default the dimensions are inherited from ancestors, unless a transform return
  20976. * a new dimensions definition.
  20977. * Consider the case:
  20978. * ```js
  20979. * dataset: [{
  20980. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  20981. * }, {
  20982. * transform: { type: 'filter', ... }
  20983. * }]
  20984. * dataset: [{
  20985. * dimension: ['Product', 'Sales', 'Prise'],
  20986. * source: [ ['Cookies', 321, 44.21], ...]
  20987. * }, {
  20988. * transform: { type: 'filter', ... }
  20989. * }]
  20990. * ```
  20991. * The two types of option should have the same behavior after transform.
  20992. *
  20993. *
  20994. * [SCENARIO]:
  20995. * (1) Provide source data directly:
  20996. * ```js
  20997. * series: {
  20998. * encode: {...},
  20999. * dimensions: [...]
  21000. * seriesLayoutBy: 'row',
  21001. * data: [[...]]
  21002. * }
  21003. * ```
  21004. * (2) Series refer to dataset.
  21005. * ```js
  21006. * series: [{
  21007. * encode: {...}
  21008. * // Ignore datasetIndex means `datasetIndex: 0`
  21009. * // and the dimensions defination in dataset is used
  21010. * }, {
  21011. * encode: {...},
  21012. * seriesLayoutBy: 'column',
  21013. * datasetIndex: 1
  21014. * }]
  21015. * ```
  21016. * (3) dataset transform
  21017. * ```js
  21018. * dataset: [{
  21019. * source: [...]
  21020. * }, {
  21021. * source: [...]
  21022. * }, {
  21023. * // By default from 0.
  21024. * transform: { type: 'filter', config: {...} }
  21025. * }, {
  21026. * // Piped.
  21027. * transform: [
  21028. * { type: 'filter', config: {...} },
  21029. * { type: 'sort', config: {...} }
  21030. * ]
  21031. * }, {
  21032. * id: 'regressionData',
  21033. * fromDatasetIndex: 1,
  21034. * // Third-party transform
  21035. * transform: { type: 'ecStat:regression', config: {...} }
  21036. * }, {
  21037. * // retrieve the extra result.
  21038. * id: 'regressionFormula',
  21039. * fromDatasetId: 'regressionData',
  21040. * fromTransformResult: 1
  21041. * }]
  21042. * ```
  21043. */
  21044. var SourceManager =
  21045. /** @class */
  21046. function () {
  21047. function SourceManager(sourceHost) {
  21048. // Cached source. Do not repeat calculating if not dirty.
  21049. this._sourceList = [];
  21050. this._storeList = []; // version sign of each upstream source manager.
  21051. this._upstreamSignList = [];
  21052. this._versionSignBase = 0;
  21053. this._dirty = true;
  21054. this._sourceHost = sourceHost;
  21055. }
  21056. /**
  21057. * Mark dirty.
  21058. */
  21059. SourceManager.prototype.dirty = function () {
  21060. this._setLocalSource([], []);
  21061. this._storeList = [];
  21062. this._dirty = true;
  21063. };
  21064. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21065. this._sourceList = sourceList;
  21066. this._upstreamSignList = upstreamSignList;
  21067. this._versionSignBase++;
  21068. if (this._versionSignBase > 9e10) {
  21069. this._versionSignBase = 0;
  21070. }
  21071. };
  21072. /**
  21073. * For detecting whether the upstream source is dirty, so that
  21074. * the local cached source (in `_sourceList`) should be discarded.
  21075. */
  21076. SourceManager.prototype._getVersionSign = function () {
  21077. return this._sourceHost.uid + '_' + this._versionSignBase;
  21078. };
  21079. /**
  21080. * Always return a source instance. Otherwise throw error.
  21081. */
  21082. SourceManager.prototype.prepareSource = function () {
  21083. // For the case that call `setOption` multiple time but no data changed,
  21084. // cache the result source to prevent from repeating transform.
  21085. if (this._isDirty()) {
  21086. this._createSource();
  21087. this._dirty = false;
  21088. }
  21089. };
  21090. SourceManager.prototype._createSource = function () {
  21091. this._setLocalSource([], []);
  21092. var sourceHost = this._sourceHost;
  21093. var upSourceMgrList = this._getUpstreamSourceManagers();
  21094. var hasUpstream = !!upSourceMgrList.length;
  21095. var resultSourceList;
  21096. var upstreamSignList;
  21097. if (isSeries(sourceHost)) {
  21098. var seriesModel = sourceHost;
  21099. var data = void 0;
  21100. var sourceFormat = void 0;
  21101. var upSource = void 0; // Has upstream dataset
  21102. if (hasUpstream) {
  21103. var upSourceMgr = upSourceMgrList[0];
  21104. upSourceMgr.prepareSource();
  21105. upSource = upSourceMgr.getSource();
  21106. data = upSource.data;
  21107. sourceFormat = upSource.sourceFormat;
  21108. upstreamSignList = [upSourceMgr._getVersionSign()];
  21109. } // Series data is from own.
  21110. else {
  21111. data = seriesModel.get('data', true);
  21112. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21113. upstreamSignList = [];
  21114. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21115. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21116. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21117. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21118. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21119. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21120. // but series need `seriesLayoutBy: 'row'`.
  21121. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21122. // to avoid extra memroy cost of high dimensional data.
  21123. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21124. resultSourceList = needsCreateSource ? [createSource(data, {
  21125. seriesLayoutBy: seriesLayoutBy,
  21126. sourceHeader: sourceHeader,
  21127. dimensions: dimensions
  21128. }, sourceFormat)] : [];
  21129. } else {
  21130. var datasetModel = sourceHost; // Has upstream dataset.
  21131. if (hasUpstream) {
  21132. var result = this._applyTransform(upSourceMgrList);
  21133. resultSourceList = result.sourceList;
  21134. upstreamSignList = result.upstreamSignList;
  21135. } // Is root dataset.
  21136. else {
  21137. var sourceData = datasetModel.get('source', true);
  21138. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21139. upstreamSignList = [];
  21140. }
  21141. }
  21142. if ("development" !== 'production') {
  21143. assert(resultSourceList && upstreamSignList);
  21144. }
  21145. this._setLocalSource(resultSourceList, upstreamSignList);
  21146. };
  21147. SourceManager.prototype._applyTransform = function (upMgrList) {
  21148. var datasetModel = this._sourceHost;
  21149. var transformOption = datasetModel.get('transform', true);
  21150. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21151. if ("development" !== 'production') {
  21152. assert(fromTransformResult != null || transformOption != null);
  21153. }
  21154. if (fromTransformResult != null) {
  21155. var errMsg = '';
  21156. if (upMgrList.length !== 1) {
  21157. if ("development" !== 'production') {
  21158. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21159. }
  21160. doThrow(errMsg);
  21161. }
  21162. }
  21163. var sourceList;
  21164. var upSourceList = [];
  21165. var upstreamSignList = [];
  21166. each(upMgrList, function (upMgr) {
  21167. upMgr.prepareSource();
  21168. var upSource = upMgr.getSource(fromTransformResult || 0);
  21169. var errMsg = '';
  21170. if (fromTransformResult != null && !upSource) {
  21171. if ("development" !== 'production') {
  21172. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21173. }
  21174. doThrow(errMsg);
  21175. }
  21176. upSourceList.push(upSource);
  21177. upstreamSignList.push(upMgr._getVersionSign());
  21178. });
  21179. if (transformOption) {
  21180. sourceList = applyDataTransform(transformOption, upSourceList, {
  21181. datasetIndex: datasetModel.componentIndex
  21182. });
  21183. } else if (fromTransformResult != null) {
  21184. sourceList = [cloneSourceShallow(upSourceList[0])];
  21185. }
  21186. return {
  21187. sourceList: sourceList,
  21188. upstreamSignList: upstreamSignList
  21189. };
  21190. };
  21191. SourceManager.prototype._isDirty = function () {
  21192. if (this._dirty) {
  21193. return true;
  21194. } // All sourceList is from the some upsteam.
  21195. var upSourceMgrList = this._getUpstreamSourceManagers();
  21196. for (var i = 0; i < upSourceMgrList.length; i++) {
  21197. var upSrcMgr = upSourceMgrList[i];
  21198. if ( // Consider the case that there is ancestor diry, call it recursively.
  21199. // The performance is probably not an issue because usually the chain is not long.
  21200. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21201. return true;
  21202. }
  21203. }
  21204. };
  21205. /**
  21206. * @param sourceIndex By defualt 0, means "main source".
  21207. * Most cases there is only one source.
  21208. */
  21209. SourceManager.prototype.getSource = function (sourceIndex) {
  21210. sourceIndex = sourceIndex || 0;
  21211. var source = this._sourceList[sourceIndex];
  21212. if (!source) {
  21213. // Series may share source instance with dataset.
  21214. var upSourceMgrList = this._getUpstreamSourceManagers();
  21215. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21216. }
  21217. return source;
  21218. };
  21219. /**
  21220. *
  21221. * Get a data store which can be shared across series.
  21222. * Only available for series.
  21223. *
  21224. * @param seriesDimRequest Dimensions that are generated in series.
  21225. * Should have been sorted by `storeDimIndex` asc.
  21226. */
  21227. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21228. if ("development" !== 'production') {
  21229. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21230. }
  21231. var schema = seriesDimRequest.makeStoreSchema();
  21232. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21233. };
  21234. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21235. // TODO Can use other sourceIndex?
  21236. var sourceIndex = 0;
  21237. var storeList = this._storeList;
  21238. var cachedStoreMap = storeList[sourceIndex];
  21239. if (!cachedStoreMap) {
  21240. cachedStoreMap = storeList[sourceIndex] = {};
  21241. }
  21242. var cachedStore = cachedStoreMap[sourceReadKey];
  21243. if (!cachedStore) {
  21244. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21245. if (isSeries(this._sourceHost) && upSourceMgr) {
  21246. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21247. } else {
  21248. cachedStore = new DataStore(); // Always create store from source of series.
  21249. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21250. }
  21251. cachedStoreMap[sourceReadKey] = cachedStore;
  21252. }
  21253. return cachedStore;
  21254. };
  21255. /**
  21256. * PEDING: Is it fast enough?
  21257. * If no upstream, return empty array.
  21258. */
  21259. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21260. // Always get the relationship from the raw option.
  21261. // Do not cache the link of the dependency graph, so that
  21262. // no need to update them when change happen.
  21263. var sourceHost = this._sourceHost;
  21264. if (isSeries(sourceHost)) {
  21265. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21266. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21267. } else {
  21268. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21269. return datasetModel.getSourceManager();
  21270. });
  21271. }
  21272. };
  21273. SourceManager.prototype._getSourceMetaRawOption = function () {
  21274. var sourceHost = this._sourceHost;
  21275. var seriesLayoutBy;
  21276. var sourceHeader;
  21277. var dimensions;
  21278. if (isSeries(sourceHost)) {
  21279. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21280. sourceHeader = sourceHost.get('sourceHeader', true);
  21281. dimensions = sourceHost.get('dimensions', true);
  21282. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21283. else if (!this._getUpstreamSourceManagers().length) {
  21284. var model = sourceHost;
  21285. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21286. sourceHeader = model.get('sourceHeader', true);
  21287. dimensions = model.get('dimensions', true);
  21288. }
  21289. return {
  21290. seriesLayoutBy: seriesLayoutBy,
  21291. sourceHeader: sourceHeader,
  21292. dimensions: dimensions
  21293. };
  21294. };
  21295. return SourceManager;
  21296. }();
  21297. // disable the transform merge, but do not disable transfrom clone from rawOption.
  21298. function disableTransformOptionMerge(datasetModel) {
  21299. var transformOption = datasetModel.option.transform;
  21300. transformOption && setAsPrimitive(datasetModel.option.transform);
  21301. }
  21302. function isSeries(sourceHost) {
  21303. // Avoid circular dependency with Series.ts
  21304. return sourceHost.mainType === 'series';
  21305. }
  21306. function doThrow(errMsg) {
  21307. throw new Error(errMsg);
  21308. }
  21309. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21310. function getTooltipTextStyle(textStyle, renderMode) {
  21311. var nameFontColor = textStyle.color || '#6e7079';
  21312. var nameFontSize = textStyle.fontSize || 12;
  21313. var nameFontWeight = textStyle.fontWeight || '400';
  21314. var valueFontColor = textStyle.color || '#464646';
  21315. var valueFontSize = textStyle.fontSize || 14;
  21316. var valueFontWeight = textStyle.fontWeight || '900';
  21317. if (renderMode === 'html') {
  21318. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21319. return {
  21320. // eslint-disable-next-line max-len
  21321. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21322. // eslint-disable-next-line max-len
  21323. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21324. };
  21325. } else {
  21326. return {
  21327. nameStyle: {
  21328. fontSize: nameFontSize,
  21329. fill: nameFontColor,
  21330. fontWeight: nameFontWeight
  21331. },
  21332. valueStyle: {
  21333. fontSize: valueFontSize,
  21334. fill: valueFontColor,
  21335. fontWeight: valueFontWeight
  21336. }
  21337. };
  21338. }
  21339. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21340. // (value from UI design)
  21341. var HTML_GAPS = [0, 10, 20, 30];
  21342. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21343. function createTooltipMarkup(type, option) {
  21344. option.type = type;
  21345. return option;
  21346. }
  21347. function isSectionFragment(frag) {
  21348. return frag.type === 'section';
  21349. }
  21350. function getBuilder(frag) {
  21351. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21352. }
  21353. function getBlockGapLevel(frag) {
  21354. if (isSectionFragment(frag)) {
  21355. var gapLevel_1 = 0;
  21356. var subBlockLen = frag.blocks.length;
  21357. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21358. each(frag.blocks, function (subBlock) {
  21359. var subGapLevel = getBlockGapLevel(subBlock); // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21360. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21361. if (subGapLevel >= gapLevel_1) {
  21362. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && ( // 0 always can not be readable gap level.
  21363. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21364. // look weird in case `multipleSeries`.
  21365. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21366. }
  21367. });
  21368. return gapLevel_1;
  21369. }
  21370. return 0;
  21371. }
  21372. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21373. var noHeader = fragment.noHeader;
  21374. var gaps = getGap(getBlockGapLevel(fragment));
  21375. var subMarkupTextList = [];
  21376. var subBlocks = fragment.blocks || [];
  21377. assert(!subBlocks || isArray(subBlocks));
  21378. subBlocks = subBlocks || [];
  21379. var orderMode = ctx.orderMode;
  21380. if (fragment.sortBlocks && orderMode) {
  21381. subBlocks = subBlocks.slice();
  21382. var orderMap = {
  21383. valueAsc: 'asc',
  21384. valueDesc: 'desc'
  21385. };
  21386. if (hasOwn(orderMap, orderMode)) {
  21387. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21388. subBlocks.sort(function (a, b) {
  21389. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21390. });
  21391. } // FIXME 'seriesDesc' necessary?
  21392. else if (orderMode === 'seriesDesc') {
  21393. subBlocks.reverse();
  21394. }
  21395. }
  21396. each(subBlocks, function (subBlock, idx) {
  21397. var valueFormatter = fragment.valueFormatter;
  21398. var subMarkupText = getBuilder(subBlock)( // Inherit valueFormatter
  21399. valueFormatter ? extend(extend({}, ctx), {
  21400. valueFormatter: valueFormatter
  21401. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21402. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21403. });
  21404. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21405. if (noHeader) {
  21406. return subMarkupText;
  21407. }
  21408. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21409. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21410. if (ctx.renderMode === 'richText') {
  21411. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21412. } else {
  21413. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21414. }
  21415. }
  21416. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21417. var renderMode = ctx.renderMode;
  21418. var noName = fragment.noName;
  21419. var noValue = fragment.noValue;
  21420. var noMarker = !fragment.markerType;
  21421. var name = fragment.name;
  21422. var useUTC = ctx.useUTC;
  21423. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21424. value = isArray(value) ? value : [value];
  21425. return map(value, function (val, idx) {
  21426. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21427. });
  21428. };
  21429. if (noName && noValue) {
  21430. return;
  21431. }
  21432. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21433. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21434. var valueTypeOption = fragment.valueType;
  21435. var readableValueList = noValue ? [] : valueFormatter(fragment.value);
  21436. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21437. var valueCloseToMarker = !noMarker && noName;
  21438. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21439. nameStyle = _a.nameStyle,
  21440. valueStyle = _a.valueStyle;
  21441. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21442. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21443. }
  21444. /**
  21445. * @return markupText. null/undefined means no content.
  21446. */
  21447. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21448. if (!fragment) {
  21449. return;
  21450. }
  21451. var builder = getBuilder(fragment);
  21452. var ctx = {
  21453. useUTC: useUTC,
  21454. renderMode: renderMode,
  21455. orderMode: orderMode,
  21456. markupStyleCreator: markupStyleCreator,
  21457. valueFormatter: fragment.valueFormatter
  21458. };
  21459. return builder(ctx, fragment, 0, toolTipTextStyle);
  21460. }
  21461. function getGap(gapLevel) {
  21462. return {
  21463. html: HTML_GAPS[gapLevel],
  21464. richText: RICH_TEXT_GAPS[gapLevel]
  21465. };
  21466. }
  21467. function wrapBlockHTML(encodedContent, topGap) {
  21468. var clearfix = '<div style="clear:both"></div>';
  21469. var marginCSS = "margin: " + topGap + "px 0 0";
  21470. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21471. }
  21472. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21473. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21474. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21475. }
  21476. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21477. // Do not too close to marker, considering there are multiple values separated by spaces.
  21478. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21479. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21480. valueList = isArray(valueList) ? valueList : [valueList];
  21481. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21482. + map(valueList, function (value) {
  21483. return encodeHTML(value);
  21484. }).join('&nbsp;&nbsp;') + '</span>';
  21485. }
  21486. function wrapInlineNameRichText(ctx, name, style) {
  21487. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21488. }
  21489. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21490. var styles = [style];
  21491. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21492. alignRight && styles.push({
  21493. padding: [0, 0, 0, paddingLeft],
  21494. align: 'right'
  21495. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21496. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  21497. }
  21498. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21499. var style = series.getData().getItemVisual(dataIndex, 'style');
  21500. var color = style[series.visualDrawType];
  21501. return convertToColorString(color);
  21502. }
  21503. function getPaddingFromTooltipModel(model, renderMode) {
  21504. var padding = model.get('padding');
  21505. return padding != null ? padding // We give slightly different to look pretty.
  21506. : renderMode === 'richText' ? [8, 10] : 10;
  21507. }
  21508. /**
  21509. * The major feature is generate styles for `renderMode: 'richText'`.
  21510. * But it also serves `renderMode: 'html'` to provide
  21511. * "renderMode-independent" API.
  21512. */
  21513. var TooltipMarkupStyleCreator =
  21514. /** @class */
  21515. function () {
  21516. function TooltipMarkupStyleCreator() {
  21517. this.richTextStyles = {}; // Notice that "generate a style name" usuall happens repeatly when mouse moving and
  21518. // displaying a tooltip. So we put the `_nextStyleNameId` as a member of each creator
  21519. // rather than static shared by all creators (which will cause it increase to fast).
  21520. this._nextStyleNameId = getRandomIdBase();
  21521. }
  21522. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21523. return '__EC_aUTo_' + this._nextStyleNameId++;
  21524. };
  21525. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21526. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21527. var marker = getTooltipMarker({
  21528. color: colorStr,
  21529. type: markerType,
  21530. renderMode: renderMode,
  21531. markerId: markerId
  21532. });
  21533. if (isString(marker)) {
  21534. return marker;
  21535. } else {
  21536. if ("development" !== 'production') {
  21537. assert(markerId);
  21538. }
  21539. this.richTextStyles[markerId] = marker.style;
  21540. return marker.content;
  21541. }
  21542. };
  21543. /**
  21544. * @usage
  21545. * ```ts
  21546. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21547. * // The styles will be auto merged.
  21548. * {
  21549. * fontSize: 12,
  21550. * color: 'blue'
  21551. * },
  21552. * {
  21553. * padding: 20
  21554. * }
  21555. * ]);
  21556. * ```
  21557. */
  21558. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21559. var finalStl = {};
  21560. if (isArray(styles)) {
  21561. each(styles, function (stl) {
  21562. return extend(finalStl, stl);
  21563. });
  21564. } else {
  21565. extend(finalStl, styles);
  21566. }
  21567. var styleName = this._generateStyleName();
  21568. this.richTextStyles[styleName] = finalStl;
  21569. return "{" + styleName + "|" + text + "}";
  21570. };
  21571. return TooltipMarkupStyleCreator;
  21572. }();
  21573. function defaultSeriesFormatTooltip(opt) {
  21574. var series = opt.series;
  21575. var dataIndex = opt.dataIndex;
  21576. var multipleSeries = opt.multipleSeries;
  21577. var data = series.getData();
  21578. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21579. var tooltipDimLen = tooltipDims.length;
  21580. var value = series.getRawValue(dataIndex);
  21581. var isValueArr = isArray(value);
  21582. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21583. var inlineValue;
  21584. var inlineValueType;
  21585. var subBlocks;
  21586. var sortParam;
  21587. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21588. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21589. inlineValue = formatArrResult.inlineValues;
  21590. inlineValueType = formatArrResult.inlineValueTypes;
  21591. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  21592. sortParam = formatArrResult.inlineValues[0];
  21593. } else if (tooltipDimLen) {
  21594. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  21595. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  21596. inlineValueType = dimInfo.type;
  21597. } else {
  21598. sortParam = inlineValue = isValueArr ? value[0] : value;
  21599. } // Do not show generated series name. It might not be readable.
  21600. var seriesNameSpecified = isNameSpecified(series);
  21601. var seriesName = seriesNameSpecified && series.name || '';
  21602. var itemName = data.getName(dataIndex);
  21603. var inlineName = multipleSeries ? seriesName : itemName;
  21604. return createTooltipMarkup('section', {
  21605. header: seriesName,
  21606. // When series name not specified, do not show a header line with only '-'.
  21607. // This case alway happen in tooltip.trigger: 'item'.
  21608. noHeader: multipleSeries || !seriesNameSpecified,
  21609. sortParam: sortParam,
  21610. blocks: [createTooltipMarkup('nameValue', {
  21611. markerType: 'item',
  21612. markerColor: markerColor,
  21613. // Do not mix display seriesName and itemName in one tooltip,
  21614. // which might confuses users.
  21615. name: inlineName,
  21616. // name dimension might be auto assigned, where the name might
  21617. // be not readable. So we check trim here.
  21618. noName: !trim(inlineName),
  21619. value: inlineValue,
  21620. valueType: inlineValueType
  21621. })].concat(subBlocks || [])
  21622. });
  21623. }
  21624. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  21625. // check: category-no-encode-has-axis-data in dataset.html
  21626. var data = series.getData();
  21627. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  21628. var dimItem = data.getDimensionInfo(idx);
  21629. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21630. }, false);
  21631. var inlineValues = [];
  21632. var inlineValueTypes = [];
  21633. var blocks = [];
  21634. tooltipDims.length ? each(tooltipDims, function (dim) {
  21635. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21636. }) // By default, all dims is used on tooltip.
  21637. : each(value, setEachItem);
  21638. function setEachItem(val, dim) {
  21639. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  21640. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21641. return;
  21642. }
  21643. if (isValueMultipleLine) {
  21644. blocks.push(createTooltipMarkup('nameValue', {
  21645. markerType: 'subItem',
  21646. markerColor: colorStr,
  21647. name: dimInfo.displayName,
  21648. value: val,
  21649. valueType: dimInfo.type
  21650. }));
  21651. } else {
  21652. inlineValues.push(val);
  21653. inlineValueTypes.push(dimInfo.type);
  21654. }
  21655. }
  21656. return {
  21657. inlineValues: inlineValues,
  21658. inlineValueTypes: inlineValueTypes,
  21659. blocks: blocks
  21660. };
  21661. }
  21662. var inner$1 = makeInner();
  21663. function getSelectionKey(data, dataIndex) {
  21664. return data.getName(dataIndex) || data.getId(dataIndex);
  21665. }
  21666. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  21667. var SeriesModel =
  21668. /** @class */
  21669. function (_super) {
  21670. __extends(SeriesModel, _super);
  21671. function SeriesModel() {
  21672. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  21673. // the class members must not be initialized in constructor or declaration place.
  21674. // Otherwise there is bad case:
  21675. // class A {xxx = 1;}
  21676. // enableClassExtend(A);
  21677. // class B extends A {}
  21678. // var C = B.extend({xxx: 5});
  21679. // var c = new C();
  21680. // console.log(c.xxx); // expect 5 but always 1.
  21681. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  21682. // Props about data selection
  21683. // ---------------------------------------
  21684. _this._selectedDataIndicesMap = {};
  21685. return _this;
  21686. }
  21687. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  21688. this.seriesIndex = this.componentIndex;
  21689. this.dataTask = createTask({
  21690. count: dataTaskCount,
  21691. reset: dataTaskReset
  21692. });
  21693. this.dataTask.context = {
  21694. model: this
  21695. };
  21696. this.mergeDefaultAndTheme(option, ecModel);
  21697. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  21698. sourceManager.prepareSource();
  21699. var data = this.getInitialData(option, ecModel);
  21700. wrapData(data, this);
  21701. this.dataTask.context.data = data;
  21702. if ("development" !== 'production') {
  21703. assert(data, 'getInitialData returned invalid data.');
  21704. }
  21705. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  21706. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21707. // cause data.graph.data !== data when using
  21708. // module:echarts/data/Graph or module:echarts/data/Tree.
  21709. // See module:echarts/data/helper/linkSeriesData
  21710. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21711. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21712. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21713. // Call `seriesModel.getRawData()` instead.
  21714. // this.restoreData();
  21715. autoSeriesName(this);
  21716. this._initSelectedMapFromData(data);
  21717. };
  21718. /**
  21719. * Util for merge default and theme to option
  21720. */
  21721. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  21722. var layoutMode = fetchLayoutMode(this);
  21723. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  21724. // But if name duplicate between series subType
  21725. // (for example: parallel) add component mainType,
  21726. // add suffix 'Series'.
  21727. var themeSubType = this.subType;
  21728. if (ComponentModel.hasClass(themeSubType)) {
  21729. themeSubType += 'Series';
  21730. }
  21731. merge(option, ecModel.getTheme().get(this.subType));
  21732. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  21733. defaultEmphasis(option, 'label', ['show']);
  21734. this.fillDataTextStyle(option.data);
  21735. if (layoutMode) {
  21736. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21737. }
  21738. };
  21739. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  21740. // this.settingTask.dirty();
  21741. newSeriesOption = merge(this.option, newSeriesOption, true);
  21742. this.fillDataTextStyle(newSeriesOption.data);
  21743. var layoutMode = fetchLayoutMode(this);
  21744. if (layoutMode) {
  21745. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21746. }
  21747. var sourceManager = inner$1(this).sourceManager;
  21748. sourceManager.dirty();
  21749. sourceManager.prepareSource();
  21750. var data = this.getInitialData(newSeriesOption, ecModel);
  21751. wrapData(data, this);
  21752. this.dataTask.dirty();
  21753. this.dataTask.context.data = data;
  21754. inner$1(this).dataBeforeProcessed = data;
  21755. autoSeriesName(this);
  21756. this._initSelectedMapFromData(data);
  21757. };
  21758. SeriesModel.prototype.fillDataTextStyle = function (data) {
  21759. // Default data label emphasis `show`
  21760. // FIXME Tree structure data ?
  21761. // FIXME Performance ?
  21762. if (data && !isTypedArray(data)) {
  21763. var props = ['show'];
  21764. for (var i = 0; i < data.length; i++) {
  21765. if (data[i] && data[i].label) {
  21766. defaultEmphasis(data[i], 'label', props);
  21767. }
  21768. }
  21769. }
  21770. };
  21771. /**
  21772. * Init a data structure from data related option in series
  21773. * Must be overriden.
  21774. */
  21775. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  21776. return;
  21777. };
  21778. /**
  21779. * Append data to list
  21780. */
  21781. SeriesModel.prototype.appendData = function (params) {
  21782. // FIXME ???
  21783. // (1) If data from dataset, forbidden append.
  21784. // (2) support append data of dataset.
  21785. var data = this.getRawData();
  21786. data.appendData(params.data);
  21787. };
  21788. /**
  21789. * Consider some method like `filter`, `map` need make new data,
  21790. * We should make sure that `seriesModel.getData()` get correct
  21791. * data in the stream procedure. So we fetch data from upstream
  21792. * each time `task.perform` called.
  21793. */
  21794. SeriesModel.prototype.getData = function (dataType) {
  21795. var task = getCurrentTask(this);
  21796. if (task) {
  21797. var data = task.context.data;
  21798. return dataType == null ? data : data.getLinkedData(dataType);
  21799. } else {
  21800. // When series is not alive (that may happen when click toolbox
  21801. // restore or setOption with not merge mode), series data may
  21802. // be still need to judge animation or something when graphic
  21803. // elements want to know whether fade out.
  21804. return inner$1(this).data;
  21805. }
  21806. };
  21807. SeriesModel.prototype.getAllData = function () {
  21808. var mainData = this.getData();
  21809. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  21810. data: mainData
  21811. }];
  21812. };
  21813. SeriesModel.prototype.setData = function (data) {
  21814. var task = getCurrentTask(this);
  21815. if (task) {
  21816. var context = task.context; // Consider case: filter, data sample.
  21817. // FIXME:TS never used, so comment it
  21818. // if (context.data !== data && task.modifyOutputEnd) {
  21819. // task.setOutputEnd(data.count());
  21820. // }
  21821. context.outputData = data; // Caution: setData should update context.data,
  21822. // Because getData may be called multiply in a
  21823. // single stage and expect to get the data just
  21824. // set. (For example, AxisProxy, x y both call
  21825. // getData and setDate sequentially).
  21826. // So the context.data should be fetched from
  21827. // upstream each time when a stage starts to be
  21828. // performed.
  21829. if (task !== this.dataTask) {
  21830. context.data = data;
  21831. }
  21832. }
  21833. inner$1(this).data = data;
  21834. };
  21835. SeriesModel.prototype.getEncode = function () {
  21836. var encode = this.get('encode', true);
  21837. if (encode) {
  21838. return createHashMap(encode);
  21839. }
  21840. };
  21841. SeriesModel.prototype.getSourceManager = function () {
  21842. return inner$1(this).sourceManager;
  21843. };
  21844. SeriesModel.prototype.getSource = function () {
  21845. return this.getSourceManager().getSource();
  21846. };
  21847. /**
  21848. * Get data before processed
  21849. */
  21850. SeriesModel.prototype.getRawData = function () {
  21851. return inner$1(this).dataBeforeProcessed;
  21852. };
  21853. SeriesModel.prototype.getColorBy = function () {
  21854. var colorBy = this.get('colorBy');
  21855. return colorBy || 'series';
  21856. };
  21857. SeriesModel.prototype.isColorBySeries = function () {
  21858. return this.getColorBy() === 'series';
  21859. };
  21860. /**
  21861. * Get base axis if has coordinate system and has axis.
  21862. * By default use coordSys.getBaseAxis();
  21863. * Can be overrided for some chart.
  21864. * @return {type} description
  21865. */
  21866. SeriesModel.prototype.getBaseAxis = function () {
  21867. var coordSys = this.coordinateSystem; // @ts-ignore
  21868. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21869. };
  21870. /**
  21871. * Default tooltip formatter
  21872. *
  21873. * @param dataIndex
  21874. * @param multipleSeries
  21875. * @param dataType
  21876. * @param renderMode valid values: 'html'(by default) and 'richText'.
  21877. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21878. * string is used as DOM HTML content.
  21879. * 'richText' is used for rendering tooltip in rich text form, for those where
  21880. * DOM operation is not supported.
  21881. * @return formatted tooltip with `html` and `markers`
  21882. * Notice: The override method can also return string
  21883. */
  21884. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  21885. return defaultSeriesFormatTooltip({
  21886. series: this,
  21887. dataIndex: dataIndex,
  21888. multipleSeries: multipleSeries
  21889. });
  21890. };
  21891. SeriesModel.prototype.isAnimationEnabled = function () {
  21892. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  21893. // In ssr mode, renderToString will generate svg with css animation.
  21894. if (env.node && !(ecModel && ecModel.ssr)) {
  21895. return false;
  21896. }
  21897. var animationEnabled = this.getShallow('animation');
  21898. if (animationEnabled) {
  21899. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21900. animationEnabled = false;
  21901. }
  21902. }
  21903. return !!animationEnabled;
  21904. };
  21905. SeriesModel.prototype.restoreData = function () {
  21906. this.dataTask.dirty();
  21907. };
  21908. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  21909. var ecModel = this.ecModel; // PENDING
  21910. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  21911. if (!color) {
  21912. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21913. }
  21914. return color;
  21915. };
  21916. /**
  21917. * Use `data.mapDimensionsAll(coordDim)` instead.
  21918. * @deprecated
  21919. */
  21920. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  21921. return this.getRawData().mapDimensionsAll(coordDim);
  21922. };
  21923. /**
  21924. * Get progressive rendering count each step
  21925. */
  21926. SeriesModel.prototype.getProgressive = function () {
  21927. return this.get('progressive');
  21928. };
  21929. /**
  21930. * Get progressive rendering count each step
  21931. */
  21932. SeriesModel.prototype.getProgressiveThreshold = function () {
  21933. return this.get('progressiveThreshold');
  21934. }; // PENGING If selectedMode is null ?
  21935. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  21936. this._innerSelect(this.getData(dataType), innerDataIndices);
  21937. };
  21938. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  21939. var selectedMap = this.option.selectedMap;
  21940. if (!selectedMap) {
  21941. return;
  21942. }
  21943. var selectedMode = this.option.selectedMode;
  21944. var data = this.getData(dataType);
  21945. if (selectedMode === 'series' || selectedMap === 'all') {
  21946. this.option.selectedMap = {};
  21947. this._selectedDataIndicesMap = {};
  21948. return;
  21949. }
  21950. for (var i = 0; i < innerDataIndices.length; i++) {
  21951. var dataIndex = innerDataIndices[i];
  21952. var nameOrId = getSelectionKey(data, dataIndex);
  21953. selectedMap[nameOrId] = false;
  21954. this._selectedDataIndicesMap[nameOrId] = -1;
  21955. }
  21956. };
  21957. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  21958. var tmpArr = [];
  21959. for (var i = 0; i < innerDataIndices.length; i++) {
  21960. tmpArr[0] = innerDataIndices[i];
  21961. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  21962. }
  21963. };
  21964. SeriesModel.prototype.getSelectedDataIndices = function () {
  21965. if (this.option.selectedMap === 'all') {
  21966. return [].slice.call(this.getData().getIndices());
  21967. }
  21968. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  21969. var nameOrIds = keys(selectedDataIndicesMap);
  21970. var dataIndices = [];
  21971. for (var i = 0; i < nameOrIds.length; i++) {
  21972. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  21973. if (dataIndex >= 0) {
  21974. dataIndices.push(dataIndex);
  21975. }
  21976. }
  21977. return dataIndices;
  21978. };
  21979. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  21980. var selectedMap = this.option.selectedMap;
  21981. if (!selectedMap) {
  21982. return false;
  21983. }
  21984. var data = this.getData(dataType);
  21985. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  21986. };
  21987. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  21988. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  21989. return true;
  21990. }
  21991. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  21992. if (!universalTransitionOpt) {
  21993. return false;
  21994. }
  21995. if (universalTransitionOpt === true) {
  21996. return true;
  21997. } // Can be simply 'universalTransition: true'
  21998. return universalTransitionOpt && universalTransitionOpt.enabled;
  21999. };
  22000. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22001. var _a, _b;
  22002. var option = this.option;
  22003. var selectedMode = option.selectedMode;
  22004. var len = innerDataIndices.length;
  22005. if (!selectedMode || !len) {
  22006. return;
  22007. }
  22008. if (selectedMode === 'series') {
  22009. option.selectedMap = 'all';
  22010. } else if (selectedMode === 'multiple') {
  22011. if (!isObject(option.selectedMap)) {
  22012. option.selectedMap = {};
  22013. }
  22014. var selectedMap = option.selectedMap;
  22015. for (var i = 0; i < len; i++) {
  22016. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  22017. var nameOrId = getSelectionKey(data, dataIndex);
  22018. selectedMap[nameOrId] = true;
  22019. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22020. }
  22021. } else if (selectedMode === 'single' || selectedMode === true) {
  22022. var lastDataIndex = innerDataIndices[len - 1];
  22023. var nameOrId = getSelectionKey(data, lastDataIndex);
  22024. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22025. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22026. }
  22027. };
  22028. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22029. // Ignore select info in data if selectedMap exists.
  22030. // NOTE It's only for legacy usage. edge data is not supported.
  22031. if (this.option.selectedMap) {
  22032. return;
  22033. }
  22034. var dataIndices = [];
  22035. if (data.hasItemOption) {
  22036. data.each(function (idx) {
  22037. var rawItem = data.getRawDataItem(idx);
  22038. if (rawItem && rawItem.selected) {
  22039. dataIndices.push(idx);
  22040. }
  22041. });
  22042. }
  22043. if (dataIndices.length > 0) {
  22044. this._innerSelect(data, dataIndices);
  22045. }
  22046. }; // /**
  22047. // * @see {module:echarts/stream/Scheduler}
  22048. // */
  22049. // abstract pipeTask: null
  22050. SeriesModel.registerClass = function (clz) {
  22051. return ComponentModel.registerClass(clz);
  22052. };
  22053. SeriesModel.protoInitialize = function () {
  22054. var proto = SeriesModel.prototype;
  22055. proto.type = 'series.__base__';
  22056. proto.seriesIndex = 0;
  22057. proto.ignoreStyleOnData = false;
  22058. proto.hasSymbolVisual = false;
  22059. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22060. proto.visualStyleAccessPath = 'itemStyle';
  22061. proto.visualDrawType = 'fill';
  22062. }();
  22063. return SeriesModel;
  22064. }(ComponentModel);
  22065. mixin(SeriesModel, DataFormatMixin);
  22066. mixin(SeriesModel, PaletteMixin);
  22067. mountExtend(SeriesModel, ComponentModel);
  22068. /**
  22069. * MUST be called after `prepareSource` called
  22070. * Here we need to make auto series, especially for auto legend. But we
  22071. * do not modify series.name in option to avoid side effects.
  22072. */
  22073. function autoSeriesName(seriesModel) {
  22074. // User specified name has higher priority, otherwise it may cause
  22075. // series can not be queried unexpectedly.
  22076. var name = seriesModel.name;
  22077. if (!isNameSpecified(seriesModel)) {
  22078. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22079. }
  22080. }
  22081. function getSeriesAutoName(seriesModel) {
  22082. var data = seriesModel.getRawData();
  22083. var dataDims = data.mapDimensionsAll('seriesName');
  22084. var nameArr = [];
  22085. each(dataDims, function (dataDim) {
  22086. var dimInfo = data.getDimensionInfo(dataDim);
  22087. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22088. });
  22089. return nameArr.join(' ');
  22090. }
  22091. function dataTaskCount(context) {
  22092. return context.model.getRawData().count();
  22093. }
  22094. function dataTaskReset(context) {
  22095. var seriesModel = context.model;
  22096. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22097. return dataTaskProgress;
  22098. }
  22099. function dataTaskProgress(param, context) {
  22100. // Avoid repead cloneShallow when data just created in reset.
  22101. if (context.outputData && param.end > context.outputData.count()) {
  22102. context.model.getRawData().cloneShallow(context.outputData);
  22103. }
  22104. } // TODO refactor
  22105. function wrapData(data, seriesModel) {
  22106. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22107. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22108. });
  22109. }
  22110. function onDataChange(seriesModel, newList) {
  22111. var task = getCurrentTask(seriesModel);
  22112. if (task) {
  22113. // Consider case: filter, selectRange
  22114. task.setOutputEnd((newList || this).count());
  22115. }
  22116. return newList;
  22117. }
  22118. function getCurrentTask(seriesModel) {
  22119. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22120. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22121. if (pipeline) {
  22122. // When pipline finished, the currrentTask keep the last
  22123. // task (renderTask).
  22124. var task = pipeline.currentTask;
  22125. if (task) {
  22126. var agentStubMap = task.agentStubMap;
  22127. if (agentStubMap) {
  22128. task = agentStubMap.get(seriesModel.uid);
  22129. }
  22130. }
  22131. return task;
  22132. }
  22133. }
  22134. var ComponentView =
  22135. /** @class */
  22136. function () {
  22137. function ComponentView() {
  22138. this.group = new Group();
  22139. this.uid = getUID('viewComponent');
  22140. }
  22141. ComponentView.prototype.init = function (ecModel, api) {};
  22142. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22143. ComponentView.prototype.dispose = function (ecModel, api) {};
  22144. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22145. };
  22146. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22147. };
  22148. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22149. };
  22150. /**
  22151. * Hook for toggle blur target series.
  22152. * Can be used in marker for blur or leave blur the markers
  22153. */
  22154. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  22155. };
  22156. /**
  22157. * Traverse the new rendered elements.
  22158. *
  22159. * It will traverse the new added element in progressive rendering.
  22160. * And traverse all in normal rendering.
  22161. */
  22162. ComponentView.prototype.eachRendered = function (cb) {
  22163. var group = this.group;
  22164. if (group) {
  22165. group.traverse(cb);
  22166. }
  22167. };
  22168. return ComponentView;
  22169. }();
  22170. enableClassExtend(ComponentView);
  22171. enableClassManagement(ComponentView);
  22172. /**
  22173. * @return {string} If large mode changed, return string 'reset';
  22174. */
  22175. function createRenderPlanner() {
  22176. var inner = makeInner();
  22177. return function (seriesModel) {
  22178. var fields = inner(seriesModel);
  22179. var pipelineContext = seriesModel.pipelineContext;
  22180. var originalLarge = !!fields.large;
  22181. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22182. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22183. // on `performRawSeries` in `Schedular.js`.
  22184. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22185. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22186. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22187. };
  22188. }
  22189. var inner$2 = makeInner();
  22190. var renderPlanner = createRenderPlanner();
  22191. var ChartView =
  22192. /** @class */
  22193. function () {
  22194. function ChartView() {
  22195. this.group = new Group();
  22196. this.uid = getUID('viewChart');
  22197. this.renderTask = createTask({
  22198. plan: renderTaskPlan,
  22199. reset: renderTaskReset
  22200. });
  22201. this.renderTask.context = {
  22202. view: this
  22203. };
  22204. }
  22205. ChartView.prototype.init = function (ecModel, api) {};
  22206. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22207. if ("development" !== 'production') {
  22208. throw new Error('render method must been implemented');
  22209. }
  22210. };
  22211. /**
  22212. * Highlight series or specified data item.
  22213. */
  22214. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22215. var data = seriesModel.getData(payload && payload.dataType);
  22216. if (!data) {
  22217. if ("development" !== 'production') {
  22218. error("Unknown dataType " + payload.dataType);
  22219. }
  22220. return;
  22221. }
  22222. toggleHighlight(data, payload, 'emphasis');
  22223. };
  22224. /**
  22225. * Downplay series or specified data item.
  22226. */
  22227. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22228. var data = seriesModel.getData(payload && payload.dataType);
  22229. if (!data) {
  22230. if ("development" !== 'production') {
  22231. error("Unknown dataType " + payload.dataType);
  22232. }
  22233. return;
  22234. }
  22235. toggleHighlight(data, payload, 'normal');
  22236. };
  22237. /**
  22238. * Remove self.
  22239. */
  22240. ChartView.prototype.remove = function (ecModel, api) {
  22241. this.group.removeAll();
  22242. };
  22243. /**
  22244. * Dispose self.
  22245. */
  22246. ChartView.prototype.dispose = function (ecModel, api) {};
  22247. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22248. this.render(seriesModel, ecModel, api, payload);
  22249. }; // FIXME never used?
  22250. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22251. this.render(seriesModel, ecModel, api, payload);
  22252. }; // FIXME never used?
  22253. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22254. this.render(seriesModel, ecModel, api, payload);
  22255. };
  22256. /**
  22257. * Traverse the new rendered elements.
  22258. *
  22259. * It will traverse the new added element in progressive rendering.
  22260. * And traverse all in normal rendering.
  22261. */
  22262. ChartView.prototype.eachRendered = function (cb) {
  22263. traverseElements(this.group, cb);
  22264. };
  22265. ChartView.markUpdateMethod = function (payload, methodName) {
  22266. inner$2(payload).updateMethod = methodName;
  22267. };
  22268. ChartView.protoInitialize = function () {
  22269. var proto = ChartView.prototype;
  22270. proto.type = 'chart';
  22271. }();
  22272. return ChartView;
  22273. }();
  22274. /**
  22275. * Set state of single element
  22276. */
  22277. function elSetState(el, state, highlightDigit) {
  22278. if (el && isHighDownDispatcher(el)) {
  22279. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22280. }
  22281. }
  22282. function toggleHighlight(data, payload, state) {
  22283. var dataIndex = queryDataIndex(data, payload);
  22284. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22285. if (dataIndex != null) {
  22286. each(normalizeToArray(dataIndex), function (dataIdx) {
  22287. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22288. });
  22289. } else {
  22290. data.eachItemGraphicEl(function (el) {
  22291. elSetState(el, state, highlightDigit);
  22292. });
  22293. }
  22294. }
  22295. enableClassExtend(ChartView, ['dispose']);
  22296. enableClassManagement(ChartView);
  22297. function renderTaskPlan(context) {
  22298. return renderPlanner(context.model);
  22299. }
  22300. function renderTaskReset(context) {
  22301. var seriesModel = context.model;
  22302. var ecModel = context.ecModel;
  22303. var api = context.api;
  22304. var payload = context.payload; // FIXME: remove updateView updateVisual
  22305. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22306. var view = context.view;
  22307. var updateMethod = payload && inner$2(payload).updateMethod;
  22308. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22309. // is less than progressive threshold.
  22310. : 'render';
  22311. if (methodName !== 'render') {
  22312. view[methodName](seriesModel, ecModel, api, payload);
  22313. }
  22314. return progressMethodMap[methodName];
  22315. }
  22316. var progressMethodMap = {
  22317. incrementalPrepareRender: {
  22318. progress: function (params, context) {
  22319. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22320. }
  22321. },
  22322. render: {
  22323. // Put view.render in `progress` to support appendData. But in this case
  22324. // view.render should not be called in reset, otherwise it will be called
  22325. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22326. // in any cases.
  22327. forceFirstProgress: true,
  22328. progress: function (params, context) {
  22329. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22330. }
  22331. }
  22332. };
  22333. /*
  22334. * Licensed to the Apache Software Foundation (ASF) under one
  22335. * or more contributor license agreements. See the NOTICE file
  22336. * distributed with this work for additional information
  22337. * regarding copyright ownership. The ASF licenses this file
  22338. * to you under the Apache License, Version 2.0 (the
  22339. * "License"); you may not use this file except in compliance
  22340. * with the License. You may obtain a copy of the License at
  22341. *
  22342. * http://www.apache.org/licenses/LICENSE-2.0
  22343. *
  22344. * Unless required by applicable law or agreed to in writing,
  22345. * software distributed under the License is distributed on an
  22346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22347. * KIND, either express or implied. See the License for the
  22348. * specific language governing permissions and limitations
  22349. * under the License.
  22350. */
  22351. /**
  22352. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22353. */
  22354. /*
  22355. * Licensed to the Apache Software Foundation (ASF) under one
  22356. * or more contributor license agreements. See the NOTICE file
  22357. * distributed with this work for additional information
  22358. * regarding copyright ownership. The ASF licenses this file
  22359. * to you under the Apache License, Version 2.0 (the
  22360. * "License"); you may not use this file except in compliance
  22361. * with the License. You may obtain a copy of the License at
  22362. *
  22363. * http://www.apache.org/licenses/LICENSE-2.0
  22364. *
  22365. * Unless required by applicable law or agreed to in writing,
  22366. * software distributed under the License is distributed on an
  22367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22368. * KIND, either express or implied. See the License for the
  22369. * specific language governing permissions and limitations
  22370. * under the License.
  22371. */
  22372. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22373. var RATE = '\0__throttleRate';
  22374. var THROTTLE_TYPE = '\0__throttleType';
  22375. /**
  22376. * @public
  22377. * @param {(Function)} fn
  22378. * @param {number} [delay=0] Unit: ms.
  22379. * @param {boolean} [debounce=false]
  22380. * true: If call interval less than `delay`, only the last call works.
  22381. * false: If call interval less than `delay, call works on fixed rate.
  22382. * @return {(Function)} throttled fn.
  22383. */
  22384. function throttle(fn, delay, debounce) {
  22385. var currCall;
  22386. var lastCall = 0;
  22387. var lastExec = 0;
  22388. var timer = null;
  22389. var diff;
  22390. var scope;
  22391. var args;
  22392. var debounceNextCall;
  22393. delay = delay || 0;
  22394. function exec() {
  22395. lastExec = new Date().getTime();
  22396. timer = null;
  22397. fn.apply(scope, args || []);
  22398. }
  22399. var cb = function () {
  22400. var cbArgs = [];
  22401. for (var _i = 0; _i < arguments.length; _i++) {
  22402. cbArgs[_i] = arguments[_i];
  22403. }
  22404. currCall = new Date().getTime();
  22405. scope = this;
  22406. args = cbArgs;
  22407. var thisDelay = debounceNextCall || delay;
  22408. var thisDebounce = debounceNextCall || debounce;
  22409. debounceNextCall = null;
  22410. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22411. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22412. // than a new call of `cb`, that is, preserving the command order. Consider
  22413. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22414. // happens, either the `exec` is called dierectly, or the call is delayed.
  22415. // But the delayed call should never be later than next call of `cb`. Under
  22416. // this assurance, we can simply update view state each time `dispatchAction`
  22417. // triggered by user roaming, but not need to add extra code to avoid the
  22418. // state being "rolled-back".
  22419. if (thisDebounce) {
  22420. timer = setTimeout(exec, thisDelay);
  22421. } else {
  22422. if (diff >= 0) {
  22423. exec();
  22424. } else {
  22425. timer = setTimeout(exec, -diff);
  22426. }
  22427. }
  22428. lastCall = currCall;
  22429. };
  22430. /**
  22431. * Clear throttle.
  22432. * @public
  22433. */
  22434. cb.clear = function () {
  22435. if (timer) {
  22436. clearTimeout(timer);
  22437. timer = null;
  22438. }
  22439. };
  22440. /**
  22441. * Enable debounce once.
  22442. */
  22443. cb.debounceNextCall = function (debounceDelay) {
  22444. debounceNextCall = debounceDelay;
  22445. };
  22446. return cb;
  22447. }
  22448. /**
  22449. * Create throttle method or update throttle rate.
  22450. *
  22451. * @example
  22452. * ComponentView.prototype.render = function () {
  22453. * ...
  22454. * throttle.createOrUpdate(
  22455. * this,
  22456. * '_dispatchAction',
  22457. * this.model.get('throttle'),
  22458. * 'fixRate'
  22459. * );
  22460. * };
  22461. * ComponentView.prototype.remove = function () {
  22462. * throttle.clear(this, '_dispatchAction');
  22463. * };
  22464. * ComponentView.prototype.dispose = function () {
  22465. * throttle.clear(this, '_dispatchAction');
  22466. * };
  22467. *
  22468. */
  22469. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22470. var fn = obj[fnAttr];
  22471. if (!fn) {
  22472. return;
  22473. }
  22474. var originFn = fn[ORIGIN_METHOD] || fn;
  22475. var lastThrottleType = fn[THROTTLE_TYPE];
  22476. var lastRate = fn[RATE];
  22477. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22478. if (rate == null || !throttleType) {
  22479. return obj[fnAttr] = originFn;
  22480. }
  22481. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22482. fn[ORIGIN_METHOD] = originFn;
  22483. fn[THROTTLE_TYPE] = throttleType;
  22484. fn[RATE] = rate;
  22485. }
  22486. return fn;
  22487. }
  22488. /**
  22489. * Clear throttle. Example see throttle.createOrUpdate.
  22490. */
  22491. function clear(obj, fnAttr) {
  22492. var fn = obj[fnAttr];
  22493. if (fn && fn[ORIGIN_METHOD]) {
  22494. // Clear throttle
  22495. fn.clear && fn.clear();
  22496. obj[fnAttr] = fn[ORIGIN_METHOD];
  22497. }
  22498. }
  22499. var inner$3 = makeInner();
  22500. var defaultStyleMappers = {
  22501. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22502. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22503. };
  22504. var defaultColorKey = {
  22505. lineStyle: 'stroke',
  22506. itemStyle: 'fill'
  22507. };
  22508. function getStyleMapper(seriesModel, stylePath) {
  22509. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22510. if (!styleMapper) {
  22511. console.warn("Unkown style type '" + stylePath + "'.");
  22512. return defaultStyleMappers.itemStyle;
  22513. }
  22514. return styleMapper;
  22515. }
  22516. function getDefaultColorKey(seriesModel, stylePath) {
  22517. // return defaultColorKey[stylePath] ||
  22518. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22519. if (!colorKey) {
  22520. console.warn("Unkown style type '" + stylePath + "'.");
  22521. return 'fill';
  22522. }
  22523. return colorKey;
  22524. }
  22525. var seriesStyleTask = {
  22526. createOnAllSeries: true,
  22527. performRawSeries: true,
  22528. reset: function (seriesModel, ecModel) {
  22529. var data = seriesModel.getData();
  22530. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22531. var styleModel = seriesModel.getModel(stylePath);
  22532. var getStyle = getStyleMapper(seriesModel, stylePath);
  22533. var globalStyle = getStyle(styleModel);
  22534. var decalOption = styleModel.getShallow('decal');
  22535. if (decalOption) {
  22536. data.setVisual('decal', decalOption);
  22537. decalOption.dirty = true;
  22538. } // TODO
  22539. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22540. var color = globalStyle[colorKey]; // TODO style callback
  22541. var colorCallback = isFunction(color) ? color : null;
  22542. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22543. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22544. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  22545. // make it effect palette. Bacause some scenarios users need to make some series
  22546. // transparent or as background, which should better not effect the palette.
  22547. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22548. seriesModel.name, null, ecModel.getSeriesCount());
  22549. if (!globalStyle[colorKey]) {
  22550. globalStyle[colorKey] = colorPalette;
  22551. data.setVisual('colorFromPalette', true);
  22552. }
  22553. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22554. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22555. }
  22556. data.setVisual('style', globalStyle);
  22557. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22558. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22559. data.setVisual('colorFromPalette', false);
  22560. return {
  22561. dataEach: function (data, idx) {
  22562. var dataParams = seriesModel.getDataParams(idx);
  22563. var itemStyle = extend({}, globalStyle);
  22564. itemStyle[colorKey] = colorCallback(dataParams);
  22565. data.setItemVisual(idx, 'style', itemStyle);
  22566. }
  22567. };
  22568. }
  22569. }
  22570. };
  22571. var sharedModel = new Model();
  22572. var dataStyleTask = {
  22573. createOnAllSeries: true,
  22574. performRawSeries: true,
  22575. reset: function (seriesModel, ecModel) {
  22576. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22577. return;
  22578. }
  22579. var data = seriesModel.getData();
  22580. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22581. var getStyle = getStyleMapper(seriesModel, stylePath);
  22582. var colorKey = data.getVisual('drawType');
  22583. return {
  22584. dataEach: data.hasItemOption ? function (data, idx) {
  22585. // Not use getItemModel for performance considuration
  22586. var rawItem = data.getRawDataItem(idx);
  22587. if (rawItem && rawItem[stylePath]) {
  22588. sharedModel.option = rawItem[stylePath];
  22589. var style = getStyle(sharedModel);
  22590. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  22591. extend(existsStyle, style);
  22592. if (sharedModel.option.decal) {
  22593. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  22594. sharedModel.option.decal.dirty = true;
  22595. }
  22596. if (colorKey in style) {
  22597. data.setItemVisual(idx, 'colorFromPalette', false);
  22598. }
  22599. }
  22600. } : null
  22601. };
  22602. }
  22603. }; // Pick color from palette for the data which has not been set with color yet.
  22604. // Note: do not support stream rendering. No such cases yet.
  22605. var dataColorPaletteTask = {
  22606. performRawSeries: true,
  22607. overallReset: function (ecModel) {
  22608. // Each type of series use one scope.
  22609. // Pie and funnel are using diferrent scopes
  22610. var paletteScopeGroupByType = createHashMap();
  22611. ecModel.eachSeries(function (seriesModel) {
  22612. var colorBy = seriesModel.getColorBy();
  22613. if (seriesModel.isColorBySeries()) {
  22614. return;
  22615. }
  22616. var key = seriesModel.type + '-' + colorBy;
  22617. var colorScope = paletteScopeGroupByType.get(key);
  22618. if (!colorScope) {
  22619. colorScope = {};
  22620. paletteScopeGroupByType.set(key, colorScope);
  22621. }
  22622. inner$3(seriesModel).scope = colorScope;
  22623. });
  22624. ecModel.eachSeries(function (seriesModel) {
  22625. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  22626. return;
  22627. }
  22628. var dataAll = seriesModel.getRawData();
  22629. var idxMap = {};
  22630. var data = seriesModel.getData();
  22631. var colorScope = inner$3(seriesModel).scope;
  22632. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22633. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22634. data.each(function (idx) {
  22635. var rawIdx = data.getRawIndex(idx);
  22636. idxMap[rawIdx] = idx;
  22637. }); // Iterate on data before filtered. To make sure color from palette can be
  22638. // Consistent when toggling legend.
  22639. dataAll.each(function (rawIdx) {
  22640. var idx = idxMap[rawIdx];
  22641. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  22642. // also picked from color palette. So following situation is not in the case:
  22643. // 1. series.itemStyle.color is set
  22644. // 2. color is encoded by visualMap
  22645. if (fromPalette) {
  22646. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  22647. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  22648. var dataCount = dataAll.count();
  22649. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  22650. }
  22651. });
  22652. });
  22653. }
  22654. };
  22655. var PI$3 = Math.PI;
  22656. /**
  22657. * @param {module:echarts/ExtensionAPI} api
  22658. * @param {Object} [opts]
  22659. * @param {string} [opts.text]
  22660. * @param {string} [opts.color]
  22661. * @param {string} [opts.textColor]
  22662. * @return {module:zrender/Element}
  22663. */
  22664. function defaultLoading(api, opts) {
  22665. opts = opts || {};
  22666. defaults(opts, {
  22667. text: 'loading',
  22668. textColor: '#000',
  22669. fontSize: 12,
  22670. fontWeight: 'normal',
  22671. fontStyle: 'normal',
  22672. fontFamily: 'sans-serif',
  22673. maskColor: 'rgba(255, 255, 255, 0.8)',
  22674. showSpinner: true,
  22675. color: '#5470c6',
  22676. spinnerRadius: 10,
  22677. lineWidth: 5,
  22678. zlevel: 0
  22679. });
  22680. var group = new Group();
  22681. var mask = new Rect({
  22682. style: {
  22683. fill: opts.maskColor
  22684. },
  22685. zlevel: opts.zlevel,
  22686. z: 10000
  22687. });
  22688. group.add(mask);
  22689. var textContent = new ZRText({
  22690. style: {
  22691. text: opts.text,
  22692. fill: opts.textColor,
  22693. fontSize: opts.fontSize,
  22694. fontWeight: opts.fontWeight,
  22695. fontStyle: opts.fontStyle,
  22696. fontFamily: opts.fontFamily
  22697. },
  22698. zlevel: opts.zlevel,
  22699. z: 10001
  22700. });
  22701. var labelRect = new Rect({
  22702. style: {
  22703. fill: 'none'
  22704. },
  22705. textContent: textContent,
  22706. textConfig: {
  22707. position: 'right',
  22708. distance: 10
  22709. },
  22710. zlevel: opts.zlevel,
  22711. z: 10001
  22712. });
  22713. group.add(labelRect);
  22714. var arc;
  22715. if (opts.showSpinner) {
  22716. arc = new Arc({
  22717. shape: {
  22718. startAngle: -PI$3 / 2,
  22719. endAngle: -PI$3 / 2 + 0.1,
  22720. r: opts.spinnerRadius
  22721. },
  22722. style: {
  22723. stroke: opts.color,
  22724. lineCap: 'round',
  22725. lineWidth: opts.lineWidth
  22726. },
  22727. zlevel: opts.zlevel,
  22728. z: 10001
  22729. });
  22730. arc.animateShape(true).when(1000, {
  22731. endAngle: PI$3 * 3 / 2
  22732. }).start('circularInOut');
  22733. arc.animateShape(true).when(1000, {
  22734. startAngle: PI$3 * 3 / 2
  22735. }).delay(300).start('circularInOut');
  22736. group.add(arc);
  22737. } // Inject resize
  22738. group.resize = function () {
  22739. var textWidth = textContent.getBoundingRect().width;
  22740. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22741. // textDistance needs to be calculated when both animation and text exist
  22742. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  22743. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  22744. + (textWidth ? 0 : r);
  22745. var cy = api.getHeight() / 2;
  22746. opts.showSpinner && arc.setShape({
  22747. cx: cx,
  22748. cy: cy
  22749. });
  22750. labelRect.setShape({
  22751. x: cx - r,
  22752. y: cy - r,
  22753. width: r * 2,
  22754. height: r * 2
  22755. });
  22756. mask.setShape({
  22757. x: 0,
  22758. y: 0,
  22759. width: api.getWidth(),
  22760. height: api.getHeight()
  22761. });
  22762. };
  22763. group.resize();
  22764. return group;
  22765. }
  22766. var Scheduler =
  22767. /** @class */
  22768. function () {
  22769. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22770. // key: handlerUID
  22771. this._stageTaskMap = createHashMap();
  22772. this.ecInstance = ecInstance;
  22773. this.api = api; // Fix current processors in case that in some rear cases that
  22774. // processors might be registered after echarts instance created.
  22775. // Register processors incrementally for a echarts instance is
  22776. // not supported by this stream architecture.
  22777. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22778. visualHandlers = this._visualHandlers = visualHandlers.slice();
  22779. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22780. }
  22781. Scheduler.prototype.restoreData = function (ecModel, payload) {
  22782. // TODO: Only restore needed series and components, but not all components.
  22783. // Currently `restoreData` of all of the series and component will be called.
  22784. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22785. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22786. // and some components like coordinate system, axes, dataZoom, visualMap only
  22787. // need their target series refresh.
  22788. // (1) If we are implementing this feature some day, we should consider these cases:
  22789. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22790. // on the settings of `dataZoom`), it should be re-performed if the component
  22791. // is modified by `setOption`.
  22792. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22793. // it should be re-performed when the result array of `getTargetSeries` changed.
  22794. // We use `dependencies` to cover these issues.
  22795. // (3) How to update target series when coordinate system related components modified.
  22796. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22797. // and this case all of the tasks will be set as dirty.
  22798. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  22799. // depends on all of the series.
  22800. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22801. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22802. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22803. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22804. // probably cause state chaos (consider `dataZoomProcessor`).
  22805. this._stageTaskMap.each(function (taskRecord) {
  22806. var overallTask = taskRecord.overallTask;
  22807. overallTask && overallTask.dirty();
  22808. });
  22809. }; // If seriesModel provided, incremental threshold is check by series data.
  22810. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  22811. // For overall task
  22812. if (!task.__pipeline) {
  22813. return;
  22814. }
  22815. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22816. var pCtx = pipeline.context;
  22817. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  22818. var step = incremental ? pipeline.step : null;
  22819. var modDataCount = pCtx && pCtx.modDataCount;
  22820. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22821. return {
  22822. step: step,
  22823. modBy: modBy,
  22824. modDataCount: modDataCount
  22825. };
  22826. };
  22827. Scheduler.prototype.getPipeline = function (pipelineId) {
  22828. return this._pipelineMap.get(pipelineId);
  22829. };
  22830. /**
  22831. * Current, progressive rendering starts from visual and layout.
  22832. * Always detect render mode in the same stage, avoiding that incorrect
  22833. * detection caused by data filtering.
  22834. * Caution:
  22835. * `updateStreamModes` use `seriesModel.getData()`.
  22836. */
  22837. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  22838. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22839. var data = seriesModel.getData();
  22840. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  22841. // animation frame. Note that some types of series do not provide
  22842. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22843. // use the term `incremental` but not `progressive` to describe the
  22844. // case that `chart.appendData`.
  22845. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  22846. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22847. // see `test/candlestick-large3.html`
  22848. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22849. seriesModel.pipelineContext = pipeline.context = {
  22850. progressiveRender: progressiveRender,
  22851. modDataCount: modDataCount,
  22852. large: large
  22853. };
  22854. };
  22855. Scheduler.prototype.restorePipelines = function (ecModel) {
  22856. var scheduler = this;
  22857. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22858. ecModel.eachSeries(function (seriesModel) {
  22859. var progressive = seriesModel.getProgressive();
  22860. var pipelineId = seriesModel.uid;
  22861. pipelineMap.set(pipelineId, {
  22862. id: pipelineId,
  22863. head: null,
  22864. tail: null,
  22865. threshold: seriesModel.getProgressiveThreshold(),
  22866. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22867. blockIndex: -1,
  22868. step: Math.round(progressive || 700),
  22869. count: 0
  22870. });
  22871. scheduler._pipe(seriesModel, seriesModel.dataTask);
  22872. });
  22873. };
  22874. Scheduler.prototype.prepareStageTasks = function () {
  22875. var stageTaskMap = this._stageTaskMap;
  22876. var ecModel = this.api.getModel();
  22877. var api = this.api;
  22878. each(this._allHandlers, function (handler) {
  22879. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  22880. var errMsg = '';
  22881. if ("development" !== 'production') {
  22882. // Currently do not need to support to sepecify them both.
  22883. errMsg = '"reset" and "overallReset" must not be both specified.';
  22884. }
  22885. assert(!(handler.reset && handler.overallReset), errMsg);
  22886. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  22887. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  22888. }, this);
  22889. };
  22890. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  22891. var renderTask = view.renderTask;
  22892. var context = renderTask.context;
  22893. context.model = model;
  22894. context.ecModel = ecModel;
  22895. context.api = api;
  22896. renderTask.__block = !view.incrementalPrepareRender;
  22897. this._pipe(model, renderTask);
  22898. };
  22899. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  22900. // If we do not use `block` here, it should be considered when to update modes.
  22901. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  22902. block: true
  22903. });
  22904. };
  22905. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  22906. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  22907. };
  22908. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  22909. opt = opt || {};
  22910. var unfinished = false;
  22911. var scheduler = this;
  22912. each(stageHandlers, function (stageHandler, idx) {
  22913. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22914. return;
  22915. }
  22916. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22917. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22918. var overallTask = stageHandlerRecord.overallTask;
  22919. if (overallTask) {
  22920. var overallNeedDirty_1;
  22921. var agentStubMap = overallTask.agentStubMap;
  22922. agentStubMap.each(function (stub) {
  22923. if (needSetDirty(opt, stub)) {
  22924. stub.dirty();
  22925. overallNeedDirty_1 = true;
  22926. }
  22927. });
  22928. overallNeedDirty_1 && overallTask.dirty();
  22929. scheduler.updatePayload(overallTask, payload);
  22930. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  22931. // then execute the overall task. And stub will call seriesModel.setData,
  22932. // which ensures that in the overallTask seriesModel.getData() will not
  22933. // return incorrect data.
  22934. agentStubMap.each(function (stub) {
  22935. stub.perform(performArgs_1);
  22936. });
  22937. if (overallTask.perform(performArgs_1)) {
  22938. unfinished = true;
  22939. }
  22940. } else if (seriesTaskMap) {
  22941. seriesTaskMap.each(function (task, pipelineId) {
  22942. if (needSetDirty(opt, task)) {
  22943. task.dirty();
  22944. }
  22945. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  22946. // if intending to decalare `performRawSeries` in handlers, only
  22947. // stream-independent (specifically, data item independent) operations can be
  22948. // performed. Because is a series is filtered, most of the tasks will not
  22949. // be performed. A stream-dependent operation probably cause wrong biz logic.
  22950. // Perhaps we should not provide a separate callback for this case instead
  22951. // of providing the config `performRawSeries`. The stream-dependent operaions
  22952. // and stream-independent operations should better not be mixed.
  22953. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  22954. scheduler.updatePayload(task, payload);
  22955. if (task.perform(performArgs)) {
  22956. unfinished = true;
  22957. }
  22958. });
  22959. }
  22960. });
  22961. function needSetDirty(opt, task) {
  22962. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22963. }
  22964. this.unfinished = unfinished || this.unfinished;
  22965. };
  22966. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  22967. var unfinished;
  22968. ecModel.eachSeries(function (seriesModel) {
  22969. // Progress to the end for dataInit and dataRestore.
  22970. unfinished = seriesModel.dataTask.perform() || unfinished;
  22971. });
  22972. this.unfinished = unfinished || this.unfinished;
  22973. };
  22974. Scheduler.prototype.plan = function () {
  22975. // Travel pipelines, check block.
  22976. this._pipelineMap.each(function (pipeline) {
  22977. var task = pipeline.tail;
  22978. do {
  22979. if (task.__block) {
  22980. pipeline.blockIndex = task.__idxInPipeline;
  22981. break;
  22982. }
  22983. task = task.getUpstream();
  22984. } while (task);
  22985. });
  22986. };
  22987. Scheduler.prototype.updatePayload = function (task, payload) {
  22988. payload !== 'remain' && (task.context.payload = payload);
  22989. };
  22990. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  22991. var scheduler = this;
  22992. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  22993. // do not need to reuse the map.
  22994. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  22995. var seriesType = stageHandler.seriesType;
  22996. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22997. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22998. // it works but it may cause other irrelevant charts blocked.
  22999. if (stageHandler.createOnAllSeries) {
  23000. ecModel.eachRawSeries(create);
  23001. } else if (seriesType) {
  23002. ecModel.eachRawSeriesByType(seriesType, create);
  23003. } else if (getTargetSeries) {
  23004. getTargetSeries(ecModel, api).each(create);
  23005. }
  23006. function create(seriesModel) {
  23007. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23008. // Reuse original task instance.
  23009. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23010. plan: seriesTaskPlan,
  23011. reset: seriesTaskReset,
  23012. count: seriesTaskCount
  23013. }));
  23014. task.context = {
  23015. model: seriesModel,
  23016. ecModel: ecModel,
  23017. api: api,
  23018. // PENDING: `useClearVisual` not used?
  23019. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23020. plan: stageHandler.plan,
  23021. reset: stageHandler.reset,
  23022. scheduler: scheduler
  23023. };
  23024. scheduler._pipe(seriesModel, task);
  23025. }
  23026. };
  23027. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23028. var scheduler = this;
  23029. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23030. || createTask({
  23031. reset: overallTaskReset
  23032. });
  23033. overallTask.context = {
  23034. ecModel: ecModel,
  23035. api: api,
  23036. overallReset: stageHandler.overallReset,
  23037. scheduler: scheduler
  23038. };
  23039. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23040. // do not need to reuse the map.
  23041. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23042. var seriesType = stageHandler.seriesType;
  23043. var getTargetSeries = stageHandler.getTargetSeries;
  23044. var overallProgress = true;
  23045. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23046. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23047. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23048. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23049. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23050. // we set the pipeline block.
  23051. var errMsg = '';
  23052. if ("development" !== 'production') {
  23053. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  23054. }
  23055. assert(!stageHandler.createOnAllSeries, errMsg);
  23056. if (seriesType) {
  23057. ecModel.eachRawSeriesByType(seriesType, createStub);
  23058. } else if (getTargetSeries) {
  23059. getTargetSeries(ecModel, api).each(createStub);
  23060. } // Otherwise, (usually it is legancy case), the overall task will only be
  23061. // executed when upstream dirty. Otherwise the progressive rendering of all
  23062. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23063. // dirty info from upsteam.
  23064. else {
  23065. overallProgress = false;
  23066. each(ecModel.getSeries(), createStub);
  23067. }
  23068. function createStub(seriesModel) {
  23069. var pipelineId = seriesModel.uid;
  23070. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23071. // should be set as dirty and re-performed.
  23072. shouldOverallTaskDirty = true, createTask({
  23073. reset: stubReset,
  23074. onDirty: stubOnDirty
  23075. })));
  23076. stub.context = {
  23077. model: seriesModel,
  23078. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23079. // modifyOutputEnd: modifyOutputEnd
  23080. };
  23081. stub.agent = overallTask;
  23082. stub.__block = overallProgress;
  23083. scheduler._pipe(seriesModel, stub);
  23084. }
  23085. if (shouldOverallTaskDirty) {
  23086. overallTask.dirty();
  23087. }
  23088. };
  23089. Scheduler.prototype._pipe = function (seriesModel, task) {
  23090. var pipelineId = seriesModel.uid;
  23091. var pipeline = this._pipelineMap.get(pipelineId);
  23092. !pipeline.head && (pipeline.head = task);
  23093. pipeline.tail && pipeline.tail.pipe(task);
  23094. pipeline.tail = task;
  23095. task.__idxInPipeline = pipeline.count++;
  23096. task.__pipeline = pipeline;
  23097. };
  23098. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23099. if (isFunction(stageHandler)) {
  23100. stageHandler = {
  23101. overallReset: stageHandler,
  23102. seriesType: detectSeriseType(stageHandler)
  23103. };
  23104. }
  23105. stageHandler.uid = getUID('stageHandler');
  23106. visualType && (stageHandler.visualType = visualType);
  23107. return stageHandler;
  23108. };
  23109. return Scheduler;
  23110. }();
  23111. function overallTaskReset(context) {
  23112. context.overallReset(context.ecModel, context.api, context.payload);
  23113. }
  23114. function stubReset(context) {
  23115. return context.overallProgress && stubProgress;
  23116. }
  23117. function stubProgress() {
  23118. this.agent.dirty();
  23119. this.getDownstream().dirty();
  23120. }
  23121. function stubOnDirty() {
  23122. this.agent && this.agent.dirty();
  23123. }
  23124. function seriesTaskPlan(context) {
  23125. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23126. }
  23127. function seriesTaskReset(context) {
  23128. if (context.useClearVisual) {
  23129. context.data.clearAllVisual();
  23130. }
  23131. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23132. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23133. return makeSeriesTaskProgress(idx);
  23134. }) : singleSeriesTaskProgress;
  23135. }
  23136. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23137. function makeSeriesTaskProgress(resetDefineIdx) {
  23138. return function (params, context) {
  23139. var data = context.data;
  23140. var resetDefine = context.resetDefines[resetDefineIdx];
  23141. if (resetDefine && resetDefine.dataEach) {
  23142. for (var i = params.start; i < params.end; i++) {
  23143. resetDefine.dataEach(data, i);
  23144. }
  23145. } else if (resetDefine && resetDefine.progress) {
  23146. resetDefine.progress(params, data);
  23147. }
  23148. };
  23149. }
  23150. function seriesTaskCount(context) {
  23151. return context.data.count();
  23152. }
  23153. /**
  23154. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23155. * To ensure that they can work normally, they should work in block mode, that is,
  23156. * they should not be started util the previous tasks finished. So they cause the
  23157. * progressive rendering disabled. We try to detect the series type, to narrow down
  23158. * the block range to only the series type they concern, but not all series.
  23159. */
  23160. function detectSeriseType(legacyFunc) {
  23161. seriesType = null;
  23162. try {
  23163. // Assume there is no async when calling `eachSeriesByType`.
  23164. legacyFunc(ecModelMock, apiMock);
  23165. } catch (e) {}
  23166. return seriesType;
  23167. }
  23168. var ecModelMock = {};
  23169. var apiMock = {};
  23170. var seriesType;
  23171. mockMethods(ecModelMock, GlobalModel);
  23172. mockMethods(apiMock, ExtensionAPI);
  23173. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23174. seriesType = type;
  23175. };
  23176. ecModelMock.eachComponent = function (cond) {
  23177. if (cond.mainType === 'series' && cond.subType) {
  23178. seriesType = cond.subType;
  23179. }
  23180. };
  23181. function mockMethods(target, Clz) {
  23182. /* eslint-disable */
  23183. for (var name_1 in Clz.prototype) {
  23184. // Do not use hasOwnProperty
  23185. target[name_1] = noop;
  23186. }
  23187. /* eslint-enable */
  23188. }
  23189. /*
  23190. * Licensed to the Apache Software Foundation (ASF) under one
  23191. * or more contributor license agreements. See the NOTICE file
  23192. * distributed with this work for additional information
  23193. * regarding copyright ownership. The ASF licenses this file
  23194. * to you under the Apache License, Version 2.0 (the
  23195. * "License"); you may not use this file except in compliance
  23196. * with the License. You may obtain a copy of the License at
  23197. *
  23198. * http://www.apache.org/licenses/LICENSE-2.0
  23199. *
  23200. * Unless required by applicable law or agreed to in writing,
  23201. * software distributed under the License is distributed on an
  23202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23203. * KIND, either express or implied. See the License for the
  23204. * specific language governing permissions and limitations
  23205. * under the License.
  23206. */
  23207. /**
  23208. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23209. */
  23210. /*
  23211. * Licensed to the Apache Software Foundation (ASF) under one
  23212. * or more contributor license agreements. See the NOTICE file
  23213. * distributed with this work for additional information
  23214. * regarding copyright ownership. The ASF licenses this file
  23215. * to you under the Apache License, Version 2.0 (the
  23216. * "License"); you may not use this file except in compliance
  23217. * with the License. You may obtain a copy of the License at
  23218. *
  23219. * http://www.apache.org/licenses/LICENSE-2.0
  23220. *
  23221. * Unless required by applicable law or agreed to in writing,
  23222. * software distributed under the License is distributed on an
  23223. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23224. * KIND, either express or implied. See the License for the
  23225. * specific language governing permissions and limitations
  23226. * under the License.
  23227. */
  23228. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23229. var lightTheme = {
  23230. color: colorAll,
  23231. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23232. };
  23233. /*
  23234. * Licensed to the Apache Software Foundation (ASF) under one
  23235. * or more contributor license agreements. See the NOTICE file
  23236. * distributed with this work for additional information
  23237. * regarding copyright ownership. The ASF licenses this file
  23238. * to you under the Apache License, Version 2.0 (the
  23239. * "License"); you may not use this file except in compliance
  23240. * with the License. You may obtain a copy of the License at
  23241. *
  23242. * http://www.apache.org/licenses/LICENSE-2.0
  23243. *
  23244. * Unless required by applicable law or agreed to in writing,
  23245. * software distributed under the License is distributed on an
  23246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23247. * KIND, either express or implied. See the License for the
  23248. * specific language governing permissions and limitations
  23249. * under the License.
  23250. */
  23251. /**
  23252. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23253. */
  23254. /*
  23255. * Licensed to the Apache Software Foundation (ASF) under one
  23256. * or more contributor license agreements. See the NOTICE file
  23257. * distributed with this work for additional information
  23258. * regarding copyright ownership. The ASF licenses this file
  23259. * to you under the Apache License, Version 2.0 (the
  23260. * "License"); you may not use this file except in compliance
  23261. * with the License. You may obtain a copy of the License at
  23262. *
  23263. * http://www.apache.org/licenses/LICENSE-2.0
  23264. *
  23265. * Unless required by applicable law or agreed to in writing,
  23266. * software distributed under the License is distributed on an
  23267. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23268. * KIND, either express or implied. See the License for the
  23269. * specific language governing permissions and limitations
  23270. * under the License.
  23271. */
  23272. var contrastColor = '#B9B8CE';
  23273. var backgroundColor = '#100C2A';
  23274. var axisCommon = function () {
  23275. return {
  23276. axisLine: {
  23277. lineStyle: {
  23278. color: contrastColor
  23279. }
  23280. },
  23281. splitLine: {
  23282. lineStyle: {
  23283. color: '#484753'
  23284. }
  23285. },
  23286. splitArea: {
  23287. areaStyle: {
  23288. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23289. }
  23290. },
  23291. minorSplitLine: {
  23292. lineStyle: {
  23293. color: '#20203B'
  23294. }
  23295. }
  23296. };
  23297. };
  23298. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23299. var theme = {
  23300. darkMode: true,
  23301. color: colorPalette,
  23302. backgroundColor: backgroundColor,
  23303. axisPointer: {
  23304. lineStyle: {
  23305. color: '#817f91'
  23306. },
  23307. crossStyle: {
  23308. color: '#817f91'
  23309. },
  23310. label: {
  23311. // TODO Contrast of label backgorundColor
  23312. color: '#fff'
  23313. }
  23314. },
  23315. legend: {
  23316. textStyle: {
  23317. color: contrastColor
  23318. }
  23319. },
  23320. textStyle: {
  23321. color: contrastColor
  23322. },
  23323. title: {
  23324. textStyle: {
  23325. color: '#EEF1FA'
  23326. },
  23327. subtextStyle: {
  23328. color: '#B9B8CE'
  23329. }
  23330. },
  23331. toolbox: {
  23332. iconStyle: {
  23333. borderColor: contrastColor
  23334. }
  23335. },
  23336. dataZoom: {
  23337. borderColor: '#71708A',
  23338. textStyle: {
  23339. color: contrastColor
  23340. },
  23341. brushStyle: {
  23342. color: 'rgba(135,163,206,0.3)'
  23343. },
  23344. handleStyle: {
  23345. color: '#353450',
  23346. borderColor: '#C5CBE3'
  23347. },
  23348. moveHandleStyle: {
  23349. color: '#B0B6C3',
  23350. opacity: 0.3
  23351. },
  23352. fillerColor: 'rgba(135,163,206,0.2)',
  23353. emphasis: {
  23354. handleStyle: {
  23355. borderColor: '#91B7F2',
  23356. color: '#4D587D'
  23357. },
  23358. moveHandleStyle: {
  23359. color: '#636D9A',
  23360. opacity: 0.7
  23361. }
  23362. },
  23363. dataBackground: {
  23364. lineStyle: {
  23365. color: '#71708A',
  23366. width: 1
  23367. },
  23368. areaStyle: {
  23369. color: '#71708A'
  23370. }
  23371. },
  23372. selectedDataBackground: {
  23373. lineStyle: {
  23374. color: '#87A3CE'
  23375. },
  23376. areaStyle: {
  23377. color: '#87A3CE'
  23378. }
  23379. }
  23380. },
  23381. visualMap: {
  23382. textStyle: {
  23383. color: contrastColor
  23384. }
  23385. },
  23386. timeline: {
  23387. lineStyle: {
  23388. color: contrastColor
  23389. },
  23390. label: {
  23391. color: contrastColor
  23392. },
  23393. controlStyle: {
  23394. color: contrastColor,
  23395. borderColor: contrastColor
  23396. }
  23397. },
  23398. calendar: {
  23399. itemStyle: {
  23400. color: backgroundColor
  23401. },
  23402. dayLabel: {
  23403. color: contrastColor
  23404. },
  23405. monthLabel: {
  23406. color: contrastColor
  23407. },
  23408. yearLabel: {
  23409. color: contrastColor
  23410. }
  23411. },
  23412. timeAxis: axisCommon(),
  23413. logAxis: axisCommon(),
  23414. valueAxis: axisCommon(),
  23415. categoryAxis: axisCommon(),
  23416. line: {
  23417. symbol: 'circle'
  23418. },
  23419. graph: {
  23420. color: colorPalette
  23421. },
  23422. gauge: {
  23423. title: {
  23424. color: contrastColor
  23425. },
  23426. axisLine: {
  23427. lineStyle: {
  23428. color: [[1, 'rgba(207,212,219,0.2)']]
  23429. }
  23430. },
  23431. axisLabel: {
  23432. color: contrastColor
  23433. },
  23434. detail: {
  23435. color: '#EEF1FA'
  23436. }
  23437. },
  23438. candlestick: {
  23439. itemStyle: {
  23440. color: '#f64e56',
  23441. color0: '#54ea92',
  23442. borderColor: '#f64e56',
  23443. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23444. // borderColor0: '#09a443'
  23445. }
  23446. }
  23447. };
  23448. theme.categoryAxis.splitLine.show = false;
  23449. /**
  23450. * Usage of query:
  23451. * `chart.on('click', query, handler);`
  23452. * The `query` can be:
  23453. * + The component type query string, only `mainType` or `mainType.subType`,
  23454. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23455. * + The component query object, like:
  23456. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23457. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23458. * + The data query object, like:
  23459. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23460. * + The other query object (cmponent customized query), like:
  23461. * `{element: 'some'}` (only available in custom series).
  23462. *
  23463. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23464. * same as there is no such prop in the `query` object.
  23465. */
  23466. var ECEventProcessor =
  23467. /** @class */
  23468. function () {
  23469. function ECEventProcessor() {}
  23470. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23471. var cptQuery = {};
  23472. var dataQuery = {};
  23473. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23474. if (isString(query)) {
  23475. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23476. cptQuery.mainType = condCptType.main || null;
  23477. cptQuery.subType = condCptType.sub || null;
  23478. } // `query` is an object, convert to {mainType, index, name, id}.
  23479. else {
  23480. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23481. // can not be used in `compomentModel.filterForExposedEvent`.
  23482. var suffixes_1 = ['Index', 'Name', 'Id'];
  23483. var dataKeys_1 = {
  23484. name: 1,
  23485. dataIndex: 1,
  23486. dataType: 1
  23487. };
  23488. each(query, function (val, key) {
  23489. var reserved = false;
  23490. for (var i = 0; i < suffixes_1.length; i++) {
  23491. var propSuffix = suffixes_1[i];
  23492. var suffixPos = key.lastIndexOf(propSuffix);
  23493. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23494. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23495. if (mainType !== 'data') {
  23496. cptQuery.mainType = mainType;
  23497. cptQuery[propSuffix.toLowerCase()] = val;
  23498. reserved = true;
  23499. }
  23500. }
  23501. }
  23502. if (dataKeys_1.hasOwnProperty(key)) {
  23503. dataQuery[key] = val;
  23504. reserved = true;
  23505. }
  23506. if (!reserved) {
  23507. otherQuery[key] = val;
  23508. }
  23509. });
  23510. }
  23511. return {
  23512. cptQuery: cptQuery,
  23513. dataQuery: dataQuery,
  23514. otherQuery: otherQuery
  23515. };
  23516. };
  23517. ECEventProcessor.prototype.filter = function (eventType, query) {
  23518. // They should be assigned before each trigger call.
  23519. var eventInfo = this.eventInfo;
  23520. if (!eventInfo) {
  23521. return true;
  23522. }
  23523. var targetEl = eventInfo.targetEl;
  23524. var packedEvent = eventInfo.packedEvent;
  23525. var model = eventInfo.model;
  23526. var view = eventInfo.view; // For event like 'globalout'.
  23527. if (!model || !view) {
  23528. return true;
  23529. }
  23530. var cptQuery = query.cptQuery;
  23531. var dataQuery = query.dataQuery;
  23532. 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));
  23533. function check(query, host, prop, propOnHost) {
  23534. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23535. }
  23536. };
  23537. ECEventProcessor.prototype.afterTrigger = function () {
  23538. // Make sure the eventInfo wont be used in next trigger.
  23539. this.eventInfo = null;
  23540. };
  23541. return ECEventProcessor;
  23542. }();
  23543. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23544. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  23545. var seriesSymbolTask = {
  23546. createOnAllSeries: true,
  23547. // For legend.
  23548. performRawSeries: true,
  23549. reset: function (seriesModel, ecModel) {
  23550. var data = seriesModel.getData();
  23551. if (seriesModel.legendIcon) {
  23552. data.setVisual('legendIcon', seriesModel.legendIcon);
  23553. }
  23554. if (!seriesModel.hasSymbolVisual) {
  23555. return;
  23556. }
  23557. var symbolOptions = {};
  23558. var symbolOptionsCb = {};
  23559. var hasCallback = false;
  23560. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23561. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23562. var val = seriesModel.get(symbolPropName);
  23563. if (isFunction(val)) {
  23564. hasCallback = true;
  23565. symbolOptionsCb[symbolPropName] = val;
  23566. } else {
  23567. symbolOptions[symbolPropName] = val;
  23568. }
  23569. }
  23570. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23571. data.setVisual(extend({
  23572. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23573. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23574. }, symbolOptions)); // Only visible series has each data be visual encoded
  23575. if (ecModel.isSeriesFiltered(seriesModel)) {
  23576. return;
  23577. }
  23578. var symbolPropsCb = keys(symbolOptionsCb);
  23579. function dataEach(data, idx) {
  23580. var rawValue = seriesModel.getRawValue(idx);
  23581. var params = seriesModel.getDataParams(idx);
  23582. for (var i = 0; i < symbolPropsCb.length; i++) {
  23583. var symbolPropName = symbolPropsCb[i];
  23584. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23585. }
  23586. }
  23587. return {
  23588. dataEach: hasCallback ? dataEach : null
  23589. };
  23590. }
  23591. };
  23592. var dataSymbolTask = {
  23593. createOnAllSeries: true,
  23594. // For legend.
  23595. performRawSeries: true,
  23596. reset: function (seriesModel, ecModel) {
  23597. if (!seriesModel.hasSymbolVisual) {
  23598. return;
  23599. } // Only visible series has each data be visual encoded
  23600. if (ecModel.isSeriesFiltered(seriesModel)) {
  23601. return;
  23602. }
  23603. var data = seriesModel.getData();
  23604. function dataEach(data, idx) {
  23605. var itemModel = data.getItemModel(idx);
  23606. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  23607. var symbolPropName = SYMBOL_PROPS[i];
  23608. var val = itemModel.getShallow(symbolPropName, true);
  23609. if (val != null) {
  23610. data.setItemVisual(idx, symbolPropName, val);
  23611. }
  23612. }
  23613. }
  23614. return {
  23615. dataEach: data.hasItemOption ? dataEach : null
  23616. };
  23617. }
  23618. };
  23619. /*
  23620. * Licensed to the Apache Software Foundation (ASF) under one
  23621. * or more contributor license agreements. See the NOTICE file
  23622. * distributed with this work for additional information
  23623. * regarding copyright ownership. The ASF licenses this file
  23624. * to you under the Apache License, Version 2.0 (the
  23625. * "License"); you may not use this file except in compliance
  23626. * with the License. You may obtain a copy of the License at
  23627. *
  23628. * http://www.apache.org/licenses/LICENSE-2.0
  23629. *
  23630. * Unless required by applicable law or agreed to in writing,
  23631. * software distributed under the License is distributed on an
  23632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23633. * KIND, either express or implied. See the License for the
  23634. * specific language governing permissions and limitations
  23635. * under the License.
  23636. */
  23637. /**
  23638. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23639. */
  23640. /*
  23641. * Licensed to the Apache Software Foundation (ASF) under one
  23642. * or more contributor license agreements. See the NOTICE file
  23643. * distributed with this work for additional information
  23644. * regarding copyright ownership. The ASF licenses this file
  23645. * to you under the Apache License, Version 2.0 (the
  23646. * "License"); you may not use this file except in compliance
  23647. * with the License. You may obtain a copy of the License at
  23648. *
  23649. * http://www.apache.org/licenses/LICENSE-2.0
  23650. *
  23651. * Unless required by applicable law or agreed to in writing,
  23652. * software distributed under the License is distributed on an
  23653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23654. * KIND, either express or implied. See the License for the
  23655. * specific language governing permissions and limitations
  23656. * under the License.
  23657. */
  23658. function getItemVisualFromData(data, dataIndex, key) {
  23659. switch (key) {
  23660. case 'color':
  23661. var style = data.getItemVisual(dataIndex, 'style');
  23662. return style[data.getVisual('drawType')];
  23663. case 'opacity':
  23664. return data.getItemVisual(dataIndex, 'style').opacity;
  23665. case 'symbol':
  23666. case 'symbolSize':
  23667. case 'liftZ':
  23668. return data.getItemVisual(dataIndex, key);
  23669. default:
  23670. if ("development" !== 'production') {
  23671. console.warn("Unknown visual type " + key);
  23672. }
  23673. }
  23674. }
  23675. function getVisualFromData(data, key) {
  23676. switch (key) {
  23677. case 'color':
  23678. var style = data.getVisual('style');
  23679. return style[data.getVisual('drawType')];
  23680. case 'opacity':
  23681. return data.getVisual('style').opacity;
  23682. case 'symbol':
  23683. case 'symbolSize':
  23684. case 'liftZ':
  23685. return data.getVisual(key);
  23686. default:
  23687. if ("development" !== 'production') {
  23688. console.warn("Unknown visual type " + key);
  23689. }
  23690. }
  23691. }
  23692. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23693. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23694. function getSeriesIndices(ecModel, payload) {
  23695. var seriesIndices = [];
  23696. ecModel.eachComponent({
  23697. mainType: 'series',
  23698. subType: seriesType,
  23699. query: payload
  23700. }, function (seriesModel) {
  23701. seriesIndices.push(seriesModel.seriesIndex);
  23702. });
  23703. return seriesIndices;
  23704. }
  23705. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23706. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23707. payload = extend({}, payload);
  23708. if ("development" !== 'production') {
  23709. deprecateReplaceLog(payload.type, eventsMap[1]);
  23710. }
  23711. api.dispatchAction(extend(payload, {
  23712. type: eventsMap[1],
  23713. seriesIndex: getSeriesIndices(ecModel, payload)
  23714. }));
  23715. });
  23716. });
  23717. }
  23718. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23719. var legacyEventName = type + eventPostfix;
  23720. if (!ecIns.isSilent(legacyEventName)) {
  23721. if ("development" !== 'production') {
  23722. deprecateLog("event " + legacyEventName + " is deprecated.");
  23723. }
  23724. ecModel.eachComponent({
  23725. mainType: 'series',
  23726. subType: 'pie'
  23727. }, function (seriesModel) {
  23728. var seriesIndex = seriesModel.seriesIndex;
  23729. var selectedMap = seriesModel.option.selectedMap;
  23730. var selected = payload.selected;
  23731. for (var i = 0; i < selected.length; i++) {
  23732. if (selected[i].seriesIndex === seriesIndex) {
  23733. var data = seriesModel.getData();
  23734. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23735. ecIns.trigger(legacyEventName, {
  23736. type: legacyEventName,
  23737. seriesId: seriesModel.id,
  23738. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23739. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  23740. });
  23741. }
  23742. }
  23743. });
  23744. }
  23745. }
  23746. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23747. messageCenter.on('selectchanged', function (params) {
  23748. var ecModel = api.getModel();
  23749. if (params.isFromClick) {
  23750. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23751. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23752. } else if (params.fromAction === 'select') {
  23753. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23754. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23755. } else if (params.fromAction === 'unselect') {
  23756. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23757. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23758. }
  23759. });
  23760. }
  23761. /*
  23762. * Licensed to the Apache Software Foundation (ASF) under one
  23763. * or more contributor license agreements. See the NOTICE file
  23764. * distributed with this work for additional information
  23765. * regarding copyright ownership. The ASF licenses this file
  23766. * to you under the Apache License, Version 2.0 (the
  23767. * "License"); you may not use this file except in compliance
  23768. * with the License. You may obtain a copy of the License at
  23769. *
  23770. * http://www.apache.org/licenses/LICENSE-2.0
  23771. *
  23772. * Unless required by applicable law or agreed to in writing,
  23773. * software distributed under the License is distributed on an
  23774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23775. * KIND, either express or implied. See the License for the
  23776. * specific language governing permissions and limitations
  23777. * under the License.
  23778. */
  23779. /**
  23780. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23781. */
  23782. /*
  23783. * Licensed to the Apache Software Foundation (ASF) under one
  23784. * or more contributor license agreements. See the NOTICE file
  23785. * distributed with this work for additional information
  23786. * regarding copyright ownership. The ASF licenses this file
  23787. * to you under the Apache License, Version 2.0 (the
  23788. * "License"); you may not use this file except in compliance
  23789. * with the License. You may obtain a copy of the License at
  23790. *
  23791. * http://www.apache.org/licenses/LICENSE-2.0
  23792. *
  23793. * Unless required by applicable law or agreed to in writing,
  23794. * software distributed under the License is distributed on an
  23795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23796. * KIND, either express or implied. See the License for the
  23797. * specific language governing permissions and limitations
  23798. * under the License.
  23799. */
  23800. function findEventDispatcher(target, det, returnFirstMatch) {
  23801. var found;
  23802. while (target) {
  23803. if (det(target)) {
  23804. found = target;
  23805. if (returnFirstMatch) {
  23806. break;
  23807. }
  23808. }
  23809. target = target.__hostTarget || target.parent;
  23810. }
  23811. return found;
  23812. }
  23813. var wmUniqueIndex = Math.round(Math.random() * 9);
  23814. var supportDefineProperty = typeof Object.defineProperty === 'function';
  23815. var WeakMap = (function () {
  23816. function WeakMap() {
  23817. this._id = '__ec_inner_' + wmUniqueIndex++;
  23818. }
  23819. WeakMap.prototype.get = function (key) {
  23820. return this._guard(key)[this._id];
  23821. };
  23822. WeakMap.prototype.set = function (key, value) {
  23823. var target = this._guard(key);
  23824. if (supportDefineProperty) {
  23825. Object.defineProperty(target, this._id, {
  23826. value: value,
  23827. enumerable: false,
  23828. configurable: true
  23829. });
  23830. }
  23831. else {
  23832. target[this._id] = value;
  23833. }
  23834. return this;
  23835. };
  23836. WeakMap.prototype["delete"] = function (key) {
  23837. if (this.has(key)) {
  23838. delete this._guard(key)[this._id];
  23839. return true;
  23840. }
  23841. return false;
  23842. };
  23843. WeakMap.prototype.has = function (key) {
  23844. return !!this._guard(key)[this._id];
  23845. };
  23846. WeakMap.prototype._guard = function (key) {
  23847. if (key !== Object(key)) {
  23848. throw TypeError('Value of WeakMap is not a non-null object.');
  23849. }
  23850. return key;
  23851. };
  23852. return WeakMap;
  23853. }());
  23854. /**
  23855. * Triangle shape
  23856. * @inner
  23857. */
  23858. var Triangle = Path.extend({
  23859. type: 'triangle',
  23860. shape: {
  23861. cx: 0,
  23862. cy: 0,
  23863. width: 0,
  23864. height: 0
  23865. },
  23866. buildPath: function (path, shape) {
  23867. var cx = shape.cx;
  23868. var cy = shape.cy;
  23869. var width = shape.width / 2;
  23870. var height = shape.height / 2;
  23871. path.moveTo(cx, cy - height);
  23872. path.lineTo(cx + width, cy + height);
  23873. path.lineTo(cx - width, cy + height);
  23874. path.closePath();
  23875. }
  23876. });
  23877. /**
  23878. * Diamond shape
  23879. * @inner
  23880. */
  23881. var Diamond = Path.extend({
  23882. type: 'diamond',
  23883. shape: {
  23884. cx: 0,
  23885. cy: 0,
  23886. width: 0,
  23887. height: 0
  23888. },
  23889. buildPath: function (path, shape) {
  23890. var cx = shape.cx;
  23891. var cy = shape.cy;
  23892. var width = shape.width / 2;
  23893. var height = shape.height / 2;
  23894. path.moveTo(cx, cy - height);
  23895. path.lineTo(cx + width, cy);
  23896. path.lineTo(cx, cy + height);
  23897. path.lineTo(cx - width, cy);
  23898. path.closePath();
  23899. }
  23900. });
  23901. /**
  23902. * Pin shape
  23903. * @inner
  23904. */
  23905. var Pin = Path.extend({
  23906. type: 'pin',
  23907. shape: {
  23908. // x, y on the cusp
  23909. x: 0,
  23910. y: 0,
  23911. width: 0,
  23912. height: 0
  23913. },
  23914. buildPath: function (path, shape) {
  23915. var x = shape.x;
  23916. var y = shape.y;
  23917. var w = shape.width / 5 * 3; // Height must be larger than width
  23918. var h = Math.max(w, shape.height);
  23919. var r = w / 2; // Dist on y with tangent point and circle center
  23920. var dy = r * r / (h - r);
  23921. var cy = y - h + r + dy;
  23922. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  23923. var dx = Math.cos(angle) * r;
  23924. var tanX = Math.sin(angle);
  23925. var tanY = Math.cos(angle);
  23926. var cpLen = r * 0.6;
  23927. var cpLen2 = r * 0.7;
  23928. path.moveTo(x - dx, cy + dy);
  23929. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  23930. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  23931. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  23932. path.closePath();
  23933. }
  23934. });
  23935. /**
  23936. * Arrow shape
  23937. * @inner
  23938. */
  23939. var Arrow = Path.extend({
  23940. type: 'arrow',
  23941. shape: {
  23942. x: 0,
  23943. y: 0,
  23944. width: 0,
  23945. height: 0
  23946. },
  23947. buildPath: function (ctx, shape) {
  23948. var height = shape.height;
  23949. var width = shape.width;
  23950. var x = shape.x;
  23951. var y = shape.y;
  23952. var dx = width / 3 * 2;
  23953. ctx.moveTo(x, y);
  23954. ctx.lineTo(x + dx, y + height);
  23955. ctx.lineTo(x, y + height / 4 * 3);
  23956. ctx.lineTo(x - dx, y + height);
  23957. ctx.lineTo(x, y);
  23958. ctx.closePath();
  23959. }
  23960. });
  23961. /**
  23962. * Map of path contructors
  23963. */
  23964. // TODO Use function to build symbol path.
  23965. var symbolCtors = {
  23966. line: Line,
  23967. rect: Rect,
  23968. roundRect: Rect,
  23969. square: Rect,
  23970. circle: Circle,
  23971. diamond: Diamond,
  23972. pin: Pin,
  23973. arrow: Arrow,
  23974. triangle: Triangle
  23975. };
  23976. var symbolShapeMakers = {
  23977. line: function (x, y, w, h, shape) {
  23978. shape.x1 = x;
  23979. shape.y1 = y + h / 2;
  23980. shape.x2 = x + w;
  23981. shape.y2 = y + h / 2;
  23982. },
  23983. rect: function (x, y, w, h, shape) {
  23984. shape.x = x;
  23985. shape.y = y;
  23986. shape.width = w;
  23987. shape.height = h;
  23988. },
  23989. roundRect: function (x, y, w, h, shape) {
  23990. shape.x = x;
  23991. shape.y = y;
  23992. shape.width = w;
  23993. shape.height = h;
  23994. shape.r = Math.min(w, h) / 4;
  23995. },
  23996. square: function (x, y, w, h, shape) {
  23997. var size = Math.min(w, h);
  23998. shape.x = x;
  23999. shape.y = y;
  24000. shape.width = size;
  24001. shape.height = size;
  24002. },
  24003. circle: function (x, y, w, h, shape) {
  24004. // Put circle in the center of square
  24005. shape.cx = x + w / 2;
  24006. shape.cy = y + h / 2;
  24007. shape.r = Math.min(w, h) / 2;
  24008. },
  24009. diamond: function (x, y, w, h, shape) {
  24010. shape.cx = x + w / 2;
  24011. shape.cy = y + h / 2;
  24012. shape.width = w;
  24013. shape.height = h;
  24014. },
  24015. pin: function (x, y, w, h, shape) {
  24016. shape.x = x + w / 2;
  24017. shape.y = y + h / 2;
  24018. shape.width = w;
  24019. shape.height = h;
  24020. },
  24021. arrow: function (x, y, w, h, shape) {
  24022. shape.x = x + w / 2;
  24023. shape.y = y + h / 2;
  24024. shape.width = w;
  24025. shape.height = h;
  24026. },
  24027. triangle: function (x, y, w, h, shape) {
  24028. shape.cx = x + w / 2;
  24029. shape.cy = y + h / 2;
  24030. shape.width = w;
  24031. shape.height = h;
  24032. }
  24033. };
  24034. var symbolBuildProxies = {};
  24035. each(symbolCtors, function (Ctor, name) {
  24036. symbolBuildProxies[name] = new Ctor();
  24037. });
  24038. var SymbolClz = Path.extend({
  24039. type: 'symbol',
  24040. shape: {
  24041. symbolType: '',
  24042. x: 0,
  24043. y: 0,
  24044. width: 0,
  24045. height: 0
  24046. },
  24047. calculateTextPosition: function (out, config, rect) {
  24048. var res = calculateTextPosition(out, config, rect);
  24049. var shape = this.shape;
  24050. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24051. res.y = rect.y + rect.height * 0.4;
  24052. }
  24053. return res;
  24054. },
  24055. buildPath: function (ctx, shape, inBundle) {
  24056. var symbolType = shape.symbolType;
  24057. if (symbolType !== 'none') {
  24058. var proxySymbol = symbolBuildProxies[symbolType];
  24059. if (!proxySymbol) {
  24060. // Default rect
  24061. symbolType = 'rect';
  24062. proxySymbol = symbolBuildProxies[symbolType];
  24063. }
  24064. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24065. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24066. }
  24067. }
  24068. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24069. function symbolPathSetColor(color, innerColor) {
  24070. if (this.type !== 'image') {
  24071. var symbolStyle = this.style;
  24072. if (this.__isEmptyBrush) {
  24073. symbolStyle.stroke = color;
  24074. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24075. symbolStyle.lineWidth = 2;
  24076. } else if (this.shape.symbolType === 'line') {
  24077. symbolStyle.stroke = color;
  24078. } else {
  24079. symbolStyle.fill = color;
  24080. }
  24081. this.markRedraw();
  24082. }
  24083. }
  24084. /**
  24085. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24086. */
  24087. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24088. keepAspect) {
  24089. // TODO Support image object, DynamicImage.
  24090. var isEmpty = symbolType.indexOf('empty') === 0;
  24091. if (isEmpty) {
  24092. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24093. }
  24094. var symbolPath;
  24095. if (symbolType.indexOf('image://') === 0) {
  24096. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24097. } else if (symbolType.indexOf('path://') === 0) {
  24098. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24099. } else {
  24100. symbolPath = new SymbolClz({
  24101. shape: {
  24102. symbolType: symbolType,
  24103. x: x,
  24104. y: y,
  24105. width: w,
  24106. height: h
  24107. }
  24108. });
  24109. }
  24110. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24111. symbolPath.setColor = symbolPathSetColor;
  24112. if (color) {
  24113. symbolPath.setColor(color);
  24114. }
  24115. return symbolPath;
  24116. }
  24117. function normalizeSymbolSize(symbolSize) {
  24118. if (!isArray(symbolSize)) {
  24119. symbolSize = [+symbolSize, +symbolSize];
  24120. }
  24121. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24122. }
  24123. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24124. if (symbolOffset == null) {
  24125. return;
  24126. }
  24127. if (!isArray(symbolOffset)) {
  24128. symbolOffset = [symbolOffset, symbolOffset];
  24129. }
  24130. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24131. }
  24132. function createLinearGradient(ctx, obj, rect) {
  24133. var x = obj.x == null ? 0 : obj.x;
  24134. var x2 = obj.x2 == null ? 1 : obj.x2;
  24135. var y = obj.y == null ? 0 : obj.y;
  24136. var y2 = obj.y2 == null ? 0 : obj.y2;
  24137. if (!obj.global) {
  24138. x = x * rect.width + rect.x;
  24139. x2 = x2 * rect.width + rect.x;
  24140. y = y * rect.height + rect.y;
  24141. y2 = y2 * rect.height + rect.y;
  24142. }
  24143. x = isNaN(x) ? 0 : x;
  24144. x2 = isNaN(x2) ? 1 : x2;
  24145. y = isNaN(y) ? 0 : y;
  24146. y2 = isNaN(y2) ? 0 : y2;
  24147. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24148. return canvasGradient;
  24149. }
  24150. function createRadialGradient(ctx, obj, rect) {
  24151. var width = rect.width;
  24152. var height = rect.height;
  24153. var min = Math.min(width, height);
  24154. var x = obj.x == null ? 0.5 : obj.x;
  24155. var y = obj.y == null ? 0.5 : obj.y;
  24156. var r = obj.r == null ? 0.5 : obj.r;
  24157. if (!obj.global) {
  24158. x = x * width + rect.x;
  24159. y = y * height + rect.y;
  24160. r = r * min;
  24161. }
  24162. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24163. return canvasGradient;
  24164. }
  24165. function getCanvasGradient(ctx, obj, rect) {
  24166. var canvasGradient = obj.type === 'radial'
  24167. ? createRadialGradient(ctx, obj, rect)
  24168. : createLinearGradient(ctx, obj, rect);
  24169. var colorStops = obj.colorStops;
  24170. for (var i = 0; i < colorStops.length; i++) {
  24171. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24172. }
  24173. return canvasGradient;
  24174. }
  24175. function isClipPathChanged(clipPaths, prevClipPaths) {
  24176. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24177. return false;
  24178. }
  24179. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24180. return true;
  24181. }
  24182. for (var i = 0; i < clipPaths.length; i++) {
  24183. if (clipPaths[i] !== prevClipPaths[i]) {
  24184. return true;
  24185. }
  24186. }
  24187. return false;
  24188. }
  24189. function parseInt10(val) {
  24190. return parseInt(val, 10);
  24191. }
  24192. function getSize(root, whIdx, opts) {
  24193. var wh = ['width', 'height'][whIdx];
  24194. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24195. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24196. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24197. if (opts[wh] != null && opts[wh] !== 'auto') {
  24198. return parseFloat(opts[wh]);
  24199. }
  24200. var stl = document.defaultView.getComputedStyle(root);
  24201. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24202. - (parseInt10(stl[plt]) || 0)
  24203. - (parseInt10(stl[prb]) || 0)) | 0;
  24204. }
  24205. function normalizeLineDash(lineType, lineWidth) {
  24206. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24207. return null;
  24208. }
  24209. return lineType === 'dashed'
  24210. ? [4 * lineWidth, 2 * lineWidth]
  24211. : lineType === 'dotted'
  24212. ? [lineWidth]
  24213. : isNumber(lineType)
  24214. ? [lineType] : isArray(lineType) ? lineType : null;
  24215. }
  24216. function getLineDash(el) {
  24217. var style = el.style;
  24218. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24219. var lineDashOffset = style.lineDashOffset;
  24220. if (lineDash) {
  24221. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24222. if (lineScale_1 && lineScale_1 !== 1) {
  24223. lineDash = map(lineDash, function (rawVal) {
  24224. return rawVal / lineScale_1;
  24225. });
  24226. lineDashOffset /= lineScale_1;
  24227. }
  24228. }
  24229. return [lineDash, lineDashOffset];
  24230. }
  24231. var pathProxyForDraw = new PathProxy(true);
  24232. function styleHasStroke(style) {
  24233. var stroke = style.stroke;
  24234. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24235. }
  24236. function isValidStrokeFillStyle(strokeOrFill) {
  24237. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24238. }
  24239. function styleHasFill(style) {
  24240. var fill = style.fill;
  24241. return fill != null && fill !== 'none';
  24242. }
  24243. function doFillPath(ctx, style) {
  24244. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24245. var originalGlobalAlpha = ctx.globalAlpha;
  24246. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24247. ctx.fill();
  24248. ctx.globalAlpha = originalGlobalAlpha;
  24249. }
  24250. else {
  24251. ctx.fill();
  24252. }
  24253. }
  24254. function doStrokePath(ctx, style) {
  24255. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24256. var originalGlobalAlpha = ctx.globalAlpha;
  24257. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24258. ctx.stroke();
  24259. ctx.globalAlpha = originalGlobalAlpha;
  24260. }
  24261. else {
  24262. ctx.stroke();
  24263. }
  24264. }
  24265. function createCanvasPattern(ctx, pattern, el) {
  24266. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24267. if (isImageReady(image)) {
  24268. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24269. if (typeof DOMMatrix === 'function'
  24270. && canvasPattern
  24271. && canvasPattern.setTransform) {
  24272. var matrix = new DOMMatrix();
  24273. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24274. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24275. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24276. canvasPattern.setTransform(matrix);
  24277. }
  24278. return canvasPattern;
  24279. }
  24280. }
  24281. function brushPath(ctx, el, style, inBatch) {
  24282. var _a;
  24283. var hasStroke = styleHasStroke(style);
  24284. var hasFill = styleHasFill(style);
  24285. var strokePercent = style.strokePercent;
  24286. var strokePart = strokePercent < 1;
  24287. var firstDraw = !el.path;
  24288. if ((!el.silent || strokePart) && firstDraw) {
  24289. el.createPathProxy();
  24290. }
  24291. var path = el.path || pathProxyForDraw;
  24292. var dirtyFlag = el.__dirty;
  24293. if (!inBatch) {
  24294. var fill = style.fill;
  24295. var stroke = style.stroke;
  24296. var hasFillGradient = hasFill && !!fill.colorStops;
  24297. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24298. var hasFillPattern = hasFill && !!fill.image;
  24299. var hasStrokePattern = hasStroke && !!stroke.image;
  24300. var fillGradient = void 0;
  24301. var strokeGradient = void 0;
  24302. var fillPattern = void 0;
  24303. var strokePattern = void 0;
  24304. var rect = void 0;
  24305. if (hasFillGradient || hasStrokeGradient) {
  24306. rect = el.getBoundingRect();
  24307. }
  24308. if (hasFillGradient) {
  24309. fillGradient = dirtyFlag
  24310. ? getCanvasGradient(ctx, fill, rect)
  24311. : el.__canvasFillGradient;
  24312. el.__canvasFillGradient = fillGradient;
  24313. }
  24314. if (hasStrokeGradient) {
  24315. strokeGradient = dirtyFlag
  24316. ? getCanvasGradient(ctx, stroke, rect)
  24317. : el.__canvasStrokeGradient;
  24318. el.__canvasStrokeGradient = strokeGradient;
  24319. }
  24320. if (hasFillPattern) {
  24321. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24322. ? createCanvasPattern(ctx, fill, el)
  24323. : el.__canvasFillPattern;
  24324. el.__canvasFillPattern = fillPattern;
  24325. }
  24326. if (hasStrokePattern) {
  24327. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24328. ? createCanvasPattern(ctx, stroke, el)
  24329. : el.__canvasStrokePattern;
  24330. el.__canvasStrokePattern = fillPattern;
  24331. }
  24332. if (hasFillGradient) {
  24333. ctx.fillStyle = fillGradient;
  24334. }
  24335. else if (hasFillPattern) {
  24336. if (fillPattern) {
  24337. ctx.fillStyle = fillPattern;
  24338. }
  24339. else {
  24340. hasFill = false;
  24341. }
  24342. }
  24343. if (hasStrokeGradient) {
  24344. ctx.strokeStyle = strokeGradient;
  24345. }
  24346. else if (hasStrokePattern) {
  24347. if (strokePattern) {
  24348. ctx.strokeStyle = strokePattern;
  24349. }
  24350. else {
  24351. hasStroke = false;
  24352. }
  24353. }
  24354. }
  24355. var scale = el.getGlobalScale();
  24356. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24357. var lineDash;
  24358. var lineDashOffset;
  24359. if (ctx.setLineDash && style.lineDash) {
  24360. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24361. }
  24362. var needsRebuild = true;
  24363. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24364. path.setDPR(ctx.dpr);
  24365. if (strokePart) {
  24366. path.setContext(null);
  24367. }
  24368. else {
  24369. path.setContext(ctx);
  24370. needsRebuild = false;
  24371. }
  24372. path.reset();
  24373. el.buildPath(path, el.shape, inBatch);
  24374. path.toStatic();
  24375. el.pathUpdated();
  24376. }
  24377. if (needsRebuild) {
  24378. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24379. }
  24380. if (lineDash) {
  24381. ctx.setLineDash(lineDash);
  24382. ctx.lineDashOffset = lineDashOffset;
  24383. }
  24384. if (!inBatch) {
  24385. if (style.strokeFirst) {
  24386. if (hasStroke) {
  24387. doStrokePath(ctx, style);
  24388. }
  24389. if (hasFill) {
  24390. doFillPath(ctx, style);
  24391. }
  24392. }
  24393. else {
  24394. if (hasFill) {
  24395. doFillPath(ctx, style);
  24396. }
  24397. if (hasStroke) {
  24398. doStrokePath(ctx, style);
  24399. }
  24400. }
  24401. }
  24402. if (lineDash) {
  24403. ctx.setLineDash([]);
  24404. }
  24405. }
  24406. function brushImage(ctx, el, style) {
  24407. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24408. if (!image || !isImageReady(image)) {
  24409. return;
  24410. }
  24411. var x = style.x || 0;
  24412. var y = style.y || 0;
  24413. var width = el.getWidth();
  24414. var height = el.getHeight();
  24415. var aspect = image.width / image.height;
  24416. if (width == null && height != null) {
  24417. width = height * aspect;
  24418. }
  24419. else if (height == null && width != null) {
  24420. height = width / aspect;
  24421. }
  24422. else if (width == null && height == null) {
  24423. width = image.width;
  24424. height = image.height;
  24425. }
  24426. if (style.sWidth && style.sHeight) {
  24427. var sx = style.sx || 0;
  24428. var sy = style.sy || 0;
  24429. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24430. }
  24431. else if (style.sx && style.sy) {
  24432. var sx = style.sx;
  24433. var sy = style.sy;
  24434. var sWidth = width - sx;
  24435. var sHeight = height - sy;
  24436. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24437. }
  24438. else {
  24439. ctx.drawImage(image, x, y, width, height);
  24440. }
  24441. }
  24442. function brushText(ctx, el, style) {
  24443. var _a;
  24444. var text = style.text;
  24445. text != null && (text += '');
  24446. if (text) {
  24447. ctx.font = style.font || DEFAULT_FONT;
  24448. ctx.textAlign = style.textAlign;
  24449. ctx.textBaseline = style.textBaseline;
  24450. var lineDash = void 0;
  24451. var lineDashOffset = void 0;
  24452. if (ctx.setLineDash && style.lineDash) {
  24453. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24454. }
  24455. if (lineDash) {
  24456. ctx.setLineDash(lineDash);
  24457. ctx.lineDashOffset = lineDashOffset;
  24458. }
  24459. if (style.strokeFirst) {
  24460. if (styleHasStroke(style)) {
  24461. ctx.strokeText(text, style.x, style.y);
  24462. }
  24463. if (styleHasFill(style)) {
  24464. ctx.fillText(text, style.x, style.y);
  24465. }
  24466. }
  24467. else {
  24468. if (styleHasFill(style)) {
  24469. ctx.fillText(text, style.x, style.y);
  24470. }
  24471. if (styleHasStroke(style)) {
  24472. ctx.strokeText(text, style.x, style.y);
  24473. }
  24474. }
  24475. if (lineDash) {
  24476. ctx.setLineDash([]);
  24477. }
  24478. }
  24479. }
  24480. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24481. var STROKE_PROPS = [
  24482. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24483. ];
  24484. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24485. var styleChanged = false;
  24486. if (!forceSetAll) {
  24487. prevStyle = prevStyle || {};
  24488. if (style === prevStyle) {
  24489. return false;
  24490. }
  24491. }
  24492. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24493. flushPathDrawn(ctx, scope);
  24494. styleChanged = true;
  24495. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24496. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24497. }
  24498. if (forceSetAll || style.blend !== prevStyle.blend) {
  24499. if (!styleChanged) {
  24500. flushPathDrawn(ctx, scope);
  24501. styleChanged = true;
  24502. }
  24503. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24504. }
  24505. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24506. var propName = SHADOW_NUMBER_PROPS[i];
  24507. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24508. if (!styleChanged) {
  24509. flushPathDrawn(ctx, scope);
  24510. styleChanged = true;
  24511. }
  24512. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24513. }
  24514. }
  24515. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24516. if (!styleChanged) {
  24517. flushPathDrawn(ctx, scope);
  24518. styleChanged = true;
  24519. }
  24520. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24521. }
  24522. return styleChanged;
  24523. }
  24524. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24525. var style = getStyle(el, scope.inHover);
  24526. var prevStyle = forceSetAll
  24527. ? null
  24528. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24529. if (style === prevStyle) {
  24530. return false;
  24531. }
  24532. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24533. if (forceSetAll || style.fill !== prevStyle.fill) {
  24534. if (!styleChanged) {
  24535. flushPathDrawn(ctx, scope);
  24536. styleChanged = true;
  24537. }
  24538. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24539. }
  24540. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24541. if (!styleChanged) {
  24542. flushPathDrawn(ctx, scope);
  24543. styleChanged = true;
  24544. }
  24545. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24546. }
  24547. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24548. if (!styleChanged) {
  24549. flushPathDrawn(ctx, scope);
  24550. styleChanged = true;
  24551. }
  24552. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24553. }
  24554. if (el.hasStroke()) {
  24555. var lineWidth = style.lineWidth;
  24556. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24557. if (ctx.lineWidth !== newLineWidth) {
  24558. if (!styleChanged) {
  24559. flushPathDrawn(ctx, scope);
  24560. styleChanged = true;
  24561. }
  24562. ctx.lineWidth = newLineWidth;
  24563. }
  24564. }
  24565. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24566. var prop = STROKE_PROPS[i];
  24567. var propName = prop[0];
  24568. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24569. if (!styleChanged) {
  24570. flushPathDrawn(ctx, scope);
  24571. styleChanged = true;
  24572. }
  24573. ctx[propName] = style[propName] || prop[1];
  24574. }
  24575. }
  24576. return styleChanged;
  24577. }
  24578. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24579. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24580. }
  24581. function setContextTransform(ctx, el) {
  24582. var m = el.transform;
  24583. var dpr = ctx.dpr || 1;
  24584. if (m) {
  24585. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24586. }
  24587. else {
  24588. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24589. }
  24590. }
  24591. function updateClipStatus(clipPaths, ctx, scope) {
  24592. var allClipped = false;
  24593. for (var i = 0; i < clipPaths.length; i++) {
  24594. var clipPath = clipPaths[i];
  24595. allClipped = allClipped || clipPath.isZeroArea();
  24596. setContextTransform(ctx, clipPath);
  24597. ctx.beginPath();
  24598. clipPath.buildPath(ctx, clipPath.shape);
  24599. ctx.clip();
  24600. }
  24601. scope.allClipped = allClipped;
  24602. }
  24603. function isTransformChanged(m0, m1) {
  24604. if (m0 && m1) {
  24605. return m0[0] !== m1[0]
  24606. || m0[1] !== m1[1]
  24607. || m0[2] !== m1[2]
  24608. || m0[3] !== m1[3]
  24609. || m0[4] !== m1[4]
  24610. || m0[5] !== m1[5];
  24611. }
  24612. else if (!m0 && !m1) {
  24613. return false;
  24614. }
  24615. return true;
  24616. }
  24617. var DRAW_TYPE_PATH = 1;
  24618. var DRAW_TYPE_IMAGE = 2;
  24619. var DRAW_TYPE_TEXT = 3;
  24620. var DRAW_TYPE_INCREMENTAL = 4;
  24621. function canPathBatch(style) {
  24622. var hasFill = styleHasFill(style);
  24623. var hasStroke = styleHasStroke(style);
  24624. return !(style.lineDash
  24625. || !(+hasFill ^ +hasStroke)
  24626. || (hasFill && typeof style.fill !== 'string')
  24627. || (hasStroke && typeof style.stroke !== 'string')
  24628. || style.strokePercent < 1
  24629. || style.strokeOpacity < 1
  24630. || style.fillOpacity < 1);
  24631. }
  24632. function flushPathDrawn(ctx, scope) {
  24633. scope.batchFill && ctx.fill();
  24634. scope.batchStroke && ctx.stroke();
  24635. scope.batchFill = '';
  24636. scope.batchStroke = '';
  24637. }
  24638. function getStyle(el, inHover) {
  24639. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24640. }
  24641. function brushSingle(ctx, el) {
  24642. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24643. }
  24644. function brush(ctx, el, scope, isLast) {
  24645. var m = el.transform;
  24646. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24647. el.__dirty &= ~REDRAW_BIT;
  24648. el.__isRendered = false;
  24649. return;
  24650. }
  24651. var clipPaths = el.__clipPaths;
  24652. var prevElClipPaths = scope.prevElClipPaths;
  24653. var forceSetTransform = false;
  24654. var forceSetStyle = false;
  24655. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24656. if (prevElClipPaths && prevElClipPaths.length) {
  24657. flushPathDrawn(ctx, scope);
  24658. ctx.restore();
  24659. forceSetStyle = forceSetTransform = true;
  24660. scope.prevElClipPaths = null;
  24661. scope.allClipped = false;
  24662. scope.prevEl = null;
  24663. }
  24664. if (clipPaths && clipPaths.length) {
  24665. flushPathDrawn(ctx, scope);
  24666. ctx.save();
  24667. updateClipStatus(clipPaths, ctx, scope);
  24668. forceSetTransform = true;
  24669. }
  24670. scope.prevElClipPaths = clipPaths;
  24671. }
  24672. if (scope.allClipped) {
  24673. el.__isRendered = false;
  24674. return;
  24675. }
  24676. el.beforeBrush && el.beforeBrush();
  24677. el.innerBeforeBrush();
  24678. var prevEl = scope.prevEl;
  24679. if (!prevEl) {
  24680. forceSetStyle = forceSetTransform = true;
  24681. }
  24682. var canBatchPath = el instanceof Path
  24683. && el.autoBatch
  24684. && canPathBatch(el.style);
  24685. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24686. flushPathDrawn(ctx, scope);
  24687. setContextTransform(ctx, el);
  24688. }
  24689. else if (!canBatchPath) {
  24690. flushPathDrawn(ctx, scope);
  24691. }
  24692. var style = getStyle(el, scope.inHover);
  24693. if (el instanceof Path) {
  24694. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24695. forceSetStyle = true;
  24696. scope.lastDrawType = DRAW_TYPE_PATH;
  24697. }
  24698. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24699. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24700. ctx.beginPath();
  24701. }
  24702. brushPath(ctx, el, style, canBatchPath);
  24703. if (canBatchPath) {
  24704. scope.batchFill = style.fill || '';
  24705. scope.batchStroke = style.stroke || '';
  24706. }
  24707. }
  24708. else {
  24709. if (el instanceof TSpan) {
  24710. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24711. forceSetStyle = true;
  24712. scope.lastDrawType = DRAW_TYPE_TEXT;
  24713. }
  24714. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24715. brushText(ctx, el, style);
  24716. }
  24717. else if (el instanceof ZRImage) {
  24718. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24719. forceSetStyle = true;
  24720. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24721. }
  24722. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24723. brushImage(ctx, el, style);
  24724. }
  24725. else if (el.getTemporalDisplayables) {
  24726. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24727. forceSetStyle = true;
  24728. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24729. }
  24730. brushIncremental(ctx, el, scope);
  24731. }
  24732. }
  24733. if (canBatchPath && isLast) {
  24734. flushPathDrawn(ctx, scope);
  24735. }
  24736. el.innerAfterBrush();
  24737. el.afterBrush && el.afterBrush();
  24738. scope.prevEl = el;
  24739. el.__dirty = 0;
  24740. el.__isRendered = true;
  24741. }
  24742. function brushIncremental(ctx, el, scope) {
  24743. var displayables = el.getDisplayables();
  24744. var temporalDisplayables = el.getTemporalDisplayables();
  24745. ctx.save();
  24746. var innerScope = {
  24747. prevElClipPaths: null,
  24748. prevEl: null,
  24749. allClipped: false,
  24750. viewWidth: scope.viewWidth,
  24751. viewHeight: scope.viewHeight,
  24752. inHover: scope.inHover
  24753. };
  24754. var i;
  24755. var len;
  24756. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24757. var displayable = displayables[i];
  24758. displayable.beforeBrush && displayable.beforeBrush();
  24759. displayable.innerBeforeBrush();
  24760. brush(ctx, displayable, innerScope, i === len - 1);
  24761. displayable.innerAfterBrush();
  24762. displayable.afterBrush && displayable.afterBrush();
  24763. innerScope.prevEl = displayable;
  24764. }
  24765. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24766. var displayable = temporalDisplayables[i_1];
  24767. displayable.beforeBrush && displayable.beforeBrush();
  24768. displayable.innerBeforeBrush();
  24769. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24770. displayable.innerAfterBrush();
  24771. displayable.afterBrush && displayable.afterBrush();
  24772. innerScope.prevEl = displayable;
  24773. }
  24774. el.clearTemporalDisplayables();
  24775. el.notClear = true;
  24776. ctx.restore();
  24777. }
  24778. var decalMap = new WeakMap();
  24779. var decalCache = new LRU(100);
  24780. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24781. /**
  24782. * Create or update pattern image from decal options
  24783. *
  24784. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24785. * @return {Pattern} pattern with generated image, null if no decal
  24786. */
  24787. function createOrUpdatePatternFromDecal(decalObject, api) {
  24788. if (decalObject === 'none') {
  24789. return null;
  24790. }
  24791. var dpr = api.getDevicePixelRatio();
  24792. var zr = api.getZr();
  24793. var isSVG = zr.painter.type === 'svg';
  24794. if (decalObject.dirty) {
  24795. decalMap["delete"](decalObject);
  24796. }
  24797. var oldPattern = decalMap.get(decalObject);
  24798. if (oldPattern) {
  24799. return oldPattern;
  24800. }
  24801. var decalOpt = defaults(decalObject, {
  24802. symbol: 'rect',
  24803. symbolSize: 1,
  24804. symbolKeepAspect: true,
  24805. color: 'rgba(0, 0, 0, 0.2)',
  24806. backgroundColor: null,
  24807. dashArrayX: 5,
  24808. dashArrayY: 5,
  24809. rotation: 0,
  24810. maxTileWidth: 512,
  24811. maxTileHeight: 512
  24812. });
  24813. if (decalOpt.backgroundColor === 'none') {
  24814. decalOpt.backgroundColor = null;
  24815. }
  24816. var pattern = {
  24817. repeat: 'repeat'
  24818. };
  24819. setPatternnSource(pattern);
  24820. pattern.rotation = decalOpt.rotation;
  24821. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24822. decalMap.set(decalObject, pattern);
  24823. decalObject.dirty = false;
  24824. return pattern;
  24825. function setPatternnSource(pattern) {
  24826. var keys = [dpr];
  24827. var isValidKey = true;
  24828. for (var i = 0; i < decalKeys.length; ++i) {
  24829. var value = decalOpt[decalKeys[i]];
  24830. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  24831. isValidKey = false;
  24832. break;
  24833. }
  24834. keys.push(value);
  24835. }
  24836. var cacheKey;
  24837. if (isValidKey) {
  24838. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24839. var cache = decalCache.get(cacheKey);
  24840. if (cache) {
  24841. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24842. }
  24843. }
  24844. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24845. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24846. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24847. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24848. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24849. var canvas = !isSVG && platformApi.createCanvas();
  24850. var svgRoot = isSVG && {
  24851. tag: 'g',
  24852. attrs: {},
  24853. key: 'dcl',
  24854. children: []
  24855. };
  24856. var pSize = getPatternSize();
  24857. var ctx;
  24858. if (canvas) {
  24859. canvas.width = pSize.width * dpr;
  24860. canvas.height = pSize.height * dpr;
  24861. ctx = canvas.getContext('2d');
  24862. }
  24863. brushDecal();
  24864. if (isValidKey) {
  24865. decalCache.put(cacheKey, canvas || svgRoot);
  24866. }
  24867. pattern.image = canvas;
  24868. pattern.svgElement = svgRoot;
  24869. pattern.svgWidth = pSize.width;
  24870. pattern.svgHeight = pSize.height;
  24871. /**
  24872. * Get minumum length that can make a repeatable pattern.
  24873. *
  24874. * @return {Object} pattern width and height
  24875. */
  24876. function getPatternSize() {
  24877. /**
  24878. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  24879. * |--- --- --- --- --- ...
  24880. * |-- -- -- -- -- -- -- -- ...
  24881. * |--- --- --- --- --- ...
  24882. * |-- -- -- -- -- -- -- -- ...
  24883. * So the minumum length of X is 15,
  24884. * which is the least common multiple of `3 + 2` and `2 + 1`
  24885. * |--- --- --- |--- --- ...
  24886. * |-- -- -- -- -- |-- -- -- ...
  24887. */
  24888. var width = 1;
  24889. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24890. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24891. }
  24892. var symbolRepeats = 1;
  24893. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  24894. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  24895. }
  24896. width *= symbolRepeats;
  24897. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  24898. if ("development" !== 'production') {
  24899. var warn = function (attrName) {
  24900. /* eslint-disable-next-line */
  24901. 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.");
  24902. };
  24903. if (width > decalOpt.maxTileWidth) {
  24904. warn('maxTileWidth');
  24905. }
  24906. if (height > decalOpt.maxTileHeight) {
  24907. warn('maxTileHeight');
  24908. }
  24909. }
  24910. return {
  24911. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  24912. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  24913. };
  24914. }
  24915. function brushDecal() {
  24916. if (ctx) {
  24917. ctx.clearRect(0, 0, canvas.width, canvas.height);
  24918. if (decalOpt.backgroundColor) {
  24919. ctx.fillStyle = decalOpt.backgroundColor;
  24920. ctx.fillRect(0, 0, canvas.width, canvas.height);
  24921. }
  24922. }
  24923. var ySum = 0;
  24924. for (var i = 0; i < dashArrayY.length; ++i) {
  24925. ySum += dashArrayY[i];
  24926. }
  24927. if (ySum <= 0) {
  24928. // dashArrayY is 0, draw nothing
  24929. return;
  24930. }
  24931. var y = -lineBlockLengthY;
  24932. var yId = 0;
  24933. var yIdTotal = 0;
  24934. var xId0 = 0;
  24935. while (y < pSize.height) {
  24936. if (yId % 2 === 0) {
  24937. var symbolYId = yIdTotal / 2 % symbolArray.length;
  24938. var x = 0;
  24939. var xId1 = 0;
  24940. var xId1Total = 0;
  24941. while (x < pSize.width * 2) {
  24942. var xSum = 0;
  24943. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  24944. xSum += dashArrayX[xId0][i];
  24945. }
  24946. if (xSum <= 0) {
  24947. // Skip empty line
  24948. break;
  24949. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  24950. if (xId1 % 2 === 0) {
  24951. var size = (1 - decalOpt.symbolSize) * 0.5;
  24952. var left = x + dashArrayX[xId0][xId1] * size;
  24953. var top_1 = y + dashArrayY[yId] * size;
  24954. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  24955. var height = dashArrayY[yId] * decalOpt.symbolSize;
  24956. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  24957. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  24958. }
  24959. x += dashArrayX[xId0][xId1];
  24960. ++xId1Total;
  24961. ++xId1;
  24962. if (xId1 === dashArrayX[xId0].length) {
  24963. xId1 = 0;
  24964. }
  24965. }
  24966. ++xId0;
  24967. if (xId0 === dashArrayX.length) {
  24968. xId0 = 0;
  24969. }
  24970. }
  24971. y += dashArrayY[yId];
  24972. ++yIdTotal;
  24973. ++yId;
  24974. if (yId === dashArrayY.length) {
  24975. yId = 0;
  24976. }
  24977. }
  24978. function brushSymbol(x, y, width, height, symbolType) {
  24979. var scale = isSVG ? 1 : dpr;
  24980. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  24981. if (isSVG) {
  24982. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  24983. if (symbolVNode) {
  24984. svgRoot.children.push(symbolVNode);
  24985. }
  24986. } else {
  24987. // Paint to canvas for all other renderers.
  24988. brushSingle(ctx, symbol);
  24989. }
  24990. }
  24991. }
  24992. }
  24993. }
  24994. /**
  24995. * Convert symbol array into normalized array
  24996. *
  24997. * @param {string | (string | string[])[]} symbol symbol input
  24998. * @return {string[][]} normolized symbol array
  24999. */
  25000. function normalizeSymbolArray(symbol) {
  25001. if (!symbol || symbol.length === 0) {
  25002. return [['rect']];
  25003. }
  25004. if (isString(symbol)) {
  25005. return [[symbol]];
  25006. }
  25007. var isAllString = true;
  25008. for (var i = 0; i < symbol.length; ++i) {
  25009. if (!isString(symbol[i])) {
  25010. isAllString = false;
  25011. break;
  25012. }
  25013. }
  25014. if (isAllString) {
  25015. return normalizeSymbolArray([symbol]);
  25016. }
  25017. var result = [];
  25018. for (var i = 0; i < symbol.length; ++i) {
  25019. if (isString(symbol[i])) {
  25020. result.push([symbol[i]]);
  25021. } else {
  25022. result.push(symbol[i]);
  25023. }
  25024. }
  25025. return result;
  25026. }
  25027. /**
  25028. * Convert dash input into dashArray
  25029. *
  25030. * @param {DecalDashArrayX} dash dash input
  25031. * @return {number[][]} normolized dash array
  25032. */
  25033. function normalizeDashArrayX(dash) {
  25034. if (!dash || dash.length === 0) {
  25035. return [[0, 0]];
  25036. }
  25037. if (isNumber(dash)) {
  25038. var dashValue = Math.ceil(dash);
  25039. return [[dashValue, dashValue]];
  25040. }
  25041. /**
  25042. * [20, 5] should be normalized into [[20, 5]],
  25043. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25044. */
  25045. var isAllNumber = true;
  25046. for (var i = 0; i < dash.length; ++i) {
  25047. if (!isNumber(dash[i])) {
  25048. isAllNumber = false;
  25049. break;
  25050. }
  25051. }
  25052. if (isAllNumber) {
  25053. return normalizeDashArrayX([dash]);
  25054. }
  25055. var result = [];
  25056. for (var i = 0; i < dash.length; ++i) {
  25057. if (isNumber(dash[i])) {
  25058. var dashValue = Math.ceil(dash[i]);
  25059. result.push([dashValue, dashValue]);
  25060. } else {
  25061. var dashValue = map(dash[i], function (n) {
  25062. return Math.ceil(n);
  25063. });
  25064. if (dashValue.length % 2 === 1) {
  25065. // [4, 2, 1] means |---- - -- |---- - -- |
  25066. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25067. result.push(dashValue.concat(dashValue));
  25068. } else {
  25069. result.push(dashValue);
  25070. }
  25071. }
  25072. }
  25073. return result;
  25074. }
  25075. /**
  25076. * Convert dash input into dashArray
  25077. *
  25078. * @param {DecalDashArrayY} dash dash input
  25079. * @return {number[]} normolized dash array
  25080. */
  25081. function normalizeDashArrayY(dash) {
  25082. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25083. return [0, 0];
  25084. }
  25085. if (isNumber(dash)) {
  25086. var dashValue_1 = Math.ceil(dash);
  25087. return [dashValue_1, dashValue_1];
  25088. }
  25089. var dashValue = map(dash, function (n) {
  25090. return Math.ceil(n);
  25091. });
  25092. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25093. }
  25094. /**
  25095. * Get block length of each line. A block is the length of dash line and space.
  25096. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25097. * that, so the block length of this line is 5.
  25098. *
  25099. * @param {number[][]} dash dash arrary of X or Y
  25100. * @return {number[]} block length of each line
  25101. */
  25102. function getLineBlockLengthX(dash) {
  25103. return map(dash, function (line) {
  25104. return getLineBlockLengthY(line);
  25105. });
  25106. }
  25107. function getLineBlockLengthY(dash) {
  25108. var blockLength = 0;
  25109. for (var i = 0; i < dash.length; ++i) {
  25110. blockLength += dash[i];
  25111. }
  25112. if (dash.length % 2 === 1) {
  25113. // [4, 2, 1] means |---- - -- |---- - -- |
  25114. // So total length is (4 + 2 + 1) * 2
  25115. return blockLength * 2;
  25116. }
  25117. return blockLength;
  25118. }
  25119. function decalVisual(ecModel, api) {
  25120. ecModel.eachRawSeries(function (seriesModel) {
  25121. if (ecModel.isSeriesFiltered(seriesModel)) {
  25122. return;
  25123. }
  25124. var data = seriesModel.getData();
  25125. if (data.hasItemVisual()) {
  25126. data.each(function (idx) {
  25127. var decal = data.getItemVisual(idx, 'decal');
  25128. if (decal) {
  25129. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25130. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25131. }
  25132. });
  25133. }
  25134. var decal = data.getVisual('decal');
  25135. if (decal) {
  25136. var style = data.getVisual('style');
  25137. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25138. }
  25139. });
  25140. }
  25141. var lifecycle = new Eventful();
  25142. // The implentations will be registered when installing the component.
  25143. // Avoid these code being bundled to the core module.
  25144. var implsStore = {}; // TODO Type
  25145. function registerImpl(name, impl) {
  25146. if ("development" !== 'production') {
  25147. if (implsStore[name]) {
  25148. error("Already has an implementation of " + name + ".");
  25149. }
  25150. }
  25151. implsStore[name] = impl;
  25152. }
  25153. function getImpl(name) {
  25154. if ("development" !== 'production') {
  25155. if (!implsStore[name]) {
  25156. error("Implementation of " + name + " doesn't exists.");
  25157. }
  25158. }
  25159. return implsStore[name];
  25160. }
  25161. var hasWindow = typeof window !== 'undefined';
  25162. var version$1 = '5.3.2';
  25163. var dependencies = {
  25164. zrender: '5.3.1'
  25165. };
  25166. var TEST_FRAME_REMAIN_TIME = 1;
  25167. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  25168. // So data stack stage should be in front of data processing stage.
  25169. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  25170. // put at the begining of data processing.
  25171. var PRIORITY_PROCESSOR_FILTER = 1000;
  25172. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25173. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25174. var PRIORITY_VISUAL_LAYOUT = 1000;
  25175. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25176. var PRIORITY_VISUAL_GLOBAL = 2000;
  25177. var PRIORITY_VISUAL_CHART = 3000;
  25178. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25179. // overwrite the viusal result of component (like `visualMap`)
  25180. // using data item specific setting (like itemStyle.xxx on data item)
  25181. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25182. // visual result like `symbolSize`.
  25183. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25184. var PRIORITY_VISUAL_BRUSH = 5000;
  25185. var PRIORITY_VISUAL_ARIA = 6000;
  25186. var PRIORITY_VISUAL_DECAL = 7000;
  25187. var PRIORITY = {
  25188. PROCESSOR: {
  25189. FILTER: PRIORITY_PROCESSOR_FILTER,
  25190. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25191. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25192. },
  25193. VISUAL: {
  25194. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25195. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25196. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25197. CHART: PRIORITY_VISUAL_CHART,
  25198. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25199. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25200. BRUSH: PRIORITY_VISUAL_BRUSH,
  25201. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25202. ARIA: PRIORITY_VISUAL_ARIA,
  25203. DECAL: PRIORITY_VISUAL_DECAL
  25204. }
  25205. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25206. // where they must not be invoked nestedly, except the only case: invoke
  25207. // dispatchAction with updateMethod "none" in main process.
  25208. // This flag is used to carry out this rule.
  25209. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25210. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25211. var PENDING_UPDATE = '__pendingUpdate';
  25212. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25213. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25214. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25215. var CONNECT_STATUS_PENDING = 0;
  25216. var CONNECT_STATUS_UPDATING = 1;
  25217. var CONNECT_STATUS_UPDATED = 2;
  25218. function createRegisterEventWithLowercaseECharts(method) {
  25219. return function () {
  25220. var args = [];
  25221. for (var _i = 0; _i < arguments.length; _i++) {
  25222. args[_i] = arguments[_i];
  25223. }
  25224. if (this.isDisposed()) {
  25225. disposedWarning(this.id);
  25226. return;
  25227. }
  25228. return toLowercaseNameAndCallEventful(this, method, args);
  25229. };
  25230. }
  25231. function createRegisterEventWithLowercaseMessageCenter(method) {
  25232. return function () {
  25233. var args = [];
  25234. for (var _i = 0; _i < arguments.length; _i++) {
  25235. args[_i] = arguments[_i];
  25236. }
  25237. return toLowercaseNameAndCallEventful(this, method, args);
  25238. };
  25239. }
  25240. function toLowercaseNameAndCallEventful(host, method, args) {
  25241. // `args[0]` is event name. Event name is all lowercase.
  25242. args[0] = args[0] && args[0].toLowerCase();
  25243. return Eventful.prototype[method].apply(host, args);
  25244. }
  25245. var MessageCenter =
  25246. /** @class */
  25247. function (_super) {
  25248. __extends(MessageCenter, _super);
  25249. function MessageCenter() {
  25250. return _super !== null && _super.apply(this, arguments) || this;
  25251. }
  25252. return MessageCenter;
  25253. }(Eventful);
  25254. var messageCenterProto = MessageCenter.prototype;
  25255. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25256. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25257. // Internal method names for class ECharts
  25258. // ---------------------------------------
  25259. var prepare;
  25260. var prepareView;
  25261. var updateDirectly;
  25262. var updateMethods;
  25263. var doConvertPixel;
  25264. var updateStreamModes;
  25265. var doDispatchAction;
  25266. var flushPendingActions;
  25267. var triggerUpdatedEvent;
  25268. var bindRenderedEvent;
  25269. var bindMouseEvent;
  25270. var render;
  25271. var renderComponents;
  25272. var renderSeries;
  25273. var createExtensionAPI;
  25274. var enableConnect;
  25275. var markStatusToUpdate;
  25276. var applyChangedStates;
  25277. var ECharts =
  25278. /** @class */
  25279. function (_super) {
  25280. __extends(ECharts, _super);
  25281. function ECharts(dom, // Theme name or themeOption.
  25282. theme, opts) {
  25283. var _this = _super.call(this, new ECEventProcessor()) || this;
  25284. _this._chartsViews = [];
  25285. _this._chartsMap = {};
  25286. _this._componentsViews = [];
  25287. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25288. _this._pendingActions = [];
  25289. opts = opts || {}; // Get theme by name
  25290. if (isString(theme)) {
  25291. theme = themeStorage[theme];
  25292. }
  25293. _this._dom = dom;
  25294. var defaultRenderer = 'canvas';
  25295. var defaultUseDirtyRect = false;
  25296. if ("development" !== 'production') {
  25297. var root =
  25298. /* eslint-disable-next-line */
  25299. hasWindow ? window : global;
  25300. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25301. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25302. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25303. }
  25304. var zr = _this._zr = init(dom, {
  25305. renderer: opts.renderer || defaultRenderer,
  25306. devicePixelRatio: opts.devicePixelRatio,
  25307. width: opts.width,
  25308. height: opts.height,
  25309. ssr: opts.ssr,
  25310. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  25311. });
  25312. _this._ssr = opts.ssr; // Expect 60 fps.
  25313. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25314. theme = clone(theme);
  25315. theme && globalBackwardCompat(theme, true);
  25316. _this._theme = theme;
  25317. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25318. _this._coordSysMgr = new CoordinateSystemManager();
  25319. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25320. function prioritySortFunc(a, b) {
  25321. return a.__prio - b.__prio;
  25322. }
  25323. sort(visualFuncs, prioritySortFunc);
  25324. sort(dataProcessorFuncs, prioritySortFunc);
  25325. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25326. _this._messageCenter = new MessageCenter(); // Init mouse events
  25327. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25328. _this.resize = bind(_this.resize, _this);
  25329. zr.animation.on('frame', _this._onframe, _this);
  25330. bindRenderedEvent(zr, _this);
  25331. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25332. setAsPrimitive(_this);
  25333. return _this;
  25334. }
  25335. ECharts.prototype._onframe = function () {
  25336. if (this._disposed) {
  25337. return;
  25338. }
  25339. applyChangedStates(this);
  25340. var scheduler = this._scheduler; // Lazy update
  25341. if (this[PENDING_UPDATE]) {
  25342. var silent = this[PENDING_UPDATE].silent;
  25343. this[IN_MAIN_PROCESS_KEY] = true;
  25344. try {
  25345. prepare(this);
  25346. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25347. } catch (e) {
  25348. this[IN_MAIN_PROCESS_KEY] = false;
  25349. this[PENDING_UPDATE] = null;
  25350. throw e;
  25351. } // At present, in each frame, zrender performs:
  25352. // (1) animation step forward.
  25353. // (2) trigger('frame') (where this `_onframe` is called)
  25354. // (3) zrender flush (render).
  25355. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25356. // will render the final state of the elements before the real animation started.
  25357. this._zr.flush();
  25358. this[IN_MAIN_PROCESS_KEY] = false;
  25359. this[PENDING_UPDATE] = null;
  25360. flushPendingActions.call(this, silent);
  25361. triggerUpdatedEvent.call(this, silent);
  25362. } // Avoid do both lazy update and progress in one frame.
  25363. else if (scheduler.unfinished) {
  25364. // Stream progress.
  25365. var remainTime = TEST_FRAME_REMAIN_TIME;
  25366. var ecModel = this._model;
  25367. var api = this._api;
  25368. scheduler.unfinished = false;
  25369. do {
  25370. var startTime = +new Date();
  25371. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25372. scheduler.performDataProcessorTasks(ecModel);
  25373. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25374. // each frame is not a good user experience. So we follow the rule that
  25375. // the extent of the coordinate system is determin in the first frame (the
  25376. // frame is executed immedietely after task reset.
  25377. // this._coordSysMgr.update(ecModel, api);
  25378. // console.log('--- ec frame visual ---', remainTime);
  25379. scheduler.performVisualTasks(ecModel);
  25380. renderSeries(this, this._model, api, 'remain', {});
  25381. remainTime -= +new Date() - startTime;
  25382. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25383. if (!scheduler.unfinished) {
  25384. this._zr.flush();
  25385. } // Else, zr flushing be ensue within the same frame,
  25386. // because zr flushing is after onframe event.
  25387. }
  25388. };
  25389. ECharts.prototype.getDom = function () {
  25390. return this._dom;
  25391. };
  25392. ECharts.prototype.getId = function () {
  25393. return this.id;
  25394. };
  25395. ECharts.prototype.getZr = function () {
  25396. return this._zr;
  25397. };
  25398. ECharts.prototype.isSSR = function () {
  25399. return this._ssr;
  25400. };
  25401. /* eslint-disable-next-line */
  25402. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25403. if (this[IN_MAIN_PROCESS_KEY]) {
  25404. if ("development" !== 'production') {
  25405. error('`setOption` should not be called during main process.');
  25406. }
  25407. return;
  25408. }
  25409. if (this._disposed) {
  25410. disposedWarning(this.id);
  25411. return;
  25412. }
  25413. var silent;
  25414. var replaceMerge;
  25415. var transitionOpt;
  25416. if (isObject(notMerge)) {
  25417. lazyUpdate = notMerge.lazyUpdate;
  25418. silent = notMerge.silent;
  25419. replaceMerge = notMerge.replaceMerge;
  25420. transitionOpt = notMerge.transition;
  25421. notMerge = notMerge.notMerge;
  25422. }
  25423. this[IN_MAIN_PROCESS_KEY] = true;
  25424. if (!this._model || notMerge) {
  25425. var optionManager = new OptionManager(this._api);
  25426. var theme = this._theme;
  25427. var ecModel = this._model = new GlobalModel();
  25428. ecModel.scheduler = this._scheduler;
  25429. ecModel.ssr = this._ssr;
  25430. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25431. }
  25432. this._model.setOption(option, {
  25433. replaceMerge: replaceMerge
  25434. }, optionPreprocessorFuncs);
  25435. var updateParams = {
  25436. seriesTransition: transitionOpt,
  25437. optionChanged: true
  25438. };
  25439. if (lazyUpdate) {
  25440. this[PENDING_UPDATE] = {
  25441. silent: silent,
  25442. updateParams: updateParams
  25443. };
  25444. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25445. // It should wake it up to make sure zrender start to render at the next frame.
  25446. this.getZr().wakeUp();
  25447. } else {
  25448. try {
  25449. prepare(this);
  25450. updateMethods.update.call(this, null, updateParams);
  25451. } catch (e) {
  25452. this[PENDING_UPDATE] = null;
  25453. this[IN_MAIN_PROCESS_KEY] = false;
  25454. throw e;
  25455. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  25456. // fetched after `setOption`.
  25457. if (!this._ssr) {
  25458. // not use flush when using ssr mode.
  25459. this._zr.flush();
  25460. }
  25461. this[PENDING_UPDATE] = null;
  25462. this[IN_MAIN_PROCESS_KEY] = false;
  25463. flushPendingActions.call(this, silent);
  25464. triggerUpdatedEvent.call(this, silent);
  25465. }
  25466. };
  25467. /**
  25468. * @deprecated
  25469. */
  25470. ECharts.prototype.setTheme = function () {
  25471. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25472. }; // We don't want developers to use getModel directly.
  25473. ECharts.prototype.getModel = function () {
  25474. return this._model;
  25475. };
  25476. ECharts.prototype.getOption = function () {
  25477. return this._model && this._model.getOption();
  25478. };
  25479. ECharts.prototype.getWidth = function () {
  25480. return this._zr.getWidth();
  25481. };
  25482. ECharts.prototype.getHeight = function () {
  25483. return this._zr.getHeight();
  25484. };
  25485. ECharts.prototype.getDevicePixelRatio = function () {
  25486. return this._zr.painter.dpr
  25487. /* eslint-disable-next-line */
  25488. || hasWindow && window.devicePixelRatio || 1;
  25489. };
  25490. /**
  25491. * Get canvas which has all thing rendered
  25492. * @deprecated Use renderToCanvas instead.
  25493. */
  25494. ECharts.prototype.getRenderedCanvas = function (opts) {
  25495. if ("development" !== 'production') {
  25496. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25497. }
  25498. return this.renderToCanvas(opts);
  25499. };
  25500. ECharts.prototype.renderToCanvas = function (opts) {
  25501. opts = opts || {};
  25502. var painter = this._zr.painter;
  25503. if ("development" !== 'production') {
  25504. if (painter.type !== 'canvas') {
  25505. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25506. }
  25507. }
  25508. return painter.getRenderedCanvas({
  25509. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25510. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25511. });
  25512. };
  25513. ECharts.prototype.renderToSVGString = function (opts) {
  25514. opts = opts || {};
  25515. var painter = this._zr.painter;
  25516. if ("development" !== 'production') {
  25517. if (painter.type !== 'svg') {
  25518. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25519. }
  25520. }
  25521. return painter.renderToString({
  25522. useViewBox: opts.useViewBox
  25523. });
  25524. };
  25525. /**
  25526. * Get svg data url
  25527. */
  25528. ECharts.prototype.getSvgDataURL = function () {
  25529. if (!env.svgSupported) {
  25530. return;
  25531. }
  25532. var zr = this._zr;
  25533. var list = zr.storage.getDisplayList(); // Stop animations
  25534. each(list, function (el) {
  25535. el.stopAnimation(null, true);
  25536. });
  25537. return zr.painter.toDataURL();
  25538. };
  25539. ECharts.prototype.getDataURL = function (opts) {
  25540. if (this._disposed) {
  25541. disposedWarning(this.id);
  25542. return;
  25543. }
  25544. opts = opts || {};
  25545. var excludeComponents = opts.excludeComponents;
  25546. var ecModel = this._model;
  25547. var excludesComponentViews = [];
  25548. var self = this;
  25549. each(excludeComponents, function (componentType) {
  25550. ecModel.eachComponent({
  25551. mainType: componentType
  25552. }, function (component) {
  25553. var view = self._componentsMap[component.__viewId];
  25554. if (!view.group.ignore) {
  25555. excludesComponentViews.push(view);
  25556. view.group.ignore = true;
  25557. }
  25558. });
  25559. });
  25560. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25561. each(excludesComponentViews, function (view) {
  25562. view.group.ignore = false;
  25563. });
  25564. return url;
  25565. };
  25566. ECharts.prototype.getConnectedDataURL = function (opts) {
  25567. if (this._disposed) {
  25568. disposedWarning(this.id);
  25569. return;
  25570. }
  25571. var isSvg = opts.type === 'svg';
  25572. var groupId = this.group;
  25573. var mathMin = Math.min;
  25574. var mathMax = Math.max;
  25575. var MAX_NUMBER = Infinity;
  25576. if (connectedGroups[groupId]) {
  25577. var left_1 = MAX_NUMBER;
  25578. var top_1 = MAX_NUMBER;
  25579. var right_1 = -MAX_NUMBER;
  25580. var bottom_1 = -MAX_NUMBER;
  25581. var canvasList_1 = [];
  25582. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  25583. each(instances$1, function (chart, id) {
  25584. if (chart.group === groupId) {
  25585. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  25586. var boundingRect = chart.getDom().getBoundingClientRect();
  25587. left_1 = mathMin(boundingRect.left, left_1);
  25588. top_1 = mathMin(boundingRect.top, top_1);
  25589. right_1 = mathMax(boundingRect.right, right_1);
  25590. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  25591. canvasList_1.push({
  25592. dom: canvas,
  25593. left: boundingRect.left,
  25594. top: boundingRect.top
  25595. });
  25596. }
  25597. });
  25598. left_1 *= dpr_1;
  25599. top_1 *= dpr_1;
  25600. right_1 *= dpr_1;
  25601. bottom_1 *= dpr_1;
  25602. var width = right_1 - left_1;
  25603. var height = bottom_1 - top_1;
  25604. var targetCanvas = platformApi.createCanvas();
  25605. var zr_1 = init(targetCanvas, {
  25606. renderer: isSvg ? 'svg' : 'canvas'
  25607. });
  25608. zr_1.resize({
  25609. width: width,
  25610. height: height
  25611. });
  25612. if (isSvg) {
  25613. var content_1 = '';
  25614. each(canvasList_1, function (item) {
  25615. var x = item.left - left_1;
  25616. var y = item.top - top_1;
  25617. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  25618. });
  25619. zr_1.painter.getSvgRoot().innerHTML = content_1;
  25620. if (opts.connectedBackgroundColor) {
  25621. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  25622. }
  25623. zr_1.refreshImmediately();
  25624. return zr_1.painter.toDataURL();
  25625. } else {
  25626. // Background between the charts
  25627. if (opts.connectedBackgroundColor) {
  25628. zr_1.add(new Rect({
  25629. shape: {
  25630. x: 0,
  25631. y: 0,
  25632. width: width,
  25633. height: height
  25634. },
  25635. style: {
  25636. fill: opts.connectedBackgroundColor
  25637. }
  25638. }));
  25639. }
  25640. each(canvasList_1, function (item) {
  25641. var img = new ZRImage({
  25642. style: {
  25643. x: item.left * dpr_1 - left_1,
  25644. y: item.top * dpr_1 - top_1,
  25645. image: item.dom
  25646. }
  25647. });
  25648. zr_1.add(img);
  25649. });
  25650. zr_1.refreshImmediately();
  25651. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  25652. }
  25653. } else {
  25654. return this.getDataURL(opts);
  25655. }
  25656. };
  25657. ECharts.prototype.convertToPixel = function (finder, value) {
  25658. return doConvertPixel(this, 'convertToPixel', finder, value);
  25659. };
  25660. ECharts.prototype.convertFromPixel = function (finder, value) {
  25661. return doConvertPixel(this, 'convertFromPixel', finder, value);
  25662. };
  25663. /**
  25664. * Is the specified coordinate systems or components contain the given pixel point.
  25665. * @param {Array|number} value
  25666. * @return {boolean} result
  25667. */
  25668. ECharts.prototype.containPixel = function (finder, value) {
  25669. if (this._disposed) {
  25670. disposedWarning(this.id);
  25671. return;
  25672. }
  25673. var ecModel = this._model;
  25674. var result;
  25675. var findResult = parseFinder(ecModel, finder);
  25676. each(findResult, function (models, key) {
  25677. key.indexOf('Models') >= 0 && each(models, function (model) {
  25678. var coordSys = model.coordinateSystem;
  25679. if (coordSys && coordSys.containPoint) {
  25680. result = result || !!coordSys.containPoint(value);
  25681. } else if (key === 'seriesModels') {
  25682. var view = this._chartsMap[model.__viewId];
  25683. if (view && view.containPoint) {
  25684. result = result || view.containPoint(value, model);
  25685. } else {
  25686. if ("development" !== 'production') {
  25687. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  25688. }
  25689. }
  25690. } else {
  25691. if ("development" !== 'production') {
  25692. console.warn(key + ': containPoint is not supported');
  25693. }
  25694. }
  25695. }, this);
  25696. }, this);
  25697. return !!result;
  25698. };
  25699. /**
  25700. * Get visual from series or data.
  25701. * @param finder
  25702. * If string, e.g., 'series', means {seriesIndex: 0}.
  25703. * If Object, could contain some of these properties below:
  25704. * {
  25705. * seriesIndex / seriesId / seriesName,
  25706. * dataIndex / dataIndexInside
  25707. * }
  25708. * If dataIndex is not specified, series visual will be fetched,
  25709. * but not data item visual.
  25710. * If all of seriesIndex, seriesId, seriesName are not specified,
  25711. * visual will be fetched from first series.
  25712. * @param visualType 'color', 'symbol', 'symbolSize'
  25713. */
  25714. ECharts.prototype.getVisual = function (finder, visualType) {
  25715. var ecModel = this._model;
  25716. var parsedFinder = parseFinder(ecModel, finder, {
  25717. defaultMainType: 'series'
  25718. });
  25719. var seriesModel = parsedFinder.seriesModel;
  25720. if ("development" !== 'production') {
  25721. if (!seriesModel) {
  25722. console.warn('There is no specified seires model');
  25723. }
  25724. }
  25725. var data = seriesModel.getData();
  25726. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  25727. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  25728. };
  25729. /**
  25730. * Get view of corresponding component model
  25731. */
  25732. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  25733. return this._componentsMap[componentModel.__viewId];
  25734. };
  25735. /**
  25736. * Get view of corresponding series model
  25737. */
  25738. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  25739. return this._chartsMap[seriesModel.__viewId];
  25740. };
  25741. ECharts.prototype._initEvents = function () {
  25742. var _this = this;
  25743. each(MOUSE_EVENT_NAMES, function (eveName) {
  25744. var handler = function (e) {
  25745. var ecModel = _this.getModel();
  25746. var el = e.target;
  25747. var params;
  25748. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  25749. if (isGlobalOut) {
  25750. params = {};
  25751. } else {
  25752. el && findEventDispatcher(el, function (parent) {
  25753. var ecData = getECData(parent);
  25754. if (ecData && ecData.dataIndex != null) {
  25755. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  25756. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  25757. return true;
  25758. } // If element has custom eventData of components
  25759. else if (ecData.eventData) {
  25760. params = extend({}, ecData.eventData);
  25761. return true;
  25762. }
  25763. }, true);
  25764. } // Contract: if params prepared in mouse event,
  25765. // these properties must be specified:
  25766. // {
  25767. // componentType: string (component main type)
  25768. // componentIndex: number
  25769. // }
  25770. // Otherwise event query can not work.
  25771. if (params) {
  25772. var componentType = params.componentType;
  25773. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  25774. // markLine/markPoint/markArea, the componentType is
  25775. // 'markLine'/'markPoint'/'markArea', but we should better
  25776. // enable them to be queried by seriesIndex, since their
  25777. // option is set in each series.
  25778. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  25779. componentType = 'series';
  25780. componentIndex = params.seriesIndex;
  25781. }
  25782. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  25783. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  25784. if ("development" !== 'production') {
  25785. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25786. // be missed, otherwise there is no way to distinguish source component.
  25787. // See `dataFormat.getDataParams`.
  25788. if (!isGlobalOut && !(model && view)) {
  25789. console.warn('model or view can not be found by params');
  25790. }
  25791. }
  25792. params.event = e;
  25793. params.type = eveName;
  25794. _this._$eventProcessor.eventInfo = {
  25795. targetEl: el,
  25796. packedEvent: params,
  25797. model: model,
  25798. view: view
  25799. };
  25800. _this.trigger(eveName, params);
  25801. }
  25802. }; // Consider that some component (like tooltip, brush, ...)
  25803. // register zr event handler, but user event handler might
  25804. // do anything, such as call `setOption` or `dispatchAction`,
  25805. // which probably update any of the content and probably
  25806. // cause problem if it is called previous other inner handlers.
  25807. handler.zrEventfulCallAtLast = true;
  25808. _this._zr.on(eveName, handler, _this);
  25809. });
  25810. each(eventActionMap, function (actionType, eventType) {
  25811. _this._messageCenter.on(eventType, function (event) {
  25812. this.trigger(eventType, event);
  25813. }, _this);
  25814. }); // Extra events
  25815. // TODO register?
  25816. each(['selectchanged'], function (eventType) {
  25817. _this._messageCenter.on(eventType, function (event) {
  25818. this.trigger(eventType, event);
  25819. }, _this);
  25820. });
  25821. handleLegacySelectEvents(this._messageCenter, this, this._api);
  25822. };
  25823. ECharts.prototype.isDisposed = function () {
  25824. return this._disposed;
  25825. };
  25826. ECharts.prototype.clear = function () {
  25827. if (this._disposed) {
  25828. disposedWarning(this.id);
  25829. return;
  25830. }
  25831. this.setOption({
  25832. series: []
  25833. }, true);
  25834. };
  25835. ECharts.prototype.dispose = function () {
  25836. if (this._disposed) {
  25837. disposedWarning(this.id);
  25838. return;
  25839. }
  25840. this._disposed = true;
  25841. var dom = this.getDom();
  25842. if (dom) {
  25843. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25844. }
  25845. var chart = this;
  25846. var api = chart._api;
  25847. var ecModel = chart._model;
  25848. each(chart._componentsViews, function (component) {
  25849. component.dispose(ecModel, api);
  25850. });
  25851. each(chart._chartsViews, function (chart) {
  25852. chart.dispose(ecModel, api);
  25853. }); // Dispose after all views disposed
  25854. chart._zr.dispose(); // Set properties to null.
  25855. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  25856. 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;
  25857. delete instances$1[chart.id];
  25858. };
  25859. /**
  25860. * Resize the chart
  25861. */
  25862. ECharts.prototype.resize = function (opts) {
  25863. if (this[IN_MAIN_PROCESS_KEY]) {
  25864. if ("development" !== 'production') {
  25865. error('`resize` should not be called during main process.');
  25866. }
  25867. return;
  25868. }
  25869. if (this._disposed) {
  25870. disposedWarning(this.id);
  25871. return;
  25872. }
  25873. this._zr.resize(opts);
  25874. var ecModel = this._model; // Resize loading effect
  25875. this._loadingFX && this._loadingFX.resize();
  25876. if (!ecModel) {
  25877. return;
  25878. }
  25879. var needPrepare = ecModel.resetOption('media');
  25880. var silent = opts && opts.silent; // There is some real cases that:
  25881. // chart.setOption(option, { lazyUpdate: true });
  25882. // chart.resize();
  25883. if (this[PENDING_UPDATE]) {
  25884. if (silent == null) {
  25885. silent = this[PENDING_UPDATE].silent;
  25886. }
  25887. needPrepare = true;
  25888. this[PENDING_UPDATE] = null;
  25889. }
  25890. this[IN_MAIN_PROCESS_KEY] = true;
  25891. try {
  25892. needPrepare && prepare(this);
  25893. updateMethods.update.call(this, {
  25894. type: 'resize',
  25895. animation: extend({
  25896. // Disable animation
  25897. duration: 0
  25898. }, opts && opts.animation)
  25899. });
  25900. } catch (e) {
  25901. this[IN_MAIN_PROCESS_KEY] = false;
  25902. throw e;
  25903. }
  25904. this[IN_MAIN_PROCESS_KEY] = false;
  25905. flushPendingActions.call(this, silent);
  25906. triggerUpdatedEvent.call(this, silent);
  25907. };
  25908. ECharts.prototype.showLoading = function (name, cfg) {
  25909. if (this._disposed) {
  25910. disposedWarning(this.id);
  25911. return;
  25912. }
  25913. if (isObject(name)) {
  25914. cfg = name;
  25915. name = '';
  25916. }
  25917. name = name || 'default';
  25918. this.hideLoading();
  25919. if (!loadingEffects[name]) {
  25920. if ("development" !== 'production') {
  25921. console.warn('Loading effects ' + name + ' not exists.');
  25922. }
  25923. return;
  25924. }
  25925. var el = loadingEffects[name](this._api, cfg);
  25926. var zr = this._zr;
  25927. this._loadingFX = el;
  25928. zr.add(el);
  25929. };
  25930. /**
  25931. * Hide loading effect
  25932. */
  25933. ECharts.prototype.hideLoading = function () {
  25934. if (this._disposed) {
  25935. disposedWarning(this.id);
  25936. return;
  25937. }
  25938. this._loadingFX && this._zr.remove(this._loadingFX);
  25939. this._loadingFX = null;
  25940. };
  25941. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  25942. var payload = extend({}, eventObj);
  25943. payload.type = eventActionMap[eventObj.type];
  25944. return payload;
  25945. };
  25946. /**
  25947. * @param opt If pass boolean, means opt.silent
  25948. * @param opt.silent Default `false`. Whether trigger events.
  25949. * @param opt.flush Default `undefined`.
  25950. * true: Flush immediately, and then pixel in canvas can be fetched
  25951. * immediately. Caution: it might affect performance.
  25952. * false: Not flush.
  25953. * undefined: Auto decide whether perform flush.
  25954. */
  25955. ECharts.prototype.dispatchAction = function (payload, opt) {
  25956. if (this._disposed) {
  25957. disposedWarning(this.id);
  25958. return;
  25959. }
  25960. if (!isObject(opt)) {
  25961. opt = {
  25962. silent: !!opt
  25963. };
  25964. }
  25965. if (!actions[payload.type]) {
  25966. return;
  25967. } // Avoid dispatch action before setOption. Especially in `connect`.
  25968. if (!this._model) {
  25969. return;
  25970. } // May dispatchAction in rendering procedure
  25971. if (this[IN_MAIN_PROCESS_KEY]) {
  25972. this._pendingActions.push(payload);
  25973. return;
  25974. }
  25975. var silent = opt.silent;
  25976. doDispatchAction.call(this, payload, silent);
  25977. var flush = opt.flush;
  25978. if (flush) {
  25979. this._zr.flush();
  25980. } else if (flush !== false && env.browser.weChat) {
  25981. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25982. // hang when sliding page (on touch event), which cause that zr does not
  25983. // refresh util user interaction finished, which is not expected.
  25984. // But `dispatchAction` may be called too frequently when pan on touch
  25985. // screen, which impacts performance if do not throttle them.
  25986. this._throttledZrFlush();
  25987. }
  25988. flushPendingActions.call(this, silent);
  25989. triggerUpdatedEvent.call(this, silent);
  25990. };
  25991. ECharts.prototype.updateLabelLayout = function () {
  25992. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  25993. // Not adding series labels.
  25994. // TODO
  25995. updatedSeries: []
  25996. });
  25997. };
  25998. ECharts.prototype.appendData = function (params) {
  25999. if (this._disposed) {
  26000. disposedWarning(this.id);
  26001. return;
  26002. }
  26003. var seriesIndex = params.seriesIndex;
  26004. var ecModel = this.getModel();
  26005. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26006. if ("development" !== 'production') {
  26007. assert(params.data && seriesModel);
  26008. }
  26009. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  26010. // system, util some scenario require that. In the expected usage of
  26011. // `appendData`, the initial extent of coordinate system should better
  26012. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26013. // the extent changed while `appendData`, the location of the painted
  26014. // graphic elements have to be changed, which make the usage of
  26015. // `appendData` meaningless.
  26016. this._scheduler.unfinished = true;
  26017. this.getZr().wakeUp();
  26018. }; // A work around for no `internal` modifier in ts yet but
  26019. // need to strictly hide private methods to JS users.
  26020. ECharts.internalField = function () {
  26021. prepare = function (ecIns) {
  26022. var scheduler = ecIns._scheduler;
  26023. scheduler.restorePipelines(ecIns._model);
  26024. scheduler.prepareStageTasks();
  26025. prepareView(ecIns, true);
  26026. prepareView(ecIns, false);
  26027. scheduler.plan();
  26028. };
  26029. /**
  26030. * Prepare view instances of charts and components
  26031. */
  26032. prepareView = function (ecIns, isComponent) {
  26033. var ecModel = ecIns._model;
  26034. var scheduler = ecIns._scheduler;
  26035. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26036. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26037. var zr = ecIns._zr;
  26038. var api = ecIns._api;
  26039. for (var i = 0; i < viewList.length; i++) {
  26040. viewList[i].__alive = false;
  26041. }
  26042. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26043. componentType !== 'series' && doPrepare(model);
  26044. }) : ecModel.eachSeries(doPrepare);
  26045. function doPrepare(model) {
  26046. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  26047. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26048. // especially no id but have the same type & name & index. See the `model.id` generation
  26049. // rule in `makeIdAndName` and `viewId` generation rule here).
  26050. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26051. // the new model has nothing to do with the old model.
  26052. var requireNewView = model.__requireNewView; // This command should not work twice.
  26053. model.__requireNewView = false; // Consider: id same and type changed.
  26054. var viewId = '_ec_' + model.id + '_' + model.type;
  26055. var view = !requireNewView && viewMap[viewId];
  26056. if (!view) {
  26057. var classType = parseClassType(model.type);
  26058. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  26059. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26060. // For backward compat, still support a chart type declared as only subType
  26061. // like "liquidfill", but recommend "series.liquidfill"
  26062. // But need a base class to make a type series.
  26063. ChartView.getClass(classType.sub);
  26064. if ("development" !== 'production') {
  26065. assert(Clazz, classType.sub + ' does not exist.');
  26066. }
  26067. view = new Clazz();
  26068. view.init(ecModel, api);
  26069. viewMap[viewId] = view;
  26070. viewList.push(view);
  26071. zr.add(view.group);
  26072. }
  26073. model.__viewId = view.__id = viewId;
  26074. view.__alive = true;
  26075. view.__model = model;
  26076. view.group.__ecComponentInfo = {
  26077. mainType: model.mainType,
  26078. index: model.componentIndex
  26079. };
  26080. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26081. }
  26082. for (var i = 0; i < viewList.length;) {
  26083. var view = viewList[i];
  26084. if (!view.__alive) {
  26085. !isComponent && view.renderTask.dispose();
  26086. zr.remove(view.group);
  26087. view.dispose(ecModel, api);
  26088. viewList.splice(i, 1);
  26089. if (viewMap[view.__id] === view) {
  26090. delete viewMap[view.__id];
  26091. }
  26092. view.__id = view.group.__ecComponentInfo = null;
  26093. } else {
  26094. i++;
  26095. }
  26096. }
  26097. };
  26098. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26099. var ecModel = ecIns._model;
  26100. ecModel.setUpdatePayload(payload); // broadcast
  26101. if (!mainType) {
  26102. // FIXME
  26103. // Chart will not be update directly here, except set dirty.
  26104. // But there is no such scenario now.
  26105. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26106. return;
  26107. }
  26108. var query = {};
  26109. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26110. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26111. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26112. var condition = {
  26113. mainType: mainType,
  26114. query: query
  26115. };
  26116. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26117. var excludeSeriesId = payload.excludeSeriesId;
  26118. var excludeSeriesIdMap;
  26119. if (excludeSeriesId != null) {
  26120. excludeSeriesIdMap = createHashMap();
  26121. each(normalizeToArray(excludeSeriesId), function (id) {
  26122. var modelId = convertOptionIdName(id, null);
  26123. if (modelId != null) {
  26124. excludeSeriesIdMap.set(modelId, true);
  26125. }
  26126. });
  26127. } // If dispatchAction before setOption, do nothing.
  26128. ecModel && ecModel.eachComponent(condition, function (model) {
  26129. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  26130. if (isExcluded) {
  26131. return;
  26132. }
  26133. if (isHighDownPayload(payload)) {
  26134. if (model instanceof SeriesModel) {
  26135. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26136. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26137. }
  26138. } else {
  26139. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26140. focusSelf = _a.focusSelf,
  26141. dispatchers = _a.dispatchers;
  26142. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26143. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26144. } // PENDING:
  26145. // Whether to put this "enter emphasis" code in `ComponentView`,
  26146. // which will be the same as `ChartView` but might be not necessary
  26147. // and will be far from this logic.
  26148. if (dispatchers) {
  26149. each(dispatchers, function (dispatcher) {
  26150. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26151. });
  26152. }
  26153. }
  26154. } else if (isSelectChangePayload(payload)) {
  26155. // TODO geo
  26156. if (model instanceof SeriesModel) {
  26157. toggleSelectionFromPayload(model, payload, ecIns._api);
  26158. updateSeriesElementSelection(model);
  26159. markStatusToUpdate(ecIns);
  26160. }
  26161. }
  26162. }, ecIns);
  26163. ecModel && ecModel.eachComponent(condition, function (model) {
  26164. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  26165. if (isExcluded) {
  26166. return;
  26167. }
  26168. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26169. }, ecIns);
  26170. function callView(view) {
  26171. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26172. }
  26173. };
  26174. updateMethods = {
  26175. prepareAndUpdate: function (payload) {
  26176. prepare(this);
  26177. updateMethods.update.call(this, payload, {
  26178. // Needs to mark option changed if newOption is given.
  26179. // It's from MagicType.
  26180. // TODO If use a separate flag optionChanged in payload?
  26181. optionChanged: payload.newOption != null
  26182. });
  26183. },
  26184. update: function (payload, updateParams) {
  26185. var ecModel = this._model;
  26186. var api = this._api;
  26187. var zr = this._zr;
  26188. var coordSysMgr = this._coordSysMgr;
  26189. var scheduler = this._scheduler; // update before setOption
  26190. if (!ecModel) {
  26191. return;
  26192. }
  26193. ecModel.setUpdatePayload(payload);
  26194. scheduler.restoreData(ecModel, payload);
  26195. scheduler.performSeriesTasks(ecModel); // TODO
  26196. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26197. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26198. // Create new coordinate system each update
  26199. // In LineView may save the old coordinate system and use it to get the orignal point
  26200. coordSysMgr.create(ecModel, api);
  26201. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  26202. // stream modes after data processing, where the filtered data is used to
  26203. // deteming whether use progressive rendering.
  26204. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  26205. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26206. // the drawback is the full coord info can not be fetched. Fortunately this full
  26207. // coord is not requied in stream mode updater currently.
  26208. coordSysMgr.update(ecModel, api);
  26209. clearColorPalette(ecModel);
  26210. scheduler.performVisualTasks(ecModel, payload);
  26211. render(this, ecModel, api, payload, updateParams); // Set background
  26212. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26213. var darkMode = ecModel.get('darkMode');
  26214. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  26215. if (darkMode != null && darkMode !== 'auto') {
  26216. zr.setDarkMode(darkMode);
  26217. }
  26218. lifecycle.trigger('afterupdate', ecModel, api);
  26219. },
  26220. updateTransform: function (payload) {
  26221. var _this = this;
  26222. var ecModel = this._model;
  26223. var api = this._api; // update before setOption
  26224. if (!ecModel) {
  26225. return;
  26226. }
  26227. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  26228. var componentDirtyList = [];
  26229. ecModel.eachComponent(function (componentType, componentModel) {
  26230. if (componentType === 'series') {
  26231. return;
  26232. }
  26233. var componentView = _this.getViewOfComponentModel(componentModel);
  26234. if (componentView && componentView.__alive) {
  26235. if (componentView.updateTransform) {
  26236. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26237. result && result.update && componentDirtyList.push(componentView);
  26238. } else {
  26239. componentDirtyList.push(componentView);
  26240. }
  26241. }
  26242. });
  26243. var seriesDirtyMap = createHashMap();
  26244. ecModel.eachSeries(function (seriesModel) {
  26245. var chartView = _this._chartsMap[seriesModel.__viewId];
  26246. if (chartView.updateTransform) {
  26247. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26248. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26249. } else {
  26250. seriesDirtyMap.set(seriesModel.uid, 1);
  26251. }
  26252. });
  26253. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26254. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26255. this._scheduler.performVisualTasks(ecModel, payload, {
  26256. setDirty: true,
  26257. dirtyMap: seriesDirtyMap
  26258. }); // Currently, not call render of components. Geo render cost a lot.
  26259. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26260. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26261. lifecycle.trigger('afterupdate', ecModel, api);
  26262. },
  26263. updateView: function (payload) {
  26264. var ecModel = this._model; // update before setOption
  26265. if (!ecModel) {
  26266. return;
  26267. }
  26268. ecModel.setUpdatePayload(payload);
  26269. ChartView.markUpdateMethod(payload, 'updateView');
  26270. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26271. this._scheduler.performVisualTasks(ecModel, payload, {
  26272. setDirty: true
  26273. });
  26274. render(this, ecModel, this._api, payload, {});
  26275. lifecycle.trigger('afterupdate', ecModel, this._api);
  26276. },
  26277. updateVisual: function (payload) {
  26278. // updateMethods.update.call(this, payload);
  26279. var _this = this;
  26280. var ecModel = this._model; // update before setOption
  26281. if (!ecModel) {
  26282. return;
  26283. }
  26284. ecModel.setUpdatePayload(payload); // clear all visual
  26285. ecModel.eachSeries(function (seriesModel) {
  26286. seriesModel.getData().clearAllVisual();
  26287. }); // Perform visual
  26288. ChartView.markUpdateMethod(payload, 'updateVisual');
  26289. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26290. this._scheduler.performVisualTasks(ecModel, payload, {
  26291. visualType: 'visual',
  26292. setDirty: true
  26293. });
  26294. ecModel.eachComponent(function (componentType, componentModel) {
  26295. if (componentType !== 'series') {
  26296. var componentView = _this.getViewOfComponentModel(componentModel);
  26297. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26298. }
  26299. });
  26300. ecModel.eachSeries(function (seriesModel) {
  26301. var chartView = _this._chartsMap[seriesModel.__viewId];
  26302. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26303. });
  26304. lifecycle.trigger('afterupdate', ecModel, this._api);
  26305. },
  26306. updateLayout: function (payload) {
  26307. updateMethods.update.call(this, payload);
  26308. }
  26309. };
  26310. doConvertPixel = function (ecIns, methodName, finder, value) {
  26311. if (ecIns._disposed) {
  26312. disposedWarning(ecIns.id);
  26313. return;
  26314. }
  26315. var ecModel = ecIns._model;
  26316. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26317. var result;
  26318. var parsedFinder = parseFinder(ecModel, finder);
  26319. for (var i = 0; i < coordSysList.length; i++) {
  26320. var coordSys = coordSysList[i];
  26321. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26322. return result;
  26323. }
  26324. }
  26325. if ("development" !== 'production') {
  26326. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26327. }
  26328. };
  26329. updateStreamModes = function (ecIns, ecModel) {
  26330. var chartsMap = ecIns._chartsMap;
  26331. var scheduler = ecIns._scheduler;
  26332. ecModel.eachSeries(function (seriesModel) {
  26333. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26334. });
  26335. };
  26336. doDispatchAction = function (payload, silent) {
  26337. var _this = this;
  26338. var ecModel = this.getModel();
  26339. var payloadType = payload.type;
  26340. var escapeConnect = payload.escapeConnect;
  26341. var actionWrap = actions[payloadType];
  26342. var actionInfo = actionWrap.actionInfo;
  26343. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26344. var updateMethod = cptTypeTmp.pop();
  26345. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26346. this[IN_MAIN_PROCESS_KEY] = true;
  26347. var payloads = [payload];
  26348. var batched = false; // Batch action
  26349. if (payload.batch) {
  26350. batched = true;
  26351. payloads = map(payload.batch, function (item) {
  26352. item = defaults(extend({}, item), payload);
  26353. item.batch = null;
  26354. return item;
  26355. });
  26356. }
  26357. var eventObjBatch = [];
  26358. var eventObj;
  26359. var isSelectChange = isSelectChangePayload(payload);
  26360. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  26361. if (isHighDown) {
  26362. allLeaveBlur(this._api);
  26363. }
  26364. each(payloads, function (batchItem) {
  26365. // Action can specify the event by return it.
  26366. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26367. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26368. eventObj.type = actionInfo.event || eventObj.type;
  26369. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26370. if (isHighDown) {
  26371. var _a = preParseFinder(payload),
  26372. queryOptionMap = _a.queryOptionMap,
  26373. mainTypeSpecified = _a.mainTypeSpecified;
  26374. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26375. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26376. markStatusToUpdate(_this);
  26377. } else if (isSelectChange) {
  26378. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26379. // geo still use 'geoselect'.
  26380. updateDirectly(_this, updateMethod, batchItem, 'series');
  26381. markStatusToUpdate(_this);
  26382. } else if (cptType) {
  26383. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26384. }
  26385. });
  26386. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26387. try {
  26388. // Still dirty
  26389. if (this[PENDING_UPDATE]) {
  26390. prepare(this);
  26391. updateMethods.update.call(this, payload);
  26392. this[PENDING_UPDATE] = null;
  26393. } else {
  26394. updateMethods[updateMethod].call(this, payload);
  26395. }
  26396. } catch (e) {
  26397. this[IN_MAIN_PROCESS_KEY] = false;
  26398. throw e;
  26399. }
  26400. } // Follow the rule of action batch
  26401. if (batched) {
  26402. eventObj = {
  26403. type: actionInfo.event || payloadType,
  26404. escapeConnect: escapeConnect,
  26405. batch: eventObjBatch
  26406. };
  26407. } else {
  26408. eventObj = eventObjBatch[0];
  26409. }
  26410. this[IN_MAIN_PROCESS_KEY] = false;
  26411. if (!silent) {
  26412. var messageCenter = this._messageCenter;
  26413. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26414. if (isSelectChange) {
  26415. var newObj = {
  26416. type: 'selectchanged',
  26417. escapeConnect: escapeConnect,
  26418. selected: getAllSelectedIndices(ecModel),
  26419. isFromClick: payload.isFromClick || false,
  26420. fromAction: payload.type,
  26421. fromActionPayload: payload
  26422. };
  26423. messageCenter.trigger(newObj.type, newObj);
  26424. }
  26425. }
  26426. };
  26427. flushPendingActions = function (silent) {
  26428. var pendingActions = this._pendingActions;
  26429. while (pendingActions.length) {
  26430. var payload = pendingActions.shift();
  26431. doDispatchAction.call(this, payload, silent);
  26432. }
  26433. };
  26434. triggerUpdatedEvent = function (silent) {
  26435. !silent && this.trigger('updated');
  26436. };
  26437. /**
  26438. * Event `rendered` is triggered when zr
  26439. * rendered. It is useful for realtime
  26440. * snapshot (reflect animation).
  26441. *
  26442. * Event `finished` is triggered when:
  26443. * (1) zrender rendering finished.
  26444. * (2) initial animation finished.
  26445. * (3) progressive rendering finished.
  26446. * (4) no pending action.
  26447. * (5) no delayed setOption needs to be processed.
  26448. */
  26449. bindRenderedEvent = function (zr, ecIns) {
  26450. zr.on('rendered', function (params) {
  26451. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  26452. // so it should only be triggered when rendering indeed happend
  26453. // in zrender. (Consider the case that dipatchAction is keep
  26454. // triggering when mouse move).
  26455. if ( // Although zr is dirty if initial animation is not finished
  26456. // and this checking is called on frame, we also check
  26457. // animation finished for robustness.
  26458. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26459. ecIns.trigger('finished');
  26460. }
  26461. });
  26462. };
  26463. bindMouseEvent = function (zr, ecIns) {
  26464. zr.on('mouseover', function (e) {
  26465. var el = e.target;
  26466. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26467. if (dispatcher) {
  26468. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26469. markStatusToUpdate(ecIns);
  26470. }
  26471. }).on('mouseout', function (e) {
  26472. var el = e.target;
  26473. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26474. if (dispatcher) {
  26475. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26476. markStatusToUpdate(ecIns);
  26477. }
  26478. }).on('click', function (e) {
  26479. var el = e.target;
  26480. var dispatcher = findEventDispatcher(el, function (target) {
  26481. return getECData(target).dataIndex != null;
  26482. }, true);
  26483. if (dispatcher) {
  26484. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26485. var ecData = getECData(dispatcher);
  26486. ecIns._api.dispatchAction({
  26487. type: actionType,
  26488. dataType: ecData.dataType,
  26489. dataIndexInside: ecData.dataIndex,
  26490. seriesIndex: ecData.seriesIndex,
  26491. isFromClick: true
  26492. });
  26493. }
  26494. });
  26495. };
  26496. function clearColorPalette(ecModel) {
  26497. ecModel.clearColorPalette();
  26498. ecModel.eachSeries(function (seriesModel) {
  26499. seriesModel.clearColorPalette();
  26500. });
  26501. }
  26502. function allocateZlevels(ecModel) {
  26503. var componentZLevels = [];
  26504. var seriesZLevels = [];
  26505. var hasSeperateZLevel = false;
  26506. ecModel.eachComponent(function (componentType, componentModel) {
  26507. var zlevel = componentModel.get('zlevel') || 0;
  26508. var z = componentModel.get('z') || 0;
  26509. var zlevelKey = componentModel.getZLevelKey();
  26510. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  26511. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26512. zlevel: zlevel,
  26513. z: z,
  26514. idx: componentModel.componentIndex,
  26515. type: componentType,
  26516. key: zlevelKey
  26517. });
  26518. });
  26519. if (hasSeperateZLevel) {
  26520. // Series after component
  26521. var zLevels = componentZLevels.concat(seriesZLevels);
  26522. var lastSeriesZLevel_1;
  26523. var lastSeriesKey_1;
  26524. sort(zLevels, function (a, b) {
  26525. if (a.zlevel === b.zlevel) {
  26526. return a.z - b.z;
  26527. }
  26528. return a.zlevel - b.zlevel;
  26529. });
  26530. each(zLevels, function (item) {
  26531. var componentModel = ecModel.getComponent(item.type, item.idx);
  26532. var zlevel = item.zlevel;
  26533. var key = item.key;
  26534. if (lastSeriesZLevel_1 != null) {
  26535. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26536. }
  26537. if (key) {
  26538. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26539. zlevel++;
  26540. }
  26541. lastSeriesKey_1 = key;
  26542. } else if (lastSeriesKey_1) {
  26543. if (zlevel === lastSeriesZLevel_1) {
  26544. zlevel++;
  26545. }
  26546. lastSeriesKey_1 = '';
  26547. }
  26548. lastSeriesZLevel_1 = zlevel;
  26549. componentModel.setZLevel(zlevel);
  26550. });
  26551. }
  26552. }
  26553. render = function (ecIns, ecModel, api, payload, updateParams) {
  26554. allocateZlevels(ecModel);
  26555. renderComponents(ecIns, ecModel, api, payload, updateParams);
  26556. each(ecIns._chartsViews, function (chart) {
  26557. chart.__alive = false;
  26558. });
  26559. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  26560. each(ecIns._chartsViews, function (chart) {
  26561. if (!chart.__alive) {
  26562. chart.remove(ecModel, api);
  26563. }
  26564. });
  26565. };
  26566. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  26567. each(dirtyList || ecIns._componentsViews, function (componentView) {
  26568. var componentModel = componentView.__model;
  26569. clearStates(componentModel, componentView);
  26570. componentView.render(componentModel, ecModel, api, payload);
  26571. updateZ(componentModel, componentView);
  26572. updateStates(componentModel, componentView);
  26573. });
  26574. };
  26575. /**
  26576. * Render each chart and component
  26577. */
  26578. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  26579. // Render all charts
  26580. var scheduler = ecIns._scheduler;
  26581. updateParams = extend(updateParams || {}, {
  26582. updatedSeries: ecModel.getSeries()
  26583. }); // TODO progressive?
  26584. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  26585. var unfinished = false;
  26586. ecModel.eachSeries(function (seriesModel) {
  26587. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26588. chartView.__alive = true;
  26589. var renderTask = chartView.renderTask;
  26590. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  26591. clearStates(seriesModel, chartView);
  26592. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  26593. renderTask.dirty();
  26594. }
  26595. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  26596. unfinished = true;
  26597. }
  26598. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  26599. // increamental render (alway render from the __startIndex each frame)
  26600. // chartView.group.markRedraw();
  26601. updateBlend(seriesModel, chartView);
  26602. updateSeriesElementSelection(seriesModel);
  26603. });
  26604. scheduler.unfinished = unfinished || scheduler.unfinished;
  26605. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  26606. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  26607. ecModel.eachSeries(function (seriesModel) {
  26608. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  26609. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  26610. // label should be in normal status when layouting.
  26611. updateStates(seriesModel, chartView);
  26612. }); // If use hover layer
  26613. updateHoverLayerStatus(ecIns, ecModel);
  26614. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  26615. };
  26616. markStatusToUpdate = function (ecIns) {
  26617. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  26618. ecIns.getZr().wakeUp();
  26619. };
  26620. applyChangedStates = function (ecIns) {
  26621. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  26622. return;
  26623. }
  26624. ecIns.getZr().storage.traverse(function (el) {
  26625. // Not applied on removed elements, it may still in fading.
  26626. if (isElementRemoved(el)) {
  26627. return;
  26628. }
  26629. applyElementStates(el);
  26630. });
  26631. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  26632. };
  26633. function applyElementStates(el) {
  26634. var newStates = [];
  26635. var oldStates = el.currentStates; // Keep other states.
  26636. for (var i = 0; i < oldStates.length; i++) {
  26637. var stateName = oldStates[i];
  26638. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  26639. newStates.push(stateName);
  26640. }
  26641. } // Only use states when it's exists.
  26642. if (el.selected && el.states.select) {
  26643. newStates.push('select');
  26644. }
  26645. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  26646. newStates.push('emphasis');
  26647. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  26648. newStates.push('blur');
  26649. }
  26650. el.useStates(newStates);
  26651. }
  26652. function updateHoverLayerStatus(ecIns, ecModel) {
  26653. var zr = ecIns._zr;
  26654. var storage = zr.storage;
  26655. var elCount = 0;
  26656. storage.traverse(function (el) {
  26657. if (!el.isGroup) {
  26658. elCount++;
  26659. }
  26660. });
  26661. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  26662. ecModel.eachSeries(function (seriesModel) {
  26663. if (seriesModel.preventUsingHoverLayer) {
  26664. return;
  26665. }
  26666. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26667. if (chartView.__alive) {
  26668. chartView.eachRendered(function (el) {
  26669. if (el.states.emphasis) {
  26670. el.states.emphasis.hoverLayer = true;
  26671. }
  26672. });
  26673. }
  26674. });
  26675. }
  26676. }
  26677. /**
  26678. * Update chart and blend.
  26679. */
  26680. function updateBlend(seriesModel, chartView) {
  26681. var blendMode = seriesModel.get('blendMode') || null;
  26682. chartView.eachRendered(function (el) {
  26683. // FIXME marker and other components
  26684. if (!el.isGroup) {
  26685. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  26686. el.style.blend = blendMode;
  26687. }
  26688. });
  26689. }
  26690. function updateZ(model, view) {
  26691. if (model.preventAutoZ) {
  26692. return;
  26693. }
  26694. var z = model.get('z') || 0;
  26695. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  26696. view.eachRendered(function (el) {
  26697. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  26698. return true;
  26699. });
  26700. }
  26701. function doUpdateZ(el, z, zlevel, maxZ2) {
  26702. // Group may also have textContent
  26703. var label = el.getTextContent();
  26704. var labelLine = el.getTextGuideLine();
  26705. var isGroup = el.isGroup;
  26706. if (isGroup) {
  26707. // set z & zlevel of children elements of Group
  26708. var children = el.childrenRef();
  26709. for (var i = 0; i < children.length; i++) {
  26710. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  26711. }
  26712. } else {
  26713. // not Group
  26714. el.z = z;
  26715. el.zlevel = zlevel;
  26716. maxZ2 = Math.max(el.z2, maxZ2);
  26717. } // always set z and zlevel if label/labelLine exists
  26718. if (label) {
  26719. label.z = z;
  26720. label.zlevel = zlevel; // lift z2 of text content
  26721. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  26722. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  26723. }
  26724. if (labelLine) {
  26725. var textGuideLineConfig = el.textGuideLineConfig;
  26726. labelLine.z = z;
  26727. labelLine.zlevel = zlevel;
  26728. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  26729. }
  26730. return maxZ2;
  26731. } // Clear states without animation.
  26732. // TODO States on component.
  26733. function clearStates(model, view) {
  26734. view.eachRendered(function (el) {
  26735. // Not applied on removed elements, it may still in fading.
  26736. if (isElementRemoved(el)) {
  26737. return;
  26738. }
  26739. var textContent = el.getTextContent();
  26740. var textGuide = el.getTextGuideLine();
  26741. if (el.stateTransition) {
  26742. el.stateTransition = null;
  26743. }
  26744. if (textContent && textContent.stateTransition) {
  26745. textContent.stateTransition = null;
  26746. }
  26747. if (textGuide && textGuide.stateTransition) {
  26748. textGuide.stateTransition = null;
  26749. } // TODO If el is incremental.
  26750. if (el.hasState()) {
  26751. el.prevStates = el.currentStates;
  26752. el.clearStates();
  26753. } else if (el.prevStates) {
  26754. el.prevStates = null;
  26755. }
  26756. });
  26757. }
  26758. function updateStates(model, view) {
  26759. var stateAnimationModel = model.getModel('stateAnimation');
  26760. var enableAnimation = model.isAnimationEnabled();
  26761. var duration = stateAnimationModel.get('duration');
  26762. var stateTransition = duration > 0 ? {
  26763. duration: duration,
  26764. delay: stateAnimationModel.get('delay'),
  26765. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  26766. } : null;
  26767. view.eachRendered(function (el) {
  26768. if (el.states && el.states.emphasis) {
  26769. // Not applied on removed elements, it may still in fading.
  26770. if (isElementRemoved(el)) {
  26771. return;
  26772. }
  26773. if (el instanceof Path) {
  26774. savePathStates(el);
  26775. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  26776. // TODO, a more proper way?
  26777. if (el.__dirty) {
  26778. var prevStates = el.prevStates; // Restore states without animation
  26779. if (prevStates) {
  26780. el.useStates(prevStates);
  26781. }
  26782. } // Update state transition and enable animation again.
  26783. if (enableAnimation) {
  26784. el.stateTransition = stateTransition;
  26785. var textContent = el.getTextContent();
  26786. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  26787. if (textContent) {
  26788. textContent.stateTransition = stateTransition;
  26789. }
  26790. if (textGuide) {
  26791. textGuide.stateTransition = stateTransition;
  26792. }
  26793. } // The use higlighted and selected flag to toggle states.
  26794. if (el.__dirty) {
  26795. applyElementStates(el);
  26796. }
  26797. }
  26798. });
  26799. }
  26800. createExtensionAPI = function (ecIns) {
  26801. return new (
  26802. /** @class */
  26803. function (_super) {
  26804. __extends(class_1, _super);
  26805. function class_1() {
  26806. return _super !== null && _super.apply(this, arguments) || this;
  26807. }
  26808. class_1.prototype.getCoordinateSystems = function () {
  26809. return ecIns._coordSysMgr.getCoordinateSystems();
  26810. };
  26811. class_1.prototype.getComponentByElement = function (el) {
  26812. while (el) {
  26813. var modelInfo = el.__ecComponentInfo;
  26814. if (modelInfo != null) {
  26815. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  26816. }
  26817. el = el.parent;
  26818. }
  26819. };
  26820. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  26821. enterEmphasis(el, highlightDigit);
  26822. markStatusToUpdate(ecIns);
  26823. };
  26824. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  26825. leaveEmphasis(el, highlightDigit);
  26826. markStatusToUpdate(ecIns);
  26827. };
  26828. class_1.prototype.enterBlur = function (el) {
  26829. enterBlur(el);
  26830. markStatusToUpdate(ecIns);
  26831. };
  26832. class_1.prototype.leaveBlur = function (el) {
  26833. leaveBlur(el);
  26834. markStatusToUpdate(ecIns);
  26835. };
  26836. class_1.prototype.enterSelect = function (el) {
  26837. enterSelect(el);
  26838. markStatusToUpdate(ecIns);
  26839. };
  26840. class_1.prototype.leaveSelect = function (el) {
  26841. leaveSelect(el);
  26842. markStatusToUpdate(ecIns);
  26843. };
  26844. class_1.prototype.getModel = function () {
  26845. return ecIns.getModel();
  26846. };
  26847. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  26848. return ecIns.getViewOfComponentModel(componentModel);
  26849. };
  26850. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  26851. return ecIns.getViewOfSeriesModel(seriesModel);
  26852. };
  26853. return class_1;
  26854. }(ExtensionAPI))(ecIns);
  26855. };
  26856. enableConnect = function (chart) {
  26857. function updateConnectedChartsStatus(charts, status) {
  26858. for (var i = 0; i < charts.length; i++) {
  26859. var otherChart = charts[i];
  26860. otherChart[CONNECT_STATUS_KEY] = status;
  26861. }
  26862. }
  26863. each(eventActionMap, function (actionType, eventType) {
  26864. chart._messageCenter.on(eventType, function (event) {
  26865. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  26866. if (event && event.escapeConnect) {
  26867. return;
  26868. }
  26869. var action_1 = chart.makeActionFromEvent(event);
  26870. var otherCharts_1 = [];
  26871. each(instances$1, function (otherChart) {
  26872. if (otherChart !== chart && otherChart.group === chart.group) {
  26873. otherCharts_1.push(otherChart);
  26874. }
  26875. });
  26876. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  26877. each(otherCharts_1, function (otherChart) {
  26878. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  26879. otherChart.dispatchAction(action_1);
  26880. }
  26881. });
  26882. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  26883. }
  26884. });
  26885. });
  26886. };
  26887. }();
  26888. return ECharts;
  26889. }(Eventful);
  26890. var echartsProto = ECharts.prototype;
  26891. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  26892. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  26893. /**
  26894. * @deprecated
  26895. */
  26896. // @ts-ignore
  26897. echartsProto.one = function (eventName, cb, ctx) {
  26898. var self = this;
  26899. deprecateLog('ECharts#one is deprecated.');
  26900. function wrapped() {
  26901. var args2 = [];
  26902. for (var _i = 0; _i < arguments.length; _i++) {
  26903. args2[_i] = arguments[_i];
  26904. }
  26905. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  26906. self.off(eventName, wrapped);
  26907. }
  26908. this.on.call(this, eventName, wrapped, ctx);
  26909. };
  26910. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  26911. function disposedWarning(id) {
  26912. if ("development" !== 'production') {
  26913. console.warn('Instance ' + id + ' has been disposed');
  26914. }
  26915. }
  26916. var actions = {};
  26917. /**
  26918. * Map eventType to actionType
  26919. */
  26920. var eventActionMap = {};
  26921. var dataProcessorFuncs = [];
  26922. var optionPreprocessorFuncs = [];
  26923. var visualFuncs = [];
  26924. var themeStorage = {};
  26925. var loadingEffects = {};
  26926. var instances$1 = {};
  26927. var connectedGroups = {};
  26928. var idBase = +new Date() - 0;
  26929. var groupIdBase = +new Date() - 0;
  26930. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  26931. /**
  26932. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  26933. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  26934. * @param opts.width Use clientWidth of the input `dom` by default.
  26935. * Can be 'auto' (the same as null/undefined)
  26936. * @param opts.height Use clientHeight of the input `dom` by default.
  26937. * Can be 'auto' (the same as null/undefined)
  26938. * @param opts.locale Specify the locale.
  26939. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  26940. */
  26941. function init$1(dom, theme, opts) {
  26942. var isClient = !(opts && opts.ssr);
  26943. if (isClient) {
  26944. if ("development" !== 'production') {
  26945. if (!dom) {
  26946. throw new Error('Initialize failed: invalid dom.');
  26947. }
  26948. }
  26949. var existInstance = getInstanceByDom(dom);
  26950. if (existInstance) {
  26951. if ("development" !== 'production') {
  26952. console.warn('There is a chart instance already initialized on the dom.');
  26953. }
  26954. return existInstance;
  26955. }
  26956. if ("development" !== 'production') {
  26957. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  26958. console.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.');
  26959. }
  26960. }
  26961. }
  26962. var chart = new ECharts(dom, theme, opts);
  26963. chart.id = 'ec_' + idBase++;
  26964. instances$1[chart.id] = chart;
  26965. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26966. enableConnect(chart);
  26967. lifecycle.trigger('afterinit', chart);
  26968. return chart;
  26969. }
  26970. /**
  26971. * @usage
  26972. * (A)
  26973. * ```js
  26974. * let chart1 = echarts.init(dom1);
  26975. * let chart2 = echarts.init(dom2);
  26976. * chart1.group = 'xxx';
  26977. * chart2.group = 'xxx';
  26978. * echarts.connect('xxx');
  26979. * ```
  26980. * (B)
  26981. * ```js
  26982. * let chart1 = echarts.init(dom1);
  26983. * let chart2 = echarts.init(dom2);
  26984. * echarts.connect('xxx', [chart1, chart2]);
  26985. * ```
  26986. */
  26987. function connect(groupId) {
  26988. // Is array of charts
  26989. if (isArray(groupId)) {
  26990. var charts = groupId;
  26991. groupId = null; // If any chart has group
  26992. each(charts, function (chart) {
  26993. if (chart.group != null) {
  26994. groupId = chart.group;
  26995. }
  26996. });
  26997. groupId = groupId || 'g_' + groupIdBase++;
  26998. each(charts, function (chart) {
  26999. chart.group = groupId;
  27000. });
  27001. }
  27002. connectedGroups[groupId] = true;
  27003. return groupId;
  27004. }
  27005. /**
  27006. * @deprecated
  27007. */
  27008. function disConnect(groupId) {
  27009. connectedGroups[groupId] = false;
  27010. }
  27011. /**
  27012. * Alias and backword compat
  27013. */
  27014. var disconnect = disConnect;
  27015. /**
  27016. * Dispose a chart instance
  27017. */
  27018. function dispose$1(chart) {
  27019. if (isString(chart)) {
  27020. chart = instances$1[chart];
  27021. } else if (!(chart instanceof ECharts)) {
  27022. // Try to treat as dom
  27023. chart = getInstanceByDom(chart);
  27024. }
  27025. if (chart instanceof ECharts && !chart.isDisposed()) {
  27026. chart.dispose();
  27027. }
  27028. }
  27029. function getInstanceByDom(dom) {
  27030. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27031. }
  27032. function getInstanceById(key) {
  27033. return instances$1[key];
  27034. }
  27035. /**
  27036. * Register theme
  27037. */
  27038. function registerTheme(name, theme) {
  27039. themeStorage[name] = theme;
  27040. }
  27041. /**
  27042. * Register option preprocessor
  27043. */
  27044. function registerPreprocessor(preprocessorFunc) {
  27045. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27046. optionPreprocessorFuncs.push(preprocessorFunc);
  27047. }
  27048. }
  27049. function registerProcessor(priority, processor) {
  27050. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27051. }
  27052. /**
  27053. * Register postIniter
  27054. * @param {Function} postInitFunc
  27055. */
  27056. function registerPostInit(postInitFunc) {
  27057. registerUpdateLifecycle('afterinit', postInitFunc);
  27058. }
  27059. /**
  27060. * Register postUpdater
  27061. * @param {Function} postUpdateFunc
  27062. */
  27063. function registerPostUpdate(postUpdateFunc) {
  27064. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27065. }
  27066. function registerUpdateLifecycle(name, cb) {
  27067. lifecycle.on(name, cb);
  27068. }
  27069. function registerAction(actionInfo, eventName, action) {
  27070. if (isFunction(eventName)) {
  27071. action = eventName;
  27072. eventName = '';
  27073. }
  27074. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27075. event: eventName
  27076. }][0]; // Event name is all lowercase
  27077. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27078. eventName = actionInfo.event;
  27079. if (eventActionMap[eventName]) {
  27080. // Already registered.
  27081. return;
  27082. } // Validate action type and event name.
  27083. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27084. if (!actions[actionType]) {
  27085. actions[actionType] = {
  27086. action: action,
  27087. actionInfo: actionInfo
  27088. };
  27089. }
  27090. eventActionMap[eventName] = actionType;
  27091. }
  27092. function registerCoordinateSystem(type, coordSysCreator) {
  27093. CoordinateSystemManager.register(type, coordSysCreator);
  27094. }
  27095. /**
  27096. * Get dimensions of specified coordinate system.
  27097. * @param {string} type
  27098. * @return {Array.<string|Object>}
  27099. */
  27100. function getCoordinateSystemDimensions(type) {
  27101. var coordSysCreator = CoordinateSystemManager.get(type);
  27102. if (coordSysCreator) {
  27103. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27104. }
  27105. }
  27106. function registerLayout(priority, layoutTask) {
  27107. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27108. }
  27109. function registerVisual(priority, visualTask) {
  27110. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27111. }
  27112. var registeredTasks = [];
  27113. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27114. if (isFunction(priority) || isObject(priority)) {
  27115. fn = priority;
  27116. priority = defaultPriority;
  27117. }
  27118. if ("development" !== 'production') {
  27119. if (isNaN(priority) || priority == null) {
  27120. throw new Error('Illegal priority');
  27121. } // Check duplicate
  27122. each(targetList, function (wrap) {
  27123. assert(wrap.__raw !== fn);
  27124. });
  27125. } // Already registered
  27126. if (indexOf(registeredTasks, fn) >= 0) {
  27127. return;
  27128. }
  27129. registeredTasks.push(fn);
  27130. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27131. stageHandler.__prio = priority;
  27132. stageHandler.__raw = fn;
  27133. targetList.push(stageHandler);
  27134. }
  27135. function registerLoading(name, loadingFx) {
  27136. loadingEffects[name] = loadingFx;
  27137. }
  27138. /**
  27139. * ZRender need a canvas context to do measureText.
  27140. * But in node environment canvas may be created by node-canvas.
  27141. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27142. *
  27143. *
  27144. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27145. *
  27146. * @example
  27147. * let Canvas = require('canvas');
  27148. * let echarts = require('echarts');
  27149. * echarts.setCanvasCreator(function () {
  27150. * // Small size is enough.
  27151. * return new Canvas(32, 32);
  27152. * });
  27153. */
  27154. function setCanvasCreator(creator) {
  27155. if ("development" !== 'production') {
  27156. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27157. }
  27158. setPlatformAPI({
  27159. createCanvas: creator
  27160. });
  27161. }
  27162. /**
  27163. * The parameters and usage: see `geoSourceManager.registerMap`.
  27164. * Compatible with previous `echarts.registerMap`.
  27165. */
  27166. function registerMap(mapName, geoJson, specialAreas) {
  27167. var registerMap = getImpl('registerMap');
  27168. registerMap && registerMap(mapName, geoJson, specialAreas);
  27169. }
  27170. function getMap(mapName) {
  27171. var getMap = getImpl('getMap');
  27172. return getMap && getMap(mapName);
  27173. }
  27174. var registerTransform = registerExternalTransform;
  27175. /**
  27176. * Globa dispatchAction to a specified chart instance.
  27177. */
  27178. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27179. // if (!payload || !payload.chartId) {
  27180. // // Must have chartId to find chart
  27181. // return;
  27182. // }
  27183. // const chart = instances[payload.chartId];
  27184. // if (chart) {
  27185. // chart.dispatchAction(payload, opt);
  27186. // }
  27187. // }
  27188. // Buitlin global visual
  27189. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27190. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27191. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27192. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27193. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27194. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27195. registerPreprocessor(globalBackwardCompat);
  27196. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27197. registerLoading('default', defaultLoading); // Default actions
  27198. registerAction({
  27199. type: HIGHLIGHT_ACTION_TYPE,
  27200. event: HIGHLIGHT_ACTION_TYPE,
  27201. update: HIGHLIGHT_ACTION_TYPE
  27202. }, noop);
  27203. registerAction({
  27204. type: DOWNPLAY_ACTION_TYPE,
  27205. event: DOWNPLAY_ACTION_TYPE,
  27206. update: DOWNPLAY_ACTION_TYPE
  27207. }, noop);
  27208. registerAction({
  27209. type: SELECT_ACTION_TYPE,
  27210. event: SELECT_ACTION_TYPE,
  27211. update: SELECT_ACTION_TYPE
  27212. }, noop);
  27213. registerAction({
  27214. type: UNSELECT_ACTION_TYPE,
  27215. event: UNSELECT_ACTION_TYPE,
  27216. update: UNSELECT_ACTION_TYPE
  27217. }, noop);
  27218. registerAction({
  27219. type: TOGGLE_SELECT_ACTION_TYPE,
  27220. event: TOGGLE_SELECT_ACTION_TYPE,
  27221. update: TOGGLE_SELECT_ACTION_TYPE
  27222. }, noop); // Default theme
  27223. registerTheme('light', lightTheme);
  27224. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  27225. // be mounted on `echarts` is the extension `dataTool` is imported.
  27226. var dataTool = {};
  27227. var extensions = [];
  27228. var extensionRegisters = {
  27229. registerPreprocessor: registerPreprocessor,
  27230. registerProcessor: registerProcessor,
  27231. registerPostInit: registerPostInit,
  27232. registerPostUpdate: registerPostUpdate,
  27233. registerUpdateLifecycle: registerUpdateLifecycle,
  27234. registerAction: registerAction,
  27235. registerCoordinateSystem: registerCoordinateSystem,
  27236. registerLayout: registerLayout,
  27237. registerVisual: registerVisual,
  27238. registerTransform: registerTransform,
  27239. registerLoading: registerLoading,
  27240. registerMap: registerMap,
  27241. registerImpl: registerImpl,
  27242. PRIORITY: PRIORITY,
  27243. ComponentModel: ComponentModel,
  27244. ComponentView: ComponentView,
  27245. SeriesModel: SeriesModel,
  27246. ChartView: ChartView,
  27247. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27248. registerComponentModel: function (ComponentModelClass) {
  27249. ComponentModel.registerClass(ComponentModelClass);
  27250. },
  27251. registerComponentView: function (ComponentViewClass) {
  27252. ComponentView.registerClass(ComponentViewClass);
  27253. },
  27254. registerSeriesModel: function (SeriesModelClass) {
  27255. SeriesModel.registerClass(SeriesModelClass);
  27256. },
  27257. registerChartView: function (ChartViewClass) {
  27258. ChartView.registerClass(ChartViewClass);
  27259. },
  27260. registerSubTypeDefaulter: function (componentType, defaulter) {
  27261. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27262. },
  27263. registerPainter: function (painterType, PainterCtor) {
  27264. registerPainter(painterType, PainterCtor);
  27265. }
  27266. };
  27267. function use(ext) {
  27268. if (isArray(ext)) {
  27269. // use([ChartLine, ChartBar]);
  27270. each(ext, function (singleExt) {
  27271. use(singleExt);
  27272. });
  27273. return;
  27274. }
  27275. if (indexOf(extensions, ext) >= 0) {
  27276. return;
  27277. }
  27278. extensions.push(ext);
  27279. if (isFunction(ext)) {
  27280. ext = {
  27281. install: ext
  27282. };
  27283. }
  27284. ext.install(extensionRegisters);
  27285. }
  27286. /*
  27287. * Licensed to the Apache Software Foundation (ASF) under one
  27288. * or more contributor license agreements. See the NOTICE file
  27289. * distributed with this work for additional information
  27290. * regarding copyright ownership. The ASF licenses this file
  27291. * to you under the Apache License, Version 2.0 (the
  27292. * "License"); you may not use this file except in compliance
  27293. * with the License. You may obtain a copy of the License at
  27294. *
  27295. * http://www.apache.org/licenses/LICENSE-2.0
  27296. *
  27297. * Unless required by applicable law or agreed to in writing,
  27298. * software distributed under the License is distributed on an
  27299. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27300. * KIND, either express or implied. See the License for the
  27301. * specific language governing permissions and limitations
  27302. * under the License.
  27303. */
  27304. /**
  27305. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27306. */
  27307. /*
  27308. * Licensed to the Apache Software Foundation (ASF) under one
  27309. * or more contributor license agreements. See the NOTICE file
  27310. * distributed with this work for additional information
  27311. * regarding copyright ownership. The ASF licenses this file
  27312. * to you under the Apache License, Version 2.0 (the
  27313. * "License"); you may not use this file except in compliance
  27314. * with the License. You may obtain a copy of the License at
  27315. *
  27316. * http://www.apache.org/licenses/LICENSE-2.0
  27317. *
  27318. * Unless required by applicable law or agreed to in writing,
  27319. * software distributed under the License is distributed on an
  27320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27321. * KIND, either express or implied. See the License for the
  27322. * specific language governing permissions and limitations
  27323. * under the License.
  27324. */
  27325. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27326. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27327. }
  27328. function defaultKeyGetter(item) {
  27329. return item;
  27330. }
  27331. var DataDiffer =
  27332. /** @class */
  27333. function () {
  27334. /**
  27335. * @param context Can be visited by this.context in callback.
  27336. */
  27337. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27338. diffMode) {
  27339. this._old = oldArr;
  27340. this._new = newArr;
  27341. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27342. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27343. this.context = context;
  27344. this._diffModeMultiple = diffMode === 'multiple';
  27345. }
  27346. /**
  27347. * Callback function when add a data
  27348. */
  27349. DataDiffer.prototype.add = function (func) {
  27350. this._add = func;
  27351. return this;
  27352. };
  27353. /**
  27354. * Callback function when update a data
  27355. */
  27356. DataDiffer.prototype.update = function (func) {
  27357. this._update = func;
  27358. return this;
  27359. };
  27360. /**
  27361. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27362. */
  27363. DataDiffer.prototype.updateManyToOne = function (func) {
  27364. this._updateManyToOne = func;
  27365. return this;
  27366. };
  27367. /**
  27368. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27369. */
  27370. DataDiffer.prototype.updateOneToMany = function (func) {
  27371. this._updateOneToMany = func;
  27372. return this;
  27373. };
  27374. /**
  27375. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27376. */
  27377. DataDiffer.prototype.updateManyToMany = function (func) {
  27378. this._updateManyToMany = func;
  27379. return this;
  27380. };
  27381. /**
  27382. * Callback function when remove a data
  27383. */
  27384. DataDiffer.prototype.remove = function (func) {
  27385. this._remove = func;
  27386. return this;
  27387. };
  27388. DataDiffer.prototype.execute = function () {
  27389. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27390. };
  27391. DataDiffer.prototype._executeOneToOne = function () {
  27392. var oldArr = this._old;
  27393. var newArr = this._new;
  27394. var newDataIndexMap = {};
  27395. var oldDataKeyArr = new Array(oldArr.length);
  27396. var newDataKeyArr = new Array(newArr.length);
  27397. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27398. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27399. for (var i = 0; i < oldArr.length; i++) {
  27400. var oldKey = oldDataKeyArr[i];
  27401. var newIdxMapVal = newDataIndexMap[oldKey];
  27402. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27403. if (newIdxMapValLen > 1) {
  27404. // Consider there is duplicate key (for example, use dataItem.name as key).
  27405. // We should make sure every item in newArr and oldArr can be visited.
  27406. var newIdx = newIdxMapVal.shift();
  27407. if (newIdxMapVal.length === 1) {
  27408. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27409. }
  27410. this._update && this._update(newIdx, i);
  27411. } else if (newIdxMapValLen === 1) {
  27412. newDataIndexMap[oldKey] = null;
  27413. this._update && this._update(newIdxMapVal, i);
  27414. } else {
  27415. this._remove && this._remove(i);
  27416. }
  27417. }
  27418. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27419. };
  27420. /**
  27421. * For example, consider the case:
  27422. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27423. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27424. * Where:
  27425. * o0, o1, n0 has key 'a' (many to one)
  27426. * o5, n4, n5, n6 has key 'b' (one to many)
  27427. * o2, n1 has key 'c' (one to one)
  27428. * n2, n3 has key 'd' (add)
  27429. * o3, o4 has key 'e' (remove)
  27430. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27431. * Then:
  27432. * (The order of the following directives are not ensured.)
  27433. * this._updateManyToOne(n0, [o0, o1]);
  27434. * this._updateOneToMany([n4, n5, n6], o5);
  27435. * this._update(n1, o2);
  27436. * this._remove(o3);
  27437. * this._remove(o4);
  27438. * this._remove(o6);
  27439. * this._remove(o7);
  27440. * this._add(n2);
  27441. * this._add(n3);
  27442. * this._add(n7);
  27443. * this._add(n8);
  27444. */
  27445. DataDiffer.prototype._executeMultiple = function () {
  27446. var oldArr = this._old;
  27447. var newArr = this._new;
  27448. var oldDataIndexMap = {};
  27449. var newDataIndexMap = {};
  27450. var oldDataKeyArr = [];
  27451. var newDataKeyArr = [];
  27452. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27453. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27454. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27455. var oldKey = oldDataKeyArr[i];
  27456. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27457. var newIdxMapVal = newDataIndexMap[oldKey];
  27458. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27459. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27460. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27461. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27462. newDataIndexMap[oldKey] = null;
  27463. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27464. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27465. newDataIndexMap[oldKey] = null;
  27466. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27467. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27468. newDataIndexMap[oldKey] = null;
  27469. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27470. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27471. newDataIndexMap[oldKey] = null;
  27472. } else if (oldIdxMapValLen > 1) {
  27473. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27474. this._remove && this._remove(oldIdxMapVal[i_1]);
  27475. }
  27476. } else {
  27477. this._remove && this._remove(oldIdxMapVal);
  27478. }
  27479. }
  27480. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27481. };
  27482. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27483. for (var i = 0; i < newDataKeyArr.length; i++) {
  27484. var newKey = newDataKeyArr[i];
  27485. var newIdxMapVal = newDataIndexMap[newKey];
  27486. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27487. if (idxMapValLen > 1) {
  27488. for (var j = 0; j < idxMapValLen; j++) {
  27489. this._add && this._add(newIdxMapVal[j]);
  27490. }
  27491. } else if (idxMapValLen === 1) {
  27492. this._add && this._add(newIdxMapVal);
  27493. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27494. newDataIndexMap[newKey] = null;
  27495. }
  27496. };
  27497. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27498. map, // In 'byKey', the output `keyArr` is duplication removed.
  27499. // In 'byIndex', the output `keyArr` is not duplication removed and
  27500. // its indices are accurately corresponding to `arr`.
  27501. keyArr, keyGetterName) {
  27502. var cbModeMultiple = this._diffModeMultiple;
  27503. for (var i = 0; i < arr.length; i++) {
  27504. // Add prefix to avoid conflict with Object.prototype.
  27505. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27506. if (!cbModeMultiple) {
  27507. keyArr[i] = key;
  27508. }
  27509. if (!map) {
  27510. continue;
  27511. }
  27512. var idxMapVal = map[key];
  27513. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27514. if (idxMapValLen === 0) {
  27515. // Simple optimize: in most cases, one index has one key,
  27516. // do not need array.
  27517. map[key] = i;
  27518. if (cbModeMultiple) {
  27519. keyArr.push(key);
  27520. }
  27521. } else if (idxMapValLen === 1) {
  27522. map[key] = [idxMapVal, i];
  27523. } else {
  27524. idxMapVal.push(i);
  27525. }
  27526. }
  27527. };
  27528. return DataDiffer;
  27529. }();
  27530. var DimensionUserOuput =
  27531. /** @class */
  27532. function () {
  27533. function DimensionUserOuput(encode, dimRequest) {
  27534. this._encode = encode;
  27535. this._schema = dimRequest;
  27536. }
  27537. DimensionUserOuput.prototype.get = function () {
  27538. return {
  27539. // Do not generate full dimension name until fist used.
  27540. fullDimensions: this._getFullDimensionNames(),
  27541. encode: this._encode
  27542. };
  27543. };
  27544. /**
  27545. * Get all data store dimension names.
  27546. * Theoretically a series data store is defined both by series and used dataset (if any).
  27547. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27548. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27549. * In this case, the dimension name is `null`/`undefined`.
  27550. */
  27551. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27552. if (!this._cachedDimNames) {
  27553. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27554. }
  27555. return this._cachedDimNames;
  27556. };
  27557. return DimensionUserOuput;
  27558. }();
  27559. function summarizeDimensions(data, schema) {
  27560. var summary = {};
  27561. var encode = summary.encode = {};
  27562. var notExtraCoordDimMap = createHashMap();
  27563. var defaultedLabel = [];
  27564. var defaultedTooltip = [];
  27565. var userOutputEncode = {};
  27566. each(data.dimensions, function (dimName) {
  27567. var dimItem = data.getDimensionInfo(dimName);
  27568. var coordDim = dimItem.coordDim;
  27569. if (coordDim) {
  27570. if ("development" !== 'production') {
  27571. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  27572. }
  27573. var coordDimIndex = dimItem.coordDimIndex;
  27574. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  27575. if (!dimItem.isExtraCoord) {
  27576. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  27577. // because when dataset is used, it is hard to guess which dimension
  27578. // can be value dimension. If both show x, y on label is not look good,
  27579. // and conventionally y axis is focused more.
  27580. if (mayLabelDimType(dimItem.type)) {
  27581. defaultedLabel[0] = dimName;
  27582. } // User output encode do not contain generated coords.
  27583. // And it only has index. User can use index to retrieve value from the raw item array.
  27584. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  27585. }
  27586. if (dimItem.defaultTooltip) {
  27587. defaultedTooltip.push(dimName);
  27588. }
  27589. }
  27590. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  27591. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  27592. var dimIndex = dimItem.otherDims[otherDim];
  27593. if (dimIndex != null && dimIndex !== false) {
  27594. encodeArr[dimIndex] = dimItem.name;
  27595. }
  27596. });
  27597. });
  27598. var dataDimsOnCoord = [];
  27599. var encodeFirstDimNotExtra = {};
  27600. notExtraCoordDimMap.each(function (v, coordDim) {
  27601. var dimArr = encode[coordDim];
  27602. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  27603. // dim canot on more than one coordDim.
  27604. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  27605. });
  27606. summary.dataDimsOnCoord = dataDimsOnCoord;
  27607. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  27608. return data.getDimensionInfo(dimName).storeDimIndex;
  27609. });
  27610. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  27611. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  27612. // in this way. Use label.formatter instead. May be remove this approach someday.
  27613. if (encodeLabel && encodeLabel.length) {
  27614. defaultedLabel = encodeLabel.slice();
  27615. }
  27616. var encodeTooltip = encode.tooltip;
  27617. if (encodeTooltip && encodeTooltip.length) {
  27618. defaultedTooltip = encodeTooltip.slice();
  27619. } else if (!defaultedTooltip.length) {
  27620. defaultedTooltip = defaultedLabel.slice();
  27621. }
  27622. encode.defaultedLabel = defaultedLabel;
  27623. encode.defaultedTooltip = defaultedTooltip;
  27624. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  27625. return summary;
  27626. }
  27627. function getOrCreateEncodeArr(encode, dim) {
  27628. if (!encode.hasOwnProperty(dim)) {
  27629. encode[dim] = [];
  27630. }
  27631. return encode[dim];
  27632. } // FIXME:TS should be type `AxisType`
  27633. function getDimensionTypeByAxis(axisType) {
  27634. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  27635. }
  27636. function mayLabelDimType(dimType) {
  27637. // In most cases, ordinal and time do not suitable for label.
  27638. // Ordinal info can be displayed on axis. Time is too long.
  27639. return !(dimType === 'ordinal' || dimType === 'time');
  27640. } // function findTheLastDimMayLabel(data) {
  27641. // // Get last value dim
  27642. // let dimensions = data.dimensions.slice();
  27643. // let valueType;
  27644. // let valueDim;
  27645. // while (dimensions.length && (
  27646. // valueDim = dimensions.pop(),
  27647. // valueType = data.getDimensionInfo(valueDim).type,
  27648. // valueType === 'ordinal' || valueType === 'time'
  27649. // )) {} // jshint ignore:line
  27650. // return valueDim;
  27651. // }
  27652. var SeriesDimensionDefine =
  27653. /** @class */
  27654. function () {
  27655. /**
  27656. * @param opt All of the fields will be shallow copied.
  27657. */
  27658. function SeriesDimensionDefine(opt) {
  27659. /**
  27660. * The format of `otherDims` is:
  27661. * ```js
  27662. * {
  27663. * tooltip?: number
  27664. * label?: number
  27665. * itemName?: number
  27666. * seriesName?: number
  27667. * }
  27668. * ```
  27669. *
  27670. * A `series.encode` can specified these fields:
  27671. * ```js
  27672. * encode: {
  27673. * // "3, 1, 5" is the index of data dimension.
  27674. * tooltip: [3, 1, 5],
  27675. * label: [0, 3],
  27676. * ...
  27677. * }
  27678. * ```
  27679. * `otherDims` is the parse result of the `series.encode` above, like:
  27680. * ```js
  27681. * // Suppose the index of this data dimension is `3`.
  27682. * this.otherDims = {
  27683. * // `3` is at the index `0` of the `encode.tooltip`
  27684. * tooltip: 0,
  27685. * // `3` is at the index `1` of the `encode.label`
  27686. * label: 1
  27687. * };
  27688. * ```
  27689. *
  27690. * This prop should never be `null`/`undefined` after initialized.
  27691. */
  27692. this.otherDims = {};
  27693. if (opt != null) {
  27694. extend(this, opt);
  27695. }
  27696. }
  27697. return SeriesDimensionDefine;
  27698. }();
  27699. var inner$4 = makeInner();
  27700. var dimTypeShort = {
  27701. float: 'f',
  27702. int: 'i',
  27703. ordinal: 'o',
  27704. number: 'n',
  27705. time: 't'
  27706. };
  27707. /**
  27708. * Represents the dimension requirement of a series.
  27709. *
  27710. * NOTICE:
  27711. * When there are too many dimensions in dataset and many series, only the used dimensions
  27712. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  27713. * But users may query data by other unused dimension names.
  27714. * In this case, users can only query data if and only if they have defined dimension names
  27715. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  27716. * `source` dimensions.
  27717. */
  27718. var SeriesDataSchema =
  27719. /** @class */
  27720. function () {
  27721. function SeriesDataSchema(opt) {
  27722. this.dimensions = opt.dimensions;
  27723. this._dimOmitted = opt.dimensionOmitted;
  27724. this.source = opt.source;
  27725. this._fullDimCount = opt.fullDimensionCount;
  27726. this._updateDimOmitted(opt.dimensionOmitted);
  27727. }
  27728. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  27729. return this._dimOmitted;
  27730. };
  27731. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  27732. this._dimOmitted = dimensionOmitted;
  27733. if (!dimensionOmitted) {
  27734. return;
  27735. }
  27736. if (!this._dimNameMap) {
  27737. this._dimNameMap = ensureSourceDimNameMap(this.source);
  27738. }
  27739. };
  27740. /**
  27741. * @caution Can only be used when `dimensionOmitted: true`.
  27742. *
  27743. * Get index by user defined dimension name (i.e., not internal generate name).
  27744. * That is, get index from `dimensionsDefine`.
  27745. * If no `dimensionsDefine`, or no name get, return -1.
  27746. */
  27747. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  27748. return retrieve2(this._dimNameMap.get(dimName), -1);
  27749. };
  27750. /**
  27751. * @caution Can only be used when `dimensionOmitted: true`.
  27752. *
  27753. * Notice: may return `null`/`undefined` if user not specify dimension names.
  27754. */
  27755. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  27756. var dimensionsDefine = this.source.dimensionsDefine;
  27757. if (dimensionsDefine) {
  27758. return dimensionsDefine[dimIndex];
  27759. }
  27760. };
  27761. SeriesDataSchema.prototype.makeStoreSchema = function () {
  27762. var dimCount = this._fullDimCount;
  27763. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  27764. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  27765. // Generate from seriesDimList directly
  27766. var dimHash = '';
  27767. var dims = [];
  27768. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  27769. var property = void 0;
  27770. var type = void 0;
  27771. var ordinalMeta = void 0;
  27772. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  27773. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27774. property = willRetrieveDataByName ? seriesDimDef.name : null;
  27775. type = seriesDimDef.type;
  27776. ordinalMeta = seriesDimDef.ordinalMeta;
  27777. seriesDimIdx++;
  27778. } else {
  27779. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27780. if (sourceDimDef) {
  27781. property = willRetrieveDataByName ? sourceDimDef.name : null;
  27782. type = sourceDimDef.type;
  27783. }
  27784. }
  27785. dims.push({
  27786. property: property,
  27787. type: type,
  27788. ordinalMeta: ordinalMeta
  27789. }); // If retrieving data by index,
  27790. // use <index, type, ordinalMeta> to determine whether data can be shared.
  27791. // (Becuase in this case there might be no dimension name defined in dataset, but indices always exists).
  27792. // (indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  27793. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  27794. // use <property, type, ordinalMeta> in hash.
  27795. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  27796. // So we do not add property to hash to make sure they can share this store.
  27797. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  27798. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  27799. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  27800. : property;
  27801. }
  27802. dimHash += '$';
  27803. dimHash += dimTypeShort[type] || 'f';
  27804. if (ordinalMeta) {
  27805. dimHash += ordinalMeta.uid;
  27806. }
  27807. dimHash += '$';
  27808. } // Source from endpoint(usually series) will be read differently
  27809. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  27810. // So we use this three props as key.
  27811. var source = this.source;
  27812. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  27813. return {
  27814. dimensions: dims,
  27815. hash: hash
  27816. };
  27817. };
  27818. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  27819. var result = [];
  27820. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  27821. var name_1 = void 0;
  27822. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  27823. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  27824. if (!seriesDimDef.isCalculationCoord) {
  27825. name_1 = seriesDimDef.name;
  27826. }
  27827. seriesDimIdx++;
  27828. } else {
  27829. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  27830. if (sourceDimDef) {
  27831. name_1 = sourceDimDef.name;
  27832. }
  27833. }
  27834. result.push(name_1);
  27835. }
  27836. return result;
  27837. };
  27838. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  27839. this.dimensions.push(dimDef);
  27840. dimDef.isCalculationCoord = true;
  27841. this._fullDimCount++; // If append dimension on a data store, consider the store
  27842. // might be shared by different series, series dimensions not
  27843. // really map to store dimensions.
  27844. this._updateDimOmitted(true);
  27845. };
  27846. return SeriesDataSchema;
  27847. }();
  27848. function isSeriesDataSchema(schema) {
  27849. return schema instanceof SeriesDataSchema;
  27850. }
  27851. function createDimNameMap(dimsDef) {
  27852. var dataDimNameMap = createHashMap();
  27853. for (var i = 0; i < (dimsDef || []).length; i++) {
  27854. var dimDefItemRaw = dimsDef[i];
  27855. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  27856. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27857. dataDimNameMap.set(userDimName, i);
  27858. }
  27859. }
  27860. return dataDimNameMap;
  27861. }
  27862. function ensureSourceDimNameMap(source) {
  27863. var innerSource = inner$4(source);
  27864. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  27865. }
  27866. function shouldOmitUnusedDimensions(dimCount) {
  27867. return dimCount > 30;
  27868. }
  27869. var isObject$2 = isObject;
  27870. var map$1 = map;
  27871. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  27872. // which will cause weird udpate animation.
  27873. var ID_PREFIX = 'e\0\0';
  27874. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  27875. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  27876. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  27877. // Internal method declarations:
  27878. // -----------------------------
  27879. var prepareInvertedIndex;
  27880. var getId;
  27881. var getIdNameFromStore;
  27882. var normalizeDimensions;
  27883. var transferProperties;
  27884. var cloneListForMapAndSample;
  27885. var makeIdFromName;
  27886. var SeriesData =
  27887. /** @class */
  27888. function () {
  27889. /**
  27890. * @param dimensionsInput.dimensions
  27891. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  27892. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  27893. */
  27894. function SeriesData(dimensionsInput, hostModel) {
  27895. this.type = 'list';
  27896. this._dimOmitted = false;
  27897. this._nameList = [];
  27898. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  27899. // Never used yet (not used yet).
  27900. // private _optionModels: Model[] = [];
  27901. // Global visual properties after visual coding
  27902. this._visual = {}; // Globel layout properties.
  27903. this._layout = {}; // Item visual properties after visual coding
  27904. this._itemVisuals = []; // Item layout properties after layout
  27905. this._itemLayouts = []; // Graphic elemnents
  27906. this._graphicEls = []; // key: dim, value: extent
  27907. this._approximateExtent = {};
  27908. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  27909. // (in type `OptionDataItemObject`).
  27910. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  27911. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  27912. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  27913. // Notice that those method should `RETURN` the new list.
  27914. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  27915. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27916. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  27917. var dimensions;
  27918. var assignStoreDimIdx = false;
  27919. if (isSeriesDataSchema(dimensionsInput)) {
  27920. dimensions = dimensionsInput.dimensions;
  27921. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  27922. this._schema = dimensionsInput;
  27923. } else {
  27924. assignStoreDimIdx = true;
  27925. dimensions = dimensionsInput;
  27926. }
  27927. dimensions = dimensions || ['x', 'y'];
  27928. var dimensionInfos = {};
  27929. var dimensionNames = [];
  27930. var invertedIndicesMap = {};
  27931. var needsHasOwn = false;
  27932. var emptyObj = {};
  27933. for (var i = 0; i < dimensions.length; i++) {
  27934. // Use the original dimensions[i], where other flag props may exists.
  27935. var dimInfoInput = dimensions[i];
  27936. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  27937. name: dimInfoInput
  27938. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  27939. var dimensionName = dimensionInfo.name;
  27940. dimensionInfo.type = dimensionInfo.type || 'float';
  27941. if (!dimensionInfo.coordDim) {
  27942. dimensionInfo.coordDim = dimensionName;
  27943. dimensionInfo.coordDimIndex = 0;
  27944. }
  27945. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  27946. dimensionNames.push(dimensionName);
  27947. dimensionInfos[dimensionName] = dimensionInfo;
  27948. if (emptyObj[dimensionName] != null) {
  27949. needsHasOwn = true;
  27950. }
  27951. if (dimensionInfo.createInvertedIndices) {
  27952. invertedIndicesMap[dimensionName] = [];
  27953. }
  27954. if (otherDims.itemName === 0) {
  27955. this._nameDimIdx = i;
  27956. }
  27957. if (otherDims.itemId === 0) {
  27958. this._idDimIdx = i;
  27959. }
  27960. if ("development" !== 'production') {
  27961. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  27962. }
  27963. if (assignStoreDimIdx) {
  27964. dimensionInfo.storeDimIndex = i;
  27965. }
  27966. }
  27967. this.dimensions = dimensionNames;
  27968. this._dimInfos = dimensionInfos;
  27969. this._initGetDimensionInfo(needsHasOwn);
  27970. this.hostModel = hostModel;
  27971. this._invertedIndicesMap = invertedIndicesMap;
  27972. if (this._dimOmitted) {
  27973. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  27974. each(dimensionNames, function (dimName) {
  27975. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  27976. });
  27977. }
  27978. }
  27979. /**
  27980. *
  27981. * Get concrete dimension name by dimension name or dimension index.
  27982. * If input a dimension name, do not validate whether the dimension name exits.
  27983. *
  27984. * @caution
  27985. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  27986. * Because only those dimensions will have auto-generated dimension names if not
  27987. * have a user-specified name, and other dimensions will get a return of null/undefined.
  27988. *
  27989. * @notice Becuause of this reason, should better use `getDimensionIndex` instead, for examples:
  27990. * ```js
  27991. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  27992. * ```
  27993. *
  27994. * @return Concrete dim name.
  27995. */
  27996. SeriesData.prototype.getDimension = function (dim) {
  27997. var dimIdx = this._recognizeDimIndex(dim);
  27998. if (dimIdx == null) {
  27999. return dim;
  28000. }
  28001. dimIdx = dim;
  28002. if (!this._dimOmitted) {
  28003. return this.dimensions[dimIdx];
  28004. } // Retrieve from series dimension definition becuase it probably contains
  28005. // generated dimension name (like 'x', 'y').
  28006. var dimName = this._dimIdxToName.get(dimIdx);
  28007. if (dimName != null) {
  28008. return dimName;
  28009. }
  28010. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28011. if (sourceDimDef) {
  28012. return sourceDimDef.name;
  28013. }
  28014. };
  28015. /**
  28016. * Get dimension index in data store. Return -1 if not found.
  28017. * Can be used to index value from getRawValue.
  28018. */
  28019. SeriesData.prototype.getDimensionIndex = function (dim) {
  28020. var dimIdx = this._recognizeDimIndex(dim);
  28021. if (dimIdx != null) {
  28022. return dimIdx;
  28023. }
  28024. if (dim == null) {
  28025. return -1;
  28026. }
  28027. var dimInfo = this._getDimInfo(dim);
  28028. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28029. };
  28030. /**
  28031. * The meanings of the input parameter `dim`:
  28032. *
  28033. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28034. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28035. * + If dim is a number-like string (e.g., `"1"`):
  28036. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28037. * it means that concrete name.
  28038. * + If not, it will be converted to a number, which means the index of the dimension.
  28039. * (why? because of the backward compatbility. We have been tolerating number-like string in
  28040. * dimension setting, although now it seems that it is not a good idea.)
  28041. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28042. * if no dimension name is defined as `"1"`.
  28043. * + If dim is a not-number-like string, it means the concrete dim name.
  28044. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28045. * or customized in `dimensions` property of option like `"age"`.
  28046. *
  28047. * @return recogonized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28048. */
  28049. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28050. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  28051. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28052. return +dim;
  28053. }
  28054. };
  28055. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28056. var dimIdx = this.getDimensionIndex(dim);
  28057. if ("development" !== 'production') {
  28058. if (dimIdx == null) {
  28059. throw new Error('Unkown dimension ' + dim);
  28060. }
  28061. }
  28062. return dimIdx;
  28063. };
  28064. /**
  28065. * Get type and calculation info of particular dimension
  28066. * @param dim
  28067. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28068. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28069. */
  28070. SeriesData.prototype.getDimensionInfo = function (dim) {
  28071. // Do not clone, because there may be categories in dimInfo.
  28072. return this._getDimInfo(this.getDimension(dim));
  28073. };
  28074. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28075. var dimensionInfos = this._dimInfos;
  28076. this._getDimInfo = needsHasOwn ? function (dimName) {
  28077. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28078. } : function (dimName) {
  28079. return dimensionInfos[dimName];
  28080. };
  28081. };
  28082. /**
  28083. * concrete dimension name list on coord.
  28084. */
  28085. SeriesData.prototype.getDimensionsOnCoord = function () {
  28086. return this._dimSummary.dataDimsOnCoord.slice();
  28087. };
  28088. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28089. var dimensionsSummary = this._dimSummary;
  28090. if (idx == null) {
  28091. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28092. }
  28093. var dims = dimensionsSummary.encode[coordDim];
  28094. return dims ? dims[idx] : null;
  28095. };
  28096. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28097. var dimensionsSummary = this._dimSummary;
  28098. var dims = dimensionsSummary.encode[coordDim];
  28099. return (dims || []).slice();
  28100. };
  28101. SeriesData.prototype.getStore = function () {
  28102. return this._store;
  28103. };
  28104. /**
  28105. * Initialize from data
  28106. * @param data source or data or data store.
  28107. * @param nameList The name of a datum is used on data diff and
  28108. * default label/tooltip.
  28109. * A name can be specified in encode.itemName,
  28110. * or dataItem.name (only for series option data),
  28111. * or provided in nameList from outside.
  28112. */
  28113. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28114. var _this = this;
  28115. var store;
  28116. if (data instanceof DataStore) {
  28117. store = data;
  28118. }
  28119. if (!store) {
  28120. var dimensions = this.dimensions;
  28121. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28122. store = new DataStore();
  28123. var dimensionInfos = map$1(dimensions, function (dimName) {
  28124. return {
  28125. type: _this._dimInfos[dimName].type,
  28126. property: dimName
  28127. };
  28128. });
  28129. store.initData(provider, dimensionInfos, dimValueGetter);
  28130. }
  28131. this._store = store; // Reset
  28132. this._nameList = (nameList || []).slice();
  28133. this._idList = [];
  28134. this._nameRepeatCount = {};
  28135. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  28136. // Needs to be initialized after store is prepared.
  28137. this._dimSummary = summarizeDimensions(this, this._schema);
  28138. this.userOutput = this._dimSummary.userOutput;
  28139. };
  28140. /**
  28141. * Caution: Can be only called on raw data (before `this._indices` created).
  28142. */
  28143. SeriesData.prototype.appendData = function (data) {
  28144. var range = this._store.appendData(data);
  28145. this._doInit(range[0], range[1]);
  28146. };
  28147. /**
  28148. * Caution: Can be only called on raw data (before `this._indices` created).
  28149. * This method does not modify `rawData` (`dataProvider`), but only
  28150. * add values to store.
  28151. *
  28152. * The final count will be increased by `Math.max(values.length, names.length)`.
  28153. *
  28154. * @param values That is the SourceType: 'arrayRows', like
  28155. * [
  28156. * [12, 33, 44],
  28157. * [NaN, 43, 1],
  28158. * ['-', 'asdf', 0]
  28159. * ]
  28160. * Each item is exaclty cooresponding to a dimension.
  28161. */
  28162. SeriesData.prototype.appendValues = function (values, names) {
  28163. var _a = this._store.appendValues(values, names.length),
  28164. start = _a.start,
  28165. end = _a.end;
  28166. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28167. this._updateOrdinalMeta();
  28168. if (names) {
  28169. for (var idx = start; idx < end; idx++) {
  28170. var sourceIdx = idx - start;
  28171. this._nameList[idx] = names[sourceIdx];
  28172. if (shouldMakeIdFromName) {
  28173. makeIdFromName(this, idx);
  28174. }
  28175. }
  28176. }
  28177. };
  28178. SeriesData.prototype._updateOrdinalMeta = function () {
  28179. var store = this._store;
  28180. var dimensions = this.dimensions;
  28181. for (var i = 0; i < dimensions.length; i++) {
  28182. var dimInfo = this._dimInfos[dimensions[i]];
  28183. if (dimInfo.ordinalMeta) {
  28184. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28185. }
  28186. }
  28187. };
  28188. SeriesData.prototype._shouldMakeIdFromName = function () {
  28189. var provider = this._store.getProvider();
  28190. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28191. };
  28192. SeriesData.prototype._doInit = function (start, end) {
  28193. if (start >= end) {
  28194. return;
  28195. }
  28196. var store = this._store;
  28197. var provider = store.getProvider();
  28198. this._updateOrdinalMeta();
  28199. var nameList = this._nameList;
  28200. var idList = this._idList;
  28201. var sourceFormat = provider.getSource().sourceFormat;
  28202. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  28203. // [1, 2]
  28204. // 2
  28205. // Bar chart, line chart which uses category axis
  28206. // only gives the 'y' value. 'x' value is the indices of category
  28207. // Use a tempValue to normalize the value to be a (x, y) value
  28208. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28209. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28210. if (isFormatOriginal && !provider.pure) {
  28211. var sharedDataItem = [];
  28212. for (var idx = start; idx < end; idx++) {
  28213. // NOTICE: Try not to write things into dataItem
  28214. var dataItem = provider.getItem(idx, sharedDataItem);
  28215. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28216. this.hasItemOption = true;
  28217. }
  28218. if (dataItem) {
  28219. var itemName = dataItem.name;
  28220. if (nameList[idx] == null && itemName != null) {
  28221. nameList[idx] = convertOptionIdName(itemName, null);
  28222. }
  28223. var itemId = dataItem.id;
  28224. if (idList[idx] == null && itemId != null) {
  28225. idList[idx] = convertOptionIdName(itemId, null);
  28226. }
  28227. }
  28228. }
  28229. }
  28230. if (this._shouldMakeIdFromName()) {
  28231. for (var idx = start; idx < end; idx++) {
  28232. makeIdFromName(this, idx);
  28233. }
  28234. }
  28235. prepareInvertedIndex(this);
  28236. };
  28237. /**
  28238. * PENDING: In fact currently this function is only used to short-circuit
  28239. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28240. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28241. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28242. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28243. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28244. * be still needed.
  28245. *
  28246. * Optimize for the scenario that data is filtered by a given extent.
  28247. * Consider that if data amount is more than hundreds of thousand,
  28248. * extent calculation will cost more than 10ms and the cache will
  28249. * be erased because of the filtering.
  28250. */
  28251. SeriesData.prototype.getApproximateExtent = function (dim) {
  28252. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28253. };
  28254. /**
  28255. * Calculate extent on a filtered data might be time consuming.
  28256. * Approximate extent is only used for: calculte extent of filtered data outside.
  28257. */
  28258. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28259. dim = this.getDimension(dim);
  28260. this._approximateExtent[dim] = extent.slice();
  28261. };
  28262. SeriesData.prototype.getCalculationInfo = function (key) {
  28263. return this._calculationInfo[key];
  28264. };
  28265. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28266. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28267. };
  28268. /**
  28269. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  28270. * In most cases, name is used in display, where returning a string is more convenient.
  28271. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28272. * rule that name `2` equals to name `'2'`.
  28273. */
  28274. SeriesData.prototype.getName = function (idx) {
  28275. var rawIndex = this.getRawIndex(idx);
  28276. var name = this._nameList[rawIndex];
  28277. if (name == null && this._nameDimIdx != null) {
  28278. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28279. }
  28280. if (name == null) {
  28281. name = '';
  28282. }
  28283. return name;
  28284. };
  28285. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28286. var ordinal = this._store.get(dimIdx, idx);
  28287. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28288. if (ordinalMeta) {
  28289. return ordinalMeta.categories[ordinal];
  28290. }
  28291. return ordinal;
  28292. };
  28293. /**
  28294. * @return Never null/undefined. `number` will be converted to string. Becuase:
  28295. * In all cases having encountered at present, id is used in making diff comparison, which
  28296. * are usually based on hash map. We can keep the rule that the internal id are always string
  28297. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28298. */
  28299. SeriesData.prototype.getId = function (idx) {
  28300. return getId(this, this.getRawIndex(idx));
  28301. };
  28302. SeriesData.prototype.count = function () {
  28303. return this._store.count();
  28304. };
  28305. /**
  28306. * Get value. Return NaN if idx is out of range.
  28307. *
  28308. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28309. */
  28310. SeriesData.prototype.get = function (dim, idx) {
  28311. var store = this._store;
  28312. var dimInfo = this._dimInfos[dim];
  28313. if (dimInfo) {
  28314. return store.get(dimInfo.storeDimIndex, idx);
  28315. }
  28316. };
  28317. /**
  28318. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28319. */
  28320. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28321. var store = this._store;
  28322. var dimInfo = this._dimInfos[dim];
  28323. if (dimInfo) {
  28324. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28325. }
  28326. };
  28327. SeriesData.prototype.getIndices = function () {
  28328. return this._store.getIndices();
  28329. };
  28330. SeriesData.prototype.getDataExtent = function (dim) {
  28331. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28332. };
  28333. SeriesData.prototype.getSum = function (dim) {
  28334. return this._store.getSum(this._getStoreDimIndex(dim));
  28335. };
  28336. SeriesData.prototype.getMedian = function (dim) {
  28337. return this._store.getMedian(this._getStoreDimIndex(dim));
  28338. };
  28339. SeriesData.prototype.getValues = function (dimensions, idx) {
  28340. var _this = this;
  28341. var store = this._store;
  28342. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28343. return _this._getStoreDimIndex(dim);
  28344. }), idx) : store.getValues(dimensions);
  28345. };
  28346. /**
  28347. * If value is NaN. Inlcuding '-'
  28348. * Only check the coord dimensions.
  28349. */
  28350. SeriesData.prototype.hasValue = function (idx) {
  28351. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28352. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28353. // Ordinal type originally can be string or number.
  28354. // But when an ordinal type is used on coord, it can
  28355. // not be string but only number. So we can also use isNaN.
  28356. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28357. return false;
  28358. }
  28359. }
  28360. return true;
  28361. };
  28362. /**
  28363. * Retreive the index with given name
  28364. */
  28365. SeriesData.prototype.indexOfName = function (name) {
  28366. for (var i = 0, len = this._store.count(); i < len; i++) {
  28367. if (this.getName(i) === name) {
  28368. return i;
  28369. }
  28370. }
  28371. return -1;
  28372. };
  28373. SeriesData.prototype.getRawIndex = function (idx) {
  28374. return this._store.getRawIndex(idx);
  28375. };
  28376. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28377. return this._store.indexOfRawIndex(rawIndex);
  28378. };
  28379. /**
  28380. * Only support the dimension which inverted index created.
  28381. * Do not support other cases until required.
  28382. * @param dim concrete dim
  28383. * @param value ordinal index
  28384. * @return rawIndex
  28385. */
  28386. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28387. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28388. if ("development" !== 'production') {
  28389. if (!invertedIndices) {
  28390. throw new Error('Do not supported yet');
  28391. }
  28392. }
  28393. var rawIndex = invertedIndices[value];
  28394. if (rawIndex == null || isNaN(rawIndex)) {
  28395. return INDEX_NOT_FOUND;
  28396. }
  28397. return rawIndex;
  28398. };
  28399. /**
  28400. * Retreive the index of nearest value
  28401. * @param dim
  28402. * @param value
  28403. * @param [maxDistance=Infinity]
  28404. * @return If and only if multiple indices has
  28405. * the same value, they are put to the result.
  28406. */
  28407. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28408. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28409. };
  28410. SeriesData.prototype.each = function (dims, cb, ctx) {
  28411. if (isFunction(dims)) {
  28412. ctx = cb;
  28413. cb = dims;
  28414. dims = [];
  28415. } // ctxCompat just for compat echarts3
  28416. var fCtx = ctx || this;
  28417. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28418. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28419. };
  28420. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28421. if (isFunction(dims)) {
  28422. ctx = cb;
  28423. cb = dims;
  28424. dims = [];
  28425. } // ctxCompat just for compat echarts3
  28426. var fCtx = ctx || this;
  28427. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28428. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28429. return this;
  28430. };
  28431. /**
  28432. * Select data in range. (For optimization of filter)
  28433. * (Manually inline code, support 5 million data filtering in data zoom.)
  28434. */
  28435. SeriesData.prototype.selectRange = function (range) {
  28436. var _this = this;
  28437. var innerRange = {};
  28438. var dims = keys(range);
  28439. each(dims, function (dim) {
  28440. var dimIdx = _this._getStoreDimIndex(dim);
  28441. innerRange[dimIdx] = range[dim];
  28442. });
  28443. this._store = this._store.selectRange(innerRange);
  28444. return this;
  28445. };
  28446. /* eslint-enable max-len */
  28447. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28448. if (isFunction(dims)) {
  28449. ctx = cb;
  28450. cb = dims;
  28451. dims = [];
  28452. } // ctxCompat just for compat echarts3
  28453. ctx = ctx || this;
  28454. var result = [];
  28455. this.each(dims, function () {
  28456. result.push(cb && cb.apply(this, arguments));
  28457. }, ctx);
  28458. return result;
  28459. };
  28460. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28461. var fCtx = ctx || ctxCompat || this;
  28462. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28463. var list = cloneListForMapAndSample(this);
  28464. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28465. return list;
  28466. };
  28467. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28468. var _this = this; // ctxCompat just for compat echarts3
  28469. var fCtx = ctx || ctxCompat || this;
  28470. if ("development" !== 'production') {
  28471. each(normalizeDimensions(dims), function (dim) {
  28472. var dimInfo = _this.getDimensionInfo(dim);
  28473. if (!dimInfo.isCalculationCoord) {
  28474. console.error('Danger: only stack dimension can be modified');
  28475. }
  28476. });
  28477. }
  28478. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  28479. // it still cost lots of memory, becuase `_store.dimensions` are not shared.
  28480. // We should consider there probably be shallow clone happen in each sereis
  28481. // in consequent filter/map.
  28482. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28483. };
  28484. /**
  28485. * Large data down sampling on given dimension
  28486. * @param sampleIndex Sample index for name and id
  28487. */
  28488. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28489. var list = cloneListForMapAndSample(this);
  28490. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28491. return list;
  28492. };
  28493. /**
  28494. * Large data down sampling using largest-triangle-three-buckets
  28495. * @param {string} valueDimension
  28496. * @param {number} targetCount
  28497. */
  28498. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28499. var list = cloneListForMapAndSample(this);
  28500. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28501. return list;
  28502. };
  28503. SeriesData.prototype.getRawDataItem = function (idx) {
  28504. return this._store.getRawDataItem(idx);
  28505. };
  28506. /**
  28507. * Get model of one data item.
  28508. */
  28509. // TODO: Type of data item
  28510. SeriesData.prototype.getItemModel = function (idx) {
  28511. var hostModel = this.hostModel;
  28512. var dataItem = this.getRawDataItem(idx);
  28513. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28514. };
  28515. /**
  28516. * Create a data differ
  28517. */
  28518. SeriesData.prototype.diff = function (otherList) {
  28519. var thisList = this;
  28520. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28521. return getId(otherList, idx);
  28522. }, function (idx) {
  28523. return getId(thisList, idx);
  28524. });
  28525. };
  28526. /**
  28527. * Get visual property.
  28528. */
  28529. SeriesData.prototype.getVisual = function (key) {
  28530. var visual = this._visual;
  28531. return visual && visual[key];
  28532. };
  28533. SeriesData.prototype.setVisual = function (kvObj, val) {
  28534. this._visual = this._visual || {};
  28535. if (isObject$2(kvObj)) {
  28536. extend(this._visual, kvObj);
  28537. } else {
  28538. this._visual[kvObj] = val;
  28539. }
  28540. };
  28541. /**
  28542. * Get visual property of single data item
  28543. */
  28544. // eslint-disable-next-line
  28545. SeriesData.prototype.getItemVisual = function (idx, key) {
  28546. var itemVisual = this._itemVisuals[idx];
  28547. var val = itemVisual && itemVisual[key];
  28548. if (val == null) {
  28549. // Use global visual property
  28550. return this.getVisual(key);
  28551. }
  28552. return val;
  28553. };
  28554. /**
  28555. * If exists visual property of single data item
  28556. */
  28557. SeriesData.prototype.hasItemVisual = function () {
  28558. return this._itemVisuals.length > 0;
  28559. };
  28560. /**
  28561. * Make sure itemVisual property is unique
  28562. */
  28563. // TODO: use key to save visual to reduce memory.
  28564. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  28565. var itemVisuals = this._itemVisuals;
  28566. var itemVisual = itemVisuals[idx];
  28567. if (!itemVisual) {
  28568. itemVisual = itemVisuals[idx] = {};
  28569. }
  28570. var val = itemVisual[key];
  28571. if (val == null) {
  28572. val = this.getVisual(key); // TODO Performance?
  28573. if (isArray(val)) {
  28574. val = val.slice();
  28575. } else if (isObject$2(val)) {
  28576. val = extend({}, val);
  28577. }
  28578. itemVisual[key] = val;
  28579. }
  28580. return val;
  28581. }; // eslint-disable-next-line
  28582. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  28583. var itemVisual = this._itemVisuals[idx] || {};
  28584. this._itemVisuals[idx] = itemVisual;
  28585. if (isObject$2(key)) {
  28586. extend(itemVisual, key);
  28587. } else {
  28588. itemVisual[key] = value;
  28589. }
  28590. };
  28591. /**
  28592. * Clear itemVisuals and list visual.
  28593. */
  28594. SeriesData.prototype.clearAllVisual = function () {
  28595. this._visual = {};
  28596. this._itemVisuals = [];
  28597. };
  28598. SeriesData.prototype.setLayout = function (key, val) {
  28599. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  28600. };
  28601. /**
  28602. * Get layout property.
  28603. */
  28604. SeriesData.prototype.getLayout = function (key) {
  28605. return this._layout[key];
  28606. };
  28607. /**
  28608. * Get layout of single data item
  28609. */
  28610. SeriesData.prototype.getItemLayout = function (idx) {
  28611. return this._itemLayouts[idx];
  28612. };
  28613. /**
  28614. * Set layout of single data item
  28615. */
  28616. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  28617. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  28618. };
  28619. /**
  28620. * Clear all layout of single data item
  28621. */
  28622. SeriesData.prototype.clearItemLayouts = function () {
  28623. this._itemLayouts.length = 0;
  28624. };
  28625. /**
  28626. * Set graphic element relative to data. It can be set as null
  28627. */
  28628. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  28629. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  28630. setCommonECData(seriesIndex, this.dataType, idx, el);
  28631. this._graphicEls[idx] = el;
  28632. };
  28633. SeriesData.prototype.getItemGraphicEl = function (idx) {
  28634. return this._graphicEls[idx];
  28635. };
  28636. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  28637. each(this._graphicEls, function (el, idx) {
  28638. if (el) {
  28639. cb && cb.call(context, el, idx);
  28640. }
  28641. });
  28642. };
  28643. /**
  28644. * Shallow clone a new list except visual and layout properties, and graph elements.
  28645. * New list only change the indices.
  28646. */
  28647. SeriesData.prototype.cloneShallow = function (list) {
  28648. if (!list) {
  28649. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  28650. }
  28651. transferProperties(list, this);
  28652. list._store = this._store;
  28653. return list;
  28654. };
  28655. /**
  28656. * Wrap some method to add more feature
  28657. */
  28658. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  28659. var originalMethod = this[methodName];
  28660. if (!isFunction(originalMethod)) {
  28661. return;
  28662. }
  28663. this.__wrappedMethods = this.__wrappedMethods || [];
  28664. this.__wrappedMethods.push(methodName);
  28665. this[methodName] = function () {
  28666. var res = originalMethod.apply(this, arguments);
  28667. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28668. };
  28669. }; // ----------------------------------------------------------
  28670. // A work around for internal method visiting private member.
  28671. // ----------------------------------------------------------
  28672. SeriesData.internalField = function () {
  28673. prepareInvertedIndex = function (data) {
  28674. var invertedIndicesMap = data._invertedIndicesMap;
  28675. each(invertedIndicesMap, function (invertedIndices, dim) {
  28676. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  28677. var ordinalMeta = dimInfo.ordinalMeta;
  28678. var store = data._store;
  28679. if (ordinalMeta) {
  28680. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  28681. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  28682. for (var i = 0; i < invertedIndices.length; i++) {
  28683. invertedIndices[i] = INDEX_NOT_FOUND;
  28684. }
  28685. for (var i = 0; i < store.count(); i++) {
  28686. // Only support the case that all values are distinct.
  28687. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  28688. }
  28689. }
  28690. });
  28691. };
  28692. getIdNameFromStore = function (data, dimIdx, idx) {
  28693. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  28694. };
  28695. /**
  28696. * @see the comment of `List['getId']`.
  28697. */
  28698. getId = function (data, rawIndex) {
  28699. var id = data._idList[rawIndex];
  28700. if (id == null && data._idDimIdx != null) {
  28701. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  28702. }
  28703. if (id == null) {
  28704. id = ID_PREFIX + rawIndex;
  28705. }
  28706. return id;
  28707. };
  28708. normalizeDimensions = function (dimensions) {
  28709. if (!isArray(dimensions)) {
  28710. dimensions = dimensions != null ? [dimensions] : [];
  28711. }
  28712. return dimensions;
  28713. };
  28714. /**
  28715. * Data in excludeDimensions is copied, otherwise transfered.
  28716. */
  28717. cloneListForMapAndSample = function (original) {
  28718. 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
  28719. transferProperties(list, original);
  28720. return list;
  28721. };
  28722. transferProperties = function (target, source) {
  28723. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  28724. if (source.hasOwnProperty(propName)) {
  28725. target[propName] = source[propName];
  28726. }
  28727. });
  28728. target.__wrappedMethods = source.__wrappedMethods;
  28729. each(CLONE_PROPERTIES, function (propName) {
  28730. target[propName] = clone(source[propName]);
  28731. });
  28732. target._calculationInfo = extend({}, source._calculationInfo);
  28733. };
  28734. makeIdFromName = function (data, idx) {
  28735. var nameList = data._nameList;
  28736. var idList = data._idList;
  28737. var nameDimIdx = data._nameDimIdx;
  28738. var idDimIdx = data._idDimIdx;
  28739. var name = nameList[idx];
  28740. var id = idList[idx];
  28741. if (name == null && nameDimIdx != null) {
  28742. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  28743. }
  28744. if (id == null && idDimIdx != null) {
  28745. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  28746. }
  28747. if (id == null && name != null) {
  28748. var nameRepeatCount = data._nameRepeatCount;
  28749. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  28750. id = name;
  28751. if (nmCnt > 1) {
  28752. id += '__ec__' + nmCnt;
  28753. }
  28754. idList[idx] = id;
  28755. }
  28756. };
  28757. }();
  28758. return SeriesData;
  28759. }();
  28760. /**
  28761. * For outside usage compat (like echarts-gl are using it).
  28762. */
  28763. function createDimensions(source, opt) {
  28764. return prepareSeriesDataSchema(source, opt).dimensions;
  28765. }
  28766. /**
  28767. * This method builds the relationship between:
  28768. * + "what the coord sys or series requires (see `coordDimensions`)",
  28769. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  28770. * + "what the data source provids (see `source`)".
  28771. *
  28772. * Some guess strategy will be adapted if user does not define something.
  28773. * If no 'value' dimension specified, the first no-named dimension will be
  28774. * named as 'value'.
  28775. *
  28776. * @return The results are always sorted by `storeDimIndex` asc.
  28777. */
  28778. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  28779. source, opt) {
  28780. if (!isSourceInstance(source)) {
  28781. source = createSourceFromSeriesDataOption(source);
  28782. }
  28783. opt = opt || {};
  28784. var sysDims = opt.coordDimensions || [];
  28785. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  28786. var coordDimNameMap = createHashMap();
  28787. var resultList = [];
  28788. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unsed dimensions if sharing a high dimension datastore
  28789. // 30 is an experience value.
  28790. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  28791. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  28792. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  28793. var encodeDef = opt.encodeDefine;
  28794. if (!encodeDef && opt.encodeDefaulter) {
  28795. encodeDef = opt.encodeDefaulter(source, dimCount);
  28796. }
  28797. var encodeDefMap = createHashMap(encodeDef);
  28798. var indicesMap = new CtorInt32Array(dimCount);
  28799. for (var i = 0; i < indicesMap.length; i++) {
  28800. indicesMap[i] = -1;
  28801. }
  28802. function getResultItem(dimIdx) {
  28803. var idx = indicesMap[dimIdx];
  28804. if (idx < 0) {
  28805. var dimDefItemRaw = dimsDef[dimIdx];
  28806. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  28807. name: dimDefItemRaw
  28808. };
  28809. var resultItem = new SeriesDimensionDefine();
  28810. var userDimName = dimDefItem.name;
  28811. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  28812. // Only if `series.dimensions` is defined in option
  28813. // displayName, will be set, and dimension will be diplayed vertically in
  28814. // tooltip by default.
  28815. resultItem.name = resultItem.displayName = userDimName;
  28816. }
  28817. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28818. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28819. var newIdx = resultList.length;
  28820. indicesMap[dimIdx] = newIdx;
  28821. resultItem.storeDimIndex = dimIdx;
  28822. resultList.push(resultItem);
  28823. return resultItem;
  28824. }
  28825. return resultList[idx];
  28826. }
  28827. if (!omitUnusedDimensions) {
  28828. for (var i = 0; i < dimCount; i++) {
  28829. getResultItem(i);
  28830. }
  28831. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  28832. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  28833. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28834. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28835. // this case.
  28836. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28837. encodeDefMap.set(coordDim, false);
  28838. return;
  28839. }
  28840. var validDataDims = encodeDefMap.set(coordDim, []);
  28841. each(dataDims, function (resultDimIdxOrName, idx) {
  28842. // The input resultDimIdx can be dim name or index.
  28843. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  28844. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28845. validDataDims[idx] = resultDimIdx;
  28846. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  28847. }
  28848. });
  28849. }); // Apply templetes and default order from `sysDims`.
  28850. var availDimIdx = 0;
  28851. each(sysDims, function (sysDimItemRaw) {
  28852. var coordDim;
  28853. var sysDimItemDimsDef;
  28854. var sysDimItemOtherDims;
  28855. var sysDimItem;
  28856. if (isString(sysDimItemRaw)) {
  28857. coordDim = sysDimItemRaw;
  28858. sysDimItem = {};
  28859. } else {
  28860. sysDimItem = sysDimItemRaw;
  28861. coordDim = sysDimItem.name;
  28862. var ordinalMeta = sysDimItem.ordinalMeta;
  28863. sysDimItem.ordinalMeta = null;
  28864. sysDimItem = extend({}, sysDimItem);
  28865. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  28866. sysDimItemDimsDef = sysDimItem.dimsDef;
  28867. sysDimItemOtherDims = sysDimItem.otherDims;
  28868. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28869. }
  28870. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  28871. if (dataDims === false) {
  28872. return;
  28873. }
  28874. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  28875. if (!dataDims.length) {
  28876. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28877. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  28878. availDimIdx++;
  28879. }
  28880. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  28881. }
  28882. } // Apply templates.
  28883. each(dataDims, function (resultDimIdx, coordDimIndex) {
  28884. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  28885. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  28886. resultItem.type = sysDimItem.type;
  28887. }
  28888. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28889. if (resultItem.name == null && sysDimItemDimsDef) {
  28890. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28891. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  28892. name: sysDimItemDimsDefItem
  28893. });
  28894. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28895. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28896. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28897. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28898. });
  28899. });
  28900. function applyDim(resultItem, coordDim, coordDimIndex) {
  28901. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28902. resultItem.otherDims[coordDim] = coordDimIndex;
  28903. } else {
  28904. resultItem.coordDim = coordDim;
  28905. resultItem.coordDimIndex = coordDimIndex;
  28906. coordDimNameMap.set(coordDim, true);
  28907. }
  28908. } // Make sure the first extra dim is 'value'.
  28909. var generateCoord = opt.generateCoord;
  28910. var generateCoordCount = opt.generateCoordCount;
  28911. var fromZero = generateCoordCount != null;
  28912. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  28913. var extra = generateCoord || 'value';
  28914. function ifNoNameFillWithCoordName(resultItem) {
  28915. if (resultItem.name == null) {
  28916. // Duplication will be removed in the next step.
  28917. resultItem.name = resultItem.coordDim;
  28918. }
  28919. } // Set dim `name` and other `coordDim` and other props.
  28920. if (!omitUnusedDimensions) {
  28921. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28922. var resultItem = getResultItem(resultDimIdx);
  28923. var coordDim = resultItem.coordDim;
  28924. if (coordDim == null) {
  28925. // TODO no need to generate coordDim for isExtraCoord?
  28926. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  28927. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  28928. if (!generateCoord || generateCoordCount <= 0) {
  28929. resultItem.isExtraCoord = true;
  28930. }
  28931. generateCoordCount--;
  28932. }
  28933. ifNoNameFillWithCoordName(resultItem);
  28934. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  28935. // {
  28936. // dataset: {source: [
  28937. // ['2001', 123],
  28938. // ['2002', 456],
  28939. // ...
  28940. // ['The others', 987],
  28941. // ]},
  28942. // series: {type: 'pie'}
  28943. // }
  28944. // The first colum should better be treated as a "ordinal" although it
  28945. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28946. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  28947. resultItem.type = 'ordinal';
  28948. }
  28949. }
  28950. } else {
  28951. each(resultList, function (resultItem) {
  28952. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  28953. ifNoNameFillWithCoordName(resultItem);
  28954. }); // Sort dimensions: there are some rule that use the last dim as label,
  28955. // and for some latter travel process easier.
  28956. resultList.sort(function (item0, item1) {
  28957. return item0.storeDimIndex - item1.storeDimIndex;
  28958. });
  28959. }
  28960. removeDuplication(resultList);
  28961. return new SeriesDataSchema({
  28962. source: source,
  28963. dimensions: resultList,
  28964. fullDimensionCount: dimCount,
  28965. dimensionOmitted: omitUnusedDimensions
  28966. });
  28967. }
  28968. function removeDuplication(result) {
  28969. var duplicationMap = createHashMap();
  28970. for (var i = 0; i < result.length; i++) {
  28971. var dim = result[i];
  28972. var dimOriginalName = dim.name;
  28973. var count = duplicationMap.get(dimOriginalName) || 0;
  28974. if (count > 0) {
  28975. // Starts from 0.
  28976. dim.name = dimOriginalName + (count - 1);
  28977. }
  28978. count++;
  28979. duplicationMap.set(dimOriginalName, count);
  28980. }
  28981. } // ??? TODO
  28982. // Originally detect dimCount by data[0]. Should we
  28983. // optimize it to only by sysDims and dimensions and encode.
  28984. // So only necessary dims will be initialized.
  28985. // But
  28986. // (1) custom series should be considered. where other dims
  28987. // may be visited.
  28988. // (2) sometimes user need to calcualte bubble size or use visualMap
  28989. // on other dimensions besides coordSys needed.
  28990. // So, dims that is not used by system, should be shared in data store?
  28991. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28992. // Note that the result dimCount should not small than columns count
  28993. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28994. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  28995. each(sysDims, function (sysDimItem) {
  28996. var sysDimItemDimsDef;
  28997. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  28998. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  28999. }
  29000. });
  29001. return dimCount;
  29002. }
  29003. function genCoordDimName(name, map, fromZero) {
  29004. var mapData = map.data;
  29005. if (fromZero || mapData.hasOwnProperty(name)) {
  29006. var i = 0;
  29007. while (mapData.hasOwnProperty(name + i)) {
  29008. i++;
  29009. }
  29010. name += i;
  29011. }
  29012. map.set(name, true);
  29013. return name;
  29014. }
  29015. /**
  29016. * @class
  29017. * For example:
  29018. * {
  29019. * coordSysName: 'cartesian2d',
  29020. * coordSysDims: ['x', 'y', ...],
  29021. * axisMap: HashMap({
  29022. * x: xAxisModel,
  29023. * y: yAxisModel
  29024. * }),
  29025. * categoryAxisMap: HashMap({
  29026. * x: xAxisModel,
  29027. * y: undefined
  29028. * }),
  29029. * // The index of the first category axis in `coordSysDims`.
  29030. * // `null/undefined` means no category axis exists.
  29031. * firstCategoryDimIndex: 1,
  29032. * // To replace user specified encode.
  29033. * }
  29034. */
  29035. var CoordSysInfo =
  29036. /** @class */
  29037. function () {
  29038. function CoordSysInfo(coordSysName) {
  29039. this.coordSysDims = [];
  29040. this.axisMap = createHashMap();
  29041. this.categoryAxisMap = createHashMap();
  29042. this.coordSysName = coordSysName;
  29043. }
  29044. return CoordSysInfo;
  29045. }();
  29046. function getCoordSysInfoBySeries(seriesModel) {
  29047. var coordSysName = seriesModel.get('coordinateSystem');
  29048. var result = new CoordSysInfo(coordSysName);
  29049. var fetch = fetchers[coordSysName];
  29050. if (fetch) {
  29051. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29052. return result;
  29053. }
  29054. }
  29055. var fetchers = {
  29056. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29057. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29058. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29059. if ("development" !== 'production') {
  29060. if (!xAxisModel) {
  29061. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29062. }
  29063. if (!yAxisModel) {
  29064. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29065. }
  29066. }
  29067. result.coordSysDims = ['x', 'y'];
  29068. axisMap.set('x', xAxisModel);
  29069. axisMap.set('y', yAxisModel);
  29070. if (isCategory(xAxisModel)) {
  29071. categoryAxisMap.set('x', xAxisModel);
  29072. result.firstCategoryDimIndex = 0;
  29073. }
  29074. if (isCategory(yAxisModel)) {
  29075. categoryAxisMap.set('y', yAxisModel);
  29076. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29077. }
  29078. },
  29079. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29080. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29081. if ("development" !== 'production') {
  29082. if (!singleAxisModel) {
  29083. throw new Error('singleAxis should be specified.');
  29084. }
  29085. }
  29086. result.coordSysDims = ['single'];
  29087. axisMap.set('single', singleAxisModel);
  29088. if (isCategory(singleAxisModel)) {
  29089. categoryAxisMap.set('single', singleAxisModel);
  29090. result.firstCategoryDimIndex = 0;
  29091. }
  29092. },
  29093. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29094. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29095. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29096. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29097. if ("development" !== 'production') {
  29098. if (!angleAxisModel) {
  29099. throw new Error('angleAxis option not found');
  29100. }
  29101. if (!radiusAxisModel) {
  29102. throw new Error('radiusAxis option not found');
  29103. }
  29104. }
  29105. result.coordSysDims = ['radius', 'angle'];
  29106. axisMap.set('radius', radiusAxisModel);
  29107. axisMap.set('angle', angleAxisModel);
  29108. if (isCategory(radiusAxisModel)) {
  29109. categoryAxisMap.set('radius', radiusAxisModel);
  29110. result.firstCategoryDimIndex = 0;
  29111. }
  29112. if (isCategory(angleAxisModel)) {
  29113. categoryAxisMap.set('angle', angleAxisModel);
  29114. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29115. }
  29116. },
  29117. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29118. result.coordSysDims = ['lng', 'lat'];
  29119. },
  29120. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29121. var ecModel = seriesModel.ecModel;
  29122. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29123. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29124. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29125. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29126. var axisDim = coordSysDims[index];
  29127. axisMap.set(axisDim, axisModel);
  29128. if (isCategory(axisModel)) {
  29129. categoryAxisMap.set(axisDim, axisModel);
  29130. if (result.firstCategoryDimIndex == null) {
  29131. result.firstCategoryDimIndex = index;
  29132. }
  29133. }
  29134. });
  29135. }
  29136. };
  29137. function isCategory(axisModel) {
  29138. return axisModel.get('type') === 'category';
  29139. }
  29140. /**
  29141. * Note that it is too complicated to support 3d stack by value
  29142. * (have to create two-dimension inverted index), so in 3d case
  29143. * we just support that stacked by index.
  29144. *
  29145. * @param seriesModel
  29146. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29147. * The input will be modified.
  29148. * @param opt
  29149. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29150. * @param opt.byIndex=false
  29151. * @return calculationInfo
  29152. * {
  29153. * stackedDimension: string
  29154. * stackedByDimension: string
  29155. * isStackedByIndex: boolean
  29156. * stackedOverDimension: string
  29157. * stackResultDimension: string
  29158. * }
  29159. */
  29160. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29161. opt = opt || {};
  29162. var byIndex = opt.byIndex;
  29163. var stackedCoordDimension = opt.stackedCoordDimension;
  29164. var dimensionDefineList;
  29165. var schema;
  29166. var store;
  29167. if (isLegacyDimensionsInput(dimensionsInput)) {
  29168. dimensionDefineList = dimensionsInput;
  29169. } else {
  29170. schema = dimensionsInput.schema;
  29171. dimensionDefineList = schema.dimensions;
  29172. store = dimensionsInput.store;
  29173. } // Compatibal: when `stack` is set as '', do not stack.
  29174. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29175. var stackedByDimInfo;
  29176. var stackedDimInfo;
  29177. var stackResultDimension;
  29178. var stackedOverDimension;
  29179. each(dimensionDefineList, function (dimensionInfo, index) {
  29180. if (isString(dimensionInfo)) {
  29181. dimensionDefineList[index] = dimensionInfo = {
  29182. name: dimensionInfo
  29183. };
  29184. }
  29185. if (mayStack && !dimensionInfo.isExtraCoord) {
  29186. // Find the first ordinal dimension as the stackedByDimInfo.
  29187. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29188. stackedByDimInfo = dimensionInfo;
  29189. } // Find the first stackable dimension as the stackedDimInfo.
  29190. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29191. stackedDimInfo = dimensionInfo;
  29192. }
  29193. }
  29194. });
  29195. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29196. // Compatible with previous design, value axis (time axis) only stack by index.
  29197. // It may make sense if the user provides elaborately constructed data.
  29198. byIndex = true;
  29199. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29200. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29201. // might not be a good way.
  29202. if (stackedDimInfo) {
  29203. // Use a weird name that not duplicated with other names.
  29204. // Also need to use seriesModel.id as postfix because different
  29205. // series may share same data store. The stack dimension needs to be distinguished.
  29206. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29207. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  29208. if (stackedByDimInfo) {
  29209. stackedByDimInfo.createInvertedIndices = true;
  29210. }
  29211. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29212. var stackedDimType = stackedDimInfo.type;
  29213. var stackedDimCoordIndex_1 = 0;
  29214. each(dimensionDefineList, function (dimensionInfo) {
  29215. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29216. stackedDimCoordIndex_1++;
  29217. }
  29218. });
  29219. var stackedOverDimensionDefine = {
  29220. name: stackResultDimension,
  29221. coordDim: stackedDimCoordDim_1,
  29222. coordDimIndex: stackedDimCoordIndex_1,
  29223. type: stackedDimType,
  29224. isExtraCoord: true,
  29225. isCalculationCoord: true,
  29226. storeDimIndex: dimensionDefineList.length
  29227. };
  29228. var stackResultDimensionDefine = {
  29229. name: stackedOverDimension,
  29230. // This dimension contains stack base (generally, 0), so do not set it as
  29231. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29232. coordDim: stackedOverDimension,
  29233. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29234. type: stackedDimType,
  29235. isExtraCoord: true,
  29236. isCalculationCoord: true,
  29237. storeDimIndex: dimensionDefineList.length + 1
  29238. };
  29239. if (schema) {
  29240. if (store) {
  29241. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29242. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29243. }
  29244. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29245. schema.appendCalculationDimension(stackResultDimensionDefine);
  29246. } else {
  29247. dimensionDefineList.push(stackedOverDimensionDefine);
  29248. dimensionDefineList.push(stackResultDimensionDefine);
  29249. }
  29250. }
  29251. return {
  29252. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29253. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29254. isStackedByIndex: byIndex,
  29255. stackedOverDimension: stackedOverDimension,
  29256. stackResultDimension: stackResultDimension
  29257. };
  29258. }
  29259. function isLegacyDimensionsInput(dimensionsInput) {
  29260. return !isSeriesDataSchema(dimensionsInput.schema);
  29261. }
  29262. function isDimensionStacked(data, stackedDim) {
  29263. // Each single series only maps to one pair of axis. So we do not need to
  29264. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29265. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29266. }
  29267. function getStackedDimension(data, targetDim) {
  29268. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29269. }
  29270. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29271. var coordSysName = seriesModel.get('coordinateSystem');
  29272. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29273. var coordSysDimDefs;
  29274. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29275. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29276. var dimInfo = {
  29277. name: dim
  29278. };
  29279. var axisModel = coordSysInfo.axisMap.get(dim);
  29280. if (axisModel) {
  29281. var axisType = axisModel.get('type');
  29282. dimInfo.type = getDimensionTypeByAxis(axisType);
  29283. }
  29284. return dimInfo;
  29285. });
  29286. }
  29287. if (!coordSysDimDefs) {
  29288. // Get dimensions from registered coordinate system
  29289. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29290. }
  29291. return coordSysDimDefs;
  29292. }
  29293. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29294. var firstCategoryDimIndex;
  29295. var hasNameEncode;
  29296. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29297. var coordDim = dimInfo.coordDim;
  29298. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29299. if (categoryAxisModel) {
  29300. if (firstCategoryDimIndex == null) {
  29301. firstCategoryDimIndex = dimIndex;
  29302. }
  29303. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29304. if (createInvertedIndices) {
  29305. dimInfo.createInvertedIndices = true;
  29306. }
  29307. }
  29308. if (dimInfo.otherDims.itemName != null) {
  29309. hasNameEncode = true;
  29310. }
  29311. });
  29312. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29313. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29314. }
  29315. return firstCategoryDimIndex;
  29316. }
  29317. /**
  29318. * Caution: there are side effects to `sourceManager` in this method.
  29319. * Should better only be called in `Series['getInitialData']`.
  29320. */
  29321. function createSeriesData(sourceRaw, seriesModel, opt) {
  29322. opt = opt || {};
  29323. var sourceManager = seriesModel.getSourceManager();
  29324. var source;
  29325. var isOriginalSource = false;
  29326. if (sourceRaw) {
  29327. isOriginalSource = true;
  29328. source = createSourceFromSeriesDataOption(sourceRaw);
  29329. } else {
  29330. source = sourceManager.getSource(); // Is series.data. not dataset.
  29331. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29332. }
  29333. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29334. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29335. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29336. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29337. var createDimensionOptions = {
  29338. coordDimensions: coordSysDimDefs,
  29339. generateCoord: opt.generateCoord,
  29340. encodeDefine: seriesModel.getEncode(),
  29341. encodeDefaulter: encodeDefaulter,
  29342. canOmitUnusedDimensions: !isOriginalSource
  29343. };
  29344. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29345. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29346. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29347. var stackCalculationInfo = enableDataStack(seriesModel, {
  29348. schema: schema,
  29349. store: store
  29350. });
  29351. var data = new SeriesData(schema, seriesModel);
  29352. data.setCalculationInfo(stackCalculationInfo);
  29353. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29354. // Use dataIndex as ordinal value in categoryAxis
  29355. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29356. } : null;
  29357. data.hasItemOption = false;
  29358. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  29359. isOriginalSource ? source : store, null, dimValueGetter);
  29360. return data;
  29361. }
  29362. function isNeedCompleteOrdinalData(source) {
  29363. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29364. var sampleItem = firstDataNotNull(source.data || []);
  29365. return !isArray(getDataItemValue(sampleItem));
  29366. }
  29367. }
  29368. function firstDataNotNull(arr) {
  29369. var i = 0;
  29370. while (i < arr.length && arr[i] == null) {
  29371. i++;
  29372. }
  29373. return arr[i];
  29374. }
  29375. var Scale =
  29376. /** @class */
  29377. function () {
  29378. function Scale(setting) {
  29379. this._setting = setting || {};
  29380. this._extent = [Infinity, -Infinity];
  29381. }
  29382. Scale.prototype.getSetting = function (name) {
  29383. return this._setting[name];
  29384. };
  29385. /**
  29386. * Set extent from data
  29387. */
  29388. Scale.prototype.unionExtent = function (other) {
  29389. var extent = this._extent;
  29390. other[0] < extent[0] && (extent[0] = other[0]);
  29391. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29392. // this.setExtent(extent[0], extent[1]);
  29393. };
  29394. /**
  29395. * Set extent from data
  29396. */
  29397. Scale.prototype.unionExtentFromData = function (data, dim) {
  29398. this.unionExtent(data.getApproximateExtent(dim));
  29399. };
  29400. /**
  29401. * Get extent
  29402. *
  29403. * Extent is always in increase order.
  29404. */
  29405. Scale.prototype.getExtent = function () {
  29406. return this._extent.slice();
  29407. };
  29408. /**
  29409. * Set extent
  29410. */
  29411. Scale.prototype.setExtent = function (start, end) {
  29412. var thisExtent = this._extent;
  29413. if (!isNaN(start)) {
  29414. thisExtent[0] = start;
  29415. }
  29416. if (!isNaN(end)) {
  29417. thisExtent[1] = end;
  29418. }
  29419. };
  29420. /**
  29421. * If value is in extent range
  29422. */
  29423. Scale.prototype.isInExtentRange = function (value) {
  29424. return this._extent[0] <= value && this._extent[1] >= value;
  29425. };
  29426. /**
  29427. * When axis extent depends on data and no data exists,
  29428. * axis ticks should not be drawn, which is named 'blank'.
  29429. */
  29430. Scale.prototype.isBlank = function () {
  29431. return this._isBlank;
  29432. };
  29433. /**
  29434. * When axis extent depends on data and no data exists,
  29435. * axis ticks should not be drawn, which is named 'blank'.
  29436. */
  29437. Scale.prototype.setBlank = function (isBlank) {
  29438. this._isBlank = isBlank;
  29439. };
  29440. return Scale;
  29441. }();
  29442. enableClassManagement(Scale);
  29443. var uidBase = 0;
  29444. var OrdinalMeta =
  29445. /** @class */
  29446. function () {
  29447. function OrdinalMeta(opt) {
  29448. this.categories = opt.categories || [];
  29449. this._needCollect = opt.needCollect;
  29450. this._deduplication = opt.deduplication;
  29451. this.uid = ++uidBase;
  29452. }
  29453. OrdinalMeta.createByAxisModel = function (axisModel) {
  29454. var option = axisModel.option;
  29455. var data = option.data;
  29456. var categories = data && map(data, getName);
  29457. return new OrdinalMeta({
  29458. categories: categories,
  29459. needCollect: !categories,
  29460. // deduplication is default in axis.
  29461. deduplication: option.dedplication !== false
  29462. });
  29463. };
  29464. OrdinalMeta.prototype.getOrdinal = function (category) {
  29465. // @ts-ignore
  29466. return this._getOrCreateMap().get(category);
  29467. };
  29468. /**
  29469. * @return The ordinal. If not found, return NaN.
  29470. */
  29471. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29472. var index;
  29473. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29474. // This feature is only supported when !needCollect, because we should
  29475. // consider a common case: a value is 2017, which is a number but is
  29476. // expected to be tread as a category. This case usually happen in dataset,
  29477. // where it happent to be no need of the index feature.
  29478. if (!isString(category) && !needCollect) {
  29479. return category;
  29480. } // Optimize for the scenario:
  29481. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29482. // data has been ensured not duplicate and is large data.
  29483. // Notice, if a dataset dimension provide categroies, usually echarts
  29484. // should remove duplication except user tell echarts dont do that
  29485. // (set axis.deduplication = false), because echarts do not know whether
  29486. // the values in the category dimension has duplication (consider the
  29487. // parallel-aqi example)
  29488. if (needCollect && !this._deduplication) {
  29489. index = this.categories.length;
  29490. this.categories[index] = category;
  29491. return index;
  29492. }
  29493. var map = this._getOrCreateMap(); // @ts-ignore
  29494. index = map.get(category);
  29495. if (index == null) {
  29496. if (needCollect) {
  29497. index = this.categories.length;
  29498. this.categories[index] = category; // @ts-ignore
  29499. map.set(category, index);
  29500. } else {
  29501. index = NaN;
  29502. }
  29503. }
  29504. return index;
  29505. }; // Consider big data, do not create map until needed.
  29506. OrdinalMeta.prototype._getOrCreateMap = function () {
  29507. return this._map || (this._map = createHashMap(this.categories));
  29508. };
  29509. return OrdinalMeta;
  29510. }();
  29511. function getName(obj) {
  29512. if (isObject(obj) && obj.value != null) {
  29513. return obj.value;
  29514. } else {
  29515. return obj + '';
  29516. }
  29517. }
  29518. function isValueNice(val) {
  29519. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29520. var f = Math.abs(val / exp10);
  29521. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29522. }
  29523. function isIntervalOrLogScale(scale) {
  29524. return scale.type === 'interval' || scale.type === 'log';
  29525. }
  29526. /**
  29527. * @param extent Both extent[0] and extent[1] should be valid number.
  29528. * Should be extent[0] < extent[1].
  29529. * @param splitNumber splitNumber should be >= 1.
  29530. */
  29531. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29532. var result = {};
  29533. var span = extent[1] - extent[0];
  29534. var interval = result.interval = nice(span / splitNumber, true);
  29535. if (minInterval != null && interval < minInterval) {
  29536. interval = result.interval = minInterval;
  29537. }
  29538. if (maxInterval != null && interval > maxInterval) {
  29539. interval = result.interval = maxInterval;
  29540. } // Tow more digital for tick.
  29541. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29542. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29543. fixExtent(niceTickExtent, extent);
  29544. return result;
  29545. }
  29546. function increaseInterval(interval) {
  29547. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  29548. var f = interval / exp10;
  29549. if (!f) {
  29550. f = 1;
  29551. } else if (f === 2) {
  29552. f = 3;
  29553. } else if (f === 3) {
  29554. f = 5;
  29555. } else {
  29556. // f is 1 or 5
  29557. f *= 2;
  29558. }
  29559. return round(f * exp10);
  29560. }
  29561. /**
  29562. * @return interval precision
  29563. */
  29564. function getIntervalPrecision(interval) {
  29565. // Tow more digital for tick.
  29566. return getPrecision(interval) + 2;
  29567. }
  29568. function clamp(niceTickExtent, idx, extent) {
  29569. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29570. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29571. function fixExtent(niceTickExtent, extent) {
  29572. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29573. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29574. clamp(niceTickExtent, 0, extent);
  29575. clamp(niceTickExtent, 1, extent);
  29576. if (niceTickExtent[0] > niceTickExtent[1]) {
  29577. niceTickExtent[0] = niceTickExtent[1];
  29578. }
  29579. }
  29580. function contain$1(val, extent) {
  29581. return val >= extent[0] && val <= extent[1];
  29582. }
  29583. function normalize$1(val, extent) {
  29584. if (extent[1] === extent[0]) {
  29585. return 0.5;
  29586. }
  29587. return (val - extent[0]) / (extent[1] - extent[0]);
  29588. }
  29589. function scale$2(val, extent) {
  29590. return val * (extent[1] - extent[0]) + extent[0];
  29591. }
  29592. var OrdinalScale =
  29593. /** @class */
  29594. function (_super) {
  29595. __extends(OrdinalScale, _super);
  29596. function OrdinalScale(setting) {
  29597. var _this = _super.call(this, setting) || this;
  29598. _this.type = 'ordinal';
  29599. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  29600. // import approach to get OrdinalMeta class.
  29601. if (!ordinalMeta) {
  29602. ordinalMeta = new OrdinalMeta({});
  29603. }
  29604. if (isArray(ordinalMeta)) {
  29605. ordinalMeta = new OrdinalMeta({
  29606. categories: map(ordinalMeta, function (item) {
  29607. return isObject(item) ? item.value : item;
  29608. })
  29609. });
  29610. }
  29611. _this._ordinalMeta = ordinalMeta;
  29612. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  29613. return _this;
  29614. }
  29615. OrdinalScale.prototype.parse = function (val) {
  29616. // Caution: Math.round(null) will return `0` rather than `NaN`
  29617. if (val == null) {
  29618. return NaN;
  29619. }
  29620. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  29621. : Math.round(val);
  29622. };
  29623. OrdinalScale.prototype.contain = function (rank) {
  29624. rank = this.parse(rank);
  29625. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  29626. };
  29627. /**
  29628. * Normalize given rank or name to linear [0, 1]
  29629. * @param val raw ordinal number.
  29630. * @return normalized value in [0, 1].
  29631. */
  29632. OrdinalScale.prototype.normalize = function (val) {
  29633. val = this._getTickNumber(this.parse(val));
  29634. return normalize$1(val, this._extent);
  29635. };
  29636. /**
  29637. * @param val normalized value in [0, 1].
  29638. * @return raw ordinal number.
  29639. */
  29640. OrdinalScale.prototype.scale = function (val) {
  29641. val = Math.round(scale$2(val, this._extent));
  29642. return this.getRawOrdinalNumber(val);
  29643. };
  29644. OrdinalScale.prototype.getTicks = function () {
  29645. var ticks = [];
  29646. var extent = this._extent;
  29647. var rank = extent[0];
  29648. while (rank <= extent[1]) {
  29649. ticks.push({
  29650. value: rank
  29651. });
  29652. rank++;
  29653. }
  29654. return ticks;
  29655. };
  29656. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  29657. // Not support.
  29658. return;
  29659. };
  29660. /**
  29661. * @see `Ordinal['_ordinalNumbersByTick']`
  29662. */
  29663. OrdinalScale.prototype.setSortInfo = function (info) {
  29664. if (info == null) {
  29665. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  29666. return;
  29667. }
  29668. var infoOrdinalNumbers = info.ordinalNumbers;
  29669. var ordinalsByTick = this._ordinalNumbersByTick = [];
  29670. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  29671. var tickNum = 0;
  29672. var allCategoryLen = this._ordinalMeta.categories.length;
  29673. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  29674. var ordinalNumber = infoOrdinalNumbers[tickNum];
  29675. ordinalsByTick[tickNum] = ordinalNumber;
  29676. ticksByOrdinal[ordinalNumber] = tickNum;
  29677. } // Handle that `series.data` only covers part of the `axis.category.data`.
  29678. var unusedOrdinal = 0;
  29679. for (; tickNum < allCategoryLen; ++tickNum) {
  29680. while (ticksByOrdinal[unusedOrdinal] != null) {
  29681. unusedOrdinal++;
  29682. }
  29683. ordinalsByTick.push(unusedOrdinal);
  29684. ticksByOrdinal[unusedOrdinal] = tickNum;
  29685. }
  29686. };
  29687. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  29688. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  29689. // where ordinal numbers are used as tick value directly.
  29690. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  29691. };
  29692. /**
  29693. * @usage
  29694. * ```js
  29695. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  29696. *
  29697. * // case0
  29698. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  29699. * // case1
  29700. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  29701. * // case2
  29702. * const coord = axis.dataToCoord(ordinalNumber);
  29703. * ```
  29704. *
  29705. * @param {OrdinalNumber} tickNumber index of display
  29706. */
  29707. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  29708. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  29709. // where ordinal numbers are used as tick value directly.
  29710. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  29711. };
  29712. /**
  29713. * Get item on tick
  29714. */
  29715. OrdinalScale.prototype.getLabel = function (tick) {
  29716. if (!this.isBlank()) {
  29717. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  29718. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  29719. // Return empty if it's not exist.
  29720. return cateogry == null ? '' : cateogry + '';
  29721. }
  29722. };
  29723. OrdinalScale.prototype.count = function () {
  29724. return this._extent[1] - this._extent[0] + 1;
  29725. };
  29726. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  29727. this.unionExtent(data.getApproximateExtent(dim));
  29728. };
  29729. /**
  29730. * @override
  29731. * If value is in extent range
  29732. */
  29733. OrdinalScale.prototype.isInExtentRange = function (value) {
  29734. value = this._getTickNumber(value);
  29735. return this._extent[0] <= value && this._extent[1] >= value;
  29736. };
  29737. OrdinalScale.prototype.getOrdinalMeta = function () {
  29738. return this._ordinalMeta;
  29739. };
  29740. OrdinalScale.prototype.calcNiceTicks = function () {};
  29741. OrdinalScale.prototype.calcNiceExtent = function () {};
  29742. OrdinalScale.type = 'ordinal';
  29743. return OrdinalScale;
  29744. }(Scale);
  29745. Scale.registerClass(OrdinalScale);
  29746. var roundNumber = round;
  29747. var IntervalScale =
  29748. /** @class */
  29749. function (_super) {
  29750. __extends(IntervalScale, _super);
  29751. function IntervalScale() {
  29752. var _this = _super !== null && _super.apply(this, arguments) || this;
  29753. _this.type = 'interval'; // Step is calculated in adjustExtent.
  29754. _this._interval = 0;
  29755. _this._intervalPrecision = 2;
  29756. return _this;
  29757. }
  29758. IntervalScale.prototype.parse = function (val) {
  29759. return val;
  29760. };
  29761. IntervalScale.prototype.contain = function (val) {
  29762. return contain$1(val, this._extent);
  29763. };
  29764. IntervalScale.prototype.normalize = function (val) {
  29765. return normalize$1(val, this._extent);
  29766. };
  29767. IntervalScale.prototype.scale = function (val) {
  29768. return scale$2(val, this._extent);
  29769. };
  29770. IntervalScale.prototype.setExtent = function (start, end) {
  29771. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  29772. if (!isNaN(start)) {
  29773. thisExtent[0] = parseFloat(start);
  29774. }
  29775. if (!isNaN(end)) {
  29776. thisExtent[1] = parseFloat(end);
  29777. }
  29778. };
  29779. IntervalScale.prototype.unionExtent = function (other) {
  29780. var extent = this._extent;
  29781. other[0] < extent[0] && (extent[0] = other[0]);
  29782. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  29783. this.setExtent(extent[0], extent[1]);
  29784. };
  29785. IntervalScale.prototype.getInterval = function () {
  29786. return this._interval;
  29787. };
  29788. IntervalScale.prototype.setInterval = function (interval) {
  29789. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  29790. // We assume user wan't to set both interval, min, max to get a better result
  29791. this._niceExtent = this._extent.slice();
  29792. this._intervalPrecision = getIntervalPrecision(interval);
  29793. };
  29794. /**
  29795. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29796. */
  29797. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  29798. var interval = this._interval;
  29799. var extent = this._extent;
  29800. var niceTickExtent = this._niceExtent;
  29801. var intervalPrecision = this._intervalPrecision;
  29802. var ticks = []; // If interval is 0, return [];
  29803. if (!interval) {
  29804. return ticks;
  29805. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  29806. var safeLimit = 10000;
  29807. if (extent[0] < niceTickExtent[0]) {
  29808. if (expandToNicedExtent) {
  29809. ticks.push({
  29810. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  29811. });
  29812. } else {
  29813. ticks.push({
  29814. value: extent[0]
  29815. });
  29816. }
  29817. }
  29818. var tick = niceTickExtent[0];
  29819. while (tick <= niceTickExtent[1]) {
  29820. ticks.push({
  29821. value: tick
  29822. }); // Avoid rounding error
  29823. tick = roundNumber(tick + interval, intervalPrecision);
  29824. if (tick === ticks[ticks.length - 1].value) {
  29825. // Consider out of safe float point, e.g.,
  29826. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29827. break;
  29828. }
  29829. if (ticks.length > safeLimit) {
  29830. return [];
  29831. }
  29832. } // Consider this case: the last item of ticks is smaller
  29833. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29834. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  29835. if (extent[1] > lastNiceTick) {
  29836. if (expandToNicedExtent) {
  29837. ticks.push({
  29838. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  29839. });
  29840. } else {
  29841. ticks.push({
  29842. value: extent[1]
  29843. });
  29844. }
  29845. }
  29846. return ticks;
  29847. };
  29848. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  29849. var ticks = this.getTicks(true);
  29850. var minorTicks = [];
  29851. var extent = this.getExtent();
  29852. for (var i = 1; i < ticks.length; i++) {
  29853. var nextTick = ticks[i];
  29854. var prevTick = ticks[i - 1];
  29855. var count = 0;
  29856. var minorTicksGroup = [];
  29857. var interval = nextTick.value - prevTick.value;
  29858. var minorInterval = interval / splitNumber;
  29859. while (count < splitNumber - 1) {
  29860. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  29861. if (minorTick > extent[0] && minorTick < extent[1]) {
  29862. minorTicksGroup.push(minorTick);
  29863. }
  29864. count++;
  29865. }
  29866. minorTicks.push(minorTicksGroup);
  29867. }
  29868. return minorTicks;
  29869. };
  29870. /**
  29871. * @param opt.precision If 'auto', use nice presision.
  29872. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  29873. */
  29874. IntervalScale.prototype.getLabel = function (data, opt) {
  29875. if (data == null) {
  29876. return '';
  29877. }
  29878. var precision = opt && opt.precision;
  29879. if (precision == null) {
  29880. precision = getPrecision(data.value) || 0;
  29881. } else if (precision === 'auto') {
  29882. // Should be more precise then tick.
  29883. precision = this._intervalPrecision;
  29884. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29885. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29886. var dataNum = roundNumber(data.value, precision, true);
  29887. return addCommas(dataNum);
  29888. };
  29889. /**
  29890. * @param splitNumber By default `5`.
  29891. */
  29892. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  29893. splitNumber = splitNumber || 5;
  29894. var extent = this._extent;
  29895. var span = extent[1] - extent[0];
  29896. if (!isFinite(span)) {
  29897. return;
  29898. } // User may set axis min 0 and data are all negative
  29899. // FIXME If it needs to reverse ?
  29900. if (span < 0) {
  29901. span = -span;
  29902. extent.reverse();
  29903. }
  29904. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  29905. this._intervalPrecision = result.intervalPrecision;
  29906. this._interval = result.interval;
  29907. this._niceExtent = result.niceTickExtent;
  29908. };
  29909. IntervalScale.prototype.calcNiceExtent = function (opt) {
  29910. var extent = this._extent; // If extent start and end are same, expand them
  29911. if (extent[0] === extent[1]) {
  29912. if (extent[0] !== 0) {
  29913. // Expand extent
  29914. var expandSize = extent[0]; // In the fowllowing case
  29915. // Axis has been fixed max 100
  29916. // Plus data are all 100 and axis extent are [100, 100].
  29917. // Extend to the both side will cause expanded max is larger than fixed max.
  29918. // So only expand to the smaller side.
  29919. if (!opt.fixMax) {
  29920. extent[1] += expandSize / 2;
  29921. extent[0] -= expandSize / 2;
  29922. } else {
  29923. extent[0] -= expandSize / 2;
  29924. }
  29925. } else {
  29926. extent[1] = 1;
  29927. }
  29928. }
  29929. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  29930. if (!isFinite(span)) {
  29931. extent[0] = 0;
  29932. extent[1] = 1;
  29933. }
  29934. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  29935. var interval = this._interval;
  29936. if (!opt.fixMin) {
  29937. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29938. }
  29939. if (!opt.fixMax) {
  29940. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29941. }
  29942. };
  29943. IntervalScale.prototype.setNiceExtent = function (min, max) {
  29944. this._niceExtent = [min, max];
  29945. };
  29946. IntervalScale.type = 'interval';
  29947. return IntervalScale;
  29948. }(Scale);
  29949. Scale.registerClass(IntervalScale);
  29950. /* global Float32Array */
  29951. var supportFloat32Array = typeof Float32Array !== 'undefined';
  29952. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  29953. function createFloat32Array(arg) {
  29954. if (isArray(arg)) {
  29955. // Return self directly if don't support TypedArray.
  29956. return supportFloat32Array ? new Float32Array(arg) : arg;
  29957. } // Else is number
  29958. return new Float32ArrayCtor(arg);
  29959. }
  29960. var STACK_PREFIX = '__ec_stack_';
  29961. function getSeriesStackId(seriesModel) {
  29962. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29963. }
  29964. function getAxisKey(axis) {
  29965. return axis.dim + axis.index;
  29966. }
  29967. function prepareLayoutBarSeries(seriesType, ecModel) {
  29968. var seriesModels = [];
  29969. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29970. // Check series coordinate, do layout for cartesian2d only
  29971. if (isOnCartesian(seriesModel)) {
  29972. seriesModels.push(seriesModel);
  29973. }
  29974. });
  29975. return seriesModels;
  29976. }
  29977. /**
  29978. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29979. * values.
  29980. * This works for time axes, value axes, and log axes.
  29981. * For a single time axis, return value is in the form like
  29982. * {'x_0': [1000000]}.
  29983. * The value of 1000000 is in milliseconds.
  29984. */
  29985. function getValueAxesMinGaps(barSeries) {
  29986. /**
  29987. * Map from axis.index to values.
  29988. * For a single time axis, axisValues is in the form like
  29989. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29990. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29991. * series.
  29992. */
  29993. var axisValues = {};
  29994. each(barSeries, function (seriesModel) {
  29995. var cartesian = seriesModel.coordinateSystem;
  29996. var baseAxis = cartesian.getBaseAxis();
  29997. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29998. return;
  29999. }
  30000. var data = seriesModel.getData();
  30001. var key = baseAxis.dim + '_' + baseAxis.index;
  30002. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30003. var store = data.getStore();
  30004. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30005. var value = store.get(dimIdx, i);
  30006. if (!axisValues[key]) {
  30007. // No previous data for the axis
  30008. axisValues[key] = [value];
  30009. } else {
  30010. // No value in previous series
  30011. axisValues[key].push(value);
  30012. } // Ignore duplicated time values in the same axis
  30013. }
  30014. });
  30015. var axisMinGaps = {};
  30016. for (var key in axisValues) {
  30017. if (axisValues.hasOwnProperty(key)) {
  30018. var valuesInAxis = axisValues[key];
  30019. if (valuesInAxis) {
  30020. // Sort axis values into ascending order to calculate gaps
  30021. valuesInAxis.sort(function (a, b) {
  30022. return a - b;
  30023. });
  30024. var min = null;
  30025. for (var j = 1; j < valuesInAxis.length; ++j) {
  30026. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30027. if (delta > 0) {
  30028. // Ignore 0 delta because they are of the same axis value
  30029. min = min === null ? delta : Math.min(min, delta);
  30030. }
  30031. } // Set to null if only have one data
  30032. axisMinGaps[key] = min;
  30033. }
  30034. }
  30035. }
  30036. return axisMinGaps;
  30037. }
  30038. function makeColumnLayout(barSeries) {
  30039. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30040. var seriesInfoList = [];
  30041. each(barSeries, function (seriesModel) {
  30042. var cartesian = seriesModel.coordinateSystem;
  30043. var baseAxis = cartesian.getBaseAxis();
  30044. var axisExtent = baseAxis.getExtent();
  30045. var bandWidth;
  30046. if (baseAxis.type === 'category') {
  30047. bandWidth = baseAxis.getBandWidth();
  30048. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30049. var key = baseAxis.dim + '_' + baseAxis.index;
  30050. var minGap = axisMinGaps[key];
  30051. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30052. var scale = baseAxis.scale.getExtent();
  30053. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30054. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30055. } else {
  30056. var data = seriesModel.getData();
  30057. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30058. }
  30059. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30060. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30061. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30062. // the auto-calculated bar width might be less than 0.5 / 1.
  30063. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30064. var barGap = seriesModel.get('barGap');
  30065. var barCategoryGap = seriesModel.get('barCategoryGap');
  30066. seriesInfoList.push({
  30067. bandWidth: bandWidth,
  30068. barWidth: barWidth,
  30069. barMaxWidth: barMaxWidth,
  30070. barMinWidth: barMinWidth,
  30071. barGap: barGap,
  30072. barCategoryGap: barCategoryGap,
  30073. axisKey: getAxisKey(baseAxis),
  30074. stackId: getSeriesStackId(seriesModel)
  30075. });
  30076. });
  30077. return doCalBarWidthAndOffset(seriesInfoList);
  30078. }
  30079. function doCalBarWidthAndOffset(seriesInfoList) {
  30080. // Columns info on each category axis. Key is cartesian name
  30081. var columnsMap = {};
  30082. each(seriesInfoList, function (seriesInfo, idx) {
  30083. var axisKey = seriesInfo.axisKey;
  30084. var bandWidth = seriesInfo.bandWidth;
  30085. var columnsOnAxis = columnsMap[axisKey] || {
  30086. bandWidth: bandWidth,
  30087. remainedWidth: bandWidth,
  30088. autoWidthCount: 0,
  30089. categoryGap: null,
  30090. gap: '20%',
  30091. stacks: {}
  30092. };
  30093. var stacks = columnsOnAxis.stacks;
  30094. columnsMap[axisKey] = columnsOnAxis;
  30095. var stackId = seriesInfo.stackId;
  30096. if (!stacks[stackId]) {
  30097. columnsOnAxis.autoWidthCount++;
  30098. }
  30099. stacks[stackId] = stacks[stackId] || {
  30100. width: 0,
  30101. maxWidth: 0
  30102. }; // Caution: In a single coordinate system, these barGrid attributes
  30103. // will be shared by series. Consider that they have default values,
  30104. // only the attributes set on the last series will work.
  30105. // Do not change this fact unless there will be a break change.
  30106. var barWidth = seriesInfo.barWidth;
  30107. if (barWidth && !stacks[stackId].width) {
  30108. // See #6312, do not restrict width.
  30109. stacks[stackId].width = barWidth;
  30110. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30111. columnsOnAxis.remainedWidth -= barWidth;
  30112. }
  30113. var barMaxWidth = seriesInfo.barMaxWidth;
  30114. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30115. var barMinWidth = seriesInfo.barMinWidth;
  30116. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30117. var barGap = seriesInfo.barGap;
  30118. barGap != null && (columnsOnAxis.gap = barGap);
  30119. var barCategoryGap = seriesInfo.barCategoryGap;
  30120. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30121. });
  30122. var result = {};
  30123. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30124. result[coordSysName] = {};
  30125. var stacks = columnsOnAxis.stacks;
  30126. var bandWidth = columnsOnAxis.bandWidth;
  30127. var categoryGapPercent = columnsOnAxis.categoryGap;
  30128. if (categoryGapPercent == null) {
  30129. var columnCount = keys(stacks).length; // More columns in one group
  30130. // the spaces between group is smaller. Or the column will be too thin.
  30131. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30132. }
  30133. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30134. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30135. var remainedWidth = columnsOnAxis.remainedWidth;
  30136. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30137. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30138. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30139. each(stacks, function (column) {
  30140. var maxWidth = column.maxWidth;
  30141. var minWidth = column.minWidth;
  30142. if (!column.width) {
  30143. var finalWidth = autoWidth;
  30144. if (maxWidth && maxWidth < finalWidth) {
  30145. finalWidth = Math.min(maxWidth, remainedWidth);
  30146. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  30147. // bar is able to be visible. So `minWidth` should not be restricted
  30148. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30149. // the extreme cases for `value` axis, bars are allowed to overlap
  30150. // with each other if `minWidth` specified.
  30151. if (minWidth && minWidth > finalWidth) {
  30152. finalWidth = minWidth;
  30153. }
  30154. if (finalWidth !== autoWidth) {
  30155. column.width = finalWidth;
  30156. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30157. autoWidthCount--;
  30158. }
  30159. } else {
  30160. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30161. // CSS does. Becuase barWidth can be a percent value, where
  30162. // `barMaxWidth` can be used to restrict the final width.
  30163. var finalWidth = column.width;
  30164. if (maxWidth) {
  30165. finalWidth = Math.min(finalWidth, maxWidth);
  30166. } // `minWidth` has higher priority, as described above
  30167. if (minWidth) {
  30168. finalWidth = Math.max(finalWidth, minWidth);
  30169. }
  30170. column.width = finalWidth;
  30171. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30172. autoWidthCount--;
  30173. }
  30174. }); // Recalculate width again
  30175. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30176. autoWidth = Math.max(autoWidth, 0);
  30177. var widthSum = 0;
  30178. var lastColumn;
  30179. each(stacks, function (column, idx) {
  30180. if (!column.width) {
  30181. column.width = autoWidth;
  30182. }
  30183. lastColumn = column;
  30184. widthSum += column.width * (1 + barGapPercent);
  30185. });
  30186. if (lastColumn) {
  30187. widthSum -= lastColumn.width * barGapPercent;
  30188. }
  30189. var offset = -widthSum / 2;
  30190. each(stacks, function (column, stackId) {
  30191. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30192. bandWidth: bandWidth,
  30193. offset: offset,
  30194. width: column.width
  30195. };
  30196. offset += column.width * (1 + barGapPercent);
  30197. });
  30198. });
  30199. return result;
  30200. }
  30201. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30202. if (barWidthAndOffset && axis) {
  30203. var result = barWidthAndOffset[getAxisKey(axis)];
  30204. if (result != null && seriesModel != null) {
  30205. return result[getSeriesStackId(seriesModel)];
  30206. }
  30207. return result;
  30208. }
  30209. }
  30210. function layout(seriesType, ecModel) {
  30211. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30212. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30213. each(seriesModels, function (seriesModel) {
  30214. var data = seriesModel.getData();
  30215. var cartesian = seriesModel.coordinateSystem;
  30216. var baseAxis = cartesian.getBaseAxis();
  30217. var stackId = getSeriesStackId(seriesModel);
  30218. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30219. var columnOffset = columnLayoutInfo.offset;
  30220. var columnWidth = columnLayoutInfo.width;
  30221. data.setLayout({
  30222. bandWidth: columnLayoutInfo.bandWidth,
  30223. offset: columnOffset,
  30224. size: columnWidth
  30225. });
  30226. });
  30227. } // TODO: Do not support stack in large mode yet.
  30228. function createProgressiveLayout(seriesType) {
  30229. return {
  30230. seriesType: seriesType,
  30231. plan: createRenderPlanner(),
  30232. reset: function (seriesModel) {
  30233. if (!isOnCartesian(seriesModel)) {
  30234. return;
  30235. }
  30236. var data = seriesModel.getData();
  30237. var cartesian = seriesModel.coordinateSystem;
  30238. var baseAxis = cartesian.getBaseAxis();
  30239. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30240. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30241. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30242. var drawBackground = seriesModel.get('showBackground', true);
  30243. var valueDim = data.mapDimension(valueAxis.dim);
  30244. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30245. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30246. var isValueAxisH = valueAxis.isHorizontal();
  30247. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30248. var isLarge = isInLargeMode(seriesModel);
  30249. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30250. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  30251. var columnWidth = data.getLayout('size');
  30252. var columnOffset = data.getLayout('offset');
  30253. return {
  30254. progress: function (params, data) {
  30255. var count = params.count;
  30256. var largePoints = isLarge && createFloat32Array(count * 3);
  30257. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30258. var largeDataIndices = isLarge && createFloat32Array(count);
  30259. var coordLayout = cartesian.master.getRect();
  30260. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30261. var dataIndex;
  30262. var store = data.getStore();
  30263. var idxOffset = 0;
  30264. while ((dataIndex = params.next()) != null) {
  30265. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30266. var baseValue = store.get(baseDimIdx, dataIndex);
  30267. var baseCoord = valueAxisStart;
  30268. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  30269. // stackResultDimension directly.
  30270. if (stacked) {
  30271. startValue = +value - store.get(valueDimIdx, dataIndex);
  30272. }
  30273. var x = void 0;
  30274. var y = void 0;
  30275. var width = void 0;
  30276. var height = void 0;
  30277. if (isValueAxisH) {
  30278. var coord = cartesian.dataToPoint([value, baseValue]);
  30279. if (stacked) {
  30280. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  30281. baseCoord = startCoord[0];
  30282. }
  30283. x = baseCoord;
  30284. y = coord[1] + columnOffset;
  30285. width = coord[0] - baseCoord;
  30286. height = columnWidth;
  30287. if (Math.abs(width) < barMinHeight) {
  30288. width = (width < 0 ? -1 : 1) * barMinHeight;
  30289. }
  30290. } else {
  30291. var coord = cartesian.dataToPoint([baseValue, value]);
  30292. if (stacked) {
  30293. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  30294. baseCoord = startCoord[1];
  30295. }
  30296. x = coord[0] + columnOffset;
  30297. y = baseCoord;
  30298. width = columnWidth;
  30299. height = coord[1] - baseCoord;
  30300. if (Math.abs(height) < barMinHeight) {
  30301. // Include zero to has a positive bar
  30302. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30303. }
  30304. }
  30305. if (!isLarge) {
  30306. data.setItemLayout(dataIndex, {
  30307. x: x,
  30308. y: y,
  30309. width: width,
  30310. height: height
  30311. });
  30312. } else {
  30313. largePoints[idxOffset] = x;
  30314. largePoints[idxOffset + 1] = y;
  30315. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30316. if (largeBackgroundPoints) {
  30317. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30318. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30319. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30320. }
  30321. largeDataIndices[dataIndex] = dataIndex;
  30322. }
  30323. idxOffset += 3;
  30324. }
  30325. if (isLarge) {
  30326. data.setLayout({
  30327. largePoints: largePoints,
  30328. largeDataIndices: largeDataIndices,
  30329. largeBackgroundPoints: largeBackgroundPoints,
  30330. valueAxisHorizontal: isValueAxisH
  30331. });
  30332. }
  30333. }
  30334. };
  30335. }
  30336. };
  30337. }
  30338. function isOnCartesian(seriesModel) {
  30339. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30340. }
  30341. function isInLargeMode(seriesModel) {
  30342. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30343. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30344. function getValueAxisStart(baseAxis, valueAxis) {
  30345. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30346. }
  30347. var bisect = function (a, x, lo, hi) {
  30348. while (lo < hi) {
  30349. var mid = lo + hi >>> 1;
  30350. if (a[mid][1] < x) {
  30351. lo = mid + 1;
  30352. } else {
  30353. hi = mid;
  30354. }
  30355. }
  30356. return lo;
  30357. };
  30358. var TimeScale =
  30359. /** @class */
  30360. function (_super) {
  30361. __extends(TimeScale, _super);
  30362. function TimeScale(settings) {
  30363. var _this = _super.call(this, settings) || this;
  30364. _this.type = 'time';
  30365. return _this;
  30366. }
  30367. /**
  30368. * Get label is mainly for other components like dataZoom, tooltip.
  30369. */
  30370. TimeScale.prototype.getLabel = function (tick) {
  30371. var useUTC = this.getSetting('useUTC');
  30372. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30373. };
  30374. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30375. var isUTC = this.getSetting('useUTC');
  30376. var lang = this.getSetting('locale');
  30377. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30378. };
  30379. /**
  30380. * @override
  30381. */
  30382. TimeScale.prototype.getTicks = function () {
  30383. var interval = this._interval;
  30384. var extent = this._extent;
  30385. var ticks = []; // If interval is 0, return [];
  30386. if (!interval) {
  30387. return ticks;
  30388. }
  30389. ticks.push({
  30390. value: extent[0],
  30391. level: 0
  30392. });
  30393. var useUTC = this.getSetting('useUTC');
  30394. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30395. ticks = ticks.concat(innerTicks);
  30396. ticks.push({
  30397. value: extent[1],
  30398. level: 0
  30399. });
  30400. return ticks;
  30401. };
  30402. TimeScale.prototype.calcNiceExtent = function (opt) {
  30403. var extent = this._extent; // If extent start and end are same, expand them
  30404. if (extent[0] === extent[1]) {
  30405. // Expand extent
  30406. extent[0] -= ONE_DAY;
  30407. extent[1] += ONE_DAY;
  30408. } // If there are no data and extent are [Infinity, -Infinity]
  30409. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30410. var d = new Date();
  30411. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30412. extent[0] = extent[1] - ONE_DAY;
  30413. }
  30414. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30415. };
  30416. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30417. approxTickNum = approxTickNum || 10;
  30418. var extent = this._extent;
  30419. var span = extent[1] - extent[0];
  30420. this._approxInterval = span / approxTickNum;
  30421. if (minInterval != null && this._approxInterval < minInterval) {
  30422. this._approxInterval = minInterval;
  30423. }
  30424. if (maxInterval != null && this._approxInterval > maxInterval) {
  30425. this._approxInterval = maxInterval;
  30426. }
  30427. var scaleIntervalsLen = scaleIntervals.length;
  30428. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30429. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30430. // We check one more level to avoid the ticks are to sparse in some case.
  30431. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30432. };
  30433. TimeScale.prototype.parse = function (val) {
  30434. // val might be float.
  30435. return isNumber(val) ? val : +parseDate(val);
  30436. };
  30437. TimeScale.prototype.contain = function (val) {
  30438. return contain$1(this.parse(val), this._extent);
  30439. };
  30440. TimeScale.prototype.normalize = function (val) {
  30441. return normalize$1(this.parse(val), this._extent);
  30442. };
  30443. TimeScale.prototype.scale = function (val) {
  30444. return scale$2(val, this._extent);
  30445. };
  30446. TimeScale.type = 'time';
  30447. return TimeScale;
  30448. }(IntervalScale);
  30449. /**
  30450. * This implementation was originally copied from "d3.js"
  30451. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30452. * with some modifications made for this program.
  30453. * See the license statement at the head of this file.
  30454. */
  30455. var scaleIntervals = [// Format interval
  30456. ['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
  30457. ];
  30458. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30459. var dateA = parseDate(valueA);
  30460. var dateB = parseDate(valueB);
  30461. var isSame = function (unit) {
  30462. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30463. };
  30464. var isSameYear = function () {
  30465. return isSame('year');
  30466. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30467. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30468. var isSameMonth = function () {
  30469. return isSameYear() && isSame('month');
  30470. };
  30471. var isSameDay = function () {
  30472. return isSameMonth() && isSame('day');
  30473. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30474. var isSameHour = function () {
  30475. return isSameDay() && isSame('hour');
  30476. };
  30477. var isSameMinute = function () {
  30478. return isSameHour() && isSame('minute');
  30479. };
  30480. var isSameSecond = function () {
  30481. return isSameMinute() && isSame('second');
  30482. };
  30483. var isSameMilliSecond = function () {
  30484. return isSameSecond() && isSame('millisecond');
  30485. };
  30486. switch (unit) {
  30487. case 'year':
  30488. return isSameYear();
  30489. case 'month':
  30490. return isSameMonth();
  30491. case 'day':
  30492. return isSameDay();
  30493. case 'hour':
  30494. return isSameHour();
  30495. case 'minute':
  30496. return isSameMinute();
  30497. case 'second':
  30498. return isSameSecond();
  30499. case 'millisecond':
  30500. return isSameMilliSecond();
  30501. }
  30502. } // const primaryUnitGetters = {
  30503. // year: fullYearGetterName(),
  30504. // month: monthGetterName(),
  30505. // day: dateGetterName(),
  30506. // hour: hoursGetterName(),
  30507. // minute: minutesGetterName(),
  30508. // second: secondsGetterName(),
  30509. // millisecond: millisecondsGetterName()
  30510. // };
  30511. // const primaryUnitUTCGetters = {
  30512. // year: fullYearGetterName(true),
  30513. // month: monthGetterName(true),
  30514. // day: dateGetterName(true),
  30515. // hour: hoursGetterName(true),
  30516. // minute: minutesGetterName(true),
  30517. // second: secondsGetterName(true),
  30518. // millisecond: millisecondsGetterName(true)
  30519. // };
  30520. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30521. // step = step || 1;
  30522. // switch (getPrimaryTimeUnit(unitName)) {
  30523. // case 'year':
  30524. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30525. // break;
  30526. // case 'month':
  30527. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30528. // break;
  30529. // case 'day':
  30530. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30531. // break;
  30532. // case 'hour':
  30533. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30534. // break;
  30535. // case 'minute':
  30536. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30537. // break;
  30538. // case 'second':
  30539. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  30540. // break;
  30541. // case 'millisecond':
  30542. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  30543. // break;
  30544. // }
  30545. // return date.getTime();
  30546. // }
  30547. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  30548. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  30549. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  30550. function getDateInterval(approxInterval, daysInMonth) {
  30551. approxInterval /= ONE_DAY;
  30552. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  30553. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  30554. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  30555. }
  30556. function getMonthInterval(approxInterval) {
  30557. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  30558. approxInterval /= APPROX_ONE_MONTH;
  30559. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  30560. }
  30561. function getHourInterval(approxInterval) {
  30562. approxInterval /= ONE_HOUR;
  30563. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  30564. }
  30565. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  30566. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  30567. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  30568. }
  30569. function getMillisecondsInterval(approxInterval) {
  30570. return nice(approxInterval, true);
  30571. }
  30572. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  30573. var outDate = new Date(date);
  30574. switch (getPrimaryTimeUnit(unitName)) {
  30575. case 'year':
  30576. case 'month':
  30577. outDate[monthSetterName(isUTC)](0);
  30578. case 'day':
  30579. outDate[dateSetterName(isUTC)](1);
  30580. case 'hour':
  30581. outDate[hoursSetterName(isUTC)](0);
  30582. case 'minute':
  30583. outDate[minutesSetterName(isUTC)](0);
  30584. case 'second':
  30585. outDate[secondsSetterName(isUTC)](0);
  30586. outDate[millisecondsSetterName(isUTC)](0);
  30587. }
  30588. return outDate.getTime();
  30589. }
  30590. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  30591. var safeLimit = 10000;
  30592. var unitNames = timeUnits;
  30593. var iter = 0;
  30594. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  30595. var date = new Date(minTimestamp);
  30596. var dateTime = minTimestamp;
  30597. var d = date[getMethodName](); // if (isDate) {
  30598. // d -= 1; // Starts with 0; PENDING
  30599. // }
  30600. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  30601. out.push({
  30602. value: dateTime
  30603. });
  30604. d += interval;
  30605. date[setMethodName](d);
  30606. dateTime = date.getTime();
  30607. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  30608. out.push({
  30609. value: dateTime,
  30610. notAdd: true
  30611. });
  30612. }
  30613. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  30614. var newAddedTicks = [];
  30615. var isFirstLevel = !lastLevelTicks.length;
  30616. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  30617. return;
  30618. }
  30619. if (isFirstLevel) {
  30620. lastLevelTicks = [{
  30621. // TODO Optimize. Not include so may ticks.
  30622. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  30623. }, {
  30624. value: extent[1]
  30625. }];
  30626. }
  30627. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  30628. var startTick = lastLevelTicks[i].value;
  30629. var endTick = lastLevelTicks[i + 1].value;
  30630. if (startTick === endTick) {
  30631. continue;
  30632. }
  30633. var interval = void 0;
  30634. var getterName = void 0;
  30635. var setterName = void 0;
  30636. var isDate = false;
  30637. switch (unitName) {
  30638. case 'year':
  30639. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  30640. getterName = fullYearGetterName(isUTC);
  30641. setterName = fullYearSetterName(isUTC);
  30642. break;
  30643. case 'half-year':
  30644. case 'quarter':
  30645. case 'month':
  30646. interval = getMonthInterval(approxInterval);
  30647. getterName = monthGetterName(isUTC);
  30648. setterName = monthSetterName(isUTC);
  30649. break;
  30650. case 'week': // PENDING If week is added. Ignore day.
  30651. case 'half-week':
  30652. case 'day':
  30653. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  30654. getterName = dateGetterName(isUTC);
  30655. setterName = dateSetterName(isUTC);
  30656. isDate = true;
  30657. break;
  30658. case 'half-day':
  30659. case 'quarter-day':
  30660. case 'hour':
  30661. interval = getHourInterval(approxInterval);
  30662. getterName = hoursGetterName(isUTC);
  30663. setterName = hoursSetterName(isUTC);
  30664. break;
  30665. case 'minute':
  30666. interval = getMinutesAndSecondsInterval(approxInterval, true);
  30667. getterName = minutesGetterName(isUTC);
  30668. setterName = minutesSetterName(isUTC);
  30669. break;
  30670. case 'second':
  30671. interval = getMinutesAndSecondsInterval(approxInterval, false);
  30672. getterName = secondsGetterName(isUTC);
  30673. setterName = secondsSetterName(isUTC);
  30674. break;
  30675. case 'millisecond':
  30676. interval = getMillisecondsInterval(approxInterval);
  30677. getterName = millisecondsGetterName(isUTC);
  30678. setterName = millisecondsSetterName(isUTC);
  30679. break;
  30680. }
  30681. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  30682. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  30683. // Add nearest years to the left extent.
  30684. levelTicks.unshift({
  30685. value: levelTicks[0].value - interval
  30686. });
  30687. }
  30688. }
  30689. for (var i = 0; i < newAddedTicks.length; i++) {
  30690. levelTicks.push(newAddedTicks[i]);
  30691. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  30692. return newAddedTicks;
  30693. }
  30694. var levelsTicks = [];
  30695. var currentLevelTicks = [];
  30696. var tickCount = 0;
  30697. var lastLevelTickCount = 0;
  30698. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  30699. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  30700. if (!isPrimaryTimeUnit(unitNames[i])) {
  30701. // TODO
  30702. continue;
  30703. }
  30704. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  30705. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  30706. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  30707. if (currentLevelTicks.length) {
  30708. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  30709. currentLevelTicks.sort(function (a, b) {
  30710. return a.value - b.value;
  30711. });
  30712. var levelTicksRemoveDuplicated = [];
  30713. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  30714. var tickValue = currentLevelTicks[i_1].value;
  30715. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  30716. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  30717. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  30718. tickCount++;
  30719. }
  30720. }
  30721. }
  30722. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  30723. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  30724. break;
  30725. } // Only treat primary time unit as one level.
  30726. levelsTicks.push(levelTicksRemoveDuplicated);
  30727. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  30728. break;
  30729. }
  30730. } // Reset if next unitName is primary
  30731. currentLevelTicks = [];
  30732. }
  30733. }
  30734. if ("development" !== 'production') {
  30735. if (iter >= safeLimit) {
  30736. warn('Exceed safe limit.');
  30737. }
  30738. }
  30739. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  30740. return filter(levelTicks, function (tick) {
  30741. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  30742. });
  30743. }), function (levelTicks) {
  30744. return levelTicks.length > 0;
  30745. });
  30746. var ticks = [];
  30747. var maxLevel = levelsTicksInExtent.length - 1;
  30748. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  30749. var levelTicks = levelsTicksInExtent[i];
  30750. for (var k = 0; k < levelTicks.length; ++k) {
  30751. ticks.push({
  30752. value: levelTicks[k].value,
  30753. level: maxLevel - i
  30754. });
  30755. }
  30756. }
  30757. ticks.sort(function (a, b) {
  30758. return a.value - b.value;
  30759. }); // Remove duplicates
  30760. var result = [];
  30761. for (var i = 0; i < ticks.length; ++i) {
  30762. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  30763. result.push(ticks[i]);
  30764. }
  30765. }
  30766. return result;
  30767. }
  30768. Scale.registerClass(TimeScale);
  30769. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  30770. var intervalScaleProto = IntervalScale.prototype;
  30771. var roundingErrorFix = round;
  30772. var mathFloor = Math.floor;
  30773. var mathCeil = Math.ceil;
  30774. var mathPow$1 = Math.pow;
  30775. var mathLog = Math.log;
  30776. var LogScale =
  30777. /** @class */
  30778. function (_super) {
  30779. __extends(LogScale, _super);
  30780. function LogScale() {
  30781. var _this = _super !== null && _super.apply(this, arguments) || this;
  30782. _this.type = 'log';
  30783. _this.base = 10;
  30784. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  30785. _this._interval = 0;
  30786. return _this;
  30787. }
  30788. /**
  30789. * @param Whether expand the ticks to niced extent.
  30790. */
  30791. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  30792. var originalScale = this._originalScale;
  30793. var extent = this._extent;
  30794. var originalExtent = originalScale.getExtent();
  30795. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  30796. return map(ticks, function (tick) {
  30797. var val = tick.value;
  30798. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  30799. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  30800. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  30801. return {
  30802. value: powVal
  30803. };
  30804. }, this);
  30805. };
  30806. LogScale.prototype.setExtent = function (start, end) {
  30807. var base = this.base;
  30808. start = mathLog(start) / mathLog(base);
  30809. end = mathLog(end) / mathLog(base);
  30810. intervalScaleProto.setExtent.call(this, start, end);
  30811. };
  30812. /**
  30813. * @return {number} end
  30814. */
  30815. LogScale.prototype.getExtent = function () {
  30816. var base = this.base;
  30817. var extent = scaleProto.getExtent.call(this);
  30818. extent[0] = mathPow$1(base, extent[0]);
  30819. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  30820. var originalScale = this._originalScale;
  30821. var originalExtent = originalScale.getExtent();
  30822. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30823. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30824. return extent;
  30825. };
  30826. LogScale.prototype.unionExtent = function (extent) {
  30827. this._originalScale.unionExtent(extent);
  30828. var base = this.base;
  30829. extent[0] = mathLog(extent[0]) / mathLog(base);
  30830. extent[1] = mathLog(extent[1]) / mathLog(base);
  30831. scaleProto.unionExtent.call(this, extent);
  30832. };
  30833. LogScale.prototype.unionExtentFromData = function (data, dim) {
  30834. // TODO
  30835. // filter value that <= 0
  30836. this.unionExtent(data.getApproximateExtent(dim));
  30837. };
  30838. /**
  30839. * Update interval and extent of intervals for nice ticks
  30840. * @param approxTickNum default 10 Given approx tick number
  30841. */
  30842. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  30843. approxTickNum = approxTickNum || 10;
  30844. var extent = this._extent;
  30845. var span = extent[1] - extent[0];
  30846. if (span === Infinity || span <= 0) {
  30847. return;
  30848. }
  30849. var interval = quantity(span);
  30850. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  30851. if (err <= 0.5) {
  30852. interval *= 10;
  30853. } // Interval should be integer
  30854. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30855. interval *= 10;
  30856. }
  30857. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  30858. this._interval = interval;
  30859. this._niceExtent = niceExtent;
  30860. };
  30861. LogScale.prototype.calcNiceExtent = function (opt) {
  30862. intervalScaleProto.calcNiceExtent.call(this, opt);
  30863. this._fixMin = opt.fixMin;
  30864. this._fixMax = opt.fixMax;
  30865. };
  30866. LogScale.prototype.parse = function (val) {
  30867. return val;
  30868. };
  30869. LogScale.prototype.contain = function (val) {
  30870. val = mathLog(val) / mathLog(this.base);
  30871. return contain$1(val, this._extent);
  30872. };
  30873. LogScale.prototype.normalize = function (val) {
  30874. val = mathLog(val) / mathLog(this.base);
  30875. return normalize$1(val, this._extent);
  30876. };
  30877. LogScale.prototype.scale = function (val) {
  30878. val = scale$2(val, this._extent);
  30879. return mathPow$1(this.base, val);
  30880. };
  30881. LogScale.type = 'log';
  30882. return LogScale;
  30883. }(Scale);
  30884. var proto = LogScale.prototype;
  30885. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  30886. proto.getLabel = intervalScaleProto.getLabel;
  30887. function fixRoundingError(val, originalVal) {
  30888. return roundingErrorFix(val, getPrecision(originalVal));
  30889. }
  30890. Scale.registerClass(LogScale);
  30891. var ScaleRawExtentInfo =
  30892. /** @class */
  30893. function () {
  30894. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30895. originalExtent) {
  30896. this._prepareParams(scale, model, originalExtent);
  30897. }
  30898. /**
  30899. * Parameters depending on ouside (like model, user callback)
  30900. * are prepared and fixed here.
  30901. */
  30902. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  30903. dataExtent) {
  30904. if (dataExtent[1] < dataExtent[0]) {
  30905. dataExtent = [NaN, NaN];
  30906. }
  30907. this._dataMin = dataExtent[0];
  30908. this._dataMax = dataExtent[1];
  30909. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  30910. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  30911. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  30912. if (isFunction(modelMinRaw)) {
  30913. // This callback alway provide users the full data extent (before data filtered).
  30914. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  30915. min: dataExtent[0],
  30916. max: dataExtent[1]
  30917. }));
  30918. } else if (modelMinRaw !== 'dataMin') {
  30919. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  30920. }
  30921. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  30922. if (isFunction(modelMaxRaw)) {
  30923. // This callback alway provide users the full data extent (before data filtered).
  30924. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  30925. min: dataExtent[0],
  30926. max: dataExtent[1]
  30927. }));
  30928. } else if (modelMaxRaw !== 'dataMax') {
  30929. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  30930. }
  30931. if (isOrdinal) {
  30932. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  30933. // and progressive rendering is using, here the category result might just only contain
  30934. // the processed chunk rather than the entire result.
  30935. this._axisDataLen = model.getCategories().length;
  30936. } else {
  30937. var boundaryGap = model.get('boundaryGap');
  30938. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  30939. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  30940. if ("development" !== 'production') {
  30941. 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.');
  30942. }
  30943. this._boundaryGapInner = [0, 0];
  30944. } else {
  30945. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  30946. }
  30947. }
  30948. };
  30949. /**
  30950. * Calculate extent by prepared parameters.
  30951. * This method has no external dependency and can be called duplicatedly,
  30952. * getting the same result.
  30953. * If parameters changed, should call this method to recalcuate.
  30954. */
  30955. ScaleRawExtentInfo.prototype.calculate = function () {
  30956. // Notice: When min/max is not set (that is, when there are null/undefined,
  30957. // which is the most common case), these cases should be ensured:
  30958. // (1) For 'ordinal', show all axis.data.
  30959. // (2) For others:
  30960. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30961. // disabled).
  30962. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30963. // be the result that originalExtent enlarged by boundaryGap.
  30964. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30965. var isOrdinal = this._isOrdinal;
  30966. var dataMin = this._dataMin;
  30967. var dataMax = this._dataMax;
  30968. var axisDataLen = this._axisDataLen;
  30969. var boundaryGapInner = this._boundaryGapInner;
  30970. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  30971. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  30972. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  30973. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  30974. var minFixed = min != null;
  30975. var maxFixed = max != null;
  30976. if (min == null) {
  30977. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  30978. }
  30979. if (max == null) {
  30980. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  30981. }
  30982. (min == null || !isFinite(min)) && (min = NaN);
  30983. (max == null || !isFinite(max)) && (max = NaN);
  30984. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  30985. if (this._needCrossZero) {
  30986. // Axis is over zero and min is not set
  30987. if (min > 0 && max > 0 && !minFixed) {
  30988. min = 0; // minFixed = true;
  30989. } // Axis is under zero and max is not set
  30990. if (min < 0 && max < 0 && !maxFixed) {
  30991. max = 0; // maxFixed = true;
  30992. } // PENDING:
  30993. // When `needCrossZero` and all data is positive/negative, should it be ensured
  30994. // that the results processed by boundaryGap are positive/negative?
  30995. // If so, here `minFixed`/`maxFixed` need to be set.
  30996. }
  30997. var determinedMin = this._determinedMin;
  30998. var determinedMax = this._determinedMax;
  30999. if (determinedMin != null) {
  31000. min = determinedMin;
  31001. minFixed = true;
  31002. }
  31003. if (determinedMax != null) {
  31004. max = determinedMax;
  31005. maxFixed = true;
  31006. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31007. // `NaN` means min/max axis is blank.
  31008. return {
  31009. min: min,
  31010. max: max,
  31011. minFixed: minFixed,
  31012. maxFixed: maxFixed,
  31013. isBlank: isBlank
  31014. };
  31015. };
  31016. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31017. if ("development" !== 'production') {
  31018. assert(!this.frozen);
  31019. }
  31020. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31021. };
  31022. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31023. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31024. if ("development" !== 'production') {
  31025. assert(!this.frozen // Earse them usually means logic flaw.
  31026. && this[attr] == null);
  31027. }
  31028. this[attr] = val;
  31029. };
  31030. ScaleRawExtentInfo.prototype.freeze = function () {
  31031. // @ts-ignore
  31032. this.frozen = true;
  31033. };
  31034. return ScaleRawExtentInfo;
  31035. }();
  31036. var DETERMINED_MIN_MAX_ATTR = {
  31037. min: '_determinedMin',
  31038. max: '_determinedMax'
  31039. };
  31040. var DATA_MIN_MAX_ATTR = {
  31041. min: '_dataMin',
  31042. max: '_dataMax'
  31043. };
  31044. /**
  31045. * Get scale min max and related info only depends on model settings.
  31046. * This method can be called after coordinate system created.
  31047. * For example, in data processing stage.
  31048. *
  31049. * Scale extent info probably be required multiple times during a workflow.
  31050. * For example:
  31051. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31052. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31053. * (3) `coordSys.update` use it to finally decide the scale extent.
  31054. * But the callback of `min`/`max` should not be called multiple times.
  31055. * The code below should not be implemented repeatedly either.
  31056. * So we cache the result in the scale instance, which will be recreated at the begining
  31057. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31058. */
  31059. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31060. originalExtent) {
  31061. // Do not permit to recreate.
  31062. var rawExtentInfo = scale.rawExtentInfo;
  31063. if (rawExtentInfo) {
  31064. return rawExtentInfo;
  31065. }
  31066. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31067. scale.rawExtentInfo = rawExtentInfo;
  31068. return rawExtentInfo;
  31069. }
  31070. function parseAxisModelMinMax(scale, minMax) {
  31071. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31072. }
  31073. /**
  31074. * Get axis scale extent before niced.
  31075. * Item of returned array can only be number (including Infinity and NaN).
  31076. *
  31077. * Caution:
  31078. * Precondition of calling this method:
  31079. * The scale extent has been initialized using series data extent via
  31080. * `scale.setExtent` or `scale.unionExtentFromData`;
  31081. */
  31082. function getScaleExtent(scale, model) {
  31083. var scaleType = scale.type;
  31084. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31085. scale.setBlank(rawExtentResult.isBlank);
  31086. var min = rawExtentResult.min;
  31087. 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
  31088. // is base axis
  31089. // FIXME
  31090. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31091. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31092. // Should not depend on series type `bar`?
  31093. // (3) Fix that might overlap when using dataZoom.
  31094. // (4) Consider other chart types using `barGrid`?
  31095. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31096. var ecModel = model.ecModel;
  31097. if (ecModel && scaleType === 'time'
  31098. /*|| scaleType === 'interval' */
  31099. ) {
  31100. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31101. var isBaseAxisAndHasBarSeries_1 = false;
  31102. each(barSeriesModels, function (seriesModel) {
  31103. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31104. });
  31105. if (isBaseAxisAndHasBarSeries_1) {
  31106. // Calculate placement of bars on axis. TODO should be decoupled
  31107. // with barLayout
  31108. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31109. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31110. min = adjustedScale.min;
  31111. max = adjustedScale.max;
  31112. }
  31113. }
  31114. return {
  31115. extent: [min, max],
  31116. // "fix" means "fixed", the value should not be
  31117. // changed in the subsequent steps.
  31118. fixMin: rawExtentResult.minFixed,
  31119. fixMax: rawExtentResult.maxFixed
  31120. };
  31121. }
  31122. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31123. barWidthAndOffset) {
  31124. // Get Axis Length
  31125. var axisExtent = model.axis.getExtent();
  31126. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31127. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31128. if (barsOnCurrentAxis === undefined) {
  31129. return {
  31130. min: min,
  31131. max: max
  31132. };
  31133. }
  31134. var minOverflow = Infinity;
  31135. each(barsOnCurrentAxis, function (item) {
  31136. minOverflow = Math.min(item.offset, minOverflow);
  31137. });
  31138. var maxOverflow = -Infinity;
  31139. each(barsOnCurrentAxis, function (item) {
  31140. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31141. });
  31142. minOverflow = Math.abs(minOverflow);
  31143. maxOverflow = Math.abs(maxOverflow);
  31144. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31145. var oldRange = max - min;
  31146. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31147. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31148. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31149. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31150. return {
  31151. min: min,
  31152. max: max
  31153. };
  31154. } // Precondition of calling this method:
  31155. // The scale extent has been initailized using series data extent via
  31156. // `scale.setExtent` or `scale.unionExtentFromData`;
  31157. function niceScaleExtent(scale, inModel) {
  31158. var model = inModel;
  31159. var extentInfo = getScaleExtent(scale, model);
  31160. var extent = extentInfo.extent;
  31161. var splitNumber = model.get('splitNumber');
  31162. if (scale instanceof LogScale) {
  31163. scale.base = model.get('logBase');
  31164. }
  31165. var scaleType = scale.type;
  31166. var interval = model.get('interval');
  31167. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31168. scale.setExtent(extent[0], extent[1]);
  31169. scale.calcNiceExtent({
  31170. splitNumber: splitNumber,
  31171. fixMin: extentInfo.fixMin,
  31172. fixMax: extentInfo.fixMax,
  31173. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31174. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31175. }); // If some one specified the min, max. And the default calculated interval
  31176. // is not good enough. He can specify the interval. It is often appeared
  31177. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31178. // to be 60.
  31179. // FIXME
  31180. if (interval != null) {
  31181. scale.setInterval && scale.setInterval(interval);
  31182. }
  31183. }
  31184. /**
  31185. * @param axisType Default retrieve from model.type
  31186. */
  31187. function createScaleByModel(model, axisType) {
  31188. axisType = axisType || model.get('type');
  31189. if (axisType) {
  31190. switch (axisType) {
  31191. // Buildin scale
  31192. case 'category':
  31193. return new OrdinalScale({
  31194. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31195. extent: [Infinity, -Infinity]
  31196. });
  31197. case 'time':
  31198. return new TimeScale({
  31199. locale: model.ecModel.getLocaleModel(),
  31200. useUTC: model.ecModel.get('useUTC')
  31201. });
  31202. default:
  31203. // case 'value'/'interval', 'log', or others.
  31204. return new (Scale.getClass(axisType) || IntervalScale)();
  31205. }
  31206. }
  31207. }
  31208. /**
  31209. * Check if the axis cross 0
  31210. */
  31211. function ifAxisCrossZero(axis) {
  31212. var dataExtent = axis.scale.getExtent();
  31213. var min = dataExtent[0];
  31214. var max = dataExtent[1];
  31215. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31216. }
  31217. /**
  31218. * @param axis
  31219. * @return Label formatter function.
  31220. * param: {number} tickValue,
  31221. * param: {number} idx, the index in all ticks.
  31222. * If category axis, this param is not required.
  31223. * return: {string} label string.
  31224. */
  31225. function makeLabelFormatter(axis) {
  31226. var labelFormatter = axis.getLabelModel().get('formatter');
  31227. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31228. if (axis.scale.type === 'time') {
  31229. return function (tpl) {
  31230. return function (tick, idx) {
  31231. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31232. };
  31233. }(labelFormatter);
  31234. } else if (isString(labelFormatter)) {
  31235. return function (tpl) {
  31236. return function (tick) {
  31237. // For category axis, get raw value; for numeric axis,
  31238. // get formatted label like '1,333,444'.
  31239. var label = axis.scale.getLabel(tick);
  31240. var text = tpl.replace('{value}', label != null ? label : '');
  31241. return text;
  31242. };
  31243. }(labelFormatter);
  31244. } else if (isFunction(labelFormatter)) {
  31245. return function (cb) {
  31246. return function (tick, idx) {
  31247. // The original intention of `idx` is "the index of the tick in all ticks".
  31248. // But the previous implementation of category axis do not consider the
  31249. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31250. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31251. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31252. // the definition here for back compatibility.
  31253. if (categoryTickStart != null) {
  31254. idx = tick.value - categoryTickStart;
  31255. }
  31256. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31257. level: tick.level
  31258. } : null);
  31259. };
  31260. }(labelFormatter);
  31261. } else {
  31262. return function (tick) {
  31263. return axis.scale.getLabel(tick);
  31264. };
  31265. }
  31266. }
  31267. function getAxisRawValue(axis, tick) {
  31268. // In category axis with data zoom, tick is not the original
  31269. // index of axis.data. So tick should not be exposed to user
  31270. // in category axis.
  31271. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31272. }
  31273. /**
  31274. * @param axis
  31275. * @return Be null/undefined if no labels.
  31276. */
  31277. function estimateLabelUnionRect(axis) {
  31278. var axisModel = axis.model;
  31279. var scale = axis.scale;
  31280. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31281. return;
  31282. }
  31283. var realNumberScaleTicks;
  31284. var tickCount;
  31285. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31286. if (scale instanceof OrdinalScale) {
  31287. tickCount = scale.count();
  31288. } else {
  31289. realNumberScaleTicks = scale.getTicks();
  31290. tickCount = realNumberScaleTicks.length;
  31291. }
  31292. var axisLabelModel = axis.getLabelModel();
  31293. var labelFormatter = makeLabelFormatter(axis);
  31294. var rect;
  31295. var step = 1; // Simple optimization for large amount of labels
  31296. if (tickCount > 40) {
  31297. step = Math.ceil(tickCount / 40);
  31298. }
  31299. for (var i = 0; i < tickCount; i += step) {
  31300. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31301. value: categoryScaleExtent[0] + i
  31302. };
  31303. var label = labelFormatter(tick, i);
  31304. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31305. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31306. rect ? rect.union(singleRect) : rect = singleRect;
  31307. }
  31308. return rect;
  31309. }
  31310. function rotateTextRect(textRect, rotate) {
  31311. var rotateRadians = rotate * Math.PI / 180;
  31312. var beforeWidth = textRect.width;
  31313. var beforeHeight = textRect.height;
  31314. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31315. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31316. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31317. return rotatedRect;
  31318. }
  31319. /**
  31320. * @param model axisLabelModel or axisTickModel
  31321. * @return {number|String} Can be null|'auto'|number|function
  31322. */
  31323. function getOptionCategoryInterval(model) {
  31324. var interval = model.get('interval');
  31325. return interval == null ? 'auto' : interval;
  31326. }
  31327. /**
  31328. * Set `categoryInterval` as 0 implicitly indicates that
  31329. * show all labels reguardless of overlap.
  31330. * @param {Object} axis axisModel.axis
  31331. */
  31332. function shouldShowAllLabels(axis) {
  31333. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31334. }
  31335. function getDataDimensionsOnAxis(data, axisDim) {
  31336. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31337. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31338. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31339. // there has been stacked result dim?
  31340. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31341. // For example, the extent of the original dimension
  31342. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31343. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31344. // because there is no graphic corresponding to [0.1, 0.5].
  31345. // See the case in `test/area-stack.html` `main1`, where area line
  31346. // stack needs `yAxis` not start from 0.
  31347. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31348. });
  31349. return keys(dataDimMap);
  31350. }
  31351. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31352. if (data) {
  31353. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31354. var seriesExtent = data.getApproximateExtent(dim);
  31355. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31356. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31357. });
  31358. }
  31359. }
  31360. /*
  31361. * Licensed to the Apache Software Foundation (ASF) under one
  31362. * or more contributor license agreements. See the NOTICE file
  31363. * distributed with this work for additional information
  31364. * regarding copyright ownership. The ASF licenses this file
  31365. * to you under the Apache License, Version 2.0 (the
  31366. * "License"); you may not use this file except in compliance
  31367. * with the License. You may obtain a copy of the License at
  31368. *
  31369. * http://www.apache.org/licenses/LICENSE-2.0
  31370. *
  31371. * Unless required by applicable law or agreed to in writing,
  31372. * software distributed under the License is distributed on an
  31373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31374. * KIND, either express or implied. See the License for the
  31375. * specific language governing permissions and limitations
  31376. * under the License.
  31377. */
  31378. /**
  31379. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31380. */
  31381. /*
  31382. * Licensed to the Apache Software Foundation (ASF) under one
  31383. * or more contributor license agreements. See the NOTICE file
  31384. * distributed with this work for additional information
  31385. * regarding copyright ownership. The ASF licenses this file
  31386. * to you under the Apache License, Version 2.0 (the
  31387. * "License"); you may not use this file except in compliance
  31388. * with the License. You may obtain a copy of the License at
  31389. *
  31390. * http://www.apache.org/licenses/LICENSE-2.0
  31391. *
  31392. * Unless required by applicable law or agreed to in writing,
  31393. * software distributed under the License is distributed on an
  31394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31395. * KIND, either express or implied. See the License for the
  31396. * specific language governing permissions and limitations
  31397. * under the License.
  31398. */
  31399. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31400. var AxisModelCommonMixin =
  31401. /** @class */
  31402. function () {
  31403. function AxisModelCommonMixin() {}
  31404. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31405. var option = this.option;
  31406. return !option.scale;
  31407. };
  31408. /**
  31409. * Should be implemented by each axis model if necessary.
  31410. * @return coordinate system model
  31411. */
  31412. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31413. return;
  31414. };
  31415. return AxisModelCommonMixin;
  31416. }();
  31417. /**
  31418. * Create a muti dimension List structure from seriesModel.
  31419. */
  31420. function createList(seriesModel) {
  31421. return createSeriesData(null, seriesModel);
  31422. } // export function createGraph(seriesModel) {
  31423. var dataStack$1 = {
  31424. isDimensionStacked: isDimensionStacked,
  31425. enableDataStack: enableDataStack,
  31426. getStackedDimension: getStackedDimension
  31427. };
  31428. /**
  31429. * Create scale
  31430. * @param {Array.<number>} dataExtent
  31431. * @param {Object|module:echarts/Model} option If `optoin.type`
  31432. * is secified, it can only be `'value'` currently.
  31433. */
  31434. function createScale(dataExtent, option) {
  31435. var axisModel = option;
  31436. if (!(option instanceof Model)) {
  31437. axisModel = new Model(option); // FIXME
  31438. // Currently AxisModelCommonMixin has nothing to do with the
  31439. // the requirements of `axisHelper.createScaleByModel`. For
  31440. // example the method `getCategories` and `getOrdinalMeta`
  31441. // are required for `'category'` axis, and ecModel are required
  31442. // for `'time'` axis. But occationally echarts-gl happened
  31443. // to only use `'value'` axis.
  31444. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31445. }
  31446. var scale = createScaleByModel(axisModel);
  31447. scale.setExtent(dataExtent[0], dataExtent[1]);
  31448. niceScaleExtent(scale, axisModel);
  31449. return scale;
  31450. }
  31451. /**
  31452. * Mixin common methods to axis model,
  31453. *
  31454. * Inlcude methods
  31455. * `getFormattedLabels() => Array.<string>`
  31456. * `getCategories() => Array.<string>`
  31457. * `getMin(origin: boolean) => number`
  31458. * `getMax(origin: boolean) => number`
  31459. * `getNeedCrossZero() => boolean`
  31460. */
  31461. function mixinAxisModelCommonMethods(Model) {
  31462. mixin(Model, AxisModelCommonMixin);
  31463. }
  31464. function createTextStyle$1(textStyleModel, opts) {
  31465. opts = opts || {};
  31466. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31467. }
  31468. var helper = /*#__PURE__*/Object.freeze({
  31469. __proto__: null,
  31470. createList: createList,
  31471. getLayoutRect: getLayoutRect,
  31472. dataStack: dataStack$1,
  31473. createScale: createScale,
  31474. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31475. getECData: getECData,
  31476. createTextStyle: createTextStyle$1,
  31477. createDimensions: createDimensions,
  31478. createSymbol: createSymbol,
  31479. enableHoverEmphasis: enableHoverEmphasis
  31480. });
  31481. var EPSILON$4 = 1e-8;
  31482. function isAroundEqual$1(a, b) {
  31483. return Math.abs(a - b) < EPSILON$4;
  31484. }
  31485. function contain$2(points, x, y) {
  31486. var w = 0;
  31487. var p = points[0];
  31488. if (!p) {
  31489. return false;
  31490. }
  31491. for (var i = 1; i < points.length; i++) {
  31492. var p2 = points[i];
  31493. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31494. p = p2;
  31495. }
  31496. var p0 = points[0];
  31497. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31498. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31499. }
  31500. return w !== 0;
  31501. }
  31502. var TMP_TRANSFORM = [];
  31503. function transformPoints(points, transform) {
  31504. for (var p = 0; p < points.length; p++) {
  31505. applyTransform(points[p], points[p], transform);
  31506. }
  31507. }
  31508. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31509. for (var i = 0; i < points.length; i++) {
  31510. var p = points[i];
  31511. if (projection) {
  31512. // projection may return null point.
  31513. p = projection.project(p);
  31514. }
  31515. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31516. min(min$1, min$1, p);
  31517. max(max$1, max$1, p);
  31518. }
  31519. }
  31520. }
  31521. function centroid(points) {
  31522. var signedArea = 0;
  31523. var cx = 0;
  31524. var cy = 0;
  31525. var len = points.length;
  31526. var x0 = points[len - 1][0];
  31527. var y0 = points[len - 1][1]; // Polygon should been closed.
  31528. for (var i = 0; i < len; i++) {
  31529. var x1 = points[i][0];
  31530. var y1 = points[i][1];
  31531. var a = x0 * y1 - x1 * y0;
  31532. signedArea += a;
  31533. cx += (x0 + x1) * a;
  31534. cy += (y0 + y1) * a;
  31535. x0 = x1;
  31536. y0 = y1;
  31537. }
  31538. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  31539. }
  31540. var Region =
  31541. /** @class */
  31542. function () {
  31543. function Region(name) {
  31544. this.name = name;
  31545. }
  31546. Region.prototype.setCenter = function (center) {
  31547. this._center = center;
  31548. };
  31549. /**
  31550. * Get center point in data unit. That is,
  31551. * for GeoJSONRegion, the unit is lat/lng,
  31552. * for GeoSVGRegion, the unit is SVG local coord.
  31553. */
  31554. Region.prototype.getCenter = function () {
  31555. var center = this._center;
  31556. if (!center) {
  31557. // In most cases there are no need to calculate this center.
  31558. // So calculate only when called.
  31559. center = this._center = this.calcCenter();
  31560. }
  31561. return center;
  31562. };
  31563. return Region;
  31564. }();
  31565. var GeoJSONPolygonGeometry =
  31566. /** @class */
  31567. function () {
  31568. function GeoJSONPolygonGeometry(exterior, interiors) {
  31569. this.type = 'polygon';
  31570. this.exterior = exterior;
  31571. this.interiors = interiors;
  31572. }
  31573. return GeoJSONPolygonGeometry;
  31574. }();
  31575. var GeoJSONLineStringGeometry =
  31576. /** @class */
  31577. function () {
  31578. function GeoJSONLineStringGeometry(points) {
  31579. this.type = 'linestring';
  31580. this.points = points;
  31581. }
  31582. return GeoJSONLineStringGeometry;
  31583. }();
  31584. var GeoJSONRegion =
  31585. /** @class */
  31586. function (_super) {
  31587. __extends(GeoJSONRegion, _super);
  31588. function GeoJSONRegion(name, geometries, cp) {
  31589. var _this = _super.call(this, name) || this;
  31590. _this.type = 'geoJSON';
  31591. _this.geometries = geometries;
  31592. _this._center = cp && [cp[0], cp[1]];
  31593. return _this;
  31594. }
  31595. GeoJSONRegion.prototype.calcCenter = function () {
  31596. var geometries = this.geometries;
  31597. var largestGeo;
  31598. var largestGeoSize = 0;
  31599. for (var i = 0; i < geometries.length; i++) {
  31600. var geo = geometries[i];
  31601. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  31602. // Ignore linestring
  31603. var size = exterior && exterior.length;
  31604. if (size > largestGeoSize) {
  31605. largestGeo = geo;
  31606. largestGeoSize = size;
  31607. }
  31608. }
  31609. if (largestGeo) {
  31610. return centroid(largestGeo.exterior);
  31611. } // from bounding rect by default.
  31612. var rect = this.getBoundingRect();
  31613. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31614. };
  31615. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  31616. var rect = this._rect; // Always recalculate if using projection.
  31617. if (rect && !projection) {
  31618. return rect;
  31619. }
  31620. var min = [Infinity, Infinity];
  31621. var max = [-Infinity, -Infinity];
  31622. var geometries = this.geometries;
  31623. each(geometries, function (geo) {
  31624. if (geo.type === 'polygon') {
  31625. // Doesn't consider hole
  31626. updateBBoxFromPoints(geo.exterior, min, max, projection);
  31627. } else {
  31628. each(geo.points, function (points) {
  31629. updateBBoxFromPoints(points, min, max, projection);
  31630. });
  31631. }
  31632. }); // Normalie invalid bounding.
  31633. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  31634. min[0] = min[1] = max[0] = max[1] = 0;
  31635. }
  31636. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  31637. if (!projection) {
  31638. this._rect = rect;
  31639. }
  31640. return rect;
  31641. };
  31642. GeoJSONRegion.prototype.contain = function (coord) {
  31643. var rect = this.getBoundingRect();
  31644. var geometries = this.geometries;
  31645. if (!rect.contain(coord[0], coord[1])) {
  31646. return false;
  31647. }
  31648. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  31649. var geo = geometries[i]; // Only support polygon.
  31650. if (geo.type !== 'polygon') {
  31651. continue;
  31652. }
  31653. var exterior = geo.exterior;
  31654. var interiors = geo.interiors;
  31655. if (contain$2(exterior, coord[0], coord[1])) {
  31656. // Not in the region if point is in the hole.
  31657. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31658. if (contain$2(interiors[k], coord[0], coord[1])) {
  31659. continue loopGeo;
  31660. }
  31661. }
  31662. return true;
  31663. }
  31664. }
  31665. return false;
  31666. };
  31667. /**
  31668. * Transform the raw coords to target bounding.
  31669. * @param x
  31670. * @param y
  31671. * @param width
  31672. * @param height
  31673. */
  31674. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  31675. var rect = this.getBoundingRect();
  31676. var aspect = rect.width / rect.height;
  31677. if (!width) {
  31678. width = aspect * height;
  31679. } else if (!height) {
  31680. height = width / aspect;
  31681. }
  31682. var target = new BoundingRect(x, y, width, height);
  31683. var transform = rect.calculateTransform(target);
  31684. var geometries = this.geometries;
  31685. for (var i = 0; i < geometries.length; i++) {
  31686. var geo = geometries[i];
  31687. if (geo.type === 'polygon') {
  31688. transformPoints(geo.exterior, transform);
  31689. each(geo.interiors, function (interior) {
  31690. transformPoints(interior, transform);
  31691. });
  31692. } else {
  31693. each(geo.points, function (points) {
  31694. transformPoints(points, transform);
  31695. });
  31696. }
  31697. }
  31698. rect = this._rect;
  31699. rect.copy(target); // Update center
  31700. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31701. };
  31702. GeoJSONRegion.prototype.cloneShallow = function (name) {
  31703. name == null && (name = this.name);
  31704. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  31705. newRegion._rect = this._rect;
  31706. newRegion.transformTo = null; // Simply avoid to be called.
  31707. return newRegion;
  31708. };
  31709. return GeoJSONRegion;
  31710. }(Region);
  31711. var GeoSVGRegion =
  31712. /** @class */
  31713. function (_super) {
  31714. __extends(GeoSVGRegion, _super);
  31715. function GeoSVGRegion(name, elOnlyForCalculate) {
  31716. var _this = _super.call(this, name) || this;
  31717. _this.type = 'geoSVG';
  31718. _this._elOnlyForCalculate = elOnlyForCalculate;
  31719. return _this;
  31720. }
  31721. GeoSVGRegion.prototype.calcCenter = function () {
  31722. var el = this._elOnlyForCalculate;
  31723. var rect = el.getBoundingRect();
  31724. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31725. var mat = identity(TMP_TRANSFORM);
  31726. var target = el;
  31727. while (target && !target.isGeoSVGGraphicRoot) {
  31728. mul$1(mat, target.getLocalTransform(), mat);
  31729. target = target.parent;
  31730. }
  31731. invert(mat, mat);
  31732. applyTransform(center, center, mat);
  31733. return center;
  31734. };
  31735. return GeoSVGRegion;
  31736. }(Region);
  31737. function decode(json) {
  31738. if (!json.UTF8Encoding) {
  31739. return json;
  31740. }
  31741. var jsonCompressed = json;
  31742. var encodeScale = jsonCompressed.UTF8Scale;
  31743. if (encodeScale == null) {
  31744. encodeScale = 1024;
  31745. }
  31746. var features = jsonCompressed.features;
  31747. each(features, function (feature) {
  31748. var geometry = feature.geometry;
  31749. var encodeOffsets = geometry.encodeOffsets;
  31750. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  31751. // In this case this geometry is usually not encoded.
  31752. if (!encodeOffsets) {
  31753. return;
  31754. }
  31755. switch (geometry.type) {
  31756. case 'LineString':
  31757. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  31758. break;
  31759. case 'Polygon':
  31760. decodeRings(coordinates, encodeOffsets, encodeScale);
  31761. break;
  31762. case 'MultiLineString':
  31763. decodeRings(coordinates, encodeOffsets, encodeScale);
  31764. break;
  31765. case 'MultiPolygon':
  31766. each(coordinates, function (rings, idx) {
  31767. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  31768. });
  31769. }
  31770. }); // Has been decoded
  31771. jsonCompressed.UTF8Encoding = false;
  31772. return jsonCompressed;
  31773. }
  31774. function decodeRings(rings, encodeOffsets, encodeScale) {
  31775. for (var c = 0; c < rings.length; c++) {
  31776. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  31777. }
  31778. }
  31779. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  31780. var result = [];
  31781. var prevX = encodeOffsets[0];
  31782. var prevY = encodeOffsets[1];
  31783. for (var i = 0; i < coordinate.length; i += 2) {
  31784. var x = coordinate.charCodeAt(i) - 64;
  31785. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  31786. x = x >> 1 ^ -(x & 1);
  31787. y = y >> 1 ^ -(y & 1); // Delta deocding
  31788. x += prevX;
  31789. y += prevY;
  31790. prevX = x;
  31791. prevY = y; // Dequantize
  31792. result.push([x / encodeScale, y / encodeScale]);
  31793. }
  31794. return result;
  31795. }
  31796. function parseGeoJSON(geoJson, nameProperty) {
  31797. geoJson = decode(geoJson);
  31798. return map(filter(geoJson.features, function (featureObj) {
  31799. // Output of mapshaper may have geometry null
  31800. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  31801. }), function (featureObj) {
  31802. var properties = featureObj.properties;
  31803. var geo = featureObj.geometry;
  31804. var geometries = [];
  31805. switch (geo.type) {
  31806. case 'Polygon':
  31807. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  31808. // First must be exterior, and the rest are all interior(holes).
  31809. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  31810. break;
  31811. case 'MultiPolygon':
  31812. each(geo.coordinates, function (item) {
  31813. if (item[0]) {
  31814. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  31815. }
  31816. });
  31817. break;
  31818. case 'LineString':
  31819. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  31820. break;
  31821. case 'MultiLineString':
  31822. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  31823. }
  31824. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  31825. region.properties = properties;
  31826. return region;
  31827. });
  31828. }
  31829. var number = /*#__PURE__*/Object.freeze({
  31830. __proto__: null,
  31831. linearMap: linearMap,
  31832. round: round,
  31833. asc: asc,
  31834. getPrecision: getPrecision,
  31835. getPrecisionSafe: getPrecisionSafe,
  31836. getPixelPrecision: getPixelPrecision,
  31837. getPercentWithPrecision: getPercentWithPrecision,
  31838. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  31839. remRadian: remRadian,
  31840. isRadianAroundZero: isRadianAroundZero,
  31841. parseDate: parseDate,
  31842. quantity: quantity,
  31843. quantityExponent: quantityExponent,
  31844. nice: nice,
  31845. quantile: quantile,
  31846. reformIntervals: reformIntervals,
  31847. isNumeric: isNumeric,
  31848. numericToNumber: numericToNumber
  31849. });
  31850. var time = /*#__PURE__*/Object.freeze({
  31851. __proto__: null,
  31852. parse: parseDate,
  31853. format: format
  31854. });
  31855. var graphic$1 = /*#__PURE__*/Object.freeze({
  31856. __proto__: null,
  31857. extendShape: extendShape,
  31858. extendPath: extendPath,
  31859. makePath: makePath,
  31860. makeImage: makeImage,
  31861. mergePath: mergePath$1,
  31862. resizePath: resizePath,
  31863. createIcon: createIcon,
  31864. updateProps: updateProps,
  31865. initProps: initProps,
  31866. getTransform: getTransform,
  31867. clipPointsByRect: clipPointsByRect,
  31868. clipRectByRect: clipRectByRect,
  31869. registerShape: registerShape,
  31870. getShapeClass: getShapeClass,
  31871. Group: Group,
  31872. Image: ZRImage,
  31873. Text: ZRText,
  31874. Circle: Circle,
  31875. Ellipse: Ellipse,
  31876. Sector: Sector,
  31877. Ring: Ring,
  31878. Polygon: Polygon,
  31879. Polyline: Polyline,
  31880. Rect: Rect,
  31881. Line: Line,
  31882. BezierCurve: BezierCurve,
  31883. Arc: Arc,
  31884. IncrementalDisplayable: IncrementalDisplayable,
  31885. CompoundPath: CompoundPath,
  31886. LinearGradient: LinearGradient,
  31887. RadialGradient: RadialGradient,
  31888. BoundingRect: BoundingRect
  31889. });
  31890. var format$1 = /*#__PURE__*/Object.freeze({
  31891. __proto__: null,
  31892. addCommas: addCommas,
  31893. toCamelCase: toCamelCase,
  31894. normalizeCssArray: normalizeCssArray$1,
  31895. encodeHTML: encodeHTML,
  31896. formatTpl: formatTpl,
  31897. getTooltipMarker: getTooltipMarker,
  31898. formatTime: formatTime,
  31899. capitalFirst: capitalFirst,
  31900. truncateText: truncateText,
  31901. getTextRect: getTextRect
  31902. });
  31903. var util$1 = /*#__PURE__*/Object.freeze({
  31904. __proto__: null,
  31905. map: map,
  31906. each: each,
  31907. indexOf: indexOf,
  31908. inherits: inherits,
  31909. reduce: reduce,
  31910. filter: filter,
  31911. bind: bind,
  31912. curry: curry,
  31913. isArray: isArray,
  31914. isString: isString,
  31915. isObject: isObject,
  31916. isFunction: isFunction,
  31917. extend: extend,
  31918. defaults: defaults,
  31919. clone: clone,
  31920. merge: merge
  31921. });
  31922. var inner$5 = makeInner();
  31923. function createAxisLabels(axis) {
  31924. // Only ordinal scale support tick interval
  31925. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  31926. }
  31927. /**
  31928. * @param {module:echats/coord/Axis} axis
  31929. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31930. * @return {Object} {
  31931. * ticks: Array.<number>
  31932. * tickCategoryInterval: number
  31933. * }
  31934. */
  31935. function createAxisTicks(axis, tickModel) {
  31936. // Only ordinal scale support tick interval
  31937. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  31938. ticks: map(axis.scale.getTicks(), function (tick) {
  31939. return tick.value;
  31940. })
  31941. };
  31942. }
  31943. function makeCategoryLabels(axis) {
  31944. var labelModel = axis.getLabelModel();
  31945. var result = makeCategoryLabelsActually(axis, labelModel);
  31946. return !labelModel.get('show') || axis.scale.isBlank() ? {
  31947. labels: [],
  31948. labelCategoryInterval: result.labelCategoryInterval
  31949. } : result;
  31950. }
  31951. function makeCategoryLabelsActually(axis, labelModel) {
  31952. var labelsCache = getListCache(axis, 'labels');
  31953. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31954. var result = listCacheGet(labelsCache, optionLabelInterval);
  31955. if (result) {
  31956. return result;
  31957. }
  31958. var labels;
  31959. var numericLabelInterval;
  31960. if (isFunction(optionLabelInterval)) {
  31961. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31962. } else {
  31963. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31964. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31965. } // Cache to avoid calling interval function repeatly.
  31966. return listCacheSet(labelsCache, optionLabelInterval, {
  31967. labels: labels,
  31968. labelCategoryInterval: numericLabelInterval
  31969. });
  31970. }
  31971. function makeCategoryTicks(axis, tickModel) {
  31972. var ticksCache = getListCache(axis, 'ticks');
  31973. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31974. var result = listCacheGet(ticksCache, optionTickInterval);
  31975. if (result) {
  31976. return result;
  31977. }
  31978. var ticks;
  31979. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  31980. // we should not return all ticks.
  31981. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31982. ticks = [];
  31983. }
  31984. if (isFunction(optionTickInterval)) {
  31985. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31986. } // Always use label interval by default despite label show. Consider this
  31987. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31988. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31989. else if (optionTickInterval === 'auto') {
  31990. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31991. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31992. ticks = map(labelsResult.labels, function (labelItem) {
  31993. return labelItem.tickValue;
  31994. });
  31995. } else {
  31996. tickCategoryInterval = optionTickInterval;
  31997. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31998. } // Cache to avoid calling interval function repeatly.
  31999. return listCacheSet(ticksCache, optionTickInterval, {
  32000. ticks: ticks,
  32001. tickCategoryInterval: tickCategoryInterval
  32002. });
  32003. }
  32004. function makeRealNumberLabels(axis) {
  32005. var ticks = axis.scale.getTicks();
  32006. var labelFormatter = makeLabelFormatter(axis);
  32007. return {
  32008. labels: map(ticks, function (tick, idx) {
  32009. return {
  32010. level: tick.level,
  32011. formattedLabel: labelFormatter(tick, idx),
  32012. rawLabel: axis.scale.getLabel(tick),
  32013. tickValue: tick.value
  32014. };
  32015. })
  32016. };
  32017. }
  32018. function getListCache(axis, prop) {
  32019. // Because key can be funciton, and cache size always be small, we use array cache.
  32020. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32021. }
  32022. function listCacheGet(cache, key) {
  32023. for (var i = 0; i < cache.length; i++) {
  32024. if (cache[i].key === key) {
  32025. return cache[i].value;
  32026. }
  32027. }
  32028. }
  32029. function listCacheSet(cache, key, value) {
  32030. cache.push({
  32031. key: key,
  32032. value: value
  32033. });
  32034. return value;
  32035. }
  32036. function makeAutoCategoryInterval(axis) {
  32037. var result = inner$5(axis).autoInterval;
  32038. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32039. }
  32040. /**
  32041. * Calculate interval for category axis ticks and labels.
  32042. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32043. * should be implemented in axis.
  32044. */
  32045. function calculateCategoryInterval(axis) {
  32046. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32047. var labelFormatter = makeLabelFormatter(axis);
  32048. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32049. var ordinalScale = axis.scale;
  32050. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  32051. // avoid generating a long array by `getTicks`
  32052. // in large category data case.
  32053. var tickCount = ordinalScale.count();
  32054. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32055. return 0;
  32056. }
  32057. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  32058. if (tickCount > 40) {
  32059. step = Math.max(1, Math.floor(tickCount / 40));
  32060. }
  32061. var tickValue = ordinalExtent[0];
  32062. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32063. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32064. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32065. var maxW = 0;
  32066. var maxH = 0; // Caution: Performance sensitive for large category data.
  32067. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32068. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32069. var width = 0;
  32070. var height = 0; // Not precise, do not consider align and vertical align
  32071. // and each distance from axis line yet.
  32072. var rect = getBoundingRect(labelFormatter({
  32073. value: tickValue
  32074. }), params.font, 'center', 'top'); // Magic number
  32075. width = rect.width * 1.3;
  32076. height = rect.height * 1.3; // Min size, void long loop.
  32077. maxW = Math.max(maxW, width, 7);
  32078. maxH = Math.max(maxH, height, 7);
  32079. }
  32080. var dw = maxW / unitW;
  32081. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  32082. isNaN(dw) && (dw = Infinity);
  32083. isNaN(dh) && (dh = Infinity);
  32084. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32085. var cache = inner$5(axis.model);
  32086. var axisExtent = axis.getExtent();
  32087. var lastAutoInterval = cache.lastAutoInterval;
  32088. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  32089. // otherwise the calculated interval might jitter when the zoom
  32090. // window size is close to the interval-changing size.
  32091. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32092. // The jitter will cause that sometimes the displayed labels are
  32093. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32094. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  32095. // point is not the same when zooming in or zooming out.
  32096. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  32097. // be used. Otherwise some hiden labels might not be shown again.
  32098. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32099. interval = lastAutoInterval;
  32100. } // Only update cache if cache not used, otherwise the
  32101. // changing of interval is too insensitive.
  32102. else {
  32103. cache.lastTickCount = tickCount;
  32104. cache.lastAutoInterval = interval;
  32105. cache.axisExtent0 = axisExtent[0];
  32106. cache.axisExtent1 = axisExtent[1];
  32107. }
  32108. return interval;
  32109. }
  32110. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32111. var labelModel = axis.getLabelModel();
  32112. return {
  32113. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32114. labelRotate: labelModel.get('rotate') || 0,
  32115. font: labelModel.getFont()
  32116. };
  32117. }
  32118. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32119. var labelFormatter = makeLabelFormatter(axis);
  32120. var ordinalScale = axis.scale;
  32121. var ordinalExtent = ordinalScale.getExtent();
  32122. var labelModel = axis.getLabelModel();
  32123. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32124. var step = Math.max((categoryInterval || 0) + 1, 1);
  32125. var startTick = ordinalExtent[0];
  32126. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32127. // while zooming and moving while interval > 0. Otherwise the selection
  32128. // of displayable ticks and symbols probably keep changing.
  32129. // 3 is empirical value.
  32130. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32131. startTick = Math.round(Math.ceil(startTick / step) * step);
  32132. } // (1) Only add min max label here but leave overlap checking
  32133. // to render stage, which also ensure the returned list
  32134. // suitable for splitLine and splitArea rendering.
  32135. // (2) Scales except category always contain min max label so
  32136. // do not need to perform this process.
  32137. var showAllLabel = shouldShowAllLabels(axis);
  32138. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32139. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32140. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32141. addItem(ordinalExtent[0]);
  32142. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32143. var tickValue = startTick;
  32144. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32145. addItem(tickValue);
  32146. }
  32147. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32148. addItem(ordinalExtent[1]);
  32149. }
  32150. function addItem(tickValue) {
  32151. var tickObj = {
  32152. value: tickValue
  32153. };
  32154. result.push(onlyTick ? tickValue : {
  32155. formattedLabel: labelFormatter(tickObj),
  32156. rawLabel: ordinalScale.getLabel(tickObj),
  32157. tickValue: tickValue
  32158. });
  32159. }
  32160. return result;
  32161. }
  32162. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32163. var ordinalScale = axis.scale;
  32164. var labelFormatter = makeLabelFormatter(axis);
  32165. var result = [];
  32166. each(ordinalScale.getTicks(), function (tick) {
  32167. var rawLabel = ordinalScale.getLabel(tick);
  32168. var tickValue = tick.value;
  32169. if (categoryInterval(tick.value, rawLabel)) {
  32170. result.push(onlyTick ? tickValue : {
  32171. formattedLabel: labelFormatter(tick),
  32172. rawLabel: rawLabel,
  32173. tickValue: tickValue
  32174. });
  32175. }
  32176. });
  32177. return result;
  32178. }
  32179. var NORMALIZED_EXTENT = [0, 1];
  32180. /**
  32181. * Base class of Axis.
  32182. */
  32183. var Axis =
  32184. /** @class */
  32185. function () {
  32186. function Axis(dim, scale, extent) {
  32187. this.onBand = false;
  32188. this.inverse = false;
  32189. this.dim = dim;
  32190. this.scale = scale;
  32191. this._extent = extent || [0, 0];
  32192. }
  32193. /**
  32194. * If axis extent contain given coord
  32195. */
  32196. Axis.prototype.contain = function (coord) {
  32197. var extent = this._extent;
  32198. var min = Math.min(extent[0], extent[1]);
  32199. var max = Math.max(extent[0], extent[1]);
  32200. return coord >= min && coord <= max;
  32201. };
  32202. /**
  32203. * If axis extent contain given data
  32204. */
  32205. Axis.prototype.containData = function (data) {
  32206. return this.scale.contain(data);
  32207. };
  32208. /**
  32209. * Get coord extent.
  32210. */
  32211. Axis.prototype.getExtent = function () {
  32212. return this._extent.slice();
  32213. };
  32214. /**
  32215. * Get precision used for formatting
  32216. */
  32217. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32218. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32219. };
  32220. /**
  32221. * Set coord extent
  32222. */
  32223. Axis.prototype.setExtent = function (start, end) {
  32224. var extent = this._extent;
  32225. extent[0] = start;
  32226. extent[1] = end;
  32227. };
  32228. /**
  32229. * Convert data to coord. Data is the rank if it has an ordinal scale
  32230. */
  32231. Axis.prototype.dataToCoord = function (data, clamp) {
  32232. var extent = this._extent;
  32233. var scale = this.scale;
  32234. data = scale.normalize(data);
  32235. if (this.onBand && scale.type === 'ordinal') {
  32236. extent = extent.slice();
  32237. fixExtentWithBands(extent, scale.count());
  32238. }
  32239. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32240. };
  32241. /**
  32242. * Convert coord to data. Data is the rank if it has an ordinal scale
  32243. */
  32244. Axis.prototype.coordToData = function (coord, clamp) {
  32245. var extent = this._extent;
  32246. var scale = this.scale;
  32247. if (this.onBand && scale.type === 'ordinal') {
  32248. extent = extent.slice();
  32249. fixExtentWithBands(extent, scale.count());
  32250. }
  32251. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32252. return this.scale.scale(t);
  32253. };
  32254. /**
  32255. * Convert pixel point to data in axis
  32256. */
  32257. Axis.prototype.pointToData = function (point, clamp) {
  32258. // Should be implemented in derived class if necessary.
  32259. return;
  32260. };
  32261. /**
  32262. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32263. * `axis.getTicksCoords` considers `onBand`, which is used by
  32264. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32265. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32266. * @param opt.clamp If `true`, the first and the last
  32267. * tick must be at the axis end points. Otherwise, clip ticks
  32268. * that outside the axis extent.
  32269. */
  32270. Axis.prototype.getTicksCoords = function (opt) {
  32271. opt = opt || {};
  32272. var tickModel = opt.tickModel || this.getTickModel();
  32273. var result = createAxisTicks(this, tickModel);
  32274. var ticks = result.ticks;
  32275. var ticksCoords = map(ticks, function (tickVal) {
  32276. return {
  32277. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32278. tickValue: tickVal
  32279. };
  32280. }, this);
  32281. var alignWithLabel = tickModel.get('alignWithLabel');
  32282. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32283. return ticksCoords;
  32284. };
  32285. Axis.prototype.getMinorTicksCoords = function () {
  32286. if (this.scale.type === 'ordinal') {
  32287. // Category axis doesn't support minor ticks
  32288. return [];
  32289. }
  32290. var minorTickModel = this.model.getModel('minorTick');
  32291. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32292. if (!(splitNumber > 0 && splitNumber < 100)) {
  32293. splitNumber = 5;
  32294. }
  32295. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32296. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32297. return map(minorTicksGroup, function (minorTick) {
  32298. return {
  32299. coord: this.dataToCoord(minorTick),
  32300. tickValue: minorTick
  32301. };
  32302. }, this);
  32303. }, this);
  32304. return minorTicksCoords;
  32305. };
  32306. Axis.prototype.getViewLabels = function () {
  32307. return createAxisLabels(this).labels;
  32308. };
  32309. Axis.prototype.getLabelModel = function () {
  32310. return this.model.getModel('axisLabel');
  32311. };
  32312. /**
  32313. * Notice here we only get the default tick model. For splitLine
  32314. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32315. * manually when calling `getTicksCoords`.
  32316. * In GL, this method may be overrided to:
  32317. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32318. */
  32319. Axis.prototype.getTickModel = function () {
  32320. return this.model.getModel('axisTick');
  32321. };
  32322. /**
  32323. * Get width of band
  32324. */
  32325. Axis.prototype.getBandWidth = function () {
  32326. var axisExtent = this._extent;
  32327. var dataExtent = this.scale.getExtent();
  32328. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32329. len === 0 && (len = 1);
  32330. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32331. return Math.abs(size) / len;
  32332. };
  32333. /**
  32334. * Only be called in category axis.
  32335. * Can be overrided, consider other axes like in 3D.
  32336. * @return Auto interval for cateogry axis tick and label
  32337. */
  32338. Axis.prototype.calculateCategoryInterval = function () {
  32339. return calculateCategoryInterval(this);
  32340. };
  32341. return Axis;
  32342. }();
  32343. function fixExtentWithBands(extent, nTick) {
  32344. var size = extent[1] - extent[0];
  32345. var len = nTick;
  32346. var margin = size / len / 2;
  32347. extent[0] += margin;
  32348. extent[1] -= margin;
  32349. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32350. // |---1---|---2---|---3---|---4---|.
  32351. // So the displayed ticks and splitLine/splitArea should between
  32352. // each data item, otherwise cause misleading (e.g., split tow bars
  32353. // of a single data item when there are two bar series).
  32354. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32355. // splitLine/spliteArea should layout appropriately corresponding
  32356. // to displayed labels. (So we should not use `getBandWidth` in this
  32357. // case).
  32358. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32359. var ticksLen = ticksCoords.length;
  32360. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32361. return;
  32362. }
  32363. var axisExtent = axis.getExtent();
  32364. var last;
  32365. var diffSize;
  32366. if (ticksLen === 1) {
  32367. ticksCoords[0].coord = axisExtent[0];
  32368. last = ticksCoords[1] = {
  32369. coord: axisExtent[0]
  32370. };
  32371. } else {
  32372. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32373. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32374. each(ticksCoords, function (ticksItem) {
  32375. ticksItem.coord -= shift_1 / 2;
  32376. });
  32377. var dataExtent = axis.scale.getExtent();
  32378. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32379. last = {
  32380. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32381. };
  32382. ticksCoords.push(last);
  32383. }
  32384. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32385. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32386. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32387. }
  32388. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32389. ticksCoords.unshift({
  32390. coord: axisExtent[0]
  32391. });
  32392. }
  32393. if (littleThan(axisExtent[1], last.coord)) {
  32394. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32395. }
  32396. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32397. ticksCoords.push({
  32398. coord: axisExtent[1]
  32399. });
  32400. }
  32401. function littleThan(a, b) {
  32402. // Avoid rounding error cause calculated tick coord different with extent.
  32403. // It may cause an extra unecessary tick added.
  32404. a = round(a);
  32405. b = round(b);
  32406. return inverse ? a > b : a < b;
  32407. }
  32408. }
  32409. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32410. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32411. // class Bar3DModel extends ComponentModel {}
  32412. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  32413. // echarts.use(install);
  32414. function extendComponentModel(proto) {
  32415. var Model = ComponentModel.extend(proto);
  32416. ComponentModel.registerClass(Model);
  32417. return Model;
  32418. }
  32419. function extendComponentView(proto) {
  32420. var View = ComponentView.extend(proto);
  32421. ComponentView.registerClass(View);
  32422. return View;
  32423. }
  32424. function extendSeriesModel(proto) {
  32425. var Model = SeriesModel.extend(proto);
  32426. SeriesModel.registerClass(Model);
  32427. return Model;
  32428. }
  32429. function extendChartView(proto) {
  32430. var View = ChartView.extend(proto);
  32431. ChartView.registerClass(View);
  32432. return View;
  32433. }
  32434. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32435. var dx = x - x1;
  32436. var dy = y - y1;
  32437. var dx1 = x2 - x1;
  32438. var dy1 = y2 - y1;
  32439. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32440. dx1 /= lineLen;
  32441. dy1 /= lineLen; // dot product
  32442. var projectedLen = dx * dx1 + dy * dy1;
  32443. var t = projectedLen / lineLen;
  32444. if (limitToEnds) {
  32445. t = Math.min(Math.max(t, 0), 1);
  32446. }
  32447. t *= lineLen;
  32448. var ox = out[0] = x1 + t * dx1;
  32449. var oy = out[1] = y1 + t * dy1;
  32450. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32451. }
  32452. var pt0 = new Point();
  32453. var pt1 = new Point();
  32454. var pt2 = new Point();
  32455. var dir = new Point();
  32456. var dir2 = new Point();
  32457. var tmpArr = [];
  32458. var tmpProjPoint = new Point();
  32459. /**
  32460. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  32461. * @param linePoints
  32462. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  32463. */
  32464. function limitTurnAngle(linePoints, minTurnAngle) {
  32465. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  32466. return;
  32467. }
  32468. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  32469. // /pt1----pt2 (label)
  32470. // /
  32471. // pt0/
  32472. pt0.fromArray(linePoints[0]);
  32473. pt1.fromArray(linePoints[1]);
  32474. pt2.fromArray(linePoints[2]);
  32475. Point.sub(dir, pt0, pt1);
  32476. Point.sub(dir2, pt2, pt1);
  32477. var len1 = dir.len();
  32478. var len2 = dir2.len();
  32479. if (len1 < 1e-3 || len2 < 1e-3) {
  32480. return;
  32481. }
  32482. dir.scale(1 / len1);
  32483. dir2.scale(1 / len2);
  32484. var angleCos = dir.dot(dir2);
  32485. var minTurnAngleCos = Math.cos(minTurnAngle);
  32486. if (minTurnAngleCos < angleCos) {
  32487. // Smaller than minTurnAngle
  32488. // Calculate project point of pt0 on pt1-pt2
  32489. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32490. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  32491. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  32492. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32493. if (isNaN(t)) {
  32494. return;
  32495. }
  32496. if (t < 0) {
  32497. Point.copy(tmpProjPoint, pt1);
  32498. } else if (t > 1) {
  32499. Point.copy(tmpProjPoint, pt2);
  32500. }
  32501. tmpProjPoint.toArray(linePoints[1]);
  32502. }
  32503. }
  32504. /**
  32505. * Limit the angle of line and the surface
  32506. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  32507. */
  32508. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  32509. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  32510. return;
  32511. }
  32512. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  32513. pt0.fromArray(linePoints[0]);
  32514. pt1.fromArray(linePoints[1]);
  32515. pt2.fromArray(linePoints[2]);
  32516. Point.sub(dir, pt1, pt0);
  32517. Point.sub(dir2, pt2, pt1);
  32518. var len1 = dir.len();
  32519. var len2 = dir2.len();
  32520. if (len1 < 1e-3 || len2 < 1e-3) {
  32521. return;
  32522. }
  32523. dir.scale(1 / len1);
  32524. dir2.scale(1 / len2);
  32525. var angleCos = dir.dot(surfaceNormal);
  32526. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  32527. if (angleCos < maxSurfaceAngleCos) {
  32528. // Calculate project point of pt0 on pt1-pt2
  32529. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  32530. tmpProjPoint.fromArray(tmpArr);
  32531. var HALF_PI = Math.PI / 2;
  32532. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  32533. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  32534. if (newAngle >= HALF_PI) {
  32535. // parallel
  32536. Point.copy(tmpProjPoint, pt2);
  32537. } else {
  32538. // Calculate new projected length with limited minTurnAngle and get the new connect point
  32539. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  32540. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  32541. if (isNaN(t)) {
  32542. return;
  32543. }
  32544. if (t < 0) {
  32545. Point.copy(tmpProjPoint, pt1);
  32546. } else if (t > 1) {
  32547. Point.copy(tmpProjPoint, pt2);
  32548. }
  32549. }
  32550. tmpProjPoint.toArray(linePoints[1]);
  32551. }
  32552. }
  32553. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  32554. var isNormal = stateName === 'normal';
  32555. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  32556. stateObj.ignore = ignore; // Set smooth
  32557. var smooth = stateModel.get('smooth');
  32558. if (smooth && smooth === true) {
  32559. smooth = 0.3;
  32560. }
  32561. stateObj.shape = stateObj.shape || {};
  32562. if (smooth > 0) {
  32563. stateObj.shape.smooth = smooth;
  32564. }
  32565. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  32566. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  32567. }
  32568. function buildLabelLinePath(path, shape) {
  32569. var smooth = shape.smooth;
  32570. var points = shape.points;
  32571. if (!points) {
  32572. return;
  32573. }
  32574. path.moveTo(points[0][0], points[0][1]);
  32575. if (smooth > 0 && points.length >= 3) {
  32576. var len1 = dist(points[0], points[1]);
  32577. var len2 = dist(points[1], points[2]);
  32578. if (!len1 || !len2) {
  32579. path.lineTo(points[1][0], points[1][1]);
  32580. path.lineTo(points[2][0], points[2][1]);
  32581. return;
  32582. }
  32583. var moveLen = Math.min(len1, len2) * smooth;
  32584. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  32585. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  32586. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  32587. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  32588. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  32589. } else {
  32590. for (var i = 1; i < points.length; i++) {
  32591. path.lineTo(points[i][0], points[i][1]);
  32592. }
  32593. }
  32594. }
  32595. /**
  32596. * Create a label line if necessary and set it's style.
  32597. */
  32598. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  32599. var labelLine = targetEl.getTextGuideLine();
  32600. var label = targetEl.getTextContent();
  32601. if (!label) {
  32602. // Not show label line if there is no label.
  32603. if (labelLine) {
  32604. targetEl.removeTextGuideLine();
  32605. }
  32606. return;
  32607. }
  32608. var normalModel = statesModels.normal;
  32609. var showNormal = normalModel.get('show');
  32610. var labelIgnoreNormal = label.ignore;
  32611. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  32612. var stateName = DISPLAY_STATES[i];
  32613. var stateModel = statesModels[stateName];
  32614. var isNormal = stateName === 'normal';
  32615. if (stateModel) {
  32616. var stateShow = stateModel.get('show');
  32617. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  32618. if (isLabelIgnored // Not show when label is not shown in this state.
  32619. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  32620. ) {
  32621. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  32622. if (stateObj) {
  32623. stateObj.ignore = true;
  32624. }
  32625. continue;
  32626. } // Create labelLine if not exists
  32627. if (!labelLine) {
  32628. labelLine = new Polyline();
  32629. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  32630. // NOTE: NORMAL should always been the first!
  32631. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  32632. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  32633. } // Use same state proxy.
  32634. if (targetEl.stateProxy) {
  32635. labelLine.stateProxy = targetEl.stateProxy;
  32636. }
  32637. }
  32638. setLabelLineState(labelLine, false, stateName, stateModel);
  32639. }
  32640. }
  32641. if (labelLine) {
  32642. defaults(labelLine.style, defaultStyle); // Not fill.
  32643. labelLine.style.fill = null;
  32644. var showAbove = normalModel.get('showAbove');
  32645. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  32646. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  32647. labelLine.buildPath = buildLabelLinePath;
  32648. }
  32649. }
  32650. function getLabelLineStatesModels(itemModel, labelLineName) {
  32651. labelLineName = labelLineName || 'labelLine';
  32652. var statesModels = {
  32653. normal: itemModel.getModel(labelLineName)
  32654. };
  32655. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  32656. var stateName = SPECIAL_STATES[i];
  32657. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  32658. }
  32659. return statesModels;
  32660. }
  32661. function prepareLayoutList(input) {
  32662. var list = [];
  32663. for (var i = 0; i < input.length; i++) {
  32664. var rawItem = input[i];
  32665. if (rawItem.defaultAttr.ignore) {
  32666. continue;
  32667. }
  32668. var label = rawItem.label;
  32669. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  32670. var localRect = label.getBoundingRect();
  32671. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  32672. var minMargin = label.style.margin || 0;
  32673. var globalRect = localRect.clone();
  32674. globalRect.applyTransform(transform);
  32675. globalRect.x -= minMargin / 2;
  32676. globalRect.y -= minMargin / 2;
  32677. globalRect.width += minMargin;
  32678. globalRect.height += minMargin;
  32679. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  32680. list.push({
  32681. label: label,
  32682. labelLine: rawItem.labelLine,
  32683. rect: globalRect,
  32684. localRect: localRect,
  32685. obb: obb,
  32686. priority: rawItem.priority,
  32687. defaultAttr: rawItem.defaultAttr,
  32688. layoutOption: rawItem.computedLayoutOption,
  32689. axisAligned: isAxisAligned,
  32690. transform: transform
  32691. });
  32692. }
  32693. return list;
  32694. }
  32695. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  32696. var len = list.length;
  32697. if (len < 2) {
  32698. return;
  32699. }
  32700. list.sort(function (a, b) {
  32701. return a.rect[xyDim] - b.rect[xyDim];
  32702. });
  32703. var lastPos = 0;
  32704. var delta;
  32705. var adjusted = false;
  32706. var totalShifts = 0;
  32707. for (var i = 0; i < len; i++) {
  32708. var item = list[i];
  32709. var rect = item.rect;
  32710. delta = rect[xyDim] - lastPos;
  32711. if (delta < 0) {
  32712. // shiftForward(i, len, -delta);
  32713. rect[xyDim] -= delta;
  32714. item.label[xyDim] -= delta;
  32715. adjusted = true;
  32716. }
  32717. var shift = Math.max(-delta, 0);
  32718. totalShifts += shift;
  32719. lastPos = rect[xyDim] + rect[sizeDim];
  32720. }
  32721. if (totalShifts > 0 && balanceShift) {
  32722. // Shift back to make the distribution more equally.
  32723. shiftList(-totalShifts / len, 0, len);
  32724. } // TODO bleedMargin?
  32725. var first = list[0];
  32726. var last = list[len - 1];
  32727. var minGap;
  32728. var maxGap;
  32729. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  32730. minGap < 0 && squeezeGaps(-minGap, 0.8);
  32731. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  32732. updateMinMaxGap();
  32733. takeBoundsGap(minGap, maxGap, 1);
  32734. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  32735. updateMinMaxGap();
  32736. if (minGap < 0) {
  32737. squeezeWhenBailout(-minGap);
  32738. }
  32739. if (maxGap < 0) {
  32740. squeezeWhenBailout(maxGap);
  32741. }
  32742. function updateMinMaxGap() {
  32743. minGap = first.rect[xyDim] - minBound;
  32744. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  32745. }
  32746. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  32747. if (gapThisBound < 0) {
  32748. // Move from other gap if can.
  32749. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  32750. if (moveFromMaxGap > 0) {
  32751. shiftList(moveFromMaxGap * moveDir, 0, len);
  32752. var remained = moveFromMaxGap + gapThisBound;
  32753. if (remained < 0) {
  32754. squeezeGaps(-remained * moveDir, 1);
  32755. }
  32756. } else {
  32757. squeezeGaps(-gapThisBound * moveDir, 1);
  32758. }
  32759. }
  32760. }
  32761. function shiftList(delta, start, end) {
  32762. if (delta !== 0) {
  32763. adjusted = true;
  32764. }
  32765. for (var i = start; i < end; i++) {
  32766. var item = list[i];
  32767. var rect = item.rect;
  32768. rect[xyDim] += delta;
  32769. item.label[xyDim] += delta;
  32770. }
  32771. } // Squeeze gaps if the labels exceed margin.
  32772. function squeezeGaps(delta, maxSqeezePercent) {
  32773. var gaps = [];
  32774. var totalGaps = 0;
  32775. for (var i = 1; i < len; i++) {
  32776. var prevItemRect = list[i - 1].rect;
  32777. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  32778. gaps.push(gap);
  32779. totalGaps += gap;
  32780. }
  32781. if (!totalGaps) {
  32782. return;
  32783. }
  32784. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  32785. if (delta > 0) {
  32786. for (var i = 0; i < len - 1; i++) {
  32787. // Distribute the shift delta to all gaps.
  32788. var movement = gaps[i] * squeezePercent; // Forward
  32789. shiftList(movement, 0, i + 1);
  32790. }
  32791. } else {
  32792. // Backward
  32793. for (var i = len - 1; i > 0; i--) {
  32794. // Distribute the shift delta to all gaps.
  32795. var movement = gaps[i - 1] * squeezePercent;
  32796. shiftList(-movement, i, len);
  32797. }
  32798. }
  32799. }
  32800. /**
  32801. * Squeeze to allow overlap if there is no more space available.
  32802. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  32803. */
  32804. function squeezeWhenBailout(delta) {
  32805. var dir = delta < 0 ? -1 : 1;
  32806. delta = Math.abs(delta);
  32807. var moveForEachLabel = Math.ceil(delta / (len - 1));
  32808. for (var i = 0; i < len - 1; i++) {
  32809. if (dir > 0) {
  32810. // Forward
  32811. shiftList(moveForEachLabel, 0, i + 1);
  32812. } else {
  32813. // Backward
  32814. shiftList(-moveForEachLabel, len - i - 1, len);
  32815. }
  32816. delta -= moveForEachLabel;
  32817. if (delta <= 0) {
  32818. return;
  32819. }
  32820. }
  32821. }
  32822. return adjusted;
  32823. }
  32824. /**
  32825. * Adjust labels on y direction to avoid overlap.
  32826. */
  32827. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  32828. balanceShift) {
  32829. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  32830. }
  32831. function hideOverlap(labelList) {
  32832. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  32833. labelList.sort(function (a, b) {
  32834. return b.priority - a.priority;
  32835. });
  32836. var globalRect = new BoundingRect(0, 0, 0, 0);
  32837. function hideEl(el) {
  32838. if (!el.ignore) {
  32839. // Show on emphasis.
  32840. var emphasisState = el.ensureState('emphasis');
  32841. if (emphasisState.ignore == null) {
  32842. emphasisState.ignore = false;
  32843. }
  32844. }
  32845. el.ignore = true;
  32846. }
  32847. for (var i = 0; i < labelList.length; i++) {
  32848. var labelItem = labelList[i];
  32849. var isAxisAligned = labelItem.axisAligned;
  32850. var localRect = labelItem.localRect;
  32851. var transform = labelItem.transform;
  32852. var label = labelItem.label;
  32853. var labelLine = labelItem.labelLine;
  32854. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  32855. globalRect.width -= 0.1;
  32856. globalRect.height -= 0.1;
  32857. globalRect.x += 0.05;
  32858. globalRect.y += 0.05;
  32859. var obb = labelItem.obb;
  32860. var overlapped = false;
  32861. for (var j = 0; j < displayedLabels.length; j++) {
  32862. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  32863. if (!globalRect.intersect(existsTextCfg.rect)) {
  32864. continue;
  32865. }
  32866. if (isAxisAligned && existsTextCfg.axisAligned) {
  32867. // Is overlapped
  32868. overlapped = true;
  32869. break;
  32870. }
  32871. if (!existsTextCfg.obb) {
  32872. // If self is not axis aligned. But other is.
  32873. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  32874. }
  32875. if (!obb) {
  32876. // If self is axis aligned. But other is not.
  32877. obb = new OrientedBoundingRect(localRect, transform);
  32878. }
  32879. if (obb.intersect(existsTextCfg.obb)) {
  32880. overlapped = true;
  32881. break;
  32882. }
  32883. } // TODO Callback to determine if this overlap should be handled?
  32884. if (overlapped) {
  32885. hideEl(label);
  32886. labelLine && hideEl(labelLine);
  32887. } else {
  32888. label.attr('ignore', labelItem.defaultAttr.ignore);
  32889. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  32890. displayedLabels.push(labelItem);
  32891. }
  32892. }
  32893. }
  32894. var mathSin$4 = Math.sin;
  32895. var mathCos$4 = Math.cos;
  32896. var PI$4 = Math.PI;
  32897. var PI2$6 = Math.PI * 2;
  32898. var degree = 180 / PI$4;
  32899. var SVGPathRebuilder = (function () {
  32900. function SVGPathRebuilder() {
  32901. }
  32902. SVGPathRebuilder.prototype.reset = function (precision) {
  32903. this._start = true;
  32904. this._d = [];
  32905. this._str = '';
  32906. this._p = Math.pow(10, precision || 4);
  32907. };
  32908. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  32909. this._add('M', x, y);
  32910. };
  32911. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  32912. this._add('L', x, y);
  32913. };
  32914. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  32915. this._add('C', x, y, x2, y2, x3, y3);
  32916. };
  32917. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  32918. this._add('Q', x, y, x2, y2);
  32919. };
  32920. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  32921. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  32922. };
  32923. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  32924. var dTheta = endAngle - startAngle;
  32925. var clockwise = !anticlockwise;
  32926. var dThetaPositive = Math.abs(dTheta);
  32927. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  32928. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  32929. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  32930. var large = false;
  32931. if (isCircle) {
  32932. large = true;
  32933. }
  32934. else if (isAroundZero$1(dThetaPositive)) {
  32935. large = false;
  32936. }
  32937. else {
  32938. large = (unifiedTheta >= PI$4) === !!clockwise;
  32939. }
  32940. var x0 = cx + rx * mathCos$4(startAngle);
  32941. var y0 = cy + ry * mathSin$4(startAngle);
  32942. if (this._start) {
  32943. this._add('M', x0, y0);
  32944. }
  32945. var xRot = Math.round(psi * degree);
  32946. if (isCircle) {
  32947. var p = 1 / this._p;
  32948. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$6 - p);
  32949. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  32950. if (p > 1e-2) {
  32951. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  32952. }
  32953. }
  32954. else {
  32955. var x = cx + rx * mathCos$4(endAngle);
  32956. var y = cy + ry * mathSin$4(endAngle);
  32957. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  32958. }
  32959. };
  32960. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  32961. this._add('M', x, y);
  32962. this._add('l', w, 0);
  32963. this._add('l', 0, h);
  32964. this._add('l', -w, 0);
  32965. this._add('Z');
  32966. };
  32967. SVGPathRebuilder.prototype.closePath = function () {
  32968. if (this._d.length > 0) {
  32969. this._add('Z');
  32970. }
  32971. };
  32972. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  32973. var vals = [];
  32974. var p = this._p;
  32975. for (var i = 1; i < arguments.length; i++) {
  32976. var val = arguments[i];
  32977. if (isNaN(val)) {
  32978. this._invalid = true;
  32979. return;
  32980. }
  32981. vals.push(Math.round(val * p) / p);
  32982. }
  32983. this._d.push(cmd + vals.join(' '));
  32984. this._start = cmd === 'Z';
  32985. };
  32986. SVGPathRebuilder.prototype.generateStr = function () {
  32987. this._str = this._invalid ? '' : this._d.join('');
  32988. this._d = [];
  32989. };
  32990. SVGPathRebuilder.prototype.getStr = function () {
  32991. return this._str;
  32992. };
  32993. return SVGPathRebuilder;
  32994. }());
  32995. var NONE = 'none';
  32996. var mathRound$1 = Math.round;
  32997. function pathHasFill(style) {
  32998. var fill = style.fill;
  32999. return fill != null && fill !== NONE;
  33000. }
  33001. function pathHasStroke(style) {
  33002. var stroke = style.stroke;
  33003. return stroke != null && stroke !== NONE;
  33004. }
  33005. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  33006. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  33007. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  33008. var opacity = style.opacity == null ? 1 : style.opacity;
  33009. if (el instanceof ZRImage) {
  33010. updateAttr('opacity', opacity);
  33011. return;
  33012. }
  33013. if (pathHasFill(style)) {
  33014. var fill = normalizeColor(style.fill);
  33015. updateAttr('fill', fill.color);
  33016. var fillOpacity = style.fillOpacity != null
  33017. ? style.fillOpacity * fill.opacity * opacity
  33018. : fill.opacity * opacity;
  33019. if (forceUpdate || fillOpacity < 1) {
  33020. updateAttr('fill-opacity', fillOpacity);
  33021. }
  33022. }
  33023. else {
  33024. updateAttr('fill', NONE);
  33025. }
  33026. if (pathHasStroke(style)) {
  33027. var stroke = normalizeColor(style.stroke);
  33028. updateAttr('stroke', stroke.color);
  33029. var strokeScale = style.strokeNoScale
  33030. ? el.getLineScale()
  33031. : 1;
  33032. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  33033. var strokeOpacity = style.strokeOpacity != null
  33034. ? style.strokeOpacity * stroke.opacity * opacity
  33035. : stroke.opacity * opacity;
  33036. var strokeFirst = style.strokeFirst;
  33037. if (forceUpdate || strokeWidth !== 1) {
  33038. updateAttr('stroke-width', strokeWidth);
  33039. }
  33040. if (forceUpdate || strokeFirst) {
  33041. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  33042. }
  33043. if (forceUpdate || strokeOpacity < 1) {
  33044. updateAttr('stroke-opacity', strokeOpacity);
  33045. }
  33046. if (style.lineDash) {
  33047. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  33048. if (lineDash) {
  33049. lineDashOffset = mathRound$1(lineDashOffset || 0);
  33050. updateAttr('stroke-dasharray', lineDash.join(','));
  33051. if (lineDashOffset || forceUpdate) {
  33052. updateAttr('stroke-dashoffset', lineDashOffset);
  33053. }
  33054. }
  33055. }
  33056. else if (forceUpdate) {
  33057. updateAttr('stroke-dasharray', NONE);
  33058. }
  33059. for (var i = 0; i < strokeProps.length; i++) {
  33060. var propName = strokeProps[i];
  33061. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  33062. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  33063. val && updateAttr(svgStrokeProps[i], val);
  33064. }
  33065. }
  33066. }
  33067. else if (forceUpdate) {
  33068. updateAttr('stroke', NONE);
  33069. }
  33070. }
  33071. var SVGNS = 'http://www.w3.org/2000/svg';
  33072. var XLINKNS = 'http://www.w3.org/1999/xlink';
  33073. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  33074. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  33075. function createElement(name) {
  33076. return document.createElementNS(SVGNS, name);
  33077. }
  33078. function createVNode(tag, key, attrs, children, text) {
  33079. return {
  33080. tag: tag,
  33081. attrs: attrs || {},
  33082. children: children,
  33083. text: text,
  33084. key: key
  33085. };
  33086. }
  33087. function createElementOpen(name, attrs) {
  33088. var attrsStr = [];
  33089. if (attrs) {
  33090. for (var key in attrs) {
  33091. var val = attrs[key];
  33092. var part = key;
  33093. if (val === false) {
  33094. continue;
  33095. }
  33096. else if (val !== true && val != null) {
  33097. part += "=\"" + val + "\"";
  33098. }
  33099. attrsStr.push(part);
  33100. }
  33101. }
  33102. return "<" + name + " " + attrsStr.join(' ') + ">";
  33103. }
  33104. function createElementClose(name) {
  33105. return "</" + name + ">";
  33106. }
  33107. function vNodeToString(el, opts) {
  33108. opts = opts || {};
  33109. var S = opts.newline ? '\n' : '';
  33110. function convertElToString(el) {
  33111. var children = el.children, tag = el.tag, attrs = el.attrs;
  33112. return createElementOpen(tag, attrs)
  33113. + (el.text || '')
  33114. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  33115. + createElementClose(tag);
  33116. }
  33117. return convertElToString(el);
  33118. }
  33119. function getCssString(selectorNodes, animationNodes, opts) {
  33120. opts = opts || {};
  33121. var S = opts.newline ? '\n' : '';
  33122. var bracketBegin = " {" + S;
  33123. var bracketEnd = S + "}";
  33124. var selectors = map(keys(selectorNodes), function (className) {
  33125. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  33126. return attrName + ":" + selectorNodes[className][attrName] + ";";
  33127. }).join(S) + bracketEnd;
  33128. }).join(S);
  33129. var animations = map(keys(animationNodes), function (animationName) {
  33130. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  33131. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  33132. var val = animationNodes[animationName][percent][attrName];
  33133. if (attrName === 'd') {
  33134. val = "path(\"" + val + "\")";
  33135. }
  33136. return attrName + ":" + val + ";";
  33137. }).join(S) + bracketEnd;
  33138. }).join(S) + bracketEnd;
  33139. }).join(S);
  33140. if (!selectors && !animations) {
  33141. return '';
  33142. }
  33143. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  33144. }
  33145. function createBrushScope(zrId) {
  33146. return {
  33147. zrId: zrId,
  33148. shadowCache: {},
  33149. patternCache: {},
  33150. gradientCache: {},
  33151. clipPathCache: {},
  33152. defs: {},
  33153. cssNodes: {},
  33154. cssAnims: {},
  33155. cssClassIdx: 0,
  33156. cssAnimIdx: 0,
  33157. shadowIdx: 0,
  33158. gradientIdx: 0,
  33159. patternIdx: 0,
  33160. clipPathIdx: 0
  33161. };
  33162. }
  33163. function createSVGVNode(width, height, children, useViewBox) {
  33164. return createVNode('svg', 'root', {
  33165. 'width': width,
  33166. 'height': height,
  33167. 'xmlns': SVGNS,
  33168. 'xmlns:xlink': XLINKNS,
  33169. 'version': '1.1',
  33170. 'baseProfile': 'full',
  33171. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  33172. }, children);
  33173. }
  33174. var EASING_MAP = {
  33175. cubicIn: '0.32,0,0.67,0',
  33176. cubicOut: '0.33,1,0.68,1',
  33177. cubicInOut: '0.65,0,0.35,1',
  33178. quadraticIn: '0.11,0,0.5,0',
  33179. quadraticOut: '0.5,1,0.89,1',
  33180. quadraticInOut: '0.45,0,0.55,1',
  33181. quarticIn: '0.5,0,0.75,0',
  33182. quarticOut: '0.25,1,0.5,1',
  33183. quarticInOut: '0.76,0,0.24,1',
  33184. quinticIn: '0.64,0,0.78,0',
  33185. quinticOut: '0.22,1,0.36,1',
  33186. quinticInOut: '0.83,0,0.17,1',
  33187. sinusoidalIn: '0.12,0,0.39,0',
  33188. sinusoidalOut: '0.61,1,0.88,1',
  33189. sinusoidalInOut: '0.37,0,0.63,1',
  33190. exponentialIn: '0.7,0,0.84,0',
  33191. exponentialOut: '0.16,1,0.3,1',
  33192. exponentialInOut: '0.87,0,0.13,1',
  33193. circularIn: '0.55,0,1,0.45',
  33194. circularOut: '0,0.55,0.45,1',
  33195. circularInOut: '0.85,0,0.15,1'
  33196. };
  33197. var transformOriginKey = 'transform-origin';
  33198. function buildPathString(el, kfShape, path) {
  33199. var shape = extend({}, el.shape);
  33200. extend(shape, kfShape);
  33201. el.buildPath(path, shape);
  33202. var svgPathBuilder = new SVGPathRebuilder();
  33203. svgPathBuilder.reset(getPathPrecision(el));
  33204. path.rebuildPath(svgPathBuilder, 1);
  33205. svgPathBuilder.generateStr();
  33206. return svgPathBuilder.getStr();
  33207. }
  33208. function setTransformOrigin(target, transform) {
  33209. var originX = transform.originX, originY = transform.originY;
  33210. if (originX || originY) {
  33211. target[transformOriginKey] = originX + "px " + originY + "px";
  33212. }
  33213. }
  33214. var ANIMATE_STYLE_MAP = {
  33215. fill: 'fill',
  33216. opacity: 'opacity',
  33217. lineWidth: 'stroke-width',
  33218. lineDashOffset: 'stroke-dashoffset'
  33219. };
  33220. function addAnimation(cssAnim, scope) {
  33221. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  33222. scope.cssAnims[animationName] = cssAnim;
  33223. return animationName;
  33224. }
  33225. function createCompoundPathCSSAnimation(el, attrs, scope) {
  33226. var paths = el.shape.paths;
  33227. var composedAnim = {};
  33228. var cssAnimationCfg;
  33229. var cssAnimationName;
  33230. each(paths, function (path) {
  33231. var subScope = createBrushScope(scope.zrId);
  33232. subScope.animation = true;
  33233. createCSSAnimation(path, {}, subScope, true);
  33234. var cssAnims = subScope.cssAnims;
  33235. var cssNodes = subScope.cssNodes;
  33236. var animNames = keys(cssAnims);
  33237. var len = animNames.length;
  33238. if (!len) {
  33239. return;
  33240. }
  33241. cssAnimationName = animNames[len - 1];
  33242. var lastAnim = cssAnims[cssAnimationName];
  33243. for (var percent in lastAnim) {
  33244. var kf = lastAnim[percent];
  33245. composedAnim[percent] = composedAnim[percent] || { d: '' };
  33246. composedAnim[percent].d += kf.d || '';
  33247. }
  33248. for (var className in cssNodes) {
  33249. var val = cssNodes[className].animation;
  33250. if (val.indexOf(cssAnimationName) >= 0) {
  33251. cssAnimationCfg = val;
  33252. }
  33253. }
  33254. });
  33255. if (!cssAnimationCfg) {
  33256. return;
  33257. }
  33258. attrs.d = false;
  33259. var animationName = addAnimation(composedAnim, scope);
  33260. return cssAnimationCfg.replace(cssAnimationName, animationName);
  33261. }
  33262. function getEasingFunc(easing) {
  33263. return isString(easing)
  33264. ? EASING_MAP[easing]
  33265. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  33266. : createCubicEasingFunc(easing) ? easing : ''
  33267. : '';
  33268. }
  33269. function createCSSAnimation(el, attrs, scope, onlyShape) {
  33270. var animators = el.animators;
  33271. var len = animators.length;
  33272. var cssAnimations = [];
  33273. if (el instanceof CompoundPath) {
  33274. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  33275. if (animationCfg) {
  33276. cssAnimations.push(animationCfg);
  33277. }
  33278. else if (!len) {
  33279. return;
  33280. }
  33281. }
  33282. else if (!len) {
  33283. return;
  33284. }
  33285. var groupAnimators = {};
  33286. for (var i = 0; i < len; i++) {
  33287. var animator = animators[i];
  33288. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  33289. var easing = getEasingFunc(animator.getClip().easing);
  33290. var delay = animator.getDelay();
  33291. if (easing) {
  33292. cfgArr.push(easing);
  33293. }
  33294. else {
  33295. cfgArr.push('linear');
  33296. }
  33297. if (delay) {
  33298. cfgArr.push(delay / 1000 + 's');
  33299. }
  33300. if (animator.getLoop()) {
  33301. cfgArr.push('infinite');
  33302. }
  33303. var cfg = cfgArr.join(' ');
  33304. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  33305. groupAnimators[cfg][1].push(animator);
  33306. }
  33307. function createSingleCSSAnimation(groupAnimator) {
  33308. var animators = groupAnimator[1];
  33309. var len = animators.length;
  33310. var transformKfs = {};
  33311. var shapeKfs = {};
  33312. var finalKfs = {};
  33313. var animationTimingFunctionAttrName = 'animation-timing-function';
  33314. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  33315. var tracks = animator.getTracks();
  33316. var maxTime = animator.getMaxTime();
  33317. for (var k = 0; k < tracks.length; k++) {
  33318. var track = tracks[k];
  33319. if (track.needsAnimate()) {
  33320. var kfs = track.keyframes;
  33321. var attrName = track.propName;
  33322. toCssAttrName && (attrName = toCssAttrName(attrName));
  33323. if (attrName) {
  33324. for (var i = 0; i < kfs.length; i++) {
  33325. var kf = kfs[i];
  33326. var percent = Math.round(kf.time / maxTime * 100) + '%';
  33327. var kfEasing = getEasingFunc(kf.easing);
  33328. var rawValue = kf.rawValue;
  33329. if (isString(rawValue) || isNumber(rawValue)) {
  33330. cssKfs[percent] = cssKfs[percent] || {};
  33331. cssKfs[percent][attrName] = kf.rawValue;
  33332. if (kfEasing) {
  33333. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  33334. }
  33335. }
  33336. }
  33337. }
  33338. }
  33339. }
  33340. }
  33341. for (var i = 0; i < len; i++) {
  33342. var animator = animators[i];
  33343. var targetProp = animator.targetName;
  33344. if (!targetProp) {
  33345. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  33346. }
  33347. else if (targetProp === 'shape') {
  33348. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  33349. }
  33350. }
  33351. for (var percent in transformKfs) {
  33352. var transform = {};
  33353. copyTransform(transform, el);
  33354. extend(transform, transformKfs[percent]);
  33355. var str = getSRTTransformString(transform);
  33356. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  33357. finalKfs[percent] = str ? {
  33358. transform: str
  33359. } : {};
  33360. setTransformOrigin(finalKfs[percent], transform);
  33361. if (timingFunction) {
  33362. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  33363. }
  33364. }
  33365. var path;
  33366. var canAnimateShape = true;
  33367. for (var percent in shapeKfs) {
  33368. finalKfs[percent] = finalKfs[percent] || {};
  33369. var isFirst = !path;
  33370. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  33371. if (isFirst) {
  33372. path = new PathProxy();
  33373. }
  33374. var len_1 = path.len();
  33375. path.reset();
  33376. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  33377. var newLen = path.len();
  33378. if (!isFirst && len_1 !== newLen) {
  33379. canAnimateShape = false;
  33380. break;
  33381. }
  33382. if (timingFunction) {
  33383. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  33384. }
  33385. }
  33386. if (!canAnimateShape) {
  33387. for (var percent in finalKfs) {
  33388. delete finalKfs[percent].d;
  33389. }
  33390. }
  33391. if (!onlyShape) {
  33392. for (var i = 0; i < len; i++) {
  33393. var animator = animators[i];
  33394. var targetProp = animator.targetName;
  33395. if (targetProp === 'style') {
  33396. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  33397. }
  33398. }
  33399. }
  33400. var percents = keys(finalKfs);
  33401. var allTransformOriginSame = true;
  33402. var transformOrigin;
  33403. for (var i = 1; i < percents.length; i++) {
  33404. var p0 = percents[i - 1];
  33405. var p1 = percents[i];
  33406. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  33407. allTransformOriginSame = false;
  33408. break;
  33409. }
  33410. transformOrigin = finalKfs[p0][transformOriginKey];
  33411. }
  33412. if (allTransformOriginSame && transformOrigin) {
  33413. for (var percent in finalKfs) {
  33414. if (finalKfs[percent][transformOriginKey]) {
  33415. delete finalKfs[percent][transformOriginKey];
  33416. }
  33417. }
  33418. attrs[transformOriginKey] = transformOrigin;
  33419. }
  33420. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  33421. var animationName = addAnimation(finalKfs, scope);
  33422. return animationName + " " + groupAnimator[0] + " both";
  33423. }
  33424. }
  33425. for (var key in groupAnimators) {
  33426. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  33427. if (animationCfg) {
  33428. cssAnimations.push(animationCfg);
  33429. }
  33430. }
  33431. if (cssAnimations.length) {
  33432. var className = scope.zrId + '-cls-' + scope.cssClassIdx++;
  33433. scope.cssNodes['.' + className] = {
  33434. animation: cssAnimations.join(',')
  33435. };
  33436. attrs["class"] = className;
  33437. }
  33438. }
  33439. var round$2 = Math.round;
  33440. function isImageLike$1(val) {
  33441. return val && isString(val.src);
  33442. }
  33443. function isCanvasLike(val) {
  33444. return val && isFunction(val.toDataURL);
  33445. }
  33446. function setStyleAttrs(attrs, style, el, scope) {
  33447. mapStyleToAttrs(function (key, val) {
  33448. var isFillStroke = key === 'fill' || key === 'stroke';
  33449. if (isFillStroke && isGradient(val)) {
  33450. setGradient(style, attrs, key, scope);
  33451. }
  33452. else if (isFillStroke && isPattern(val)) {
  33453. setPattern(el, attrs, key, scope);
  33454. }
  33455. else {
  33456. attrs[key] = val;
  33457. }
  33458. }, style, el, false);
  33459. setShadow(el, attrs, scope);
  33460. }
  33461. function noRotateScale(m) {
  33462. return isAroundZero$1(m[0] - 1)
  33463. && isAroundZero$1(m[1])
  33464. && isAroundZero$1(m[2])
  33465. && isAroundZero$1(m[3] - 1);
  33466. }
  33467. function noTranslate(m) {
  33468. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  33469. }
  33470. function setTransform(attrs, m, compress) {
  33471. if (m && !(noTranslate(m) && noRotateScale(m))) {
  33472. var mul = compress ? 10 : 1e4;
  33473. attrs.transform = noRotateScale(m)
  33474. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  33475. }
  33476. }
  33477. function convertPolyShape(shape, attrs, mul) {
  33478. var points = shape.points;
  33479. var strArr = [];
  33480. for (var i = 0; i < points.length; i++) {
  33481. strArr.push(round$2(points[i][0] * mul) / mul);
  33482. strArr.push(round$2(points[i][1] * mul) / mul);
  33483. }
  33484. attrs.points = strArr.join(' ');
  33485. }
  33486. function validatePolyShape(shape) {
  33487. return !shape.smooth;
  33488. }
  33489. function createAttrsConvert(desc) {
  33490. var normalizedDesc = map(desc, function (item) {
  33491. return (typeof item === 'string' ? [item, item] : item);
  33492. });
  33493. return function (shape, attrs, mul) {
  33494. for (var i = 0; i < normalizedDesc.length; i++) {
  33495. var item = normalizedDesc[i];
  33496. var val = shape[item[0]];
  33497. if (val != null) {
  33498. attrs[item[1]] = round$2(val * mul) / mul;
  33499. }
  33500. }
  33501. };
  33502. }
  33503. var buitinShapesDef = {
  33504. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  33505. polyline: [convertPolyShape, validatePolyShape],
  33506. polygon: [convertPolyShape, validatePolyShape]
  33507. };
  33508. function hasShapeAnimation(el) {
  33509. var animators = el.animators;
  33510. for (var i = 0; i < animators.length; i++) {
  33511. if (animators[i].targetName === 'shape') {
  33512. return true;
  33513. }
  33514. }
  33515. return false;
  33516. }
  33517. function brushSVGPath(el, scope) {
  33518. var style = el.style;
  33519. var shape = el.shape;
  33520. var builtinShpDef = buitinShapesDef[el.type];
  33521. var attrs = {};
  33522. var needsAnimate = scope.animation;
  33523. var svgElType = 'path';
  33524. var strokePercent = el.style.strokePercent;
  33525. var precision = (scope.compress && getPathPrecision(el)) || 4;
  33526. if (builtinShpDef
  33527. && !scope.willUpdate
  33528. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  33529. && !(needsAnimate && hasShapeAnimation(el))
  33530. && !(strokePercent < 1)) {
  33531. svgElType = el.type;
  33532. var mul = Math.pow(10, precision);
  33533. builtinShpDef[0](shape, attrs, mul);
  33534. }
  33535. else {
  33536. if (!el.path) {
  33537. el.createPathProxy();
  33538. }
  33539. var path = el.path;
  33540. if (el.shapeChanged()) {
  33541. path.beginPath();
  33542. el.buildPath(path, el.shape);
  33543. el.pathUpdated();
  33544. }
  33545. var pathVersion = path.getVersion();
  33546. var elExt = el;
  33547. var svgPathBuilder = elExt.__svgPathBuilder;
  33548. if (elExt.__svgPathVersion !== pathVersion
  33549. || !svgPathBuilder
  33550. || strokePercent !== elExt.__svgPathStrokePercent) {
  33551. if (!svgPathBuilder) {
  33552. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  33553. }
  33554. svgPathBuilder.reset(precision);
  33555. path.rebuildPath(svgPathBuilder, strokePercent);
  33556. svgPathBuilder.generateStr();
  33557. elExt.__svgPathVersion = pathVersion;
  33558. elExt.__svgPathStrokePercent = strokePercent;
  33559. }
  33560. attrs.d = svgPathBuilder.getStr();
  33561. }
  33562. setTransform(attrs, el.transform);
  33563. setStyleAttrs(attrs, style, el, scope);
  33564. scope.animation && createCSSAnimation(el, attrs, scope);
  33565. return createVNode(svgElType, el.id + '', attrs);
  33566. }
  33567. function brushSVGImage(el, scope) {
  33568. var style = el.style;
  33569. var image = style.image;
  33570. if (image && !isString(image)) {
  33571. if (isImageLike$1(image)) {
  33572. image = image.src;
  33573. }
  33574. else if (isCanvasLike(image)) {
  33575. image = image.toDataURL();
  33576. }
  33577. }
  33578. if (!image) {
  33579. return;
  33580. }
  33581. var x = style.x || 0;
  33582. var y = style.y || 0;
  33583. var dw = style.width;
  33584. var dh = style.height;
  33585. var attrs = {
  33586. href: image,
  33587. width: dw,
  33588. height: dh
  33589. };
  33590. if (x) {
  33591. attrs.x = x;
  33592. }
  33593. if (y) {
  33594. attrs.y = y;
  33595. }
  33596. setTransform(attrs, el.transform);
  33597. setStyleAttrs(attrs, style, el, scope);
  33598. scope.animation && createCSSAnimation(el, attrs, scope);
  33599. return createVNode('image', el.id + '', attrs);
  33600. }
  33601. function brushSVGTSpan(el, scope) {
  33602. var style = el.style;
  33603. var text = style.text;
  33604. text != null && (text += '');
  33605. if (!text || isNaN(style.x) || isNaN(style.y)) {
  33606. return;
  33607. }
  33608. var font = style.font || DEFAULT_FONT;
  33609. var x = style.x || 0;
  33610. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  33611. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  33612. || style.textAlign;
  33613. var attrs = {
  33614. 'dominant-baseline': 'central',
  33615. 'text-anchor': textAlign
  33616. };
  33617. if (hasSeparateFont(style)) {
  33618. var separatedFontStr = '';
  33619. var fontStyle = style.fontStyle;
  33620. var fontSize = parseFontSize(style.fontSize);
  33621. if (!parseFloat(fontSize)) {
  33622. return;
  33623. }
  33624. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  33625. var fontWeight = style.fontWeight;
  33626. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  33627. if (fontStyle && fontStyle !== 'normal') {
  33628. separatedFontStr += "font-style:" + fontStyle + ";";
  33629. }
  33630. if (fontWeight && fontWeight !== 'normal') {
  33631. separatedFontStr += "font-weight:" + fontWeight + ";";
  33632. }
  33633. attrs.style = separatedFontStr;
  33634. }
  33635. else {
  33636. attrs.style = "font: " + font;
  33637. }
  33638. if (text.match(/\s/)) {
  33639. attrs['xml:space'] = 'preserve';
  33640. }
  33641. if (x) {
  33642. attrs.x = x;
  33643. }
  33644. if (y) {
  33645. attrs.y = y;
  33646. }
  33647. setTransform(attrs, el.transform);
  33648. setStyleAttrs(attrs, style, el, scope);
  33649. scope.animation && createCSSAnimation(el, attrs, scope);
  33650. return createVNode('text', el.id + '', attrs, undefined, text);
  33651. }
  33652. function brush$1(el, scope) {
  33653. if (el instanceof Path) {
  33654. return brushSVGPath(el, scope);
  33655. }
  33656. else if (el instanceof ZRImage) {
  33657. return brushSVGImage(el, scope);
  33658. }
  33659. else if (el instanceof TSpan) {
  33660. return brushSVGTSpan(el, scope);
  33661. }
  33662. }
  33663. function setShadow(el, attrs, scope) {
  33664. var style = el.style;
  33665. if (hasShadow(style)) {
  33666. var shadowKey = getShadowKey(el);
  33667. var shadowCache = scope.shadowCache;
  33668. var shadowId = shadowCache[shadowKey];
  33669. if (!shadowId) {
  33670. var globalScale = el.getGlobalScale();
  33671. var scaleX = globalScale[0];
  33672. var scaleY = globalScale[1];
  33673. if (!scaleX || !scaleY) {
  33674. return;
  33675. }
  33676. var offsetX = style.shadowOffsetX || 0;
  33677. var offsetY = style.shadowOffsetY || 0;
  33678. var blur_1 = style.shadowBlur;
  33679. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  33680. var stdDx = blur_1 / 2 / scaleX;
  33681. var stdDy = blur_1 / 2 / scaleY;
  33682. var stdDeviation = stdDx + ' ' + stdDy;
  33683. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  33684. scope.defs[shadowId] = createVNode('filter', shadowId, {
  33685. 'id': shadowId,
  33686. 'x': '-100%',
  33687. 'y': '-100%',
  33688. 'width': '300%',
  33689. 'height': '300%'
  33690. }, [
  33691. createVNode('feDropShadow', '', {
  33692. 'dx': offsetX / scaleX,
  33693. 'dy': offsetY / scaleY,
  33694. 'stdDeviation': stdDeviation,
  33695. 'flood-color': color,
  33696. 'flood-opacity': opacity
  33697. })
  33698. ]);
  33699. shadowCache[shadowKey] = shadowId;
  33700. }
  33701. attrs.filter = getIdURL(shadowId);
  33702. }
  33703. }
  33704. function setGradient(style, attrs, target, scope) {
  33705. var val = style[target];
  33706. var gradientTag;
  33707. var gradientAttrs = {
  33708. 'gradientUnits': val.global
  33709. ? 'userSpaceOnUse'
  33710. : 'objectBoundingBox'
  33711. };
  33712. if (isLinearGradient(val)) {
  33713. gradientTag = 'linearGradient';
  33714. gradientAttrs.x1 = val.x;
  33715. gradientAttrs.y1 = val.y;
  33716. gradientAttrs.x2 = val.x2;
  33717. gradientAttrs.y2 = val.y2;
  33718. }
  33719. else if (isRadialGradient(val)) {
  33720. gradientTag = 'radialGradient';
  33721. gradientAttrs.cx = retrieve2(val.x, 0.5);
  33722. gradientAttrs.cy = retrieve2(val.y, 0.5);
  33723. gradientAttrs.r = retrieve2(val.r, 0.5);
  33724. }
  33725. else {
  33726. if ("development" !== 'production') {
  33727. logError('Illegal gradient type.');
  33728. }
  33729. return;
  33730. }
  33731. var colors = val.colorStops;
  33732. var colorStops = [];
  33733. for (var i = 0, len = colors.length; i < len; ++i) {
  33734. var offset = round4(colors[i].offset) * 100 + '%';
  33735. var stopColor = colors[i].color;
  33736. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  33737. var stopsAttrs = {
  33738. 'offset': offset
  33739. };
  33740. stopsAttrs['stop-color'] = color;
  33741. if (opacity < 1) {
  33742. stopsAttrs['stop-opacity'] = opacity;
  33743. }
  33744. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  33745. }
  33746. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  33747. var gradientKey = vNodeToString(gradientVNode);
  33748. var gradientCache = scope.gradientCache;
  33749. var gradientId = gradientCache[gradientKey];
  33750. if (!gradientId) {
  33751. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  33752. gradientCache[gradientKey] = gradientId;
  33753. gradientAttrs.id = gradientId;
  33754. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  33755. }
  33756. attrs[target] = getIdURL(gradientId);
  33757. }
  33758. function setPattern(el, attrs, target, scope) {
  33759. var val = el.style[target];
  33760. var patternAttrs = {
  33761. 'patternUnits': 'userSpaceOnUse'
  33762. };
  33763. var child;
  33764. if (isImagePattern(val)) {
  33765. var imageWidth_1 = val.imageWidth;
  33766. var imageHeight_1 = val.imageHeight;
  33767. var imageSrc = void 0;
  33768. var patternImage = val.image;
  33769. if (isString(patternImage)) {
  33770. imageSrc = patternImage;
  33771. }
  33772. else if (isImageLike$1(patternImage)) {
  33773. imageSrc = patternImage.src;
  33774. }
  33775. else if (isCanvasLike(patternImage)) {
  33776. imageSrc = patternImage.toDataURL();
  33777. }
  33778. if (typeof Image === 'undefined') {
  33779. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  33780. assert(imageWidth_1, errMsg);
  33781. assert(imageHeight_1, errMsg);
  33782. }
  33783. else if (imageWidth_1 == null || imageHeight_1 == null) {
  33784. var setSizeToVNode_1 = function (vNode, img) {
  33785. if (vNode) {
  33786. var svgEl = vNode.elm;
  33787. var width = (vNode.attrs.width = imageWidth_1 || img.width);
  33788. var height = (vNode.attrs.height = imageHeight_1 || img.height);
  33789. if (svgEl) {
  33790. svgEl.setAttribute('width', width);
  33791. svgEl.setAttribute('height', height);
  33792. }
  33793. }
  33794. };
  33795. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  33796. setSizeToVNode_1(patternVNode, img);
  33797. setSizeToVNode_1(child, img);
  33798. });
  33799. if (createdImage && createdImage.width && createdImage.height) {
  33800. imageWidth_1 = imageWidth_1 || createdImage.width;
  33801. imageHeight_1 = imageHeight_1 || createdImage.height;
  33802. }
  33803. }
  33804. child = createVNode('image', 'img', {
  33805. href: imageSrc,
  33806. width: imageWidth_1,
  33807. height: imageHeight_1
  33808. });
  33809. patternAttrs.width = imageWidth_1;
  33810. patternAttrs.height = imageHeight_1;
  33811. }
  33812. else if (val.svgElement) {
  33813. child = clone(val.svgElement);
  33814. patternAttrs.width = val.svgWidth;
  33815. patternAttrs.height = val.svgHeight;
  33816. }
  33817. if (!child) {
  33818. return;
  33819. }
  33820. patternAttrs.patternTransform = getSRTTransformString(val);
  33821. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  33822. var patternKey = vNodeToString(patternVNode);
  33823. var patternCache = scope.patternCache;
  33824. var patternId = patternCache[patternKey];
  33825. if (!patternId) {
  33826. patternId = scope.zrId + '-p' + scope.patternIdx++;
  33827. patternCache[patternKey] = patternId;
  33828. patternAttrs.id = patternId;
  33829. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  33830. }
  33831. attrs[target] = getIdURL(patternId);
  33832. }
  33833. function setClipPath(clipPath, attrs, scope) {
  33834. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  33835. var clipPathId = clipPathCache[clipPath.id];
  33836. if (!clipPathId) {
  33837. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  33838. var clipPathAttrs = {
  33839. id: clipPathId
  33840. };
  33841. clipPathCache[clipPath.id] = clipPathId;
  33842. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  33843. }
  33844. attrs['clip-path'] = getIdURL(clipPathId);
  33845. }
  33846. function createTextNode(text) {
  33847. return document.createTextNode(text);
  33848. }
  33849. function insertBefore(parentNode, newNode, referenceNode) {
  33850. parentNode.insertBefore(newNode, referenceNode);
  33851. }
  33852. function removeChild(node, child) {
  33853. node.removeChild(child);
  33854. }
  33855. function appendChild(node, child) {
  33856. node.appendChild(child);
  33857. }
  33858. function parentNode(node) {
  33859. return node.parentNode;
  33860. }
  33861. function nextSibling(node) {
  33862. return node.nextSibling;
  33863. }
  33864. function setTextContent(node, text) {
  33865. node.textContent = text;
  33866. }
  33867. var colonChar = 58;
  33868. var xChar = 120;
  33869. var emptyNode = createVNode('', '');
  33870. function isUndef(s) {
  33871. return s === undefined;
  33872. }
  33873. function isDef(s) {
  33874. return s !== undefined;
  33875. }
  33876. function createKeyToOldIdx(children, beginIdx, endIdx) {
  33877. var map = {};
  33878. for (var i = beginIdx; i <= endIdx; ++i) {
  33879. var key = children[i].key;
  33880. if (key !== undefined) {
  33881. if ("development" !== 'production') {
  33882. if (map[key] != null) {
  33883. console.error("Duplicate key " + key);
  33884. }
  33885. }
  33886. map[key] = i;
  33887. }
  33888. }
  33889. return map;
  33890. }
  33891. function sameVnode(vnode1, vnode2) {
  33892. var isSameKey = vnode1.key === vnode2.key;
  33893. var isSameTag = vnode1.tag === vnode2.tag;
  33894. return isSameTag && isSameKey;
  33895. }
  33896. function createElm(vnode) {
  33897. var i;
  33898. var children = vnode.children;
  33899. var tag = vnode.tag;
  33900. if (isDef(tag)) {
  33901. var elm = (vnode.elm = createElement(tag));
  33902. updateAttrs(emptyNode, vnode);
  33903. if (isArray(children)) {
  33904. for (i = 0; i < children.length; ++i) {
  33905. var ch = children[i];
  33906. if (ch != null) {
  33907. appendChild(elm, createElm(ch));
  33908. }
  33909. }
  33910. }
  33911. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  33912. appendChild(elm, createTextNode(vnode.text));
  33913. }
  33914. }
  33915. else {
  33916. vnode.elm = createTextNode(vnode.text);
  33917. }
  33918. return vnode.elm;
  33919. }
  33920. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  33921. for (; startIdx <= endIdx; ++startIdx) {
  33922. var ch = vnodes[startIdx];
  33923. if (ch != null) {
  33924. insertBefore(parentElm, createElm(ch), before);
  33925. }
  33926. }
  33927. }
  33928. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  33929. for (; startIdx <= endIdx; ++startIdx) {
  33930. var ch = vnodes[startIdx];
  33931. if (ch != null) {
  33932. if (isDef(ch.tag)) {
  33933. var parent_1 = parentNode(ch.elm);
  33934. removeChild(parent_1, ch.elm);
  33935. }
  33936. else {
  33937. removeChild(parentElm, ch.elm);
  33938. }
  33939. }
  33940. }
  33941. }
  33942. function updateAttrs(oldVnode, vnode) {
  33943. var key;
  33944. var elm = vnode.elm;
  33945. var oldAttrs = oldVnode && oldVnode.attrs || {};
  33946. var attrs = vnode.attrs || {};
  33947. if (oldAttrs === attrs) {
  33948. return;
  33949. }
  33950. for (key in attrs) {
  33951. var cur = attrs[key];
  33952. var old = oldAttrs[key];
  33953. if (old !== cur) {
  33954. if (cur === true) {
  33955. elm.setAttribute(key, '');
  33956. }
  33957. else if (cur === false) {
  33958. elm.removeAttribute(key);
  33959. }
  33960. else {
  33961. if (key.charCodeAt(0) !== xChar) {
  33962. elm.setAttribute(key, cur);
  33963. }
  33964. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  33965. elm.setAttributeNS(XMLNS, key, cur);
  33966. }
  33967. else if (key.charCodeAt(3) === colonChar) {
  33968. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  33969. }
  33970. else if (key.charCodeAt(5) === colonChar) {
  33971. elm.setAttributeNS(XLINKNS, key, cur);
  33972. }
  33973. else {
  33974. elm.setAttribute(key, cur);
  33975. }
  33976. }
  33977. }
  33978. }
  33979. for (key in oldAttrs) {
  33980. if (!(key in attrs)) {
  33981. elm.removeAttribute(key);
  33982. }
  33983. }
  33984. }
  33985. function updateChildren(parentElm, oldCh, newCh) {
  33986. var oldStartIdx = 0;
  33987. var newStartIdx = 0;
  33988. var oldEndIdx = oldCh.length - 1;
  33989. var oldStartVnode = oldCh[0];
  33990. var oldEndVnode = oldCh[oldEndIdx];
  33991. var newEndIdx = newCh.length - 1;
  33992. var newStartVnode = newCh[0];
  33993. var newEndVnode = newCh[newEndIdx];
  33994. var oldKeyToIdx;
  33995. var idxInOld;
  33996. var elmToMove;
  33997. var before;
  33998. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  33999. if (oldStartVnode == null) {
  34000. oldStartVnode = oldCh[++oldStartIdx];
  34001. }
  34002. else if (oldEndVnode == null) {
  34003. oldEndVnode = oldCh[--oldEndIdx];
  34004. }
  34005. else if (newStartVnode == null) {
  34006. newStartVnode = newCh[++newStartIdx];
  34007. }
  34008. else if (newEndVnode == null) {
  34009. newEndVnode = newCh[--newEndIdx];
  34010. }
  34011. else if (sameVnode(oldStartVnode, newStartVnode)) {
  34012. patchVnode(oldStartVnode, newStartVnode);
  34013. oldStartVnode = oldCh[++oldStartIdx];
  34014. newStartVnode = newCh[++newStartIdx];
  34015. }
  34016. else if (sameVnode(oldEndVnode, newEndVnode)) {
  34017. patchVnode(oldEndVnode, newEndVnode);
  34018. oldEndVnode = oldCh[--oldEndIdx];
  34019. newEndVnode = newCh[--newEndIdx];
  34020. }
  34021. else if (sameVnode(oldStartVnode, newEndVnode)) {
  34022. patchVnode(oldStartVnode, newEndVnode);
  34023. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  34024. oldStartVnode = oldCh[++oldStartIdx];
  34025. newEndVnode = newCh[--newEndIdx];
  34026. }
  34027. else if (sameVnode(oldEndVnode, newStartVnode)) {
  34028. patchVnode(oldEndVnode, newStartVnode);
  34029. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  34030. oldEndVnode = oldCh[--oldEndIdx];
  34031. newStartVnode = newCh[++newStartIdx];
  34032. }
  34033. else {
  34034. if (isUndef(oldKeyToIdx)) {
  34035. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  34036. }
  34037. idxInOld = oldKeyToIdx[newStartVnode.key];
  34038. if (isUndef(idxInOld)) {
  34039. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  34040. }
  34041. else {
  34042. elmToMove = oldCh[idxInOld];
  34043. if (elmToMove.tag !== newStartVnode.tag) {
  34044. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  34045. }
  34046. else {
  34047. patchVnode(elmToMove, newStartVnode);
  34048. oldCh[idxInOld] = undefined;
  34049. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  34050. }
  34051. }
  34052. newStartVnode = newCh[++newStartIdx];
  34053. }
  34054. }
  34055. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  34056. if (oldStartIdx > oldEndIdx) {
  34057. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  34058. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  34059. }
  34060. else {
  34061. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  34062. }
  34063. }
  34064. }
  34065. function patchVnode(oldVnode, vnode) {
  34066. var elm = (vnode.elm = oldVnode.elm);
  34067. var oldCh = oldVnode.children;
  34068. var ch = vnode.children;
  34069. if (oldVnode === vnode) {
  34070. return;
  34071. }
  34072. updateAttrs(oldVnode, vnode);
  34073. if (isUndef(vnode.text)) {
  34074. if (isDef(oldCh) && isDef(ch)) {
  34075. if (oldCh !== ch) {
  34076. updateChildren(elm, oldCh, ch);
  34077. }
  34078. }
  34079. else if (isDef(ch)) {
  34080. if (isDef(oldVnode.text)) {
  34081. setTextContent(elm, '');
  34082. }
  34083. addVnodes(elm, null, ch, 0, ch.length - 1);
  34084. }
  34085. else if (isDef(oldCh)) {
  34086. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  34087. }
  34088. else if (isDef(oldVnode.text)) {
  34089. setTextContent(elm, '');
  34090. }
  34091. }
  34092. else if (oldVnode.text !== vnode.text) {
  34093. if (isDef(oldCh)) {
  34094. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  34095. }
  34096. setTextContent(elm, vnode.text);
  34097. }
  34098. }
  34099. function patch(oldVnode, vnode) {
  34100. if (sameVnode(oldVnode, vnode)) {
  34101. patchVnode(oldVnode, vnode);
  34102. }
  34103. else {
  34104. var elm = oldVnode.elm;
  34105. var parent_2 = parentNode(elm);
  34106. createElm(vnode);
  34107. if (parent_2 !== null) {
  34108. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  34109. removeVnodes(parent_2, [oldVnode], 0, 0);
  34110. }
  34111. }
  34112. return vnode;
  34113. }
  34114. var svgId = 0;
  34115. var SVGPainter = (function () {
  34116. function SVGPainter(root, storage, opts) {
  34117. this.type = 'svg';
  34118. this.refreshHover = createMethodNotSupport('refreshHover');
  34119. this.configLayer = createMethodNotSupport('configLayer');
  34120. this.storage = storage;
  34121. this._opts = opts = extend({}, opts);
  34122. this.root = root;
  34123. this._id = 'zr' + svgId++;
  34124. this._oldVNode = createSVGVNode(opts.width, opts.height);
  34125. if (root && !opts.ssr) {
  34126. var viewport = this._viewport = document.createElement('div');
  34127. viewport.style.cssText = 'position:relative;overflow:hidden';
  34128. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  34129. updateAttrs(null, this._oldVNode);
  34130. viewport.appendChild(svgDom);
  34131. root.appendChild(viewport);
  34132. }
  34133. this.resize(opts.width, opts.height);
  34134. }
  34135. SVGPainter.prototype.getType = function () {
  34136. return this.type;
  34137. };
  34138. SVGPainter.prototype.getViewportRoot = function () {
  34139. return this._viewport;
  34140. };
  34141. SVGPainter.prototype.getViewportRootOffset = function () {
  34142. var viewportRoot = this.getViewportRoot();
  34143. if (viewportRoot) {
  34144. return {
  34145. offsetLeft: viewportRoot.offsetLeft || 0,
  34146. offsetTop: viewportRoot.offsetTop || 0
  34147. };
  34148. }
  34149. };
  34150. SVGPainter.prototype.getSvgDom = function () {
  34151. return this._svgDom;
  34152. };
  34153. SVGPainter.prototype.refresh = function () {
  34154. if (this.root) {
  34155. var vnode = this.renderToVNode({
  34156. willUpdate: true
  34157. });
  34158. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  34159. patch(this._oldVNode, vnode);
  34160. this._oldVNode = vnode;
  34161. }
  34162. };
  34163. SVGPainter.prototype.renderOneToVNode = function (el) {
  34164. return brush$1(el, createBrushScope(this._id));
  34165. };
  34166. SVGPainter.prototype.renderToVNode = function (opts) {
  34167. opts = opts || {};
  34168. var list = this.storage.getDisplayList(true);
  34169. var bgColor = this._backgroundColor;
  34170. var width = this._width;
  34171. var height = this._height;
  34172. var scope = createBrushScope(this._id);
  34173. scope.animation = opts.animation;
  34174. scope.willUpdate = opts.willUpdate;
  34175. scope.compress = opts.compress;
  34176. var children = [];
  34177. if (bgColor && bgColor !== 'none') {
  34178. var _a = normalizeColor(bgColor), color = _a.color, opacity = _a.opacity;
  34179. this._bgVNode = createVNode('rect', 'bg', {
  34180. width: width,
  34181. height: height,
  34182. x: '0',
  34183. y: '0',
  34184. id: '0',
  34185. fill: color,
  34186. 'fill-opacity': opacity
  34187. });
  34188. children.push(this._bgVNode);
  34189. }
  34190. else {
  34191. this._bgVNode = null;
  34192. }
  34193. var mainVNode = !opts.compress
  34194. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  34195. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  34196. mainVNode && children.push(mainVNode);
  34197. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  34198. if (defs.length) {
  34199. children.push(createVNode('defs', 'defs', {}, defs));
  34200. }
  34201. if (opts.animation) {
  34202. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  34203. if (animationCssStr) {
  34204. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  34205. children.push(styleNode);
  34206. }
  34207. }
  34208. return createSVGVNode(width, height, children, opts.useViewBox);
  34209. };
  34210. SVGPainter.prototype.renderToString = function (opts) {
  34211. opts = opts || {};
  34212. return vNodeToString(this.renderToVNode({
  34213. animation: retrieve2(opts.cssAnimation, true),
  34214. willUpdate: false,
  34215. compress: true,
  34216. useViewBox: retrieve2(opts.useViewBox, true)
  34217. }), { newline: true });
  34218. };
  34219. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  34220. this._backgroundColor = backgroundColor;
  34221. var bgVNode = this._bgVNode;
  34222. if (bgVNode && bgVNode.elm) {
  34223. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  34224. bgVNode.elm.setAttribute('fill', color);
  34225. if (opacity < 1) {
  34226. bgVNode.elm.setAttribute('fill-opacity', opacity);
  34227. }
  34228. }
  34229. };
  34230. SVGPainter.prototype.getSvgRoot = function () {
  34231. return this._mainVNode && this._mainVNode.elm;
  34232. };
  34233. SVGPainter.prototype._paintList = function (list, scope, out) {
  34234. var listLen = list.length;
  34235. var clipPathsGroupsStack = [];
  34236. var clipPathsGroupsStackDepth = 0;
  34237. var currentClipPathGroup;
  34238. var prevClipPaths;
  34239. var clipGroupNodeIdx = 0;
  34240. for (var i = 0; i < listLen; i++) {
  34241. var displayable = list[i];
  34242. if (!displayable.invisible) {
  34243. var clipPaths = displayable.__clipPaths;
  34244. var len = clipPaths && clipPaths.length || 0;
  34245. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  34246. var lca = void 0;
  34247. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  34248. if (clipPaths && prevClipPaths
  34249. && clipPaths[lca] === prevClipPaths[lca]) {
  34250. break;
  34251. }
  34252. }
  34253. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  34254. clipPathsGroupsStackDepth--;
  34255. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  34256. }
  34257. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  34258. var groupAttrs = {};
  34259. setClipPath(clipPaths[i_2], groupAttrs, scope);
  34260. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  34261. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  34262. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  34263. currentClipPathGroup = g;
  34264. }
  34265. prevClipPaths = clipPaths;
  34266. var ret = brush$1(displayable, scope);
  34267. if (ret) {
  34268. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  34269. }
  34270. }
  34271. }
  34272. };
  34273. SVGPainter.prototype.resize = function (width, height) {
  34274. var opts = this._opts;
  34275. var root = this.root;
  34276. var viewport = this._viewport;
  34277. width != null && (opts.width = width);
  34278. height != null && (opts.height = height);
  34279. if (root && viewport) {
  34280. viewport.style.display = 'none';
  34281. width = getSize(root, 0, opts);
  34282. height = getSize(root, 1, opts);
  34283. viewport.style.display = '';
  34284. }
  34285. if (this._width !== width || this._height !== height) {
  34286. this._width = width;
  34287. this._height = height;
  34288. if (viewport) {
  34289. var viewportStyle = viewport.style;
  34290. viewportStyle.width = width + 'px';
  34291. viewportStyle.height = height + 'px';
  34292. }
  34293. var svgDom = this._svgDom;
  34294. if (svgDom) {
  34295. svgDom.setAttribute('width', width);
  34296. svgDom.setAttribute('height', height);
  34297. }
  34298. }
  34299. };
  34300. SVGPainter.prototype.getWidth = function () {
  34301. return this._width;
  34302. };
  34303. SVGPainter.prototype.getHeight = function () {
  34304. return this._height;
  34305. };
  34306. SVGPainter.prototype.dispose = function () {
  34307. if (this.root) {
  34308. this.root.innerHTML = '';
  34309. }
  34310. this._svgDom =
  34311. this._viewport =
  34312. this.storage =
  34313. this._oldVNode =
  34314. this._bgVNode =
  34315. this._mainVNode = null;
  34316. };
  34317. SVGPainter.prototype.clear = function () {
  34318. if (this._svgDom) {
  34319. this._svgDom.innerHTML = null;
  34320. }
  34321. this._oldVNode = null;
  34322. };
  34323. SVGPainter.prototype.toDataURL = function (base64) {
  34324. var str = encodeURIComponent(this.renderToString());
  34325. var prefix = 'data:image/svg+xml;';
  34326. if (base64) {
  34327. str = encodeBase64(str);
  34328. return str && prefix + 'base64,' + str;
  34329. }
  34330. return prefix + 'charset=UTF-8,' + str;
  34331. };
  34332. return SVGPainter;
  34333. }());
  34334. function createMethodNotSupport(method) {
  34335. return function () {
  34336. if ("development" !== 'production') {
  34337. logError('In SVG mode painter not support method "' + method + '"');
  34338. }
  34339. };
  34340. }
  34341. function install(registers) {
  34342. registers.registerPainter('svg', SVGPainter);
  34343. }
  34344. function createDom(id, painter, dpr) {
  34345. var newDom = platformApi.createCanvas();
  34346. var width = painter.getWidth();
  34347. var height = painter.getHeight();
  34348. var newDomStyle = newDom.style;
  34349. if (newDomStyle) {
  34350. newDomStyle.position = 'absolute';
  34351. newDomStyle.left = '0';
  34352. newDomStyle.top = '0';
  34353. newDomStyle.width = width + 'px';
  34354. newDomStyle.height = height + 'px';
  34355. newDom.setAttribute('data-zr-dom-id', id);
  34356. }
  34357. newDom.width = width * dpr;
  34358. newDom.height = height * dpr;
  34359. return newDom;
  34360. }
  34361. var Layer = (function (_super) {
  34362. __extends(Layer, _super);
  34363. function Layer(id, painter, dpr) {
  34364. var _this = _super.call(this) || this;
  34365. _this.motionBlur = false;
  34366. _this.lastFrameAlpha = 0.7;
  34367. _this.dpr = 1;
  34368. _this.virtual = false;
  34369. _this.config = {};
  34370. _this.incremental = false;
  34371. _this.zlevel = 0;
  34372. _this.maxRepaintRectCount = 5;
  34373. _this.__dirty = true;
  34374. _this.__firstTimePaint = true;
  34375. _this.__used = false;
  34376. _this.__drawIndex = 0;
  34377. _this.__startIndex = 0;
  34378. _this.__endIndex = 0;
  34379. _this.__prevStartIndex = null;
  34380. _this.__prevEndIndex = null;
  34381. var dom;
  34382. dpr = dpr || devicePixelRatio;
  34383. if (typeof id === 'string') {
  34384. dom = createDom(id, painter, dpr);
  34385. }
  34386. else if (isObject(id)) {
  34387. dom = id;
  34388. id = dom.id;
  34389. }
  34390. _this.id = id;
  34391. _this.dom = dom;
  34392. var domStyle = dom.style;
  34393. if (domStyle) {
  34394. disableUserSelect(dom);
  34395. dom.onselectstart = function () { return false; };
  34396. domStyle.padding = '0';
  34397. domStyle.margin = '0';
  34398. domStyle.borderWidth = '0';
  34399. }
  34400. _this.painter = painter;
  34401. _this.dpr = dpr;
  34402. return _this;
  34403. }
  34404. Layer.prototype.getElementCount = function () {
  34405. return this.__endIndex - this.__startIndex;
  34406. };
  34407. Layer.prototype.afterBrush = function () {
  34408. this.__prevStartIndex = this.__startIndex;
  34409. this.__prevEndIndex = this.__endIndex;
  34410. };
  34411. Layer.prototype.initContext = function () {
  34412. this.ctx = this.dom.getContext('2d');
  34413. this.ctx.dpr = this.dpr;
  34414. };
  34415. Layer.prototype.setUnpainted = function () {
  34416. this.__firstTimePaint = true;
  34417. };
  34418. Layer.prototype.createBackBuffer = function () {
  34419. var dpr = this.dpr;
  34420. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  34421. this.ctxBack = this.domBack.getContext('2d');
  34422. if (dpr !== 1) {
  34423. this.ctxBack.scale(dpr, dpr);
  34424. }
  34425. };
  34426. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  34427. if (this.__firstTimePaint) {
  34428. this.__firstTimePaint = false;
  34429. return null;
  34430. }
  34431. var mergedRepaintRects = [];
  34432. var maxRepaintRectCount = this.maxRepaintRectCount;
  34433. var full = false;
  34434. var pendingRect = new BoundingRect(0, 0, 0, 0);
  34435. function addRectToMergePool(rect) {
  34436. if (!rect.isFinite() || rect.isZero()) {
  34437. return;
  34438. }
  34439. if (mergedRepaintRects.length === 0) {
  34440. var boundingRect = new BoundingRect(0, 0, 0, 0);
  34441. boundingRect.copy(rect);
  34442. mergedRepaintRects.push(boundingRect);
  34443. }
  34444. else {
  34445. var isMerged = false;
  34446. var minDeltaArea = Infinity;
  34447. var bestRectToMergeIdx = 0;
  34448. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  34449. var mergedRect = mergedRepaintRects[i];
  34450. if (mergedRect.intersect(rect)) {
  34451. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  34452. pendingRect_1.copy(mergedRect);
  34453. pendingRect_1.union(rect);
  34454. mergedRepaintRects[i] = pendingRect_1;
  34455. isMerged = true;
  34456. break;
  34457. }
  34458. else if (full) {
  34459. pendingRect.copy(rect);
  34460. pendingRect.union(mergedRect);
  34461. var aArea = rect.width * rect.height;
  34462. var bArea = mergedRect.width * mergedRect.height;
  34463. var pendingArea = pendingRect.width * pendingRect.height;
  34464. var deltaArea = pendingArea - aArea - bArea;
  34465. if (deltaArea < minDeltaArea) {
  34466. minDeltaArea = deltaArea;
  34467. bestRectToMergeIdx = i;
  34468. }
  34469. }
  34470. }
  34471. if (full) {
  34472. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  34473. isMerged = true;
  34474. }
  34475. if (!isMerged) {
  34476. var boundingRect = new BoundingRect(0, 0, 0, 0);
  34477. boundingRect.copy(rect);
  34478. mergedRepaintRects.push(boundingRect);
  34479. }
  34480. if (!full) {
  34481. full = mergedRepaintRects.length >= maxRepaintRectCount;
  34482. }
  34483. }
  34484. }
  34485. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  34486. var el = displayList[i];
  34487. if (el) {
  34488. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  34489. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  34490. ? el.getPrevPaintRect()
  34491. : null;
  34492. if (prevRect) {
  34493. addRectToMergePool(prevRect);
  34494. }
  34495. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  34496. ? el.getPaintRect()
  34497. : null;
  34498. if (curRect) {
  34499. addRectToMergePool(curRect);
  34500. }
  34501. }
  34502. }
  34503. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  34504. var el = prevList[i];
  34505. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  34506. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  34507. var prevRect = el.getPrevPaintRect();
  34508. if (prevRect) {
  34509. addRectToMergePool(prevRect);
  34510. }
  34511. }
  34512. }
  34513. var hasIntersections;
  34514. do {
  34515. hasIntersections = false;
  34516. for (var i = 0; i < mergedRepaintRects.length;) {
  34517. if (mergedRepaintRects[i].isZero()) {
  34518. mergedRepaintRects.splice(i, 1);
  34519. continue;
  34520. }
  34521. for (var j = i + 1; j < mergedRepaintRects.length;) {
  34522. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  34523. hasIntersections = true;
  34524. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  34525. mergedRepaintRects.splice(j, 1);
  34526. }
  34527. else {
  34528. j++;
  34529. }
  34530. }
  34531. i++;
  34532. }
  34533. } while (hasIntersections);
  34534. this._paintRects = mergedRepaintRects;
  34535. return mergedRepaintRects;
  34536. };
  34537. Layer.prototype.debugGetPaintRects = function () {
  34538. return (this._paintRects || []).slice();
  34539. };
  34540. Layer.prototype.resize = function (width, height) {
  34541. var dpr = this.dpr;
  34542. var dom = this.dom;
  34543. var domStyle = dom.style;
  34544. var domBack = this.domBack;
  34545. if (domStyle) {
  34546. domStyle.width = width + 'px';
  34547. domStyle.height = height + 'px';
  34548. }
  34549. dom.width = width * dpr;
  34550. dom.height = height * dpr;
  34551. if (domBack) {
  34552. domBack.width = width * dpr;
  34553. domBack.height = height * dpr;
  34554. if (dpr !== 1) {
  34555. this.ctxBack.scale(dpr, dpr);
  34556. }
  34557. }
  34558. };
  34559. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  34560. var dom = this.dom;
  34561. var ctx = this.ctx;
  34562. var width = dom.width;
  34563. var height = dom.height;
  34564. clearColor = clearColor || this.clearColor;
  34565. var haveMotionBLur = this.motionBlur && !clearAll;
  34566. var lastFrameAlpha = this.lastFrameAlpha;
  34567. var dpr = this.dpr;
  34568. var self = this;
  34569. if (haveMotionBLur) {
  34570. if (!this.domBack) {
  34571. this.createBackBuffer();
  34572. }
  34573. this.ctxBack.globalCompositeOperation = 'copy';
  34574. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  34575. }
  34576. var domBack = this.domBack;
  34577. function doClear(x, y, width, height) {
  34578. ctx.clearRect(x, y, width, height);
  34579. if (clearColor && clearColor !== 'transparent') {
  34580. var clearColorGradientOrPattern = void 0;
  34581. if (isGradientObject(clearColor)) {
  34582. clearColorGradientOrPattern = clearColor.__canvasGradient
  34583. || getCanvasGradient(ctx, clearColor, {
  34584. x: 0,
  34585. y: 0,
  34586. width: width,
  34587. height: height
  34588. });
  34589. clearColor.__canvasGradient = clearColorGradientOrPattern;
  34590. }
  34591. else if (isImagePatternObject(clearColor)) {
  34592. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  34593. dirty: function () {
  34594. self.setUnpainted();
  34595. self.__painter.refresh();
  34596. }
  34597. });
  34598. }
  34599. ctx.save();
  34600. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  34601. ctx.fillRect(x, y, width, height);
  34602. ctx.restore();
  34603. }
  34604. if (haveMotionBLur) {
  34605. ctx.save();
  34606. ctx.globalAlpha = lastFrameAlpha;
  34607. ctx.drawImage(domBack, x, y, width, height);
  34608. ctx.restore();
  34609. }
  34610. }
  34611. if (!repaintRects || haveMotionBLur) {
  34612. doClear(0, 0, width, height);
  34613. }
  34614. else if (repaintRects.length) {
  34615. each(repaintRects, function (rect) {
  34616. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34617. });
  34618. }
  34619. };
  34620. return Layer;
  34621. }(Eventful));
  34622. var HOVER_LAYER_ZLEVEL = 1e5;
  34623. var CANVAS_ZLEVEL = 314159;
  34624. var EL_AFTER_INCREMENTAL_INC = 0.01;
  34625. var INCREMENTAL_INC = 0.001;
  34626. function isLayerValid(layer) {
  34627. if (!layer) {
  34628. return false;
  34629. }
  34630. if (layer.__builtin__) {
  34631. return true;
  34632. }
  34633. if (typeof (layer.resize) !== 'function'
  34634. || typeof (layer.refresh) !== 'function') {
  34635. return false;
  34636. }
  34637. return true;
  34638. }
  34639. function createRoot(width, height) {
  34640. var domRoot = document.createElement('div');
  34641. domRoot.style.cssText = [
  34642. 'position:relative',
  34643. 'width:' + width + 'px',
  34644. 'height:' + height + 'px',
  34645. 'padding:0',
  34646. 'margin:0',
  34647. 'border-width:0'
  34648. ].join(';') + ';';
  34649. return domRoot;
  34650. }
  34651. var CanvasPainter = (function () {
  34652. function CanvasPainter(root, storage, opts, id) {
  34653. this.type = 'canvas';
  34654. this._zlevelList = [];
  34655. this._prevDisplayList = [];
  34656. this._layers = {};
  34657. this._layerConfig = {};
  34658. this._needsManuallyCompositing = false;
  34659. this.type = 'canvas';
  34660. var singleCanvas = !root.nodeName
  34661. || root.nodeName.toUpperCase() === 'CANVAS';
  34662. this._opts = opts = extend({}, opts || {});
  34663. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  34664. this._singleCanvas = singleCanvas;
  34665. this.root = root;
  34666. var rootStyle = root.style;
  34667. if (rootStyle) {
  34668. disableUserSelect(root);
  34669. root.innerHTML = '';
  34670. }
  34671. this.storage = storage;
  34672. var zlevelList = this._zlevelList;
  34673. this._prevDisplayList = [];
  34674. var layers = this._layers;
  34675. if (!singleCanvas) {
  34676. this._width = getSize(root, 0, opts);
  34677. this._height = getSize(root, 1, opts);
  34678. var domRoot = this._domRoot = createRoot(this._width, this._height);
  34679. root.appendChild(domRoot);
  34680. }
  34681. else {
  34682. var rootCanvas = root;
  34683. var width = rootCanvas.width;
  34684. var height = rootCanvas.height;
  34685. if (opts.width != null) {
  34686. width = opts.width;
  34687. }
  34688. if (opts.height != null) {
  34689. height = opts.height;
  34690. }
  34691. this.dpr = opts.devicePixelRatio || 1;
  34692. rootCanvas.width = width * this.dpr;
  34693. rootCanvas.height = height * this.dpr;
  34694. this._width = width;
  34695. this._height = height;
  34696. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  34697. mainLayer.__builtin__ = true;
  34698. mainLayer.initContext();
  34699. layers[CANVAS_ZLEVEL] = mainLayer;
  34700. mainLayer.zlevel = CANVAS_ZLEVEL;
  34701. zlevelList.push(CANVAS_ZLEVEL);
  34702. this._domRoot = root;
  34703. }
  34704. }
  34705. CanvasPainter.prototype.getType = function () {
  34706. return 'canvas';
  34707. };
  34708. CanvasPainter.prototype.isSingleCanvas = function () {
  34709. return this._singleCanvas;
  34710. };
  34711. CanvasPainter.prototype.getViewportRoot = function () {
  34712. return this._domRoot;
  34713. };
  34714. CanvasPainter.prototype.getViewportRootOffset = function () {
  34715. var viewportRoot = this.getViewportRoot();
  34716. if (viewportRoot) {
  34717. return {
  34718. offsetLeft: viewportRoot.offsetLeft || 0,
  34719. offsetTop: viewportRoot.offsetTop || 0
  34720. };
  34721. }
  34722. };
  34723. CanvasPainter.prototype.refresh = function (paintAll) {
  34724. var list = this.storage.getDisplayList(true);
  34725. var prevList = this._prevDisplayList;
  34726. var zlevelList = this._zlevelList;
  34727. this._redrawId = Math.random();
  34728. this._paintList(list, prevList, paintAll, this._redrawId);
  34729. for (var i = 0; i < zlevelList.length; i++) {
  34730. var z = zlevelList[i];
  34731. var layer = this._layers[z];
  34732. if (!layer.__builtin__ && layer.refresh) {
  34733. var clearColor = i === 0 ? this._backgroundColor : null;
  34734. layer.refresh(clearColor);
  34735. }
  34736. }
  34737. if (this._opts.useDirtyRect) {
  34738. this._prevDisplayList = list.slice();
  34739. }
  34740. return this;
  34741. };
  34742. CanvasPainter.prototype.refreshHover = function () {
  34743. this._paintHoverList(this.storage.getDisplayList(false));
  34744. };
  34745. CanvasPainter.prototype._paintHoverList = function (list) {
  34746. var len = list.length;
  34747. var hoverLayer = this._hoverlayer;
  34748. hoverLayer && hoverLayer.clear();
  34749. if (!len) {
  34750. return;
  34751. }
  34752. var scope = {
  34753. inHover: true,
  34754. viewWidth: this._width,
  34755. viewHeight: this._height
  34756. };
  34757. var ctx;
  34758. for (var i = 0; i < len; i++) {
  34759. var el = list[i];
  34760. if (el.__inHover) {
  34761. if (!hoverLayer) {
  34762. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  34763. }
  34764. if (!ctx) {
  34765. ctx = hoverLayer.ctx;
  34766. ctx.save();
  34767. }
  34768. brush(ctx, el, scope, i === len - 1);
  34769. }
  34770. }
  34771. if (ctx) {
  34772. ctx.restore();
  34773. }
  34774. };
  34775. CanvasPainter.prototype.getHoverLayer = function () {
  34776. return this.getLayer(HOVER_LAYER_ZLEVEL);
  34777. };
  34778. CanvasPainter.prototype.paintOne = function (ctx, el) {
  34779. brushSingle(ctx, el);
  34780. };
  34781. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  34782. if (this._redrawId !== redrawId) {
  34783. return;
  34784. }
  34785. paintAll = paintAll || false;
  34786. this._updateLayerStatus(list);
  34787. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  34788. if (this._needsManuallyCompositing) {
  34789. this._compositeManually();
  34790. }
  34791. if (needsRefreshHover) {
  34792. this._paintHoverList(list);
  34793. }
  34794. if (!finished) {
  34795. var self_1 = this;
  34796. requestAnimationFrame$1(function () {
  34797. self_1._paintList(list, prevList, paintAll, redrawId);
  34798. });
  34799. }
  34800. else {
  34801. this.eachLayer(function (layer) {
  34802. layer.afterBrush && layer.afterBrush();
  34803. });
  34804. }
  34805. };
  34806. CanvasPainter.prototype._compositeManually = function () {
  34807. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  34808. var width = this._domRoot.width;
  34809. var height = this._domRoot.height;
  34810. ctx.clearRect(0, 0, width, height);
  34811. this.eachBuiltinLayer(function (layer) {
  34812. if (layer.virtual) {
  34813. ctx.drawImage(layer.dom, 0, 0, width, height);
  34814. }
  34815. });
  34816. };
  34817. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  34818. var _this = this;
  34819. var layerList = [];
  34820. var useDirtyRect = this._opts.useDirtyRect;
  34821. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  34822. var zlevel = this._zlevelList[zi];
  34823. var layer = this._layers[zlevel];
  34824. if (layer.__builtin__
  34825. && layer !== this._hoverlayer
  34826. && (layer.__dirty || paintAll)) {
  34827. layerList.push(layer);
  34828. }
  34829. }
  34830. var finished = true;
  34831. var needsRefreshHover = false;
  34832. var _loop_1 = function (k) {
  34833. var layer = layerList[k];
  34834. var ctx = layer.ctx;
  34835. var repaintRects = useDirtyRect
  34836. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  34837. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  34838. var useTimer = !paintAll && layer.incremental && Date.now;
  34839. var startTime = useTimer && Date.now();
  34840. var clearColor = layer.zlevel === this_1._zlevelList[0]
  34841. ? this_1._backgroundColor : null;
  34842. if (layer.__startIndex === layer.__endIndex) {
  34843. layer.clear(false, clearColor, repaintRects);
  34844. }
  34845. else if (start === layer.__startIndex) {
  34846. var firstEl = list[start];
  34847. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  34848. layer.clear(false, clearColor, repaintRects);
  34849. }
  34850. }
  34851. if (start === -1) {
  34852. console.error('For some unknown reason. drawIndex is -1');
  34853. start = layer.__startIndex;
  34854. }
  34855. var i;
  34856. var repaint = function (repaintRect) {
  34857. var scope = {
  34858. inHover: false,
  34859. allClipped: false,
  34860. prevEl: null,
  34861. viewWidth: _this._width,
  34862. viewHeight: _this._height
  34863. };
  34864. for (i = start; i < layer.__endIndex; i++) {
  34865. var el = list[i];
  34866. if (el.__inHover) {
  34867. needsRefreshHover = true;
  34868. }
  34869. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  34870. if (useTimer) {
  34871. var dTime = Date.now() - startTime;
  34872. if (dTime > 15) {
  34873. break;
  34874. }
  34875. }
  34876. }
  34877. if (scope.prevElClipPaths) {
  34878. ctx.restore();
  34879. }
  34880. };
  34881. if (repaintRects) {
  34882. if (repaintRects.length === 0) {
  34883. i = layer.__endIndex;
  34884. }
  34885. else {
  34886. var dpr = this_1.dpr;
  34887. for (var r = 0; r < repaintRects.length; ++r) {
  34888. var rect = repaintRects[r];
  34889. ctx.save();
  34890. ctx.beginPath();
  34891. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34892. ctx.clip();
  34893. repaint(rect);
  34894. ctx.restore();
  34895. }
  34896. }
  34897. }
  34898. else {
  34899. ctx.save();
  34900. repaint();
  34901. ctx.restore();
  34902. }
  34903. layer.__drawIndex = i;
  34904. if (layer.__drawIndex < layer.__endIndex) {
  34905. finished = false;
  34906. }
  34907. };
  34908. var this_1 = this;
  34909. for (var k = 0; k < layerList.length; k++) {
  34910. _loop_1(k);
  34911. }
  34912. if (env.wxa) {
  34913. each(this._layers, function (layer) {
  34914. if (layer && layer.ctx && layer.ctx.draw) {
  34915. layer.ctx.draw();
  34916. }
  34917. });
  34918. }
  34919. return {
  34920. finished: finished,
  34921. needsRefreshHover: needsRefreshHover
  34922. };
  34923. };
  34924. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  34925. var ctx = currentLayer.ctx;
  34926. if (useDirtyRect) {
  34927. var paintRect = el.getPaintRect();
  34928. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  34929. brush(ctx, el, scope, isLast);
  34930. el.setPrevPaintRect(paintRect);
  34931. }
  34932. }
  34933. else {
  34934. brush(ctx, el, scope, isLast);
  34935. }
  34936. };
  34937. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  34938. if (this._singleCanvas && !this._needsManuallyCompositing) {
  34939. zlevel = CANVAS_ZLEVEL;
  34940. }
  34941. var layer = this._layers[zlevel];
  34942. if (!layer) {
  34943. layer = new Layer('zr_' + zlevel, this, this.dpr);
  34944. layer.zlevel = zlevel;
  34945. layer.__builtin__ = true;
  34946. if (this._layerConfig[zlevel]) {
  34947. merge(layer, this._layerConfig[zlevel], true);
  34948. }
  34949. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  34950. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  34951. }
  34952. if (virtual) {
  34953. layer.virtual = virtual;
  34954. }
  34955. this.insertLayer(zlevel, layer);
  34956. layer.initContext();
  34957. }
  34958. return layer;
  34959. };
  34960. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  34961. var layersMap = this._layers;
  34962. var zlevelList = this._zlevelList;
  34963. var len = zlevelList.length;
  34964. var domRoot = this._domRoot;
  34965. var prevLayer = null;
  34966. var i = -1;
  34967. if (layersMap[zlevel]) {
  34968. if ("development" !== 'production') {
  34969. logError('ZLevel ' + zlevel + ' has been used already');
  34970. }
  34971. return;
  34972. }
  34973. if (!isLayerValid(layer)) {
  34974. if ("development" !== 'production') {
  34975. logError('Layer of zlevel ' + zlevel + ' is not valid');
  34976. }
  34977. return;
  34978. }
  34979. if (len > 0 && zlevel > zlevelList[0]) {
  34980. for (i = 0; i < len - 1; i++) {
  34981. if (zlevelList[i] < zlevel
  34982. && zlevelList[i + 1] > zlevel) {
  34983. break;
  34984. }
  34985. }
  34986. prevLayer = layersMap[zlevelList[i]];
  34987. }
  34988. zlevelList.splice(i + 1, 0, zlevel);
  34989. layersMap[zlevel] = layer;
  34990. if (!layer.virtual) {
  34991. if (prevLayer) {
  34992. var prevDom = prevLayer.dom;
  34993. if (prevDom.nextSibling) {
  34994. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  34995. }
  34996. else {
  34997. domRoot.appendChild(layer.dom);
  34998. }
  34999. }
  35000. else {
  35001. if (domRoot.firstChild) {
  35002. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  35003. }
  35004. else {
  35005. domRoot.appendChild(layer.dom);
  35006. }
  35007. }
  35008. }
  35009. layer.__painter = this;
  35010. };
  35011. CanvasPainter.prototype.eachLayer = function (cb, context) {
  35012. var zlevelList = this._zlevelList;
  35013. for (var i = 0; i < zlevelList.length; i++) {
  35014. var z = zlevelList[i];
  35015. cb.call(context, this._layers[z], z);
  35016. }
  35017. };
  35018. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  35019. var zlevelList = this._zlevelList;
  35020. for (var i = 0; i < zlevelList.length; i++) {
  35021. var z = zlevelList[i];
  35022. var layer = this._layers[z];
  35023. if (layer.__builtin__) {
  35024. cb.call(context, layer, z);
  35025. }
  35026. }
  35027. };
  35028. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  35029. var zlevelList = this._zlevelList;
  35030. for (var i = 0; i < zlevelList.length; i++) {
  35031. var z = zlevelList[i];
  35032. var layer = this._layers[z];
  35033. if (!layer.__builtin__) {
  35034. cb.call(context, layer, z);
  35035. }
  35036. }
  35037. };
  35038. CanvasPainter.prototype.getLayers = function () {
  35039. return this._layers;
  35040. };
  35041. CanvasPainter.prototype._updateLayerStatus = function (list) {
  35042. this.eachBuiltinLayer(function (layer, z) {
  35043. layer.__dirty = layer.__used = false;
  35044. });
  35045. function updatePrevLayer(idx) {
  35046. if (prevLayer) {
  35047. if (prevLayer.__endIndex !== idx) {
  35048. prevLayer.__dirty = true;
  35049. }
  35050. prevLayer.__endIndex = idx;
  35051. }
  35052. }
  35053. if (this._singleCanvas) {
  35054. for (var i_1 = 1; i_1 < list.length; i_1++) {
  35055. var el = list[i_1];
  35056. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  35057. this._needsManuallyCompositing = true;
  35058. break;
  35059. }
  35060. }
  35061. }
  35062. var prevLayer = null;
  35063. var incrementalLayerCount = 0;
  35064. var prevZlevel;
  35065. var i;
  35066. for (i = 0; i < list.length; i++) {
  35067. var el = list[i];
  35068. var zlevel = el.zlevel;
  35069. var layer = void 0;
  35070. if (prevZlevel !== zlevel) {
  35071. prevZlevel = zlevel;
  35072. incrementalLayerCount = 0;
  35073. }
  35074. if (el.incremental) {
  35075. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  35076. layer.incremental = true;
  35077. incrementalLayerCount = 1;
  35078. }
  35079. else {
  35080. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  35081. }
  35082. if (!layer.__builtin__) {
  35083. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  35084. }
  35085. if (layer !== prevLayer) {
  35086. layer.__used = true;
  35087. if (layer.__startIndex !== i) {
  35088. layer.__dirty = true;
  35089. }
  35090. layer.__startIndex = i;
  35091. if (!layer.incremental) {
  35092. layer.__drawIndex = i;
  35093. }
  35094. else {
  35095. layer.__drawIndex = -1;
  35096. }
  35097. updatePrevLayer(i);
  35098. prevLayer = layer;
  35099. }
  35100. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  35101. layer.__dirty = true;
  35102. if (layer.incremental && layer.__drawIndex < 0) {
  35103. layer.__drawIndex = i;
  35104. }
  35105. }
  35106. }
  35107. updatePrevLayer(i);
  35108. this.eachBuiltinLayer(function (layer, z) {
  35109. if (!layer.__used && layer.getElementCount() > 0) {
  35110. layer.__dirty = true;
  35111. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  35112. }
  35113. if (layer.__dirty && layer.__drawIndex < 0) {
  35114. layer.__drawIndex = layer.__startIndex;
  35115. }
  35116. });
  35117. };
  35118. CanvasPainter.prototype.clear = function () {
  35119. this.eachBuiltinLayer(this._clearLayer);
  35120. return this;
  35121. };
  35122. CanvasPainter.prototype._clearLayer = function (layer) {
  35123. layer.clear();
  35124. };
  35125. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35126. this._backgroundColor = backgroundColor;
  35127. each(this._layers, function (layer) {
  35128. layer.setUnpainted();
  35129. });
  35130. };
  35131. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  35132. if (config) {
  35133. var layerConfig = this._layerConfig;
  35134. if (!layerConfig[zlevel]) {
  35135. layerConfig[zlevel] = config;
  35136. }
  35137. else {
  35138. merge(layerConfig[zlevel], config, true);
  35139. }
  35140. for (var i = 0; i < this._zlevelList.length; i++) {
  35141. var _zlevel = this._zlevelList[i];
  35142. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  35143. var layer = this._layers[_zlevel];
  35144. merge(layer, layerConfig[zlevel], true);
  35145. }
  35146. }
  35147. }
  35148. };
  35149. CanvasPainter.prototype.delLayer = function (zlevel) {
  35150. var layers = this._layers;
  35151. var zlevelList = this._zlevelList;
  35152. var layer = layers[zlevel];
  35153. if (!layer) {
  35154. return;
  35155. }
  35156. layer.dom.parentNode.removeChild(layer.dom);
  35157. delete layers[zlevel];
  35158. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  35159. };
  35160. CanvasPainter.prototype.resize = function (width, height) {
  35161. if (!this._domRoot.style) {
  35162. if (width == null || height == null) {
  35163. return;
  35164. }
  35165. this._width = width;
  35166. this._height = height;
  35167. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  35168. }
  35169. else {
  35170. var domRoot = this._domRoot;
  35171. domRoot.style.display = 'none';
  35172. var opts = this._opts;
  35173. var root = this.root;
  35174. width != null && (opts.width = width);
  35175. height != null && (opts.height = height);
  35176. width = getSize(root, 0, opts);
  35177. height = getSize(root, 1, opts);
  35178. domRoot.style.display = '';
  35179. if (this._width !== width || height !== this._height) {
  35180. domRoot.style.width = width + 'px';
  35181. domRoot.style.height = height + 'px';
  35182. for (var id in this._layers) {
  35183. if (this._layers.hasOwnProperty(id)) {
  35184. this._layers[id].resize(width, height);
  35185. }
  35186. }
  35187. this.refresh(true);
  35188. }
  35189. this._width = width;
  35190. this._height = height;
  35191. }
  35192. return this;
  35193. };
  35194. CanvasPainter.prototype.clearLayer = function (zlevel) {
  35195. var layer = this._layers[zlevel];
  35196. if (layer) {
  35197. layer.clear();
  35198. }
  35199. };
  35200. CanvasPainter.prototype.dispose = function () {
  35201. this.root.innerHTML = '';
  35202. this.root =
  35203. this.storage =
  35204. this._domRoot =
  35205. this._layers = null;
  35206. };
  35207. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  35208. opts = opts || {};
  35209. if (this._singleCanvas && !this._compositeManually) {
  35210. return this._layers[CANVAS_ZLEVEL].dom;
  35211. }
  35212. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  35213. imageLayer.initContext();
  35214. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  35215. var ctx = imageLayer.ctx;
  35216. if (opts.pixelRatio <= this.dpr) {
  35217. this.refresh();
  35218. var width_1 = imageLayer.dom.width;
  35219. var height_1 = imageLayer.dom.height;
  35220. this.eachLayer(function (layer) {
  35221. if (layer.__builtin__) {
  35222. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  35223. }
  35224. else if (layer.renderToCanvas) {
  35225. ctx.save();
  35226. layer.renderToCanvas(ctx);
  35227. ctx.restore();
  35228. }
  35229. });
  35230. }
  35231. else {
  35232. var scope = {
  35233. inHover: false,
  35234. viewWidth: this._width,
  35235. viewHeight: this._height
  35236. };
  35237. var displayList = this.storage.getDisplayList(true);
  35238. for (var i = 0, len = displayList.length; i < len; i++) {
  35239. var el = displayList[i];
  35240. brush(ctx, el, scope, i === len - 1);
  35241. }
  35242. }
  35243. return imageLayer.dom;
  35244. };
  35245. CanvasPainter.prototype.getWidth = function () {
  35246. return this._width;
  35247. };
  35248. CanvasPainter.prototype.getHeight = function () {
  35249. return this._height;
  35250. };
  35251. return CanvasPainter;
  35252. }());
  35253. function install$1(registers) {
  35254. registers.registerPainter('canvas', CanvasPainter);
  35255. }
  35256. var LineSeriesModel =
  35257. /** @class */
  35258. function (_super) {
  35259. __extends(LineSeriesModel, _super);
  35260. function LineSeriesModel() {
  35261. var _this = _super !== null && _super.apply(this, arguments) || this;
  35262. _this.type = LineSeriesModel.type;
  35263. _this.hasSymbolVisual = true;
  35264. return _this;
  35265. }
  35266. LineSeriesModel.prototype.getInitialData = function (option) {
  35267. if ("development" !== 'production') {
  35268. var coordSys = option.coordinateSystem;
  35269. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  35270. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  35271. }
  35272. }
  35273. return createSeriesData(null, this, {
  35274. useEncodeDefaulter: true
  35275. });
  35276. };
  35277. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  35278. var group = new Group();
  35279. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  35280. group.add(line);
  35281. line.setStyle(opt.lineStyle);
  35282. var visualType = this.getData().getVisual('symbol');
  35283. var visualRotate = this.getData().getVisual('symbolRotate');
  35284. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  35285. var size = opt.itemHeight * 0.8;
  35286. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  35287. group.add(symbol);
  35288. symbol.setStyle(opt.itemStyle);
  35289. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  35290. symbol.rotation = symbolRotate * Math.PI / 180;
  35291. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  35292. if (symbolType.indexOf('empty') > -1) {
  35293. symbol.style.stroke = symbol.style.fill;
  35294. symbol.style.fill = '#fff';
  35295. symbol.style.lineWidth = 2;
  35296. }
  35297. return group;
  35298. };
  35299. LineSeriesModel.type = 'series.line';
  35300. LineSeriesModel.dependencies = ['grid', 'polar'];
  35301. LineSeriesModel.defaultOption = {
  35302. // zlevel: 0,
  35303. z: 3,
  35304. coordinateSystem: 'cartesian2d',
  35305. legendHoverLink: true,
  35306. clip: true,
  35307. label: {
  35308. position: 'top'
  35309. },
  35310. // itemStyle: {
  35311. // },
  35312. endLabel: {
  35313. show: false,
  35314. valueAnimation: true,
  35315. distance: 8
  35316. },
  35317. lineStyle: {
  35318. width: 2,
  35319. type: 'solid'
  35320. },
  35321. emphasis: {
  35322. scale: true
  35323. },
  35324. // areaStyle: {
  35325. // origin of areaStyle. Valid values:
  35326. // `'auto'/null/undefined`: from axisLine to data
  35327. // `'start'`: from min to data
  35328. // `'end'`: from data to max
  35329. // origin: 'auto'
  35330. // },
  35331. // false, 'start', 'end', 'middle'
  35332. step: false,
  35333. // Disabled if step is true
  35334. smooth: false,
  35335. smoothMonotone: null,
  35336. symbol: 'emptyCircle',
  35337. symbolSize: 4,
  35338. symbolRotate: null,
  35339. showSymbol: true,
  35340. // `false`: follow the label interval strategy.
  35341. // `true`: show all symbols.
  35342. // `'auto'`: If possible, show all symbols, otherwise
  35343. // follow the label interval strategy.
  35344. showAllSymbol: 'auto',
  35345. // Whether to connect break point.
  35346. connectNulls: false,
  35347. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  35348. sampling: 'none',
  35349. animationEasing: 'linear',
  35350. // Disable progressive
  35351. progressive: 0,
  35352. hoverLayerThreshold: Infinity,
  35353. universalTransition: {
  35354. divideShape: 'clone'
  35355. },
  35356. triggerLineEvent: false
  35357. };
  35358. return LineSeriesModel;
  35359. }(SeriesModel);
  35360. /**
  35361. * @return label string. Not null/undefined
  35362. */
  35363. function getDefaultLabel(data, dataIndex) {
  35364. var labelDims = data.mapDimensionsAll('defaultedLabel');
  35365. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  35366. if (len === 1) {
  35367. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  35368. return rawVal != null ? rawVal + '' : null;
  35369. } else if (len) {
  35370. var vals = [];
  35371. for (var i = 0; i < labelDims.length; i++) {
  35372. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  35373. }
  35374. return vals.join(' ');
  35375. }
  35376. }
  35377. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  35378. var labelDims = data.mapDimensionsAll('defaultedLabel');
  35379. if (!isArray(interpolatedValue)) {
  35380. return interpolatedValue + '';
  35381. }
  35382. var vals = [];
  35383. for (var i = 0; i < labelDims.length; i++) {
  35384. var dimIndex = data.getDimensionIndex(labelDims[i]);
  35385. if (dimIndex >= 0) {
  35386. vals.push(interpolatedValue[dimIndex]);
  35387. }
  35388. }
  35389. return vals.join(' ');
  35390. }
  35391. var Symbol =
  35392. /** @class */
  35393. function (_super) {
  35394. __extends(Symbol, _super);
  35395. function Symbol(data, idx, seriesScope, opts) {
  35396. var _this = _super.call(this) || this;
  35397. _this.updateData(data, idx, seriesScope, opts);
  35398. return _this;
  35399. }
  35400. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  35401. // Remove paths created before
  35402. this.removeAll(); // let symbolPath = createSymbol(
  35403. // symbolType, -0.5, -0.5, 1, 1, color
  35404. // );
  35405. // If width/height are set too small (e.g., set to 1) on ios10
  35406. // and macOS Sierra, a circle stroke become a rect, no matter what
  35407. // the scale is set. So we set width/height as 2. See #4150.
  35408. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  35409. symbolPath.attr({
  35410. z2: 100,
  35411. culling: true,
  35412. scaleX: symbolSize[0] / 2,
  35413. scaleY: symbolSize[1] / 2
  35414. }); // Rewrite drift method
  35415. symbolPath.drift = driftSymbol;
  35416. this._symbolType = symbolType;
  35417. this.add(symbolPath);
  35418. };
  35419. /**
  35420. * Stop animation
  35421. * @param {boolean} toLastFrame
  35422. */
  35423. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  35424. this.childAt(0).stopAnimation(null, toLastFrame);
  35425. };
  35426. Symbol.prototype.getSymbolType = function () {
  35427. return this._symbolType;
  35428. };
  35429. /**
  35430. * FIXME:
  35431. * Caution: This method breaks the encapsulation of this module,
  35432. * but it indeed brings convenience. So do not use the method
  35433. * unless you detailedly know all the implements of `Symbol`,
  35434. * especially animation.
  35435. *
  35436. * Get symbol path element.
  35437. */
  35438. Symbol.prototype.getSymbolPath = function () {
  35439. return this.childAt(0);
  35440. };
  35441. /**
  35442. * Highlight symbol
  35443. */
  35444. Symbol.prototype.highlight = function () {
  35445. enterEmphasis(this.childAt(0));
  35446. };
  35447. /**
  35448. * Downplay symbol
  35449. */
  35450. Symbol.prototype.downplay = function () {
  35451. leaveEmphasis(this.childAt(0));
  35452. };
  35453. /**
  35454. * @param {number} zlevel
  35455. * @param {number} z
  35456. */
  35457. Symbol.prototype.setZ = function (zlevel, z) {
  35458. var symbolPath = this.childAt(0);
  35459. symbolPath.zlevel = zlevel;
  35460. symbolPath.z = z;
  35461. };
  35462. Symbol.prototype.setDraggable = function (draggable) {
  35463. var symbolPath = this.childAt(0);
  35464. symbolPath.draggable = draggable;
  35465. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  35466. };
  35467. /**
  35468. * Update symbol properties
  35469. */
  35470. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  35471. this.silent = false;
  35472. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  35473. var seriesModel = data.hostModel;
  35474. var symbolSize = Symbol.getSymbolSize(data, idx);
  35475. var isInit = symbolType !== this._symbolType;
  35476. var disableAnimation = opts && opts.disableAnimation;
  35477. if (isInit) {
  35478. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  35479. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  35480. } else {
  35481. var symbolPath = this.childAt(0);
  35482. symbolPath.silent = false;
  35483. var target = {
  35484. scaleX: symbolSize[0] / 2,
  35485. scaleY: symbolSize[1] / 2
  35486. };
  35487. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  35488. saveOldStyle(symbolPath);
  35489. }
  35490. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  35491. if (isInit) {
  35492. var symbolPath = this.childAt(0);
  35493. if (!disableAnimation) {
  35494. var target = {
  35495. scaleX: this._sizeX,
  35496. scaleY: this._sizeY,
  35497. style: {
  35498. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  35499. opacity: symbolPath.style.opacity
  35500. }
  35501. };
  35502. symbolPath.scaleX = symbolPath.scaleY = 0;
  35503. symbolPath.style.opacity = 0;
  35504. initProps(symbolPath, target, seriesModel, idx);
  35505. }
  35506. }
  35507. if (disableAnimation) {
  35508. // Must stop leave transition manually if don't call initProps or updateProps.
  35509. this.childAt(0).stopAnimation('leave');
  35510. }
  35511. };
  35512. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  35513. var symbolPath = this.childAt(0);
  35514. var seriesModel = data.hostModel;
  35515. var emphasisItemStyle;
  35516. var blurItemStyle;
  35517. var selectItemStyle;
  35518. var focus;
  35519. var blurScope;
  35520. var emphasisDisabled;
  35521. var labelStatesModels;
  35522. var hoverScale;
  35523. var cursorStyle;
  35524. if (seriesScope) {
  35525. emphasisItemStyle = seriesScope.emphasisItemStyle;
  35526. blurItemStyle = seriesScope.blurItemStyle;
  35527. selectItemStyle = seriesScope.selectItemStyle;
  35528. focus = seriesScope.focus;
  35529. blurScope = seriesScope.blurScope;
  35530. labelStatesModels = seriesScope.labelStatesModels;
  35531. hoverScale = seriesScope.hoverScale;
  35532. cursorStyle = seriesScope.cursorStyle;
  35533. emphasisDisabled = seriesScope.emphasisDisabled;
  35534. }
  35535. if (!seriesScope || data.hasItemOption) {
  35536. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  35537. var emphasisModel = itemModel.getModel('emphasis');
  35538. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  35539. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  35540. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  35541. focus = emphasisModel.get('focus');
  35542. blurScope = emphasisModel.get('blurScope');
  35543. emphasisDisabled = emphasisModel.get('disabled');
  35544. labelStatesModels = getLabelStatesModels(itemModel);
  35545. hoverScale = emphasisModel.getShallow('scale');
  35546. cursorStyle = itemModel.getShallow('cursor');
  35547. }
  35548. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  35549. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  35550. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  35551. if (symbolOffset) {
  35552. symbolPath.x = symbolOffset[0];
  35553. symbolPath.y = symbolOffset[1];
  35554. }
  35555. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  35556. var symbolStyle = data.getItemVisual(idx, 'style');
  35557. var visualColor = symbolStyle.fill;
  35558. if (symbolPath instanceof ZRImage) {
  35559. var pathStyle = symbolPath.style;
  35560. symbolPath.useStyle(extend({
  35561. // TODO other properties like x, y ?
  35562. image: pathStyle.image,
  35563. x: pathStyle.x,
  35564. y: pathStyle.y,
  35565. width: pathStyle.width,
  35566. height: pathStyle.height
  35567. }, symbolStyle));
  35568. } else {
  35569. if (symbolPath.__isEmptyBrush) {
  35570. // fill and stroke will be swapped if it's empty.
  35571. // So we cloned a new style to avoid it affecting the original style in visual storage.
  35572. // TODO Better implementation. No empty logic!
  35573. symbolPath.useStyle(extend({}, symbolStyle));
  35574. } else {
  35575. symbolPath.useStyle(symbolStyle);
  35576. } // Disable decal because symbol scale will been applied on the decal.
  35577. symbolPath.style.decal = null;
  35578. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  35579. symbolPath.style.strokeNoScale = true;
  35580. }
  35581. var liftZ = data.getItemVisual(idx, 'liftZ');
  35582. var z2Origin = this._z2;
  35583. if (liftZ != null) {
  35584. if (z2Origin == null) {
  35585. this._z2 = symbolPath.z2;
  35586. symbolPath.z2 += liftZ;
  35587. }
  35588. } else if (z2Origin != null) {
  35589. symbolPath.z2 = z2Origin;
  35590. this._z2 = null;
  35591. }
  35592. var useNameLabel = opts && opts.useNameLabel;
  35593. setLabelStyle(symbolPath, labelStatesModels, {
  35594. labelFetcher: seriesModel,
  35595. labelDataIndex: idx,
  35596. defaultText: getLabelDefaultText,
  35597. inheritColor: visualColor,
  35598. defaultOpacity: symbolStyle.opacity
  35599. }); // Do not execute util needed.
  35600. function getLabelDefaultText(idx) {
  35601. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  35602. }
  35603. this._sizeX = symbolSize[0] / 2;
  35604. this._sizeY = symbolSize[1] / 2;
  35605. var emphasisState = symbolPath.ensureState('emphasis');
  35606. emphasisState.style = emphasisItemStyle;
  35607. symbolPath.ensureState('select').style = selectItemStyle;
  35608. symbolPath.ensureState('blur').style = blurItemStyle;
  35609. if (hoverScale) {
  35610. var scaleRatio = Math.max(isNumber(hoverScale) ? hoverScale : 1.1, 3 / this._sizeY);
  35611. emphasisState.scaleX = this._sizeX * scaleRatio;
  35612. emphasisState.scaleY = this._sizeY * scaleRatio;
  35613. }
  35614. this.setSymbolScale(1);
  35615. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  35616. };
  35617. Symbol.prototype.setSymbolScale = function (scale) {
  35618. this.scaleX = this.scaleY = scale;
  35619. };
  35620. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  35621. var symbolPath = this.childAt(0);
  35622. var dataIndex = getECData(this).dataIndex;
  35623. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  35624. this.silent = symbolPath.silent = true; // Not show text when animating
  35625. if (opt && opt.fadeLabel) {
  35626. var textContent = symbolPath.getTextContent();
  35627. if (textContent) {
  35628. removeElement(textContent, {
  35629. style: {
  35630. opacity: 0
  35631. }
  35632. }, seriesModel, {
  35633. dataIndex: dataIndex,
  35634. removeOpt: animationOpt,
  35635. cb: function () {
  35636. symbolPath.removeTextContent();
  35637. }
  35638. });
  35639. }
  35640. } else {
  35641. symbolPath.removeTextContent();
  35642. }
  35643. removeElement(symbolPath, {
  35644. style: {
  35645. opacity: 0
  35646. },
  35647. scaleX: 0,
  35648. scaleY: 0
  35649. }, seriesModel, {
  35650. dataIndex: dataIndex,
  35651. cb: cb,
  35652. removeOpt: animationOpt
  35653. });
  35654. };
  35655. Symbol.getSymbolSize = function (data, idx) {
  35656. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  35657. };
  35658. return Symbol;
  35659. }(Group);
  35660. function driftSymbol(dx, dy) {
  35661. this.parent.drift(dx, dy);
  35662. }
  35663. function symbolNeedsDraw(data, point, idx, opt) {
  35664. 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
  35665. // the symbol element shape. We use the same clip shape here as
  35666. // the line clip.
  35667. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  35668. }
  35669. function normalizeUpdateOpt(opt) {
  35670. if (opt != null && !isObject(opt)) {
  35671. opt = {
  35672. isIgnore: opt
  35673. };
  35674. }
  35675. return opt || {};
  35676. }
  35677. function makeSeriesScope(data) {
  35678. var seriesModel = data.hostModel;
  35679. var emphasisModel = seriesModel.getModel('emphasis');
  35680. return {
  35681. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  35682. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  35683. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  35684. focus: emphasisModel.get('focus'),
  35685. blurScope: emphasisModel.get('blurScope'),
  35686. emphasisDisabled: emphasisModel.get('disabled'),
  35687. hoverScale: emphasisModel.get('scale'),
  35688. labelStatesModels: getLabelStatesModels(seriesModel),
  35689. cursorStyle: seriesModel.get('cursor')
  35690. };
  35691. }
  35692. var SymbolDraw =
  35693. /** @class */
  35694. function () {
  35695. function SymbolDraw(SymbolCtor) {
  35696. this.group = new Group();
  35697. this._SymbolCtor = SymbolCtor || Symbol;
  35698. }
  35699. /**
  35700. * Update symbols draw by new data
  35701. */
  35702. SymbolDraw.prototype.updateData = function (data, opt) {
  35703. // Remove progressive els.
  35704. this._progressiveEls = null;
  35705. opt = normalizeUpdateOpt(opt);
  35706. var group = this.group;
  35707. var seriesModel = data.hostModel;
  35708. var oldData = this._data;
  35709. var SymbolCtor = this._SymbolCtor;
  35710. var disableAnimation = opt.disableAnimation;
  35711. var seriesScope = makeSeriesScope(data);
  35712. var symbolUpdateOpt = {
  35713. disableAnimation: disableAnimation
  35714. };
  35715. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  35716. return data.getItemLayout(idx);
  35717. }; // There is no oldLineData only when first rendering or switching from
  35718. // stream mode to normal mode, where previous elements should be removed.
  35719. if (!oldData) {
  35720. group.removeAll();
  35721. }
  35722. data.diff(oldData).add(function (newIdx) {
  35723. var point = getSymbolPoint(newIdx);
  35724. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  35725. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  35726. symbolEl.setPosition(point);
  35727. data.setItemGraphicEl(newIdx, symbolEl);
  35728. group.add(symbolEl);
  35729. }
  35730. }).update(function (newIdx, oldIdx) {
  35731. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  35732. var point = getSymbolPoint(newIdx);
  35733. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  35734. group.remove(symbolEl);
  35735. return;
  35736. }
  35737. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  35738. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  35739. if (!symbolEl // Create a new if symbol type changed.
  35740. || oldSymbolType && oldSymbolType !== newSymbolType) {
  35741. group.remove(symbolEl);
  35742. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  35743. symbolEl.setPosition(point);
  35744. } else {
  35745. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  35746. var target = {
  35747. x: point[0],
  35748. y: point[1]
  35749. };
  35750. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  35751. } // Add back
  35752. group.add(symbolEl);
  35753. data.setItemGraphicEl(newIdx, symbolEl);
  35754. }).remove(function (oldIdx) {
  35755. var el = oldData.getItemGraphicEl(oldIdx);
  35756. el && el.fadeOut(function () {
  35757. group.remove(el);
  35758. }, seriesModel);
  35759. }).execute();
  35760. this._getSymbolPoint = getSymbolPoint;
  35761. this._data = data;
  35762. };
  35763. SymbolDraw.prototype.updateLayout = function () {
  35764. var _this = this;
  35765. var data = this._data;
  35766. if (data) {
  35767. // Not use animation
  35768. data.eachItemGraphicEl(function (el, idx) {
  35769. var point = _this._getSymbolPoint(idx);
  35770. el.setPosition(point);
  35771. el.markRedraw();
  35772. });
  35773. }
  35774. };
  35775. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  35776. this._seriesScope = makeSeriesScope(data);
  35777. this._data = null;
  35778. this.group.removeAll();
  35779. };
  35780. /**
  35781. * Update symbols draw by new data
  35782. */
  35783. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  35784. // Clear
  35785. this._progressiveEls = [];
  35786. opt = normalizeUpdateOpt(opt);
  35787. function updateIncrementalAndHover(el) {
  35788. if (!el.isGroup) {
  35789. el.incremental = true;
  35790. el.ensureState('emphasis').hoverLayer = true;
  35791. }
  35792. }
  35793. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  35794. var point = data.getItemLayout(idx);
  35795. if (symbolNeedsDraw(data, point, idx, opt)) {
  35796. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  35797. el.traverse(updateIncrementalAndHover);
  35798. el.setPosition(point);
  35799. this.group.add(el);
  35800. data.setItemGraphicEl(idx, el);
  35801. this._progressiveEls.push(el);
  35802. }
  35803. }
  35804. };
  35805. SymbolDraw.prototype.eachRendered = function (cb) {
  35806. traverseElements(this._progressiveEls || this.group, cb);
  35807. };
  35808. SymbolDraw.prototype.remove = function (enableAnimation) {
  35809. var group = this.group;
  35810. var data = this._data; // Incremental model do not have this._data.
  35811. if (data && enableAnimation) {
  35812. data.eachItemGraphicEl(function (el) {
  35813. el.fadeOut(function () {
  35814. group.remove(el);
  35815. }, data.hostModel);
  35816. });
  35817. } else {
  35818. group.removeAll();
  35819. }
  35820. };
  35821. return SymbolDraw;
  35822. }();
  35823. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  35824. var baseAxis = coordSys.getBaseAxis();
  35825. var valueAxis = coordSys.getOtherAxis(baseAxis);
  35826. var valueStart = getValueStart(valueAxis, valueOrigin);
  35827. var baseAxisDim = baseAxis.dim;
  35828. var valueAxisDim = valueAxis.dim;
  35829. var valueDim = data.mapDimension(valueAxisDim);
  35830. var baseDim = data.mapDimension(baseAxisDim);
  35831. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  35832. var dims = map(coordSys.dimensions, function (coordDim) {
  35833. return data.mapDimension(coordDim);
  35834. });
  35835. var stacked = false;
  35836. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35837. if (isDimensionStacked(data, dims[0]
  35838. /*, dims[1]*/
  35839. )) {
  35840. // jshint ignore:line
  35841. stacked = true;
  35842. dims[0] = stackResultDim;
  35843. }
  35844. if (isDimensionStacked(data, dims[1]
  35845. /*, dims[0]*/
  35846. )) {
  35847. // jshint ignore:line
  35848. stacked = true;
  35849. dims[1] = stackResultDim;
  35850. }
  35851. return {
  35852. dataDimsForPoint: dims,
  35853. valueStart: valueStart,
  35854. valueAxisDim: valueAxisDim,
  35855. baseAxisDim: baseAxisDim,
  35856. stacked: !!stacked,
  35857. valueDim: valueDim,
  35858. baseDim: baseDim,
  35859. baseDataOffset: baseDataOffset,
  35860. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  35861. };
  35862. }
  35863. function getValueStart(valueAxis, valueOrigin) {
  35864. var valueStart = 0;
  35865. var extent = valueAxis.scale.getExtent();
  35866. if (valueOrigin === 'start') {
  35867. valueStart = extent[0];
  35868. } else if (valueOrigin === 'end') {
  35869. valueStart = extent[1];
  35870. } // If origin is specified as a number, use it as
  35871. // valueStart directly
  35872. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  35873. valueStart = valueOrigin;
  35874. } // auto
  35875. else {
  35876. // Both positive
  35877. if (extent[0] > 0) {
  35878. valueStart = extent[0];
  35879. } // Both negative
  35880. else if (extent[1] < 0) {
  35881. valueStart = extent[1];
  35882. } // If is one positive, and one negative, onZero shall be true
  35883. }
  35884. return valueStart;
  35885. }
  35886. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  35887. var value = NaN;
  35888. if (dataCoordInfo.stacked) {
  35889. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  35890. }
  35891. if (isNaN(value)) {
  35892. value = dataCoordInfo.valueStart;
  35893. }
  35894. var baseDataOffset = dataCoordInfo.baseDataOffset;
  35895. var stackedData = [];
  35896. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  35897. stackedData[1 - baseDataOffset] = value;
  35898. return coordSys.dataToPoint(stackedData);
  35899. }
  35900. function diffData(oldData, newData) {
  35901. var diffResult = [];
  35902. newData.diff(oldData).add(function (idx) {
  35903. diffResult.push({
  35904. cmd: '+',
  35905. idx: idx
  35906. });
  35907. }).update(function (newIdx, oldIdx) {
  35908. diffResult.push({
  35909. cmd: '=',
  35910. idx: oldIdx,
  35911. idx1: newIdx
  35912. });
  35913. }).remove(function (idx) {
  35914. diffResult.push({
  35915. cmd: '-',
  35916. idx: idx
  35917. });
  35918. }).execute();
  35919. return diffResult;
  35920. }
  35921. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  35922. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  35923. // let oldIdList = oldData.mapArray(oldData.getId);
  35924. // convertToIntId(newIdList, oldIdList);
  35925. // // FIXME One data ?
  35926. // diff = arrayDiff(oldIdList, newIdList);
  35927. var currPoints = [];
  35928. var nextPoints = []; // Points for stacking base line
  35929. var currStackedPoints = [];
  35930. var nextStackedPoints = [];
  35931. var status = [];
  35932. var sortedIndices = [];
  35933. var rawIndices = [];
  35934. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  35935. var oldPoints = oldData.getLayout('points') || [];
  35936. var newPoints = newData.getLayout('points') || [];
  35937. for (var i = 0; i < diff.length; i++) {
  35938. var diffItem = diff[i];
  35939. var pointAdded = true;
  35940. var oldIdx2 = void 0;
  35941. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  35942. // Which is in case remvoing or add more than one data in the tail or head
  35943. switch (diffItem.cmd) {
  35944. case '=':
  35945. oldIdx2 = diffItem.idx * 2;
  35946. newIdx2 = diffItem.idx1 * 2;
  35947. var currentX = oldPoints[oldIdx2];
  35948. var currentY = oldPoints[oldIdx2 + 1];
  35949. var nextX = newPoints[newIdx2];
  35950. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  35951. if (isNaN(currentX) || isNaN(currentY)) {
  35952. currentX = nextX;
  35953. currentY = nextY;
  35954. }
  35955. currPoints.push(currentX, currentY);
  35956. nextPoints.push(nextX, nextY);
  35957. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  35958. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35959. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  35960. break;
  35961. case '+':
  35962. var newIdx = diffItem.idx;
  35963. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  35964. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  35965. newIdx2 = newIdx * 2;
  35966. currPoints.push(oldPt[0], oldPt[1]);
  35967. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  35968. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  35969. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  35970. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35971. rawIndices.push(newData.getRawIndex(newIdx));
  35972. break;
  35973. case '-':
  35974. pointAdded = false;
  35975. } // Original indices
  35976. if (pointAdded) {
  35977. status.push(diffItem);
  35978. sortedIndices.push(sortedIndices.length);
  35979. }
  35980. } // Diff result may be crossed if all items are changed
  35981. // Sort by data index
  35982. sortedIndices.sort(function (a, b) {
  35983. return rawIndices[a] - rawIndices[b];
  35984. });
  35985. var len = currPoints.length;
  35986. var sortedCurrPoints = createFloat32Array(len);
  35987. var sortedNextPoints = createFloat32Array(len);
  35988. var sortedCurrStackedPoints = createFloat32Array(len);
  35989. var sortedNextStackedPoints = createFloat32Array(len);
  35990. var sortedStatus = [];
  35991. for (var i = 0; i < sortedIndices.length; i++) {
  35992. var idx = sortedIndices[i];
  35993. var i2 = i * 2;
  35994. var idx2 = idx * 2;
  35995. sortedCurrPoints[i2] = currPoints[idx2];
  35996. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  35997. sortedNextPoints[i2] = nextPoints[idx2];
  35998. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  35999. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  36000. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  36001. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  36002. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  36003. sortedStatus[i] = status[idx];
  36004. }
  36005. return {
  36006. current: sortedCurrPoints,
  36007. next: sortedNextPoints,
  36008. stackedOnCurrent: sortedCurrStackedPoints,
  36009. stackedOnNext: sortedNextStackedPoints,
  36010. status: sortedStatus
  36011. };
  36012. }
  36013. var mathMin$5 = Math.min;
  36014. var mathMax$5 = Math.max;
  36015. function isPointNull(x, y) {
  36016. return isNaN(x) || isNaN(y);
  36017. }
  36018. /**
  36019. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  36020. * situations. This should be used when points are non-monotone neither in x or
  36021. * y dimension.
  36022. */
  36023. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  36024. var prevX;
  36025. var prevY;
  36026. var cpx0;
  36027. var cpy0;
  36028. var cpx1;
  36029. var cpy1;
  36030. var idx = start;
  36031. var k = 0;
  36032. for (; k < segLen; k++) {
  36033. var x = points[idx * 2];
  36034. var y = points[idx * 2 + 1];
  36035. if (idx >= allLen || idx < 0) {
  36036. break;
  36037. }
  36038. if (isPointNull(x, y)) {
  36039. if (connectNulls) {
  36040. idx += dir;
  36041. continue;
  36042. }
  36043. break;
  36044. }
  36045. if (idx === start) {
  36046. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  36047. cpx0 = x;
  36048. cpy0 = y;
  36049. } else {
  36050. var dx = x - prevX;
  36051. var dy = y - prevY; // Ignore tiny segment.
  36052. if (dx * dx + dy * dy < 0.5) {
  36053. idx += dir;
  36054. continue;
  36055. }
  36056. if (smooth > 0) {
  36057. var nextIdx = idx + dir;
  36058. var nextX = points[nextIdx * 2];
  36059. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  36060. while (nextX === x && nextY === y && k < segLen) {
  36061. k++;
  36062. nextIdx += dir;
  36063. idx += dir;
  36064. nextX = points[nextIdx * 2];
  36065. nextY = points[nextIdx * 2 + 1];
  36066. x = points[idx * 2];
  36067. y = points[idx * 2 + 1];
  36068. dx = x - prevX;
  36069. dy = y - prevY;
  36070. }
  36071. var tmpK = k + 1;
  36072. if (connectNulls) {
  36073. // Find next point not null
  36074. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  36075. tmpK++;
  36076. nextIdx += dir;
  36077. nextX = points[nextIdx * 2];
  36078. nextY = points[nextIdx * 2 + 1];
  36079. }
  36080. }
  36081. var ratioNextSeg = 0.5;
  36082. var vx = 0;
  36083. var vy = 0;
  36084. var nextCpx0 = void 0;
  36085. var nextCpy0 = void 0; // Is last point
  36086. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  36087. cpx1 = x;
  36088. cpy1 = y;
  36089. } else {
  36090. vx = nextX - prevX;
  36091. vy = nextY - prevY;
  36092. var dx0 = x - prevX;
  36093. var dx1 = nextX - x;
  36094. var dy0 = y - prevY;
  36095. var dy1 = nextY - y;
  36096. var lenPrevSeg = void 0;
  36097. var lenNextSeg = void 0;
  36098. if (smoothMonotone === 'x') {
  36099. lenPrevSeg = Math.abs(dx0);
  36100. lenNextSeg = Math.abs(dx1);
  36101. var dir_1 = vx > 0 ? 1 : -1;
  36102. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  36103. cpy1 = y;
  36104. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  36105. nextCpy0 = y;
  36106. } else if (smoothMonotone === 'y') {
  36107. lenPrevSeg = Math.abs(dy0);
  36108. lenNextSeg = Math.abs(dy1);
  36109. var dir_2 = vy > 0 ? 1 : -1;
  36110. cpx1 = x;
  36111. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  36112. nextCpx0 = x;
  36113. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  36114. } else {
  36115. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  36116. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  36117. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  36118. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  36119. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  36120. nextCpx0 = x + vx * smooth * ratioNextSeg;
  36121. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  36122. // Avoid exceeding extreme after smoothing.
  36123. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  36124. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  36125. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  36126. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  36127. vx = nextCpx0 - x;
  36128. vy = nextCpy0 - y;
  36129. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  36130. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  36131. // Avoid exceeding extreme after smoothing.
  36132. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  36133. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  36134. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  36135. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  36136. vx = x - cpx1;
  36137. vy = y - cpy1;
  36138. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  36139. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  36140. }
  36141. }
  36142. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  36143. cpx0 = nextCpx0;
  36144. cpy0 = nextCpy0;
  36145. } else {
  36146. ctx.lineTo(x, y);
  36147. }
  36148. }
  36149. prevX = x;
  36150. prevY = y;
  36151. idx += dir;
  36152. }
  36153. return k;
  36154. }
  36155. var ECPolylineShape =
  36156. /** @class */
  36157. function () {
  36158. function ECPolylineShape() {
  36159. this.smooth = 0;
  36160. this.smoothConstraint = true;
  36161. }
  36162. return ECPolylineShape;
  36163. }();
  36164. var ECPolyline =
  36165. /** @class */
  36166. function (_super) {
  36167. __extends(ECPolyline, _super);
  36168. function ECPolyline(opts) {
  36169. var _this = _super.call(this, opts) || this;
  36170. _this.type = 'ec-polyline';
  36171. return _this;
  36172. }
  36173. ECPolyline.prototype.getDefaultStyle = function () {
  36174. return {
  36175. stroke: '#000',
  36176. fill: null
  36177. };
  36178. };
  36179. ECPolyline.prototype.getDefaultShape = function () {
  36180. return new ECPolylineShape();
  36181. };
  36182. ECPolyline.prototype.buildPath = function (ctx, shape) {
  36183. var points = shape.points;
  36184. var i = 0;
  36185. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  36186. if (shape.connectNulls) {
  36187. // Must remove first and last null values avoid draw error in polygon
  36188. for (; len > 0; len--) {
  36189. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  36190. break;
  36191. }
  36192. }
  36193. for (; i < len; i++) {
  36194. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  36195. break;
  36196. }
  36197. }
  36198. }
  36199. while (i < len) {
  36200. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  36201. }
  36202. };
  36203. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  36204. if (!this.path) {
  36205. this.createPathProxy();
  36206. this.buildPath(this.path, this.shape);
  36207. }
  36208. var path = this.path;
  36209. var data = path.data;
  36210. var CMD = PathProxy.CMD;
  36211. var x0;
  36212. var y0;
  36213. var isDimX = dim === 'x';
  36214. var roots = [];
  36215. for (var i = 0; i < data.length;) {
  36216. var cmd = data[i++];
  36217. var x = void 0;
  36218. var y = void 0;
  36219. var x2 = void 0;
  36220. var y2 = void 0;
  36221. var x3 = void 0;
  36222. var y3 = void 0;
  36223. var t = void 0;
  36224. switch (cmd) {
  36225. case CMD.M:
  36226. x0 = data[i++];
  36227. y0 = data[i++];
  36228. break;
  36229. case CMD.L:
  36230. x = data[i++];
  36231. y = data[i++];
  36232. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  36233. if (t <= 1 && t >= 0) {
  36234. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  36235. return isDimX ? [xOrY, val] : [val, xOrY];
  36236. }
  36237. x0 = x;
  36238. y0 = y;
  36239. break;
  36240. case CMD.C:
  36241. x = data[i++];
  36242. y = data[i++];
  36243. x2 = data[i++];
  36244. y2 = data[i++];
  36245. x3 = data[i++];
  36246. y3 = data[i++];
  36247. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  36248. if (nRoot > 0) {
  36249. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  36250. var t_1 = roots[i_1];
  36251. if (t_1 <= 1 && t_1 >= 0) {
  36252. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  36253. return isDimX ? [xOrY, val] : [val, xOrY];
  36254. }
  36255. }
  36256. }
  36257. x0 = x3;
  36258. y0 = y3;
  36259. break;
  36260. }
  36261. }
  36262. };
  36263. return ECPolyline;
  36264. }(Path);
  36265. var ECPolygonShape =
  36266. /** @class */
  36267. function (_super) {
  36268. __extends(ECPolygonShape, _super);
  36269. function ECPolygonShape() {
  36270. return _super !== null && _super.apply(this, arguments) || this;
  36271. }
  36272. return ECPolygonShape;
  36273. }(ECPolylineShape);
  36274. var ECPolygon =
  36275. /** @class */
  36276. function (_super) {
  36277. __extends(ECPolygon, _super);
  36278. function ECPolygon(opts) {
  36279. var _this = _super.call(this, opts) || this;
  36280. _this.type = 'ec-polygon';
  36281. return _this;
  36282. }
  36283. ECPolygon.prototype.getDefaultShape = function () {
  36284. return new ECPolygonShape();
  36285. };
  36286. ECPolygon.prototype.buildPath = function (ctx, shape) {
  36287. var points = shape.points;
  36288. var stackedOnPoints = shape.stackedOnPoints;
  36289. var i = 0;
  36290. var len = points.length / 2;
  36291. var smoothMonotone = shape.smoothMonotone;
  36292. if (shape.connectNulls) {
  36293. // Must remove first and last null values avoid draw error in polygon
  36294. for (; len > 0; len--) {
  36295. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  36296. break;
  36297. }
  36298. }
  36299. for (; i < len; i++) {
  36300. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  36301. break;
  36302. }
  36303. }
  36304. }
  36305. while (i < len) {
  36306. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  36307. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  36308. i += k + 1;
  36309. ctx.closePath();
  36310. }
  36311. };
  36312. return ECPolygon;
  36313. }(Path);
  36314. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  36315. var rect = cartesian.getArea();
  36316. var x = rect.x;
  36317. var y = rect.y;
  36318. var width = rect.width;
  36319. var height = rect.height;
  36320. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  36321. x -= lineWidth / 2;
  36322. y -= lineWidth / 2;
  36323. width += lineWidth;
  36324. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  36325. x = Math.floor(x);
  36326. width = Math.round(width);
  36327. var clipPath = new Rect({
  36328. shape: {
  36329. x: x,
  36330. y: y,
  36331. width: width,
  36332. height: height
  36333. }
  36334. });
  36335. if (hasAnimation) {
  36336. var baseAxis = cartesian.getBaseAxis();
  36337. var isHorizontal = baseAxis.isHorizontal();
  36338. var isAxisInversed = baseAxis.inverse;
  36339. if (isHorizontal) {
  36340. if (isAxisInversed) {
  36341. clipPath.shape.x += width;
  36342. }
  36343. clipPath.shape.width = 0;
  36344. } else {
  36345. if (!isAxisInversed) {
  36346. clipPath.shape.y += height;
  36347. }
  36348. clipPath.shape.height = 0;
  36349. }
  36350. var duringCb = isFunction(during) ? function (percent) {
  36351. during(percent, clipPath);
  36352. } : null;
  36353. initProps(clipPath, {
  36354. shape: {
  36355. width: width,
  36356. height: height,
  36357. x: x,
  36358. y: y
  36359. }
  36360. }, seriesModel, null, done, duringCb);
  36361. }
  36362. return clipPath;
  36363. }
  36364. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  36365. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  36366. var r0 = round(sectorArea.r0, 1);
  36367. var r = round(sectorArea.r, 1);
  36368. var clipPath = new Sector({
  36369. shape: {
  36370. cx: round(polar.cx, 1),
  36371. cy: round(polar.cy, 1),
  36372. r0: r0,
  36373. r: r,
  36374. startAngle: sectorArea.startAngle,
  36375. endAngle: sectorArea.endAngle,
  36376. clockwise: sectorArea.clockwise
  36377. }
  36378. });
  36379. if (hasAnimation) {
  36380. var isRadial = polar.getBaseAxis().dim === 'angle';
  36381. if (isRadial) {
  36382. clipPath.shape.endAngle = sectorArea.startAngle;
  36383. } else {
  36384. clipPath.shape.r = r0;
  36385. }
  36386. initProps(clipPath, {
  36387. shape: {
  36388. endAngle: sectorArea.endAngle,
  36389. r: r
  36390. }
  36391. }, seriesModel);
  36392. }
  36393. return clipPath;
  36394. }
  36395. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  36396. if (!coordSys) {
  36397. return null;
  36398. } else if (coordSys.type === 'polar') {
  36399. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  36400. } else if (coordSys.type === 'cartesian2d') {
  36401. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  36402. }
  36403. return null;
  36404. }
  36405. /*
  36406. * Licensed to the Apache Software Foundation (ASF) under one
  36407. * or more contributor license agreements. See the NOTICE file
  36408. * distributed with this work for additional information
  36409. * regarding copyright ownership. The ASF licenses this file
  36410. * to you under the Apache License, Version 2.0 (the
  36411. * "License"); you may not use this file except in compliance
  36412. * with the License. You may obtain a copy of the License at
  36413. *
  36414. * http://www.apache.org/licenses/LICENSE-2.0
  36415. *
  36416. * Unless required by applicable law or agreed to in writing,
  36417. * software distributed under the License is distributed on an
  36418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36419. * KIND, either express or implied. See the License for the
  36420. * specific language governing permissions and limitations
  36421. * under the License.
  36422. */
  36423. /**
  36424. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36425. */
  36426. /*
  36427. * Licensed to the Apache Software Foundation (ASF) under one
  36428. * or more contributor license agreements. See the NOTICE file
  36429. * distributed with this work for additional information
  36430. * regarding copyright ownership. The ASF licenses this file
  36431. * to you under the Apache License, Version 2.0 (the
  36432. * "License"); you may not use this file except in compliance
  36433. * with the License. You may obtain a copy of the License at
  36434. *
  36435. * http://www.apache.org/licenses/LICENSE-2.0
  36436. *
  36437. * Unless required by applicable law or agreed to in writing,
  36438. * software distributed under the License is distributed on an
  36439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36440. * KIND, either express or implied. See the License for the
  36441. * specific language governing permissions and limitations
  36442. * under the License.
  36443. */
  36444. function isCoordinateSystemType(coordSys, type) {
  36445. return coordSys.type === type;
  36446. }
  36447. function isPointsSame(points1, points2) {
  36448. if (points1.length !== points2.length) {
  36449. return;
  36450. }
  36451. for (var i = 0; i < points1.length; i++) {
  36452. if (points1[i] !== points2[i]) {
  36453. return;
  36454. }
  36455. }
  36456. return true;
  36457. }
  36458. function bboxFromPoints(points) {
  36459. var minX = Infinity;
  36460. var minY = Infinity;
  36461. var maxX = -Infinity;
  36462. var maxY = -Infinity;
  36463. for (var i = 0; i < points.length;) {
  36464. var x = points[i++];
  36465. var y = points[i++];
  36466. if (!isNaN(x)) {
  36467. minX = Math.min(x, minX);
  36468. maxX = Math.max(x, maxX);
  36469. }
  36470. if (!isNaN(y)) {
  36471. minY = Math.min(y, minY);
  36472. maxY = Math.max(y, maxY);
  36473. }
  36474. }
  36475. return [[minX, minY], [maxX, maxY]];
  36476. }
  36477. function getBoundingDiff(points1, points2) {
  36478. var _a = bboxFromPoints(points1),
  36479. min1 = _a[0],
  36480. max1 = _a[1];
  36481. var _b = bboxFromPoints(points2),
  36482. min2 = _b[0],
  36483. max2 = _b[1]; // Get a max value from each corner of two boundings.
  36484. 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]));
  36485. }
  36486. function getSmooth(smooth) {
  36487. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  36488. }
  36489. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  36490. if (!dataCoordInfo.valueDim) {
  36491. return [];
  36492. }
  36493. var len = data.count();
  36494. var points = createFloat32Array(len * 2);
  36495. for (var idx = 0; idx < len; idx++) {
  36496. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  36497. points[idx * 2] = pt[0];
  36498. points[idx * 2 + 1] = pt[1];
  36499. }
  36500. return points;
  36501. }
  36502. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  36503. var baseAxis = coordSys.getBaseAxis();
  36504. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  36505. var stepPoints = [];
  36506. var i = 0;
  36507. var stepPt = [];
  36508. var pt = [];
  36509. var nextPt = [];
  36510. var filteredPoints = [];
  36511. if (connectNulls) {
  36512. for (i = 0; i < points.length; i += 2) {
  36513. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  36514. filteredPoints.push(points[i], points[i + 1]);
  36515. }
  36516. }
  36517. points = filteredPoints;
  36518. }
  36519. for (i = 0; i < points.length - 2; i += 2) {
  36520. nextPt[0] = points[i + 2];
  36521. nextPt[1] = points[i + 3];
  36522. pt[0] = points[i];
  36523. pt[1] = points[i + 1];
  36524. stepPoints.push(pt[0], pt[1]);
  36525. switch (stepTurnAt) {
  36526. case 'end':
  36527. stepPt[baseIndex] = nextPt[baseIndex];
  36528. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  36529. stepPoints.push(stepPt[0], stepPt[1]);
  36530. break;
  36531. case 'middle':
  36532. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  36533. var stepPt2 = [];
  36534. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  36535. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  36536. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  36537. stepPoints.push(stepPt[0], stepPt[1]);
  36538. stepPoints.push(stepPt2[0], stepPt2[1]);
  36539. break;
  36540. default:
  36541. // default is start
  36542. stepPt[baseIndex] = pt[baseIndex];
  36543. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  36544. stepPoints.push(stepPt[0], stepPt[1]);
  36545. }
  36546. } // Last points
  36547. stepPoints.push(points[i++], points[i++]);
  36548. return stepPoints;
  36549. }
  36550. /**
  36551. * Clip color stops to edge. Avoid creating too large gradients.
  36552. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  36553. *
  36554. * The stops has been sorted from small to large.
  36555. */
  36556. function clipColorStops(colorStops, maxSize) {
  36557. var newColorStops = [];
  36558. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  36559. var prevOutOfRangeColorStop;
  36560. var prevInRangeColorStop;
  36561. function lerpStop(stop0, stop1, clippedCoord) {
  36562. var coord0 = stop0.coord;
  36563. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  36564. var color = lerp$1(p, [stop0.color, stop1.color]);
  36565. return {
  36566. coord: clippedCoord,
  36567. color: color
  36568. };
  36569. }
  36570. for (var i = 0; i < len; i++) {
  36571. var stop_1 = colorStops[i];
  36572. var coord = stop_1.coord;
  36573. if (coord < 0) {
  36574. prevOutOfRangeColorStop = stop_1;
  36575. } else if (coord > maxSize) {
  36576. if (prevInRangeColorStop) {
  36577. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  36578. } else if (prevOutOfRangeColorStop) {
  36579. // If there are two stops and coord range is between these two stops
  36580. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  36581. } // All following stop will be out of range. So just ignore them.
  36582. break;
  36583. } else {
  36584. if (prevOutOfRangeColorStop) {
  36585. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  36586. prevOutOfRangeColorStop = null;
  36587. }
  36588. newColorStops.push(stop_1);
  36589. prevInRangeColorStop = stop_1;
  36590. }
  36591. }
  36592. return newColorStops;
  36593. }
  36594. function getVisualGradient(data, coordSys, api) {
  36595. var visualMetaList = data.getVisual('visualMeta');
  36596. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  36597. // When data.count() is 0, gradient range can not be calculated.
  36598. return;
  36599. }
  36600. if (coordSys.type !== 'cartesian2d') {
  36601. if ("development" !== 'production') {
  36602. console.warn('Visual map on line style is only supported on cartesian2d.');
  36603. }
  36604. return;
  36605. }
  36606. var coordDim;
  36607. var visualMeta;
  36608. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  36609. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  36610. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  36611. if (coordDim === 'x' || coordDim === 'y') {
  36612. visualMeta = visualMetaList[i];
  36613. break;
  36614. }
  36615. }
  36616. if (!visualMeta) {
  36617. if ("development" !== 'production') {
  36618. console.warn('Visual map on line style only support x or y dimension.');
  36619. }
  36620. return;
  36621. } // If the area to be rendered is bigger than area defined by LinearGradient,
  36622. // the canvas spec prescribes that the color of the first stop and the last
  36623. // stop should be used. But if two stops are added at offset 0, in effect
  36624. // browsers use the color of the second stop to render area outside
  36625. // LinearGradient. So we can only infinitesimally extend area defined in
  36626. // LinearGradient to render `outerColors`.
  36627. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  36628. var colorStops = map(visualMeta.stops, function (stop) {
  36629. // offset will be calculated later.
  36630. return {
  36631. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  36632. color: stop.color
  36633. };
  36634. });
  36635. var stopLen = colorStops.length;
  36636. var outerColors = visualMeta.outerColors.slice();
  36637. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  36638. colorStops.reverse();
  36639. outerColors.reverse();
  36640. }
  36641. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  36642. var inRangeStopLen = colorStopsInRange.length;
  36643. if (!inRangeStopLen && stopLen) {
  36644. // All stops are out of range. All will be the same color.
  36645. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  36646. }
  36647. var tinyExtent = 10; // Arbitrary value: 10px
  36648. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  36649. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  36650. var coordSpan = maxCoord - minCoord;
  36651. if (coordSpan < 1e-3) {
  36652. return 'transparent';
  36653. }
  36654. each(colorStopsInRange, function (stop) {
  36655. stop.offset = (stop.coord - minCoord) / coordSpan;
  36656. });
  36657. colorStopsInRange.push({
  36658. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  36659. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  36660. color: outerColors[1] || 'transparent'
  36661. });
  36662. colorStopsInRange.unshift({
  36663. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  36664. color: outerColors[0] || 'transparent'
  36665. });
  36666. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  36667. gradient[coordDim] = minCoord;
  36668. gradient[coordDim + '2'] = maxCoord;
  36669. return gradient;
  36670. }
  36671. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  36672. var showAllSymbol = seriesModel.get('showAllSymbol');
  36673. var isAuto = showAllSymbol === 'auto';
  36674. if (showAllSymbol && !isAuto) {
  36675. return;
  36676. }
  36677. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  36678. if (!categoryAxis) {
  36679. return;
  36680. } // Note that category label interval strategy might bring some weird effect
  36681. // in some scenario: users may wonder why some of the symbols are not
  36682. // displayed. So we show all symbols as possible as we can.
  36683. if (isAuto // Simplify the logic, do not determine label overlap here.
  36684. && canShowAllSymbolForCategory(categoryAxis, data)) {
  36685. return;
  36686. } // Otherwise follow the label interval strategy on category axis.
  36687. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  36688. var labelMap = {};
  36689. each(categoryAxis.getViewLabels(), function (labelItem) {
  36690. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  36691. labelMap[ordinalNumber] = 1;
  36692. });
  36693. return function (dataIndex) {
  36694. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  36695. };
  36696. }
  36697. function canShowAllSymbolForCategory(categoryAxis, data) {
  36698. // In mose cases, line is monotonous on category axis, and the label size
  36699. // is close with each other. So we check the symbol size and some of the
  36700. // label size alone with the category axis to estimate whether all symbol
  36701. // can be shown without overlap.
  36702. var axisExtent = categoryAxis.getExtent();
  36703. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  36704. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  36705. // Sampling some points, max 5.
  36706. var dataLen = data.count();
  36707. var step = Math.max(1, Math.round(dataLen / 5));
  36708. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  36709. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  36710. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  36711. * 1.5 > availSize) {
  36712. return false;
  36713. }
  36714. }
  36715. return true;
  36716. }
  36717. function isPointNull$1(x, y) {
  36718. return isNaN(x) || isNaN(y);
  36719. }
  36720. function getLastIndexNotNull(points) {
  36721. var len = points.length / 2;
  36722. for (; len > 0; len--) {
  36723. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  36724. break;
  36725. }
  36726. }
  36727. return len - 1;
  36728. }
  36729. function getPointAtIndex(points, idx) {
  36730. return [points[idx * 2], points[idx * 2 + 1]];
  36731. }
  36732. function getIndexRange(points, xOrY, dim) {
  36733. var len = points.length / 2;
  36734. var dimIdx = dim === 'x' ? 0 : 1;
  36735. var a;
  36736. var b;
  36737. var prevIndex = 0;
  36738. var nextIndex = -1;
  36739. for (var i = 0; i < len; i++) {
  36740. b = points[i * 2 + dimIdx];
  36741. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  36742. continue;
  36743. }
  36744. if (i === 0) {
  36745. a = b;
  36746. continue;
  36747. }
  36748. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  36749. nextIndex = i;
  36750. break;
  36751. }
  36752. prevIndex = i;
  36753. a = b;
  36754. }
  36755. return {
  36756. range: [prevIndex, nextIndex],
  36757. t: (xOrY - a) / (b - a)
  36758. };
  36759. }
  36760. function anyStateShowEndLabel(seriesModel) {
  36761. if (seriesModel.get(['endLabel', 'show'])) {
  36762. return true;
  36763. }
  36764. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  36765. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  36766. return true;
  36767. }
  36768. }
  36769. return false;
  36770. }
  36771. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  36772. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  36773. var endLabelModel_1 = seriesModel.getModel('endLabel');
  36774. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  36775. var data_1 = seriesModel.getData();
  36776. var labelAnimationRecord_1 = {
  36777. lastFrameIndex: 0
  36778. };
  36779. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  36780. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  36781. } : null;
  36782. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  36783. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  36784. var endLabel = lineView._endLabel;
  36785. if (endLabel && hasAnimation) {
  36786. if (labelAnimationRecord_1.originalX != null) {
  36787. endLabel.attr({
  36788. x: labelAnimationRecord_1.originalX,
  36789. y: labelAnimationRecord_1.originalY
  36790. });
  36791. }
  36792. }
  36793. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  36794. if (!seriesModel.get('clip', true)) {
  36795. var rectShape = clipPath.shape;
  36796. var expandSize = Math.max(rectShape.width, rectShape.height);
  36797. if (isHorizontal) {
  36798. rectShape.y -= expandSize;
  36799. rectShape.height += expandSize * 2;
  36800. } else {
  36801. rectShape.x -= expandSize;
  36802. rectShape.width += expandSize * 2;
  36803. }
  36804. } // Set to the final frame. To make sure label layout is right.
  36805. if (during) {
  36806. during(1, clipPath);
  36807. }
  36808. return clipPath;
  36809. } else {
  36810. if ("development" !== 'production') {
  36811. if (seriesModel.get(['endLabel', 'show'])) {
  36812. console.warn('endLabel is not supported for lines in polar systems.');
  36813. }
  36814. }
  36815. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  36816. }
  36817. }
  36818. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  36819. var baseAxis = coordSys.getBaseAxis();
  36820. var isHorizontal = baseAxis.isHorizontal();
  36821. var isBaseInversed = baseAxis.inverse;
  36822. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  36823. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  36824. return {
  36825. normal: {
  36826. align: endLabelModel.get('align') || align,
  36827. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  36828. }
  36829. };
  36830. }
  36831. var LineView =
  36832. /** @class */
  36833. function (_super) {
  36834. __extends(LineView, _super);
  36835. function LineView() {
  36836. return _super !== null && _super.apply(this, arguments) || this;
  36837. }
  36838. LineView.prototype.init = function () {
  36839. var lineGroup = new Group();
  36840. var symbolDraw = new SymbolDraw();
  36841. this.group.add(symbolDraw.group);
  36842. this._symbolDraw = symbolDraw;
  36843. this._lineGroup = lineGroup;
  36844. };
  36845. LineView.prototype.render = function (seriesModel, ecModel, api) {
  36846. var _this = this;
  36847. var coordSys = seriesModel.coordinateSystem;
  36848. var group = this.group;
  36849. var data = seriesModel.getData();
  36850. var lineStyleModel = seriesModel.getModel('lineStyle');
  36851. var areaStyleModel = seriesModel.getModel('areaStyle');
  36852. var points = data.getLayout('points') || [];
  36853. var isCoordSysPolar = coordSys.type === 'polar';
  36854. var prevCoordSys = this._coordSys;
  36855. var symbolDraw = this._symbolDraw;
  36856. var polyline = this._polyline;
  36857. var polygon = this._polygon;
  36858. var lineGroup = this._lineGroup;
  36859. var hasAnimation = seriesModel.get('animation');
  36860. var isAreaChart = !areaStyleModel.isEmpty();
  36861. var valueOrigin = areaStyleModel.get('origin');
  36862. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  36863. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  36864. var showSymbol = seriesModel.get('showSymbol');
  36865. var connectNulls = seriesModel.get('connectNulls');
  36866. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  36867. var oldData = this._data;
  36868. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  36869. if (el.__temp) {
  36870. group.remove(el);
  36871. oldData.setItemGraphicEl(idx, null);
  36872. }
  36873. }); // Remove previous created symbols if showSymbol changed to false
  36874. if (!showSymbol) {
  36875. symbolDraw.remove();
  36876. }
  36877. group.add(lineGroup); // FIXME step not support polar
  36878. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  36879. var clipShapeForSymbol;
  36880. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  36881. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  36882. // See #7913 and `test/dataZoom-clip.html`.
  36883. if (clipShapeForSymbol.width != null) {
  36884. clipShapeForSymbol.x -= 0.1;
  36885. clipShapeForSymbol.y -= 0.1;
  36886. clipShapeForSymbol.width += 0.2;
  36887. clipShapeForSymbol.height += 0.2;
  36888. } else if (clipShapeForSymbol.r0) {
  36889. clipShapeForSymbol.r0 -= 0.5;
  36890. clipShapeForSymbol.r += 0.5;
  36891. }
  36892. }
  36893. this._clipShapeForSymbol = clipShapeForSymbol;
  36894. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  36895. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  36896. showSymbol && symbolDraw.updateData(data, {
  36897. isIgnore: isIgnoreFunc,
  36898. clipShape: clipShapeForSymbol,
  36899. disableAnimation: true,
  36900. getSymbolPoint: function (idx) {
  36901. return [points[idx * 2], points[idx * 2 + 1]];
  36902. }
  36903. });
  36904. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  36905. if (step) {
  36906. // TODO If stacked series is not step
  36907. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  36908. if (stackedOnPoints) {
  36909. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  36910. }
  36911. }
  36912. polyline = this._newPolyline(points);
  36913. if (isAreaChart) {
  36914. polygon = this._newPolygon(points, stackedOnPoints);
  36915. } // NOTE: Must update _endLabel before setClipPath.
  36916. if (!isCoordSysPolar) {
  36917. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36918. }
  36919. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  36920. } else {
  36921. if (isAreaChart && !polygon) {
  36922. // If areaStyle is added
  36923. polygon = this._newPolygon(points, stackedOnPoints);
  36924. } else if (polygon && !isAreaChart) {
  36925. // If areaStyle is removed
  36926. lineGroup.remove(polygon);
  36927. polygon = this._polygon = null;
  36928. } // NOTE: Must update _endLabel before setClipPath.
  36929. if (!isCoordSysPolar) {
  36930. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36931. } // Update clipPath
  36932. var oldClipPath = lineGroup.getClipPath();
  36933. if (oldClipPath) {
  36934. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  36935. initProps(oldClipPath, {
  36936. shape: newClipPath.shape
  36937. }, seriesModel);
  36938. } else {
  36939. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  36940. } // Always update, or it is wrong in the case turning on legend
  36941. // because points are not changed
  36942. showSymbol && symbolDraw.updateData(data, {
  36943. isIgnore: isIgnoreFunc,
  36944. clipShape: clipShapeForSymbol,
  36945. disableAnimation: true,
  36946. getSymbolPoint: function (idx) {
  36947. return [points[idx * 2], points[idx * 2 + 1]];
  36948. }
  36949. }); // In the case data zoom triggerred refreshing frequently
  36950. // Data may not change if line has a category axis. So it should animate nothing
  36951. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  36952. if (hasAnimation) {
  36953. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  36954. } else {
  36955. // Not do it in update with animation
  36956. if (step) {
  36957. // TODO If stacked series is not step
  36958. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  36959. if (stackedOnPoints) {
  36960. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  36961. }
  36962. }
  36963. polyline.setShape({
  36964. points: points
  36965. });
  36966. polygon && polygon.setShape({
  36967. points: points,
  36968. stackedOnPoints: stackedOnPoints
  36969. });
  36970. }
  36971. }
  36972. }
  36973. var emphasisModel = seriesModel.getModel('emphasis');
  36974. var focus = emphasisModel.get('focus');
  36975. var blurScope = emphasisModel.get('blurScope');
  36976. var emphasisDisabled = emphasisModel.get('disabled');
  36977. polyline.useStyle(defaults( // Use color in lineStyle first
  36978. lineStyleModel.getLineStyle(), {
  36979. fill: 'none',
  36980. stroke: visualColor,
  36981. lineJoin: 'bevel'
  36982. }));
  36983. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  36984. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  36985. var emphasisLineStyle = polyline.getState('emphasis').style;
  36986. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  36987. } // Needs seriesIndex for focus
  36988. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  36989. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  36990. var smooth = getSmooth(seriesModel.get('smooth'));
  36991. var smoothMonotone = seriesModel.get('smoothMonotone');
  36992. polyline.setShape({
  36993. smooth: smooth,
  36994. smoothMonotone: smoothMonotone,
  36995. connectNulls: connectNulls
  36996. });
  36997. if (polygon) {
  36998. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  36999. var stackedOnSmooth = 0;
  37000. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  37001. fill: visualColor,
  37002. opacity: 0.7,
  37003. lineJoin: 'bevel',
  37004. decal: data.getVisual('style').decal
  37005. }));
  37006. if (stackedOnSeries) {
  37007. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  37008. }
  37009. polygon.setShape({
  37010. smooth: smooth,
  37011. stackedOnSmooth: stackedOnSmooth,
  37012. smoothMonotone: smoothMonotone,
  37013. connectNulls: connectNulls
  37014. });
  37015. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  37016. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  37017. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  37018. }
  37019. var changePolyState = function (toState) {
  37020. _this._changePolyState(toState);
  37021. };
  37022. data.eachItemGraphicEl(function (el) {
  37023. // Switch polyline / polygon state if element changed its state.
  37024. el && (el.onHoverStateChange = changePolyState);
  37025. });
  37026. this._polyline.onHoverStateChange = changePolyState;
  37027. this._data = data; // Save the coordinate system for transition animation when data changed
  37028. this._coordSys = coordSys;
  37029. this._stackedOnPoints = stackedOnPoints;
  37030. this._points = points;
  37031. this._step = step;
  37032. this._valueOrigin = valueOrigin;
  37033. if (seriesModel.get('triggerLineEvent')) {
  37034. this.packEventData(seriesModel, polyline);
  37035. polygon && this.packEventData(seriesModel, polygon);
  37036. }
  37037. };
  37038. LineView.prototype.packEventData = function (seriesModel, el) {
  37039. getECData(el).eventData = {
  37040. componentType: 'series',
  37041. componentSubType: 'line',
  37042. componentIndex: seriesModel.componentIndex,
  37043. seriesIndex: seriesModel.seriesIndex,
  37044. seriesName: seriesModel.name,
  37045. seriesType: 'line'
  37046. };
  37047. };
  37048. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  37049. var data = seriesModel.getData();
  37050. var dataIndex = queryDataIndex(data, payload);
  37051. this._changePolyState('emphasis');
  37052. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  37053. var points = data.getLayout('points');
  37054. var symbol = data.getItemGraphicEl(dataIndex);
  37055. if (!symbol) {
  37056. // Create a temporary symbol if it is not exists
  37057. var x = points[dataIndex * 2];
  37058. var y = points[dataIndex * 2 + 1];
  37059. if (isNaN(x) || isNaN(y)) {
  37060. // Null data
  37061. return;
  37062. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  37063. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  37064. return;
  37065. }
  37066. var zlevel = seriesModel.get('zlevel');
  37067. var z = seriesModel.get('z');
  37068. symbol = new Symbol(data, dataIndex);
  37069. symbol.x = x;
  37070. symbol.y = y;
  37071. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  37072. var symbolLabel = symbol.getSymbolPath().getTextContent();
  37073. if (symbolLabel) {
  37074. symbolLabel.zlevel = zlevel;
  37075. symbolLabel.z = z;
  37076. symbolLabel.z2 = this._polyline.z2 + 1;
  37077. }
  37078. symbol.__temp = true;
  37079. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  37080. symbol.stopSymbolAnimation(true);
  37081. this.group.add(symbol);
  37082. }
  37083. symbol.highlight();
  37084. } else {
  37085. // Highlight whole series
  37086. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  37087. }
  37088. };
  37089. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  37090. var data = seriesModel.getData();
  37091. var dataIndex = queryDataIndex(data, payload);
  37092. this._changePolyState('normal');
  37093. if (dataIndex != null && dataIndex >= 0) {
  37094. var symbol = data.getItemGraphicEl(dataIndex);
  37095. if (symbol) {
  37096. if (symbol.__temp) {
  37097. data.setItemGraphicEl(dataIndex, null);
  37098. this.group.remove(symbol);
  37099. } else {
  37100. symbol.downplay();
  37101. }
  37102. }
  37103. } else {
  37104. // FIXME
  37105. // can not downplay completely.
  37106. // Downplay whole series
  37107. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  37108. }
  37109. };
  37110. LineView.prototype._changePolyState = function (toState) {
  37111. var polygon = this._polygon;
  37112. setStatesFlag(this._polyline, toState);
  37113. polygon && setStatesFlag(polygon, toState);
  37114. };
  37115. LineView.prototype._newPolyline = function (points) {
  37116. var polyline = this._polyline; // Remove previous created polyline
  37117. if (polyline) {
  37118. this._lineGroup.remove(polyline);
  37119. }
  37120. polyline = new ECPolyline({
  37121. shape: {
  37122. points: points
  37123. },
  37124. segmentIgnoreThreshold: 2,
  37125. z2: 10
  37126. });
  37127. this._lineGroup.add(polyline);
  37128. this._polyline = polyline;
  37129. return polyline;
  37130. };
  37131. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  37132. var polygon = this._polygon; // Remove previous created polygon
  37133. if (polygon) {
  37134. this._lineGroup.remove(polygon);
  37135. }
  37136. polygon = new ECPolygon({
  37137. shape: {
  37138. points: points,
  37139. stackedOnPoints: stackedOnPoints
  37140. },
  37141. segmentIgnoreThreshold: 2
  37142. });
  37143. this._lineGroup.add(polygon);
  37144. this._polygon = polygon;
  37145. return polygon;
  37146. };
  37147. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  37148. var isHorizontalOrRadial;
  37149. var isCoordSysPolar;
  37150. var baseAxis = coordSys.getBaseAxis();
  37151. var isAxisInverse = baseAxis.inverse;
  37152. if (coordSys.type === 'cartesian2d') {
  37153. isHorizontalOrRadial = baseAxis.isHorizontal();
  37154. isCoordSysPolar = false;
  37155. } else if (coordSys.type === 'polar') {
  37156. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37157. isCoordSysPolar = true;
  37158. }
  37159. var seriesModel = data.hostModel;
  37160. var seriesDuration = seriesModel.get('animationDuration');
  37161. if (isFunction(seriesDuration)) {
  37162. seriesDuration = seriesDuration(null);
  37163. }
  37164. var seriesDalay = seriesModel.get('animationDelay') || 0;
  37165. var seriesDalayValue = isFunction(seriesDalay) ? seriesDalay(null) : seriesDalay;
  37166. data.eachItemGraphicEl(function (symbol, idx) {
  37167. var el = symbol;
  37168. if (el) {
  37169. var point = [symbol.x, symbol.y];
  37170. var start = void 0;
  37171. var end = void 0;
  37172. var current = void 0;
  37173. if (clipShape) {
  37174. if (isCoordSysPolar) {
  37175. var polarClip = clipShape;
  37176. var coord = coordSys.pointToCoord(point);
  37177. if (isHorizontalOrRadial) {
  37178. start = polarClip.startAngle;
  37179. end = polarClip.endAngle;
  37180. current = -coord[1] / 180 * Math.PI;
  37181. } else {
  37182. start = polarClip.r0;
  37183. end = polarClip.r;
  37184. current = coord[0];
  37185. }
  37186. } else {
  37187. var gridClip = clipShape;
  37188. if (isHorizontalOrRadial) {
  37189. start = gridClip.x;
  37190. end = gridClip.x + gridClip.width;
  37191. current = symbol.x;
  37192. } else {
  37193. start = gridClip.y + gridClip.height;
  37194. end = gridClip.y;
  37195. current = symbol.y;
  37196. }
  37197. }
  37198. }
  37199. var ratio = end === start ? 0 : (current - start) / (end - start);
  37200. if (isAxisInverse) {
  37201. ratio = 1 - ratio;
  37202. }
  37203. var delay = isFunction(seriesDalay) ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  37204. var symbolPath = el.getSymbolPath();
  37205. var text = symbolPath.getTextContent();
  37206. el.attr({
  37207. scaleX: 0,
  37208. scaleY: 0
  37209. });
  37210. el.animateTo({
  37211. scaleX: 1,
  37212. scaleY: 1
  37213. }, {
  37214. duration: 200,
  37215. setToFinal: true,
  37216. delay: delay
  37217. });
  37218. if (text) {
  37219. text.animateFrom({
  37220. style: {
  37221. opacity: 0
  37222. }
  37223. }, {
  37224. duration: 300,
  37225. delay: delay
  37226. });
  37227. }
  37228. symbolPath.disableLabelAnimation = true;
  37229. }
  37230. });
  37231. };
  37232. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  37233. var endLabelModel = seriesModel.getModel('endLabel');
  37234. if (anyStateShowEndLabel(seriesModel)) {
  37235. var data_2 = seriesModel.getData();
  37236. var polyline = this._polyline; // series may be filtered.
  37237. var points = data_2.getLayout('points');
  37238. if (!points) {
  37239. polyline.removeTextContent();
  37240. this._endLabel = null;
  37241. return;
  37242. }
  37243. var endLabel = this._endLabel;
  37244. if (!endLabel) {
  37245. endLabel = this._endLabel = new ZRText({
  37246. z2: 200 // should be higher than item symbol
  37247. });
  37248. endLabel.ignoreClip = true;
  37249. polyline.setTextContent(this._endLabel);
  37250. polyline.disableLabelAnimation = true;
  37251. } // Find last non-NaN data to display data
  37252. var dataIndex = getLastIndexNotNull(points);
  37253. if (dataIndex >= 0) {
  37254. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  37255. inheritColor: inheritColor,
  37256. labelFetcher: seriesModel,
  37257. labelDataIndex: dataIndex,
  37258. defaultText: function (dataIndex, opt, interpolatedValue) {
  37259. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  37260. },
  37261. enableTextSetter: true
  37262. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  37263. polyline.textConfig.position = null;
  37264. }
  37265. } else if (this._endLabel) {
  37266. this._polyline.removeTextContent();
  37267. this._endLabel = null;
  37268. }
  37269. };
  37270. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  37271. var endLabel = this._endLabel;
  37272. var polyline = this._polyline;
  37273. if (endLabel) {
  37274. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  37275. // The label is not prepared at this time.
  37276. if (percent < 1 && animationRecord.originalX == null) {
  37277. animationRecord.originalX = endLabel.x;
  37278. animationRecord.originalY = endLabel.y;
  37279. }
  37280. var points = data.getLayout('points');
  37281. var seriesModel = data.hostModel;
  37282. var connectNulls = seriesModel.get('connectNulls');
  37283. var precision = endLabelModel.get('precision');
  37284. var distance = endLabelModel.get('distance') || 0;
  37285. var baseAxis = coordSys.getBaseAxis();
  37286. var isHorizontal = baseAxis.isHorizontal();
  37287. var isBaseInversed = baseAxis.inverse;
  37288. var clipShape = clipRect.shape;
  37289. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  37290. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  37291. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  37292. var dim = isHorizontal ? 'x' : 'y';
  37293. var dataIndexRange = getIndexRange(points, xOrY, dim);
  37294. var indices = dataIndexRange.range;
  37295. var diff = indices[1] - indices[0];
  37296. var value = void 0;
  37297. if (diff >= 1) {
  37298. // diff > 1 && connectNulls, which is on the null data.
  37299. if (diff > 1 && !connectNulls) {
  37300. var pt = getPointAtIndex(points, indices[0]);
  37301. endLabel.attr({
  37302. x: pt[0] + distanceX,
  37303. y: pt[1] + distanceY
  37304. });
  37305. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  37306. } else {
  37307. var pt = polyline.getPointOn(xOrY, dim);
  37308. pt && endLabel.attr({
  37309. x: pt[0] + distanceX,
  37310. y: pt[1] + distanceY
  37311. });
  37312. var startValue = seriesModel.getRawValue(indices[0]);
  37313. var endValue = seriesModel.getRawValue(indices[1]);
  37314. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  37315. }
  37316. animationRecord.lastFrameIndex = indices[0];
  37317. } else {
  37318. // If diff <= 0, which is the range is not found(Include NaN)
  37319. // Choose the first point or last point.
  37320. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  37321. var pt = getPointAtIndex(points, idx);
  37322. valueAnimation && (value = seriesModel.getRawValue(idx));
  37323. endLabel.attr({
  37324. x: pt[0] + distanceX,
  37325. y: pt[1] + distanceY
  37326. });
  37327. }
  37328. if (valueAnimation) {
  37329. labelInner(endLabel).setLabelText(value);
  37330. }
  37331. }
  37332. };
  37333. /**
  37334. * @private
  37335. */
  37336. // FIXME Two value axis
  37337. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  37338. var polyline = this._polyline;
  37339. var polygon = this._polygon;
  37340. var seriesModel = data.hostModel;
  37341. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  37342. var current = diff.current;
  37343. var stackedOnCurrent = diff.stackedOnCurrent;
  37344. var next = diff.next;
  37345. var stackedOnNext = diff.stackedOnNext;
  37346. if (step) {
  37347. // TODO If stacked series is not step
  37348. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  37349. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  37350. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  37351. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  37352. } // Don't apply animation if diff is large.
  37353. // For better result and avoid memory explosion problems like
  37354. // https://github.com/apache/incubator-echarts/issues/12229
  37355. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  37356. polyline.stopAnimation();
  37357. polyline.setShape({
  37358. points: next
  37359. });
  37360. if (polygon) {
  37361. polygon.stopAnimation();
  37362. polygon.setShape({
  37363. points: next,
  37364. stackedOnPoints: stackedOnNext
  37365. });
  37366. }
  37367. return;
  37368. }
  37369. polyline.shape.__points = diff.current;
  37370. polyline.shape.points = current;
  37371. var target = {
  37372. shape: {
  37373. points: next
  37374. }
  37375. }; // Also animate the original points.
  37376. // If points reference is changed when turning into step line.
  37377. if (diff.current !== current) {
  37378. target.shape.__points = diff.next;
  37379. } // Stop previous animation.
  37380. polyline.stopAnimation();
  37381. updateProps(polyline, target, seriesModel);
  37382. if (polygon) {
  37383. polygon.setShape({
  37384. // Reuse the points with polyline.
  37385. points: current,
  37386. stackedOnPoints: stackedOnCurrent
  37387. });
  37388. polygon.stopAnimation();
  37389. updateProps(polygon, {
  37390. shape: {
  37391. stackedOnPoints: stackedOnNext
  37392. }
  37393. }, seriesModel); // If use attr directly in updateProps.
  37394. if (polyline.shape.points !== polygon.shape.points) {
  37395. polygon.shape.points = polyline.shape.points;
  37396. }
  37397. }
  37398. var updatedDataInfo = [];
  37399. var diffStatus = diff.status;
  37400. for (var i = 0; i < diffStatus.length; i++) {
  37401. var cmd = diffStatus[i].cmd;
  37402. if (cmd === '=') {
  37403. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  37404. if (el) {
  37405. updatedDataInfo.push({
  37406. el: el,
  37407. ptIdx: i // Index of points
  37408. });
  37409. }
  37410. }
  37411. }
  37412. if (polyline.animators && polyline.animators.length) {
  37413. polyline.animators[0].during(function () {
  37414. polygon && polygon.dirtyShape();
  37415. var points = polyline.shape.__points;
  37416. for (var i = 0; i < updatedDataInfo.length; i++) {
  37417. var el = updatedDataInfo[i].el;
  37418. var offset = updatedDataInfo[i].ptIdx * 2;
  37419. el.x = points[offset];
  37420. el.y = points[offset + 1];
  37421. el.markRedraw();
  37422. }
  37423. });
  37424. }
  37425. };
  37426. LineView.prototype.remove = function (ecModel) {
  37427. var group = this.group;
  37428. var oldData = this._data;
  37429. this._lineGroup.removeAll();
  37430. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  37431. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  37432. if (el.__temp) {
  37433. group.remove(el);
  37434. oldData.setItemGraphicEl(idx, null);
  37435. }
  37436. });
  37437. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  37438. };
  37439. LineView.type = 'line';
  37440. return LineView;
  37441. }(ChartView);
  37442. function pointsLayout(seriesType, forceStoreInTypedArray) {
  37443. return {
  37444. seriesType: seriesType,
  37445. plan: createRenderPlanner(),
  37446. reset: function (seriesModel) {
  37447. var data = seriesModel.getData();
  37448. var coordSys = seriesModel.coordinateSystem;
  37449. var pipelineContext = seriesModel.pipelineContext;
  37450. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  37451. if (!coordSys) {
  37452. return;
  37453. }
  37454. var dims = map(coordSys.dimensions, function (dim) {
  37455. return data.mapDimension(dim);
  37456. }).slice(0, 2);
  37457. var dimLen = dims.length;
  37458. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  37459. if (isDimensionStacked(data, dims[0])) {
  37460. dims[0] = stackResultDim;
  37461. }
  37462. if (isDimensionStacked(data, dims[1])) {
  37463. dims[1] = stackResultDim;
  37464. }
  37465. var store = data.getStore();
  37466. var dimIdx0 = data.getDimensionIndex(dims[0]);
  37467. var dimIdx1 = data.getDimensionIndex(dims[1]);
  37468. return dimLen && {
  37469. progress: function (params, data) {
  37470. var segCount = params.end - params.start;
  37471. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  37472. var tmpIn = [];
  37473. var tmpOut = [];
  37474. for (var i = params.start, offset = 0; i < params.end; i++) {
  37475. var point = void 0;
  37476. if (dimLen === 1) {
  37477. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  37478. point = coordSys.dataToPoint(x, null, tmpOut);
  37479. } else {
  37480. tmpIn[0] = store.get(dimIdx0, i);
  37481. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  37482. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  37483. }
  37484. if (useTypedArray) {
  37485. points[offset++] = point[0];
  37486. points[offset++] = point[1];
  37487. } else {
  37488. data.setItemLayout(i, point.slice());
  37489. }
  37490. }
  37491. useTypedArray && data.setLayout('points', points);
  37492. }
  37493. };
  37494. }
  37495. };
  37496. }
  37497. var samplers = {
  37498. average: function (frame) {
  37499. var sum = 0;
  37500. var count = 0;
  37501. for (var i = 0; i < frame.length; i++) {
  37502. if (!isNaN(frame[i])) {
  37503. sum += frame[i];
  37504. count++;
  37505. }
  37506. } // Return NaN if count is 0
  37507. return count === 0 ? NaN : sum / count;
  37508. },
  37509. sum: function (frame) {
  37510. var sum = 0;
  37511. for (var i = 0; i < frame.length; i++) {
  37512. // Ignore NaN
  37513. sum += frame[i] || 0;
  37514. }
  37515. return sum;
  37516. },
  37517. max: function (frame) {
  37518. var max = -Infinity;
  37519. for (var i = 0; i < frame.length; i++) {
  37520. frame[i] > max && (max = frame[i]);
  37521. } // NaN will cause illegal axis extent.
  37522. return isFinite(max) ? max : NaN;
  37523. },
  37524. min: function (frame) {
  37525. var min = Infinity;
  37526. for (var i = 0; i < frame.length; i++) {
  37527. frame[i] < min && (min = frame[i]);
  37528. } // NaN will cause illegal axis extent.
  37529. return isFinite(min) ? min : NaN;
  37530. },
  37531. // TODO
  37532. // Median
  37533. nearest: function (frame) {
  37534. return frame[0];
  37535. }
  37536. };
  37537. var indexSampler = function (frame) {
  37538. return Math.round(frame.length / 2);
  37539. };
  37540. function dataSample(seriesType) {
  37541. return {
  37542. seriesType: seriesType,
  37543. // FIXME:TS never used, so comment it
  37544. // modifyOutputEnd: true,
  37545. reset: function (seriesModel, ecModel, api) {
  37546. var data = seriesModel.getData();
  37547. var sampling = seriesModel.get('sampling');
  37548. var coordSys = seriesModel.coordinateSystem;
  37549. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  37550. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  37551. var baseAxis = coordSys.getBaseAxis();
  37552. var valueAxis = coordSys.getOtherAxis(baseAxis);
  37553. var extent = baseAxis.getExtent();
  37554. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  37555. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  37556. var rate = Math.round(count / size);
  37557. if (isFinite(rate) && rate > 1) {
  37558. if (sampling === 'lttb') {
  37559. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  37560. }
  37561. var sampler = void 0;
  37562. if (isString(sampling)) {
  37563. sampler = samplers[sampling];
  37564. } else if (isFunction(sampling)) {
  37565. sampler = sampling;
  37566. }
  37567. if (sampler) {
  37568. // Only support sample the first dim mapped from value axis.
  37569. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  37570. }
  37571. }
  37572. }
  37573. }
  37574. };
  37575. }
  37576. function install$2(registers) {
  37577. registers.registerChartView(LineView);
  37578. registers.registerSeriesModel(LineSeriesModel);
  37579. registers.registerLayout(pointsLayout('line', true));
  37580. registers.registerVisual({
  37581. seriesType: 'line',
  37582. reset: function (seriesModel) {
  37583. var data = seriesModel.getData(); // Visual coding for legend
  37584. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  37585. if (lineStyle && !lineStyle.stroke) {
  37586. // Fill in visual should be palette color if
  37587. // has color callback
  37588. lineStyle.stroke = data.getVisual('style').fill;
  37589. }
  37590. data.setVisual('legendLineStyle', lineStyle);
  37591. }
  37592. }); // Down sample after filter
  37593. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  37594. }
  37595. var BaseBarSeriesModel =
  37596. /** @class */
  37597. function (_super) {
  37598. __extends(BaseBarSeriesModel, _super);
  37599. function BaseBarSeriesModel() {
  37600. var _this = _super !== null && _super.apply(this, arguments) || this;
  37601. _this.type = BaseBarSeriesModel.type;
  37602. return _this;
  37603. }
  37604. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  37605. return createSeriesData(null, this, {
  37606. useEncodeDefaulter: true
  37607. });
  37608. };
  37609. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  37610. var coordSys = this.coordinateSystem;
  37611. if (coordSys && coordSys.clampData) {
  37612. // PENDING if clamp ?
  37613. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37614. var data = this.getData();
  37615. var offset = data.getLayout('offset');
  37616. var size = data.getLayout('size');
  37617. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37618. pt[offsetIndex] += offset + size / 2;
  37619. return pt;
  37620. }
  37621. return [NaN, NaN];
  37622. };
  37623. BaseBarSeriesModel.type = 'series.__base_bar__';
  37624. BaseBarSeriesModel.defaultOption = {
  37625. // zlevel: 0,
  37626. z: 2,
  37627. coordinateSystem: 'cartesian2d',
  37628. legendHoverLink: true,
  37629. // stack: null
  37630. // Cartesian coordinate system
  37631. // xAxisIndex: 0,
  37632. // yAxisIndex: 0,
  37633. barMinHeight: 0,
  37634. barMinAngle: 0,
  37635. // cursor: null,
  37636. large: false,
  37637. largeThreshold: 400,
  37638. progressive: 3e3,
  37639. progressiveChunkMode: 'mod'
  37640. };
  37641. return BaseBarSeriesModel;
  37642. }(SeriesModel);
  37643. SeriesModel.registerClass(BaseBarSeriesModel);
  37644. var BarSeriesModel =
  37645. /** @class */
  37646. function (_super) {
  37647. __extends(BarSeriesModel, _super);
  37648. function BarSeriesModel() {
  37649. var _this = _super !== null && _super.apply(this, arguments) || this;
  37650. _this.type = BarSeriesModel.type;
  37651. return _this;
  37652. }
  37653. BarSeriesModel.prototype.getInitialData = function () {
  37654. return createSeriesData(null, this, {
  37655. useEncodeDefaulter: true,
  37656. createInvertedIndices: !!this.get('realtimeSort', true) || null
  37657. });
  37658. };
  37659. /**
  37660. * @override
  37661. */
  37662. BarSeriesModel.prototype.getProgressive = function () {
  37663. // Do not support progressive in normal mode.
  37664. return this.get('large') ? this.get('progressive') : false;
  37665. };
  37666. /**
  37667. * @override
  37668. */
  37669. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  37670. // Do not support progressive in normal mode.
  37671. var progressiveThreshold = this.get('progressiveThreshold');
  37672. var largeThreshold = this.get('largeThreshold');
  37673. if (largeThreshold > progressiveThreshold) {
  37674. progressiveThreshold = largeThreshold;
  37675. }
  37676. return progressiveThreshold;
  37677. };
  37678. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  37679. return selectors.rect(data.getItemLayout(dataIndex));
  37680. };
  37681. BarSeriesModel.type = 'series.bar';
  37682. BarSeriesModel.dependencies = ['grid', 'polar'];
  37683. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  37684. // If clipped
  37685. // Only available on cartesian2d
  37686. clip: true,
  37687. roundCap: false,
  37688. showBackground: false,
  37689. backgroundStyle: {
  37690. color: 'rgba(180, 180, 180, 0.2)',
  37691. borderColor: null,
  37692. borderWidth: 0,
  37693. borderType: 'solid',
  37694. borderRadius: 0,
  37695. shadowBlur: 0,
  37696. shadowColor: null,
  37697. shadowOffsetX: 0,
  37698. shadowOffsetY: 0,
  37699. opacity: 1
  37700. },
  37701. select: {
  37702. itemStyle: {
  37703. borderColor: '#212121'
  37704. }
  37705. },
  37706. realtimeSort: false
  37707. });
  37708. return BarSeriesModel;
  37709. }(BaseBarSeriesModel);
  37710. /**
  37711. * Sausage: similar to sector, but have half circle on both sides
  37712. */
  37713. var SausageShape =
  37714. /** @class */
  37715. function () {
  37716. function SausageShape() {
  37717. this.cx = 0;
  37718. this.cy = 0;
  37719. this.r0 = 0;
  37720. this.r = 0;
  37721. this.startAngle = 0;
  37722. this.endAngle = Math.PI * 2;
  37723. this.clockwise = true;
  37724. }
  37725. return SausageShape;
  37726. }();
  37727. var SausagePath =
  37728. /** @class */
  37729. function (_super) {
  37730. __extends(SausagePath, _super);
  37731. function SausagePath(opts) {
  37732. var _this = _super.call(this, opts) || this;
  37733. _this.type = 'sausage';
  37734. return _this;
  37735. }
  37736. SausagePath.prototype.getDefaultShape = function () {
  37737. return new SausageShape();
  37738. };
  37739. SausagePath.prototype.buildPath = function (ctx, shape) {
  37740. var cx = shape.cx;
  37741. var cy = shape.cy;
  37742. var r0 = Math.max(shape.r0 || 0, 0);
  37743. var r = Math.max(shape.r, 0);
  37744. var dr = (r - r0) * 0.5;
  37745. var rCenter = r0 + dr;
  37746. var startAngle = shape.startAngle;
  37747. var endAngle = shape.endAngle;
  37748. var clockwise = shape.clockwise;
  37749. var PI2 = Math.PI * 2;
  37750. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  37751. if (!lessThanCircle) {
  37752. // Normalize angles
  37753. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  37754. }
  37755. var unitStartX = Math.cos(startAngle);
  37756. var unitStartY = Math.sin(startAngle);
  37757. var unitEndX = Math.cos(endAngle);
  37758. var unitEndY = Math.sin(endAngle);
  37759. if (lessThanCircle) {
  37760. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  37761. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  37762. } else {
  37763. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  37764. }
  37765. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  37766. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  37767. if (r0 !== 0) {
  37768. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  37769. } // ctx.closePath();
  37770. };
  37771. return SausagePath;
  37772. }(Path);
  37773. function createSectorCalculateTextPosition(positionMapping, opts) {
  37774. opts = opts || {};
  37775. var isRoundCap = opts.isRoundCap;
  37776. return function (out, opts, boundingRect) {
  37777. var textPosition = opts.position;
  37778. if (!textPosition || textPosition instanceof Array) {
  37779. return calculateTextPosition(out, opts, boundingRect);
  37780. }
  37781. var mappedSectorPosition = positionMapping(textPosition);
  37782. var distance = opts.distance != null ? opts.distance : 5;
  37783. var sector = this.shape;
  37784. var cx = sector.cx;
  37785. var cy = sector.cy;
  37786. var r = sector.r;
  37787. var r0 = sector.r0;
  37788. var middleR = (r + r0) / 2;
  37789. var startAngle = sector.startAngle;
  37790. var endAngle = sector.endAngle;
  37791. var middleAngle = (startAngle + endAngle) / 2;
  37792. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  37793. var mathCos = Math.cos;
  37794. var mathSin = Math.sin; // base position: top-left
  37795. var x = cx + r * mathCos(startAngle);
  37796. var y = cy + r * mathSin(startAngle);
  37797. var textAlign = 'left';
  37798. var textVerticalAlign = 'top';
  37799. switch (mappedSectorPosition) {
  37800. case 'startArc':
  37801. x = cx + (r0 - distance) * mathCos(middleAngle);
  37802. y = cy + (r0 - distance) * mathSin(middleAngle);
  37803. textAlign = 'center';
  37804. textVerticalAlign = 'top';
  37805. break;
  37806. case 'insideStartArc':
  37807. x = cx + (r0 + distance) * mathCos(middleAngle);
  37808. y = cy + (r0 + distance) * mathSin(middleAngle);
  37809. textAlign = 'center';
  37810. textVerticalAlign = 'bottom';
  37811. break;
  37812. case 'startAngle':
  37813. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  37814. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  37815. textAlign = 'right';
  37816. textVerticalAlign = 'middle';
  37817. break;
  37818. case 'insideStartAngle':
  37819. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  37820. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  37821. textAlign = 'left';
  37822. textVerticalAlign = 'middle';
  37823. break;
  37824. case 'middle':
  37825. x = cx + middleR * mathCos(middleAngle);
  37826. y = cy + middleR * mathSin(middleAngle);
  37827. textAlign = 'center';
  37828. textVerticalAlign = 'middle';
  37829. break;
  37830. case 'endArc':
  37831. x = cx + (r + distance) * mathCos(middleAngle);
  37832. y = cy + (r + distance) * mathSin(middleAngle);
  37833. textAlign = 'center';
  37834. textVerticalAlign = 'bottom';
  37835. break;
  37836. case 'insideEndArc':
  37837. x = cx + (r - distance) * mathCos(middleAngle);
  37838. y = cy + (r - distance) * mathSin(middleAngle);
  37839. textAlign = 'center';
  37840. textVerticalAlign = 'top';
  37841. break;
  37842. case 'endAngle':
  37843. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  37844. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  37845. textAlign = 'left';
  37846. textVerticalAlign = 'middle';
  37847. break;
  37848. case 'insideEndAngle':
  37849. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  37850. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  37851. textAlign = 'right';
  37852. textVerticalAlign = 'middle';
  37853. break;
  37854. default:
  37855. return calculateTextPosition(out, opts, boundingRect);
  37856. }
  37857. out = out || {};
  37858. out.x = x;
  37859. out.y = y;
  37860. out.align = textAlign;
  37861. out.verticalAlign = textVerticalAlign;
  37862. return out;
  37863. };
  37864. }
  37865. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  37866. if (isNumber(rotateType)) {
  37867. // user-set rotation
  37868. sector.setTextConfig({
  37869. rotation: rotateType
  37870. });
  37871. return;
  37872. } else if (isArray(textPosition)) {
  37873. // user-set position, use 0 as auto rotation
  37874. sector.setTextConfig({
  37875. rotation: 0
  37876. });
  37877. return;
  37878. }
  37879. var shape = sector.shape;
  37880. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  37881. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  37882. var middleAngle = (startAngle + endAngle) / 2;
  37883. var anchorAngle;
  37884. var mappedSectorPosition = positionMapping(textPosition);
  37885. switch (mappedSectorPosition) {
  37886. case 'startArc':
  37887. case 'insideStartArc':
  37888. case 'middle':
  37889. case 'insideEndArc':
  37890. case 'endArc':
  37891. anchorAngle = middleAngle;
  37892. break;
  37893. case 'startAngle':
  37894. case 'insideStartAngle':
  37895. anchorAngle = startAngle;
  37896. break;
  37897. case 'endAngle':
  37898. case 'insideEndAngle':
  37899. anchorAngle = endAngle;
  37900. break;
  37901. default:
  37902. sector.setTextConfig({
  37903. rotation: 0
  37904. });
  37905. return;
  37906. }
  37907. var rotate = Math.PI * 1.5 - anchorAngle;
  37908. /**
  37909. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  37910. * half round flipped to increase readability. However, only middle
  37911. * position supports this for now, because in other positions, the
  37912. * anchor point is not at the center of the text, so the positions
  37913. * after rotating is not as expected.
  37914. */
  37915. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  37916. rotate -= Math.PI;
  37917. }
  37918. sector.setTextConfig({
  37919. rotation: rotate
  37920. });
  37921. }
  37922. function adjustAngleDistanceX(angle, distance, isEnd) {
  37923. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  37924. }
  37925. function adjustAngleDistanceY(angle, distance, isEnd) {
  37926. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  37927. }
  37928. var mathMax$6 = Math.max;
  37929. var mathMin$6 = Math.min;
  37930. function getClipArea(coord, data) {
  37931. var coordSysClipArea = coord.getArea && coord.getArea();
  37932. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  37933. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  37934. // We should not clip this part.
  37935. // See test/bar2.html
  37936. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37937. var expandWidth = data.getLayout('bandWidth');
  37938. if (baseAxis.isHorizontal()) {
  37939. coordSysClipArea.x -= expandWidth;
  37940. coordSysClipArea.width += expandWidth * 2;
  37941. } else {
  37942. coordSysClipArea.y -= expandWidth;
  37943. coordSysClipArea.height += expandWidth * 2;
  37944. }
  37945. }
  37946. }
  37947. return coordSysClipArea;
  37948. }
  37949. var BarView =
  37950. /** @class */
  37951. function (_super) {
  37952. __extends(BarView, _super);
  37953. function BarView() {
  37954. var _this = _super.call(this) || this;
  37955. _this.type = BarView.type;
  37956. _this._isFirstFrame = true;
  37957. return _this;
  37958. }
  37959. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  37960. this._model = seriesModel;
  37961. this._removeOnRenderedListener(api);
  37962. this._updateDrawMode(seriesModel);
  37963. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37964. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  37965. // Clear previously rendered progressive elements.
  37966. this._progressiveEls = null;
  37967. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  37968. } else if ("development" !== 'production') {
  37969. warn('Only cartesian2d and polar supported for bar.');
  37970. }
  37971. };
  37972. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  37973. this._clear();
  37974. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  37975. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  37976. this._updateLargeClip(seriesModel);
  37977. };
  37978. BarView.prototype.incrementalRender = function (params, seriesModel) {
  37979. // Reset
  37980. this._progressiveEls = []; // Do not support progressive in normal mode.
  37981. this._incrementalRenderLarge(params, seriesModel);
  37982. };
  37983. BarView.prototype.eachRendered = function (cb) {
  37984. traverseElements(this._progressiveEls || this.group, cb);
  37985. };
  37986. BarView.prototype._updateDrawMode = function (seriesModel) {
  37987. var isLargeDraw = seriesModel.pipelineContext.large;
  37988. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  37989. this._isLargeDraw = isLargeDraw;
  37990. this._clear();
  37991. }
  37992. };
  37993. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  37994. var group = this.group;
  37995. var data = seriesModel.getData();
  37996. var oldData = this._data;
  37997. var coord = seriesModel.coordinateSystem;
  37998. var baseAxis = coord.getBaseAxis();
  37999. var isHorizontalOrRadial;
  38000. if (coord.type === 'cartesian2d') {
  38001. isHorizontalOrRadial = baseAxis.isHorizontal();
  38002. } else if (coord.type === 'polar') {
  38003. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38004. }
  38005. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  38006. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  38007. if (realtimeSortCfg) {
  38008. this._enableRealtimeSort(realtimeSortCfg, data, api);
  38009. }
  38010. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  38011. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  38012. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  38013. // And don't want the label are clipped.
  38014. var roundCap = seriesModel.get('roundCap', true);
  38015. var drawBackground = seriesModel.get('showBackground', true);
  38016. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38017. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  38018. var bgEls = [];
  38019. var oldBgEls = this._backgroundEls;
  38020. var isInitSort = payload && payload.isInitSort;
  38021. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  38022. function createBackground(dataIndex) {
  38023. var bgLayout = getLayout[coord.type](data, dataIndex);
  38024. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  38025. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  38026. if (coord.type === 'cartesian2d') {
  38027. bgEl.setShape('r', barBorderRadius);
  38028. }
  38029. bgEls[dataIndex] = bgEl;
  38030. return bgEl;
  38031. }
  38032. data.diff(oldData).add(function (dataIndex) {
  38033. var itemModel = data.getItemModel(dataIndex);
  38034. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  38035. if (drawBackground) {
  38036. createBackground(dataIndex);
  38037. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  38038. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  38039. return;
  38040. }
  38041. var isClipped = false;
  38042. if (needsClip) {
  38043. // Clip will modify the layout params.
  38044. // And return a boolean to determine if the shape are fully clipped.
  38045. isClipped = clip[coord.type](coordSysClipArea, layout);
  38046. }
  38047. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  38048. if (realtimeSortCfg) {
  38049. /**
  38050. * Force label animation because even if the element is
  38051. * ignored because it's clipped, it may not be clipped after
  38052. * changing order. Then, if not using forceLabelAnimation,
  38053. * the label animation was never started, in which case,
  38054. * the label will be the final value and doesn't have label
  38055. * animation.
  38056. */
  38057. el.forceLabelAnimation = true;
  38058. }
  38059. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  38060. if (isInitSort) {
  38061. el.attr({
  38062. shape: layout
  38063. });
  38064. } else if (realtimeSortCfg) {
  38065. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  38066. } else {
  38067. initProps(el, {
  38068. shape: layout
  38069. }, seriesModel, dataIndex);
  38070. }
  38071. data.setItemGraphicEl(dataIndex, el);
  38072. group.add(el);
  38073. el.ignore = isClipped;
  38074. }).update(function (newIndex, oldIndex) {
  38075. var itemModel = data.getItemModel(newIndex);
  38076. var layout = getLayout[coord.type](data, newIndex, itemModel);
  38077. if (drawBackground) {
  38078. var bgEl = void 0;
  38079. if (oldBgEls.length === 0) {
  38080. bgEl = createBackground(oldIndex);
  38081. } else {
  38082. bgEl = oldBgEls[oldIndex];
  38083. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  38084. if (coord.type === 'cartesian2d') {
  38085. bgEl.setShape('r', barBorderRadius);
  38086. }
  38087. bgEls[newIndex] = bgEl;
  38088. }
  38089. var bgLayout = getLayout[coord.type](data, newIndex);
  38090. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  38091. updateProps(bgEl, {
  38092. shape: shape
  38093. }, animationModel, newIndex);
  38094. }
  38095. var el = oldData.getItemGraphicEl(oldIndex);
  38096. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  38097. group.remove(el);
  38098. return;
  38099. }
  38100. var isClipped = false;
  38101. if (needsClip) {
  38102. isClipped = clip[coord.type](coordSysClipArea, layout);
  38103. if (isClipped) {
  38104. group.remove(el);
  38105. }
  38106. }
  38107. if (!el) {
  38108. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  38109. } else {
  38110. saveOldStyle(el);
  38111. }
  38112. if (realtimeSortCfg) {
  38113. el.forceLabelAnimation = true;
  38114. }
  38115. if (isChangeOrder) {
  38116. var textEl = el.getTextContent();
  38117. if (textEl) {
  38118. var labelInnerStore = labelInner(textEl);
  38119. if (labelInnerStore.prevValue != null) {
  38120. /**
  38121. * Set preValue to be value so that no new label
  38122. * should be started, otherwise, it will take a full
  38123. * `animationDurationUpdate` time to finish the
  38124. * animation, which is not expected.
  38125. */
  38126. labelInnerStore.prevValue = labelInnerStore.value;
  38127. }
  38128. }
  38129. } // Not change anything if only order changed.
  38130. // Especially not change label.
  38131. else {
  38132. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  38133. }
  38134. if (isInitSort) {
  38135. el.attr({
  38136. shape: layout
  38137. });
  38138. } else if (realtimeSortCfg) {
  38139. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  38140. } else {
  38141. updateProps(el, {
  38142. shape: layout
  38143. }, seriesModel, newIndex, null);
  38144. }
  38145. data.setItemGraphicEl(newIndex, el);
  38146. el.ignore = isClipped;
  38147. group.add(el);
  38148. }).remove(function (dataIndex) {
  38149. var el = oldData.getItemGraphicEl(dataIndex);
  38150. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  38151. }).execute();
  38152. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  38153. bgGroup.removeAll();
  38154. for (var i = 0; i < bgEls.length; ++i) {
  38155. bgGroup.add(bgEls[i]);
  38156. }
  38157. group.add(bgGroup);
  38158. this._backgroundEls = bgEls;
  38159. this._data = data;
  38160. };
  38161. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  38162. this._clear();
  38163. createLarge(seriesModel, this.group);
  38164. this._updateLargeClip(seriesModel);
  38165. };
  38166. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  38167. this._removeBackground();
  38168. createLarge(seriesModel, this.group, this._progressiveEls, true);
  38169. };
  38170. BarView.prototype._updateLargeClip = function (seriesModel) {
  38171. // Use clipPath in large mode.
  38172. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  38173. var group = this.group;
  38174. if (clipPath) {
  38175. group.setClipPath(clipPath);
  38176. } else {
  38177. group.removeClipPath();
  38178. }
  38179. };
  38180. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  38181. var _this = this; // If no data in the first frame, wait for data to initSort
  38182. if (!data.count()) {
  38183. return;
  38184. }
  38185. var baseAxis = realtimeSortCfg.baseAxis;
  38186. if (this._isFirstFrame) {
  38187. this._dispatchInitSort(data, realtimeSortCfg, api);
  38188. this._isFirstFrame = false;
  38189. } else {
  38190. var orderMapping_1 = function (idx) {
  38191. var el = data.getItemGraphicEl(idx);
  38192. var shape = el && el.shape;
  38193. return shape && // The result should be consistent with the initial sort by data value.
  38194. // Do not support the case that both positive and negative exist.
  38195. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  38196. || 0;
  38197. };
  38198. this._onRendered = function () {
  38199. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  38200. };
  38201. api.getZr().on('rendered', this._onRendered);
  38202. }
  38203. };
  38204. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  38205. var info = [];
  38206. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  38207. var mappedValue = orderMapping(dataIdx);
  38208. mappedValue = mappedValue == null ? NaN : mappedValue;
  38209. info.push({
  38210. dataIndex: dataIdx,
  38211. mappedValue: mappedValue,
  38212. ordinalNumber: ordinalNumber
  38213. });
  38214. });
  38215. info.sort(function (a, b) {
  38216. // If NaN, it will be treated as min val.
  38217. return b.mappedValue - a.mappedValue;
  38218. });
  38219. return {
  38220. ordinalNumbers: map(info, function (item) {
  38221. return item.ordinalNumber;
  38222. })
  38223. };
  38224. };
  38225. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  38226. var scale = baseAxis.scale;
  38227. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  38228. var lastValue = Number.MAX_VALUE;
  38229. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  38230. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  38231. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  38232. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  38233. : orderMapping(data.indexOfRawIndex(rawIdx));
  38234. if (value > lastValue) {
  38235. return true;
  38236. }
  38237. lastValue = value;
  38238. }
  38239. return false;
  38240. };
  38241. /*
  38242. * Consider the case when A and B changed order, whose representing
  38243. * bars are both out of sight, we don't wish to trigger reorder action
  38244. * as long as the order in the view doesn't change.
  38245. */
  38246. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  38247. var scale = baseAxis.scale;
  38248. var extent = scale.getExtent();
  38249. var tickNum = Math.max(0, extent[0]);
  38250. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  38251. for (; tickNum <= tickMax; ++tickNum) {
  38252. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  38253. return true;
  38254. }
  38255. }
  38256. };
  38257. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  38258. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  38259. return;
  38260. }
  38261. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  38262. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  38263. this._removeOnRenderedListener(api);
  38264. api.dispatchAction({
  38265. type: 'changeAxisOrder',
  38266. componentType: baseAxis.dim + 'Axis',
  38267. axisId: baseAxis.index,
  38268. sortInfo: sortInfo
  38269. });
  38270. }
  38271. };
  38272. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  38273. var baseAxis = realtimeSortCfg.baseAxis;
  38274. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  38275. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  38276. });
  38277. api.dispatchAction({
  38278. type: 'changeAxisOrder',
  38279. componentType: baseAxis.dim + 'Axis',
  38280. isInitSort: true,
  38281. axisId: baseAxis.index,
  38282. sortInfo: sortResult
  38283. });
  38284. };
  38285. BarView.prototype.remove = function (ecModel, api) {
  38286. this._clear(this._model);
  38287. this._removeOnRenderedListener(api);
  38288. };
  38289. BarView.prototype.dispose = function (ecModel, api) {
  38290. this._removeOnRenderedListener(api);
  38291. };
  38292. BarView.prototype._removeOnRenderedListener = function (api) {
  38293. if (this._onRendered) {
  38294. api.getZr().off('rendered', this._onRendered);
  38295. this._onRendered = null;
  38296. }
  38297. };
  38298. BarView.prototype._clear = function (model) {
  38299. var group = this.group;
  38300. var data = this._data;
  38301. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  38302. this._removeBackground();
  38303. this._backgroundEls = [];
  38304. data.eachItemGraphicEl(function (el) {
  38305. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  38306. });
  38307. } else {
  38308. group.removeAll();
  38309. }
  38310. this._data = null;
  38311. this._isFirstFrame = true;
  38312. };
  38313. BarView.prototype._removeBackground = function () {
  38314. this.group.remove(this._backgroundGroup);
  38315. this._backgroundGroup = null;
  38316. };
  38317. BarView.type = 'bar';
  38318. return BarView;
  38319. }(ChartView);
  38320. var clip = {
  38321. cartesian2d: function (coordSysBoundingRect, layout) {
  38322. var signWidth = layout.width < 0 ? -1 : 1;
  38323. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  38324. if (signWidth < 0) {
  38325. layout.x += layout.width;
  38326. layout.width = -layout.width;
  38327. }
  38328. if (signHeight < 0) {
  38329. layout.y += layout.height;
  38330. layout.height = -layout.height;
  38331. }
  38332. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  38333. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  38334. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  38335. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  38336. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  38337. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  38338. var xClipped = x2 < x;
  38339. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  38340. // But we should also place the element at the edge of the coord sys bounding rect.
  38341. // Beause if data changed and the bar show again, its transition animaiton
  38342. // will begin at this place.
  38343. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  38344. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  38345. layout.width = xClipped ? 0 : x2 - x;
  38346. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  38347. if (signWidth < 0) {
  38348. layout.x += layout.width;
  38349. layout.width = -layout.width;
  38350. }
  38351. if (signHeight < 0) {
  38352. layout.y += layout.height;
  38353. layout.height = -layout.height;
  38354. }
  38355. return xClipped || yClipped;
  38356. },
  38357. polar: function (coordSysClipArea, layout) {
  38358. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  38359. if (signR < 0) {
  38360. var tmp = layout.r;
  38361. layout.r = layout.r0;
  38362. layout.r0 = tmp;
  38363. }
  38364. var r = mathMin$6(layout.r, coordSysClipArea.r);
  38365. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  38366. layout.r = r;
  38367. layout.r0 = r0;
  38368. var clipped = r - r0 < 0; // Reverse back
  38369. if (signR < 0) {
  38370. var tmp = layout.r;
  38371. layout.r = layout.r0;
  38372. layout.r0 = tmp;
  38373. }
  38374. return clipped;
  38375. }
  38376. };
  38377. var elementCreator = {
  38378. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  38379. var rect = new Rect({
  38380. shape: extend({}, layout),
  38381. z2: 1
  38382. });
  38383. rect.__dataIndex = newIndex;
  38384. rect.name = 'item';
  38385. if (animationModel) {
  38386. var rectShape = rect.shape;
  38387. var animateProperty = isHorizontal ? 'height' : 'width';
  38388. rectShape[animateProperty] = 0;
  38389. }
  38390. return rect;
  38391. },
  38392. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  38393. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  38394. var sector = new ShapeClass({
  38395. shape: layout,
  38396. z2: 1
  38397. });
  38398. sector.name = 'item';
  38399. var positionMap = createPolarPositionMapping(isRadial);
  38400. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  38401. isRoundCap: ShapeClass === SausagePath
  38402. }); // Animation
  38403. if (animationModel) {
  38404. var sectorShape = sector.shape;
  38405. var animateProperty = isRadial ? 'r' : 'endAngle';
  38406. var animateTarget = {};
  38407. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  38408. animateTarget[animateProperty] = layout[animateProperty];
  38409. (isUpdate ? updateProps : initProps)(sector, {
  38410. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  38411. }, animationModel);
  38412. }
  38413. return sector;
  38414. }
  38415. };
  38416. function shouldRealtimeSort(seriesModel, coordSys) {
  38417. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  38418. var baseAxis = coordSys.getBaseAxis();
  38419. if ("development" !== 'production') {
  38420. if (realtimeSortOption) {
  38421. if (baseAxis.type !== 'category') {
  38422. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  38423. }
  38424. if (coordSys.type !== 'cartesian2d') {
  38425. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  38426. }
  38427. }
  38428. }
  38429. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  38430. return {
  38431. baseAxis: baseAxis,
  38432. otherAxis: coordSys.getOtherAxis(baseAxis)
  38433. };
  38434. }
  38435. }
  38436. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  38437. var seriesTarget;
  38438. var axisTarget;
  38439. if (isHorizontal) {
  38440. axisTarget = {
  38441. x: layout.x,
  38442. width: layout.width
  38443. };
  38444. seriesTarget = {
  38445. y: layout.y,
  38446. height: layout.height
  38447. };
  38448. } else {
  38449. axisTarget = {
  38450. y: layout.y,
  38451. height: layout.height
  38452. };
  38453. seriesTarget = {
  38454. x: layout.x,
  38455. width: layout.width
  38456. };
  38457. }
  38458. if (!isChangeOrder) {
  38459. // Keep the original growth animation if only axis order changed.
  38460. // Not start a new animation.
  38461. (isUpdate ? updateProps : initProps)(el, {
  38462. shape: seriesTarget
  38463. }, seriesAnimationModel, newIndex, null);
  38464. }
  38465. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  38466. (isUpdate ? updateProps : initProps)(el, {
  38467. shape: axisTarget
  38468. }, axisAnimationModel, newIndex);
  38469. }
  38470. function checkPropertiesNotValid(obj, props) {
  38471. for (var i = 0; i < props.length; i++) {
  38472. if (!isFinite(obj[props[i]])) {
  38473. return true;
  38474. }
  38475. }
  38476. return false;
  38477. }
  38478. var rectPropties = ['x', 'y', 'width', 'height'];
  38479. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  38480. var isValidLayout = {
  38481. cartesian2d: function (layout) {
  38482. return !checkPropertiesNotValid(layout, rectPropties);
  38483. },
  38484. polar: function (layout) {
  38485. return !checkPropertiesNotValid(layout, polarPropties);
  38486. }
  38487. };
  38488. var getLayout = {
  38489. // itemModel is only used to get borderWidth, which is not needed
  38490. // when calculating bar background layout.
  38491. cartesian2d: function (data, dataIndex, itemModel) {
  38492. var layout = data.getItemLayout(dataIndex);
  38493. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  38494. var signX = layout.width > 0 ? 1 : -1;
  38495. var signY = layout.height > 0 ? 1 : -1;
  38496. return {
  38497. x: layout.x + signX * fixedLineWidth / 2,
  38498. y: layout.y + signY * fixedLineWidth / 2,
  38499. width: layout.width - signX * fixedLineWidth,
  38500. height: layout.height - signY * fixedLineWidth
  38501. };
  38502. },
  38503. polar: function (data, dataIndex, itemModel) {
  38504. var layout = data.getItemLayout(dataIndex);
  38505. return {
  38506. cx: layout.cx,
  38507. cy: layout.cy,
  38508. r0: layout.r0,
  38509. r: layout.r,
  38510. startAngle: layout.startAngle,
  38511. endAngle: layout.endAngle,
  38512. clockwise: layout.clockwise
  38513. };
  38514. }
  38515. };
  38516. function isZeroOnPolar(layout) {
  38517. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  38518. }
  38519. function createPolarPositionMapping(isRadial) {
  38520. return function (isRadial) {
  38521. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  38522. return function (position) {
  38523. switch (position) {
  38524. case 'start':
  38525. case 'insideStart':
  38526. case 'end':
  38527. case 'insideEnd':
  38528. return position + arcOrAngle;
  38529. default:
  38530. return position;
  38531. }
  38532. };
  38533. }(isRadial);
  38534. }
  38535. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  38536. var style = data.getItemVisual(dataIndex, 'style');
  38537. if (!isPolar) {
  38538. el.setShape('r', itemModel.get(['itemStyle', 'borderRadius']) || 0);
  38539. }
  38540. el.useStyle(style);
  38541. var cursorStyle = itemModel.getShallow('cursor');
  38542. cursorStyle && el.attr('cursor', cursorStyle);
  38543. 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';
  38544. var labelStatesModels = getLabelStatesModels(itemModel);
  38545. setLabelStyle(el, labelStatesModels, {
  38546. labelFetcher: seriesModel,
  38547. labelDataIndex: dataIndex,
  38548. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  38549. inheritColor: style.fill,
  38550. defaultOpacity: style.opacity,
  38551. defaultOutsidePosition: labelPositionOutside
  38552. });
  38553. var label = el.getTextContent();
  38554. if (isPolar && label) {
  38555. var position = itemModel.get(['label', 'position']);
  38556. el.textConfig.inside = position === 'middle' ? true : null;
  38557. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  38558. }
  38559. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  38560. return getDefaultInterpolatedLabel(data, value);
  38561. });
  38562. var emphasisModel = itemModel.getModel(['emphasis']);
  38563. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  38564. setStatesStylesFromModel(el, itemModel);
  38565. if (isZeroOnPolar(layout)) {
  38566. el.style.fill = 'none';
  38567. el.style.stroke = 'none';
  38568. each(el.states, function (state) {
  38569. if (state.style) {
  38570. state.style.fill = state.style.stroke = 'none';
  38571. }
  38572. });
  38573. }
  38574. } // In case width or height are too small.
  38575. function getLineWidth(itemModel, rawLayout) {
  38576. // Has no border.
  38577. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  38578. if (!borderColor || borderColor === 'none') {
  38579. return 0;
  38580. }
  38581. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  38582. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  38583. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  38584. return Math.min(lineWidth, width, height);
  38585. }
  38586. var LagePathShape =
  38587. /** @class */
  38588. function () {
  38589. function LagePathShape() {}
  38590. return LagePathShape;
  38591. }();
  38592. var LargePath =
  38593. /** @class */
  38594. function (_super) {
  38595. __extends(LargePath, _super);
  38596. function LargePath(opts) {
  38597. var _this = _super.call(this, opts) || this;
  38598. _this.type = 'largeBar';
  38599. return _this;
  38600. }
  38601. LargePath.prototype.getDefaultShape = function () {
  38602. return new LagePathShape();
  38603. };
  38604. LargePath.prototype.buildPath = function (ctx, shape) {
  38605. // Drawing lines is more efficient than drawing
  38606. // a whole line or drawing rects.
  38607. var points = shape.points;
  38608. var baseDimIdx = this.baseDimIdx;
  38609. var valueDimIdx = 1 - this.baseDimIdx;
  38610. var startPoint = [];
  38611. var size = [];
  38612. var barWidth = this.barWidth;
  38613. for (var i = 0; i < points.length; i += 3) {
  38614. size[baseDimIdx] = barWidth;
  38615. size[valueDimIdx] = points[i + 2];
  38616. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38617. startPoint[valueDimIdx] = points[i + valueDimIdx];
  38618. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  38619. }
  38620. };
  38621. return LargePath;
  38622. }(Path);
  38623. function createLarge(seriesModel, group, progressiveEls, incremental) {
  38624. // TODO support polar
  38625. var data = seriesModel.getData();
  38626. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38627. var largeDataIndices = data.getLayout('largeDataIndices');
  38628. var barWidth = data.getLayout('size');
  38629. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38630. var bgPoints = data.getLayout('largeBackgroundPoints');
  38631. if (bgPoints) {
  38632. var bgEl = new LargePath({
  38633. shape: {
  38634. points: bgPoints
  38635. },
  38636. incremental: !!incremental,
  38637. silent: true,
  38638. z2: 0
  38639. });
  38640. bgEl.baseDimIdx = baseDimIdx;
  38641. bgEl.largeDataIndices = largeDataIndices;
  38642. bgEl.barWidth = barWidth;
  38643. bgEl.useStyle(backgroundModel.getItemStyle());
  38644. group.add(bgEl);
  38645. progressiveEls && progressiveEls.push(bgEl);
  38646. }
  38647. var el = new LargePath({
  38648. shape: {
  38649. points: data.getLayout('largePoints')
  38650. },
  38651. incremental: !!incremental,
  38652. z2: 1
  38653. });
  38654. el.baseDimIdx = baseDimIdx;
  38655. el.largeDataIndices = largeDataIndices;
  38656. el.barWidth = barWidth;
  38657. group.add(el);
  38658. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  38659. getECData(el).seriesIndex = seriesModel.seriesIndex;
  38660. if (!seriesModel.get('silent')) {
  38661. el.on('mousedown', largePathUpdateDataIndex);
  38662. el.on('mousemove', largePathUpdateDataIndex);
  38663. }
  38664. progressiveEls && progressiveEls.push(el);
  38665. } // Use throttle to avoid frequently traverse to find dataIndex.
  38666. var largePathUpdateDataIndex = throttle(function (event) {
  38667. var largePath = this;
  38668. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38669. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  38670. }, 30, false);
  38671. function largePathFindDataIndex(largePath, x, y) {
  38672. var baseDimIdx = largePath.baseDimIdx;
  38673. var valueDimIdx = 1 - baseDimIdx;
  38674. var points = largePath.shape.points;
  38675. var largeDataIndices = largePath.largeDataIndices;
  38676. var startPoint = [];
  38677. var size = [];
  38678. var barWidth = largePath.barWidth;
  38679. for (var i = 0, len = points.length / 3; i < len; i++) {
  38680. var ii = i * 3;
  38681. size[baseDimIdx] = barWidth;
  38682. size[valueDimIdx] = points[ii + 2];
  38683. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  38684. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  38685. if (size[valueDimIdx] < 0) {
  38686. startPoint[valueDimIdx] += size[valueDimIdx];
  38687. size[valueDimIdx] = -size[valueDimIdx];
  38688. }
  38689. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  38690. return largeDataIndices[i];
  38691. }
  38692. }
  38693. return -1;
  38694. }
  38695. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  38696. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  38697. var rectShape = layout;
  38698. var coordLayout = coord.getArea();
  38699. return {
  38700. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  38701. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  38702. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  38703. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  38704. };
  38705. } else {
  38706. var coordLayout = coord.getArea();
  38707. var sectorShape = layout;
  38708. return {
  38709. cx: coordLayout.cx,
  38710. cy: coordLayout.cy,
  38711. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  38712. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  38713. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  38714. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  38715. };
  38716. }
  38717. }
  38718. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  38719. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  38720. return new ElementClz({
  38721. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  38722. silent: true,
  38723. z2: 0
  38724. });
  38725. }
  38726. function install$3(registers) {
  38727. registers.registerChartView(BarView);
  38728. registers.registerSeriesModel(BarSeriesModel);
  38729. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can preapre some informations.
  38730. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  38731. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  38732. /**
  38733. * @payload
  38734. * @property {string} [componentType=series]
  38735. * @property {number} [dx]
  38736. * @property {number} [dy]
  38737. * @property {number} [zoom]
  38738. * @property {number} [originX]
  38739. * @property {number} [originY]
  38740. */
  38741. registers.registerAction({
  38742. type: 'changeAxisOrder',
  38743. event: 'changeAxisOrder',
  38744. update: 'update'
  38745. }, function (payload, ecModel) {
  38746. var componentType = payload.componentType || 'series';
  38747. ecModel.eachComponent({
  38748. mainType: componentType,
  38749. query: payload
  38750. }, function (componentModel) {
  38751. if (payload.sortInfo) {
  38752. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  38753. }
  38754. });
  38755. });
  38756. }
  38757. var PI2$7 = Math.PI * 2;
  38758. var RADIAN = Math.PI / 180;
  38759. function getViewRect(seriesModel, api) {
  38760. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  38761. width: api.getWidth(),
  38762. height: api.getHeight()
  38763. });
  38764. }
  38765. function getBasicPieLayout(seriesModel, api) {
  38766. var viewRect = getViewRect(seriesModel, api);
  38767. var center = seriesModel.get('center');
  38768. var radius = seriesModel.get('radius');
  38769. if (!isArray(radius)) {
  38770. radius = [0, radius];
  38771. }
  38772. if (!isArray(center)) {
  38773. center = [center, center];
  38774. }
  38775. var width = parsePercent$1(viewRect.width, api.getWidth());
  38776. var height = parsePercent$1(viewRect.height, api.getHeight());
  38777. var size = Math.min(width, height);
  38778. var cx = parsePercent$1(center[0], width) + viewRect.x;
  38779. var cy = parsePercent$1(center[1], height) + viewRect.y;
  38780. var r0 = parsePercent$1(radius[0], size / 2);
  38781. var r = parsePercent$1(radius[1], size / 2);
  38782. return {
  38783. cx: cx,
  38784. cy: cy,
  38785. r0: r0,
  38786. r: r
  38787. };
  38788. }
  38789. function pieLayout(seriesType, ecModel, api) {
  38790. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38791. var data = seriesModel.getData();
  38792. var valueDim = data.mapDimension('value');
  38793. var viewRect = getViewRect(seriesModel, api);
  38794. var _a = getBasicPieLayout(seriesModel, api),
  38795. cx = _a.cx,
  38796. cy = _a.cy,
  38797. r = _a.r,
  38798. r0 = _a.r0;
  38799. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  38800. var minAngle = seriesModel.get('minAngle') * RADIAN;
  38801. var validDataCount = 0;
  38802. data.each(valueDim, function (value) {
  38803. !isNaN(value) && validDataCount++;
  38804. });
  38805. var sum = data.getSum(valueDim); // Sum may be 0
  38806. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  38807. var clockwise = seriesModel.get('clockwise');
  38808. var roseType = seriesModel.get('roseType');
  38809. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  38810. var extent = data.getDataExtent(valueDim);
  38811. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  38812. var restAngle = PI2$7;
  38813. var valueSumLargerThanMinAngle = 0;
  38814. var currentAngle = startAngle;
  38815. var dir = clockwise ? 1 : -1;
  38816. data.setLayout({
  38817. viewRect: viewRect,
  38818. r: r
  38819. });
  38820. data.each(valueDim, function (value, idx) {
  38821. var angle;
  38822. if (isNaN(value)) {
  38823. data.setItemLayout(idx, {
  38824. angle: NaN,
  38825. startAngle: NaN,
  38826. endAngle: NaN,
  38827. clockwise: clockwise,
  38828. cx: cx,
  38829. cy: cy,
  38830. r0: r0,
  38831. r: roseType ? NaN : r
  38832. });
  38833. return;
  38834. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  38835. if (roseType !== 'area') {
  38836. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  38837. } else {
  38838. angle = PI2$7 / validDataCount;
  38839. }
  38840. if (angle < minAngle) {
  38841. angle = minAngle;
  38842. restAngle -= minAngle;
  38843. } else {
  38844. valueSumLargerThanMinAngle += value;
  38845. }
  38846. var endAngle = currentAngle + dir * angle;
  38847. data.setItemLayout(idx, {
  38848. angle: angle,
  38849. startAngle: currentAngle,
  38850. endAngle: endAngle,
  38851. clockwise: clockwise,
  38852. cx: cx,
  38853. cy: cy,
  38854. r0: r0,
  38855. r: roseType ? linearMap(value, extent, [r0, r]) : r
  38856. });
  38857. currentAngle = endAngle;
  38858. }); // Some sector is constrained by minAngle
  38859. // Rest sectors needs recalculate angle
  38860. if (restAngle < PI2$7 && validDataCount) {
  38861. // Average the angle if rest angle is not enough after all angles is
  38862. // Constrained by minAngle
  38863. if (restAngle <= 1e-3) {
  38864. var angle_1 = PI2$7 / validDataCount;
  38865. data.each(valueDim, function (value, idx) {
  38866. if (!isNaN(value)) {
  38867. var layout_1 = data.getItemLayout(idx);
  38868. layout_1.angle = angle_1;
  38869. layout_1.startAngle = startAngle + dir * idx * angle_1;
  38870. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  38871. }
  38872. });
  38873. } else {
  38874. unitRadian = restAngle / valueSumLargerThanMinAngle;
  38875. currentAngle = startAngle;
  38876. data.each(valueDim, function (value, idx) {
  38877. if (!isNaN(value)) {
  38878. var layout_2 = data.getItemLayout(idx);
  38879. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  38880. layout_2.startAngle = currentAngle;
  38881. layout_2.endAngle = currentAngle + dir * angle;
  38882. currentAngle += dir * angle;
  38883. }
  38884. });
  38885. }
  38886. }
  38887. });
  38888. }
  38889. /*
  38890. * Licensed to the Apache Software Foundation (ASF) under one
  38891. * or more contributor license agreements. See the NOTICE file
  38892. * distributed with this work for additional information
  38893. * regarding copyright ownership. The ASF licenses this file
  38894. * to you under the Apache License, Version 2.0 (the
  38895. * "License"); you may not use this file except in compliance
  38896. * with the License. You may obtain a copy of the License at
  38897. *
  38898. * http://www.apache.org/licenses/LICENSE-2.0
  38899. *
  38900. * Unless required by applicable law or agreed to in writing,
  38901. * software distributed under the License is distributed on an
  38902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38903. * KIND, either express or implied. See the License for the
  38904. * specific language governing permissions and limitations
  38905. * under the License.
  38906. */
  38907. /**
  38908. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38909. */
  38910. /*
  38911. * Licensed to the Apache Software Foundation (ASF) under one
  38912. * or more contributor license agreements. See the NOTICE file
  38913. * distributed with this work for additional information
  38914. * regarding copyright ownership. The ASF licenses this file
  38915. * to you under the Apache License, Version 2.0 (the
  38916. * "License"); you may not use this file except in compliance
  38917. * with the License. You may obtain a copy of the License at
  38918. *
  38919. * http://www.apache.org/licenses/LICENSE-2.0
  38920. *
  38921. * Unless required by applicable law or agreed to in writing,
  38922. * software distributed under the License is distributed on an
  38923. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38924. * KIND, either express or implied. See the License for the
  38925. * specific language governing permissions and limitations
  38926. * under the License.
  38927. */
  38928. function dataFilter(seriesType) {
  38929. return {
  38930. seriesType: seriesType,
  38931. reset: function (seriesModel, ecModel) {
  38932. var legendModels = ecModel.findComponents({
  38933. mainType: 'legend'
  38934. });
  38935. if (!legendModels || !legendModels.length) {
  38936. return;
  38937. }
  38938. var data = seriesModel.getData();
  38939. data.filterSelf(function (idx) {
  38940. var name = data.getName(idx); // If in any legend component the status is not selected.
  38941. for (var i = 0; i < legendModels.length; i++) {
  38942. // @ts-ignore FIXME: LegendModel
  38943. if (!legendModels[i].isSelected(name)) {
  38944. return false;
  38945. }
  38946. }
  38947. return true;
  38948. });
  38949. }
  38950. };
  38951. }
  38952. var RADIAN$1 = Math.PI / 180;
  38953. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  38954. if (list.length < 2) {
  38955. return;
  38956. }
  38957. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  38958. var rB = semi.rB;
  38959. var rB2 = rB * rB;
  38960. for (var i = 0; i < semi.list.length; i++) {
  38961. var item = semi.list[i];
  38962. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  38963. var rA = r + item.len;
  38964. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  38965. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  38966. var newX = cx + (dx + item.len2) * dir;
  38967. var deltaX = newX - item.label.x;
  38968. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  38969. constrainTextWidth(item, newTargetWidth, true);
  38970. item.label.x = newX;
  38971. }
  38972. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  38973. function recalculateX(items) {
  38974. // Extremes of
  38975. var topSemi = {
  38976. list: [],
  38977. maxY: 0
  38978. };
  38979. var bottomSemi = {
  38980. list: [],
  38981. maxY: 0
  38982. };
  38983. for (var i = 0; i < items.length; i++) {
  38984. if (items[i].labelAlignTo !== 'none') {
  38985. continue;
  38986. }
  38987. var item = items[i];
  38988. var semi = item.label.y > cy ? bottomSemi : topSemi;
  38989. var dy = Math.abs(item.label.y - cy);
  38990. if (dy >= semi.maxY) {
  38991. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  38992. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  38993. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  38994. semi.rB = rB;
  38995. semi.maxY = dy;
  38996. }
  38997. semi.list.push(item);
  38998. }
  38999. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  39000. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  39001. }
  39002. var len = list.length;
  39003. for (var i = 0; i < len; i++) {
  39004. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39005. var dx = list[i].label.x - farthestX;
  39006. list[i].linePoints[1][0] += dx;
  39007. list[i].label.x = farthestX;
  39008. }
  39009. }
  39010. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  39011. recalculateX(list);
  39012. }
  39013. }
  39014. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39015. var leftList = [];
  39016. var rightList = [];
  39017. var leftmostX = Number.MAX_VALUE;
  39018. var rightmostX = -Number.MAX_VALUE;
  39019. for (var i = 0; i < labelLayoutList.length; i++) {
  39020. var label = labelLayoutList[i].label;
  39021. if (isPositionCenter(labelLayoutList[i])) {
  39022. continue;
  39023. }
  39024. if (label.x < cx) {
  39025. leftmostX = Math.min(leftmostX, label.x);
  39026. leftList.push(labelLayoutList[i]);
  39027. } else {
  39028. rightmostX = Math.max(rightmostX, label.x);
  39029. rightList.push(labelLayoutList[i]);
  39030. }
  39031. }
  39032. for (var i = 0; i < labelLayoutList.length; i++) {
  39033. var layout = labelLayoutList[i];
  39034. if (!isPositionCenter(layout) && layout.linePoints) {
  39035. if (layout.labelStyleWidth != null) {
  39036. continue;
  39037. }
  39038. var label = layout.label;
  39039. var linePoints = layout.linePoints;
  39040. var targetTextWidth = void 0;
  39041. if (layout.labelAlignTo === 'edge') {
  39042. if (label.x < cx) {
  39043. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  39044. } else {
  39045. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  39046. }
  39047. } else if (layout.labelAlignTo === 'labelLine') {
  39048. if (label.x < cx) {
  39049. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  39050. } else {
  39051. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  39052. }
  39053. } else {
  39054. if (label.x < cx) {
  39055. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  39056. } else {
  39057. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  39058. }
  39059. }
  39060. layout.targetTextWidth = targetTextWidth;
  39061. constrainTextWidth(layout, targetTextWidth);
  39062. }
  39063. }
  39064. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39065. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39066. for (var i = 0; i < labelLayoutList.length; i++) {
  39067. var layout = labelLayoutList[i];
  39068. if (!isPositionCenter(layout) && layout.linePoints) {
  39069. var label = layout.label;
  39070. var linePoints = layout.linePoints;
  39071. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39072. var padding = label.style.padding;
  39073. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  39074. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  39075. var realTextWidth = layout.rect.width + extraPaddingH;
  39076. var dist = linePoints[1][0] - linePoints[2][0];
  39077. if (isAlignToEdge) {
  39078. if (label.x < cx) {
  39079. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  39080. } else {
  39081. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  39082. }
  39083. } else {
  39084. if (label.x < cx) {
  39085. linePoints[2][0] = label.x + layout.labelDistance;
  39086. } else {
  39087. linePoints[2][0] = label.x - layout.labelDistance;
  39088. }
  39089. linePoints[1][0] = linePoints[2][0] + dist;
  39090. }
  39091. linePoints[1][1] = linePoints[2][1] = label.y;
  39092. }
  39093. }
  39094. }
  39095. /**
  39096. * Set max width of each label, and then wrap each label to the max width.
  39097. *
  39098. * @param layout label layout
  39099. * @param availableWidth max width for the label to display
  39100. * @param forceRecalculate recaculate the text layout even if the current width
  39101. * is smaller than `availableWidth`. This is useful when the text was previously
  39102. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  39103. * which case, previous wrapping should be redo.
  39104. */
  39105. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  39106. if (forceRecalculate === void 0) {
  39107. forceRecalculate = false;
  39108. }
  39109. if (layout.labelStyleWidth != null) {
  39110. // User-defined style.width has the highest priority.
  39111. return;
  39112. }
  39113. var label = layout.label;
  39114. var style = label.style;
  39115. var textRect = layout.rect;
  39116. var bgColor = style.backgroundColor;
  39117. var padding = style.padding;
  39118. var paddingH = padding ? padding[1] + padding[3] : 0;
  39119. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  39120. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  39121. if (availableWidth < oldOuterWidth || forceRecalculate) {
  39122. var oldHeight = textRect.height;
  39123. if (overflow && overflow.match('break')) {
  39124. // Temporarily set background to be null to calculate
  39125. // the bounding box without backgroud.
  39126. label.setStyle('backgroundColor', null); // Set constraining width
  39127. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding
  39128. var innerRect = label.getBoundingRect();
  39129. label.setStyle('width', Math.ceil(innerRect.width));
  39130. label.setStyle('backgroundColor', bgColor);
  39131. } else {
  39132. var availableInnerWidth = availableWidth - paddingH;
  39133. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  39134. ? availableInnerWidth : // Current available width is enough, but the text may have
  39135. // already been wrapped with a smaller available width.
  39136. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  39137. // so don't constrain width (otherwise it may have
  39138. // empty space in the background).
  39139. ? null // Current available is smaller than text width, so
  39140. // use the current available width as constraining
  39141. // width.
  39142. : availableInnerWidth : // Current available width is enough, so no need to
  39143. // constrain.
  39144. null;
  39145. label.setStyle('width', newWidth);
  39146. }
  39147. var newRect = label.getBoundingRect();
  39148. textRect.width = newRect.width;
  39149. var margin = (label.style.margin || 0) + 2.1;
  39150. textRect.height = newRect.height + margin;
  39151. textRect.y -= (textRect.height - oldHeight) / 2;
  39152. }
  39153. }
  39154. function isPositionCenter(sectorShape) {
  39155. // Not change x for center label
  39156. return sectorShape.position === 'center';
  39157. }
  39158. function pieLabelLayout(seriesModel) {
  39159. var data = seriesModel.getData();
  39160. var labelLayoutList = [];
  39161. var cx;
  39162. var cy;
  39163. var hasLabelRotate = false;
  39164. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39165. var viewRect = data.getLayout('viewRect');
  39166. var r = data.getLayout('r');
  39167. var viewWidth = viewRect.width;
  39168. var viewLeft = viewRect.x;
  39169. var viewTop = viewRect.y;
  39170. var viewHeight = viewRect.height;
  39171. function setNotShow(el) {
  39172. el.ignore = true;
  39173. }
  39174. function isLabelShown(label) {
  39175. if (!label.ignore) {
  39176. return true;
  39177. }
  39178. for (var key in label.states) {
  39179. if (label.states[key].ignore === false) {
  39180. return true;
  39181. }
  39182. }
  39183. return false;
  39184. }
  39185. data.each(function (idx) {
  39186. var sector = data.getItemGraphicEl(idx);
  39187. var sectorShape = sector.shape;
  39188. var label = sector.getTextContent();
  39189. var labelLine = sector.getTextGuideLine();
  39190. var itemModel = data.getItemModel(idx);
  39191. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  39192. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  39193. var labelDistance = labelModel.get('distanceToLabelLine');
  39194. var labelAlignTo = labelModel.get('alignTo');
  39195. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  39196. var bleedMargin = labelModel.get('bleedMargin');
  39197. var labelLineModel = itemModel.getModel('labelLine');
  39198. var labelLineLen = labelLineModel.get('length');
  39199. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39200. var labelLineLen2 = labelLineModel.get('length2');
  39201. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39202. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  39203. each(label.states, setNotShow);
  39204. label.ignore = true;
  39205. return;
  39206. }
  39207. if (!isLabelShown(label)) {
  39208. return;
  39209. }
  39210. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  39211. var nx = Math.cos(midAngle);
  39212. var ny = Math.sin(midAngle);
  39213. var textX;
  39214. var textY;
  39215. var linePoints;
  39216. var textAlign;
  39217. cx = sectorShape.cx;
  39218. cy = sectorShape.cy;
  39219. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39220. if (labelPosition === 'center') {
  39221. textX = sectorShape.cx;
  39222. textY = sectorShape.cy;
  39223. textAlign = 'center';
  39224. } else {
  39225. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  39226. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  39227. textX = x1 + nx * 3;
  39228. textY = y1 + ny * 3;
  39229. if (!isLabelInside) {
  39230. // For roseType
  39231. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  39232. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  39233. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  39234. var y3 = y2;
  39235. if (labelAlignTo === 'edge') {
  39236. // Adjust textX because text align of edge is opposite
  39237. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  39238. } else {
  39239. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  39240. }
  39241. textY = y3;
  39242. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39243. }
  39244. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  39245. }
  39246. var PI = Math.PI;
  39247. var labelRotate = 0;
  39248. var rotate = labelModel.get('rotate');
  39249. if (isNumber(rotate)) {
  39250. labelRotate = rotate * (PI / 180);
  39251. } else if (labelPosition === 'center') {
  39252. labelRotate = 0;
  39253. } else if (rotate === 'radial' || rotate === true) {
  39254. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  39255. labelRotate = radialAngle;
  39256. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  39257. var rad = Math.atan2(nx, ny);
  39258. if (rad < 0) {
  39259. rad = PI * 2 + rad;
  39260. }
  39261. var isDown = ny > 0;
  39262. if (isDown) {
  39263. rad = PI + rad;
  39264. }
  39265. labelRotate = rad - PI;
  39266. }
  39267. hasLabelRotate = !!labelRotate;
  39268. label.x = textX;
  39269. label.y = textY;
  39270. label.rotation = labelRotate;
  39271. label.setStyle({
  39272. verticalAlign: 'middle'
  39273. }); // Not sectorShape the inside label
  39274. if (!isLabelInside) {
  39275. var textRect = label.getBoundingRect().clone();
  39276. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  39277. var margin = (label.style.margin || 0) + 2.1;
  39278. textRect.y -= margin / 2;
  39279. textRect.height += margin;
  39280. labelLayoutList.push({
  39281. label: label,
  39282. labelLine: labelLine,
  39283. position: labelPosition,
  39284. len: labelLineLen,
  39285. len2: labelLineLen2,
  39286. minTurnAngle: labelLineModel.get('minTurnAngle'),
  39287. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  39288. surfaceNormal: new Point(nx, ny),
  39289. linePoints: linePoints,
  39290. textAlign: textAlign,
  39291. labelDistance: labelDistance,
  39292. labelAlignTo: labelAlignTo,
  39293. edgeDistance: edgeDistance,
  39294. bleedMargin: bleedMargin,
  39295. rect: textRect,
  39296. unconstrainedWidth: textRect.width,
  39297. labelStyleWidth: label.style.width
  39298. });
  39299. } else {
  39300. label.setStyle({
  39301. align: textAlign
  39302. });
  39303. var selectState = label.states.select;
  39304. if (selectState) {
  39305. selectState.x += label.x;
  39306. selectState.y += label.y;
  39307. }
  39308. }
  39309. sector.setTextConfig({
  39310. inside: isLabelInside
  39311. });
  39312. });
  39313. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39314. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39315. }
  39316. for (var i = 0; i < labelLayoutList.length; i++) {
  39317. var layout = labelLayoutList[i];
  39318. var label = layout.label;
  39319. var labelLine = layout.labelLine;
  39320. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  39321. if (label) {
  39322. label.setStyle({
  39323. align: layout.textAlign
  39324. });
  39325. if (notShowLabel) {
  39326. each(label.states, setNotShow);
  39327. label.ignore = true;
  39328. }
  39329. var selectState = label.states.select;
  39330. if (selectState) {
  39331. selectState.x += label.x;
  39332. selectState.y += label.y;
  39333. }
  39334. }
  39335. if (labelLine) {
  39336. var linePoints = layout.linePoints;
  39337. if (notShowLabel || !linePoints) {
  39338. each(labelLine.states, setNotShow);
  39339. labelLine.ignore = true;
  39340. } else {
  39341. limitTurnAngle(linePoints, layout.minTurnAngle);
  39342. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  39343. labelLine.setShape({
  39344. points: linePoints
  39345. }); // Set the anchor to the midpoint of sector
  39346. label.__hostTarget.textGuideLineConfig = {
  39347. anchor: new Point(linePoints[0][0], linePoints[0][1])
  39348. };
  39349. }
  39350. }
  39351. }
  39352. }
  39353. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39354. var cornerRadius = model.get('borderRadius');
  39355. if (cornerRadius == null) {
  39356. return zeroIfNull ? {
  39357. cornerRadius: 0
  39358. } : null;
  39359. }
  39360. if (!isArray(cornerRadius)) {
  39361. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39362. }
  39363. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39364. return {
  39365. cornerRadius: map(cornerRadius, function (cr) {
  39366. return parsePercent(cr, dr);
  39367. })
  39368. };
  39369. }
  39370. /**
  39371. * Piece of pie including Sector, Label, LabelLine
  39372. */
  39373. var PiePiece =
  39374. /** @class */
  39375. function (_super) {
  39376. __extends(PiePiece, _super);
  39377. function PiePiece(data, idx, startAngle) {
  39378. var _this = _super.call(this) || this;
  39379. _this.z2 = 2;
  39380. var text = new ZRText();
  39381. _this.setTextContent(text);
  39382. _this.updateData(data, idx, startAngle, true);
  39383. return _this;
  39384. }
  39385. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  39386. var sector = this;
  39387. var seriesModel = data.hostModel;
  39388. var itemModel = data.getItemModel(idx);
  39389. var emphasisModel = itemModel.getModel('emphasis');
  39390. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  39391. // see `setItemLayout` in `pieLayout.ts`.
  39392. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  39393. if (isNaN(sectorShape.startAngle)) {
  39394. // Use NaN shape to avoid drawing shape.
  39395. sector.setShape(sectorShape);
  39396. return;
  39397. }
  39398. if (firstCreate) {
  39399. sector.setShape(sectorShape);
  39400. var animationType = seriesModel.getShallow('animationType');
  39401. if (seriesModel.ecModel.ssr) {
  39402. // Use scale animation in SSR mode(opacity?)
  39403. // Because CSS SVG animation doesn't support very customized shape animation.
  39404. initProps(sector, {
  39405. scaleX: 0,
  39406. scaleY: 0
  39407. }, seriesModel, {
  39408. dataIndex: idx,
  39409. isFrom: true
  39410. });
  39411. sector.originX = sectorShape.cx;
  39412. sector.originY = sectorShape.cy;
  39413. } else if (animationType === 'scale') {
  39414. sector.shape.r = layout.r0;
  39415. initProps(sector, {
  39416. shape: {
  39417. r: layout.r
  39418. }
  39419. }, seriesModel, idx);
  39420. } // Expansion
  39421. else {
  39422. if (startAngle != null) {
  39423. sector.setShape({
  39424. startAngle: startAngle,
  39425. endAngle: startAngle
  39426. });
  39427. initProps(sector, {
  39428. shape: {
  39429. startAngle: layout.startAngle,
  39430. endAngle: layout.endAngle
  39431. }
  39432. }, seriesModel, idx);
  39433. } else {
  39434. sector.shape.endAngle = layout.startAngle;
  39435. updateProps(sector, {
  39436. shape: {
  39437. endAngle: layout.endAngle
  39438. }
  39439. }, seriesModel, idx);
  39440. }
  39441. }
  39442. } else {
  39443. saveOldStyle(sector); // Transition animation from the old shape
  39444. updateProps(sector, {
  39445. shape: sectorShape
  39446. }, seriesModel, idx);
  39447. }
  39448. sector.useStyle(data.getItemVisual(idx, 'style'));
  39449. setStatesStylesFromModel(sector, itemModel);
  39450. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39451. var offset = seriesModel.get('selectedOffset');
  39452. var dx = Math.cos(midAngle) * offset;
  39453. var dy = Math.sin(midAngle) * offset;
  39454. var cursorStyle = itemModel.getShallow('cursor');
  39455. cursorStyle && sector.attr('cursor', cursorStyle);
  39456. this._updateLabel(seriesModel, data, idx);
  39457. sector.ensureState('emphasis').shape = extend({
  39458. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  39459. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  39460. extend(sector.ensureState('select'), {
  39461. x: dx,
  39462. y: dy,
  39463. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  39464. });
  39465. extend(sector.ensureState('blur'), {
  39466. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  39467. });
  39468. var labelLine = sector.getTextGuideLine();
  39469. var labelText = sector.getTextContent();
  39470. labelLine && extend(labelLine.ensureState('select'), {
  39471. x: dx,
  39472. y: dy
  39473. }); // TODO: needs dx, dy in zrender?
  39474. extend(labelText.ensureState('select'), {
  39475. x: dx,
  39476. y: dy
  39477. });
  39478. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39479. };
  39480. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  39481. var sector = this;
  39482. var itemModel = data.getItemModel(idx);
  39483. var labelLineModel = itemModel.getModel('labelLine');
  39484. var style = data.getItemVisual(idx, 'style');
  39485. var visualColor = style && style.fill;
  39486. var visualOpacity = style && style.opacity;
  39487. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  39488. labelFetcher: data.hostModel,
  39489. labelDataIndex: idx,
  39490. inheritColor: visualColor,
  39491. defaultOpacity: visualOpacity,
  39492. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  39493. });
  39494. var labelText = sector.getTextContent(); // Set textConfig on sector.
  39495. sector.setTextConfig({
  39496. // reset position, rotation
  39497. position: null,
  39498. rotation: null
  39499. }); // Make sure update style on labelText after setLabelStyle.
  39500. // Because setLabelStyle will replace a new style on it.
  39501. labelText.attr({
  39502. z2: 10
  39503. });
  39504. var labelPosition = seriesModel.get(['label', 'position']);
  39505. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  39506. sector.removeTextGuideLine();
  39507. } else {
  39508. var polyline = this.getTextGuideLine();
  39509. if (!polyline) {
  39510. polyline = new Polyline();
  39511. this.setTextGuideLine(polyline);
  39512. } // Default use item visual color
  39513. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  39514. stroke: visualColor,
  39515. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  39516. });
  39517. }
  39518. };
  39519. return PiePiece;
  39520. }(Sector); // Pie view
  39521. var PieView =
  39522. /** @class */
  39523. function (_super) {
  39524. __extends(PieView, _super);
  39525. function PieView() {
  39526. var _this = _super !== null && _super.apply(this, arguments) || this;
  39527. _this.ignoreLabelLineUpdate = true;
  39528. return _this;
  39529. }
  39530. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39531. var data = seriesModel.getData();
  39532. var oldData = this._data;
  39533. var group = this.group;
  39534. var startAngle; // First render
  39535. if (!oldData && data.count() > 0) {
  39536. var shape = data.getItemLayout(0);
  39537. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  39538. shape = data.getItemLayout(s);
  39539. }
  39540. if (shape) {
  39541. startAngle = shape.startAngle;
  39542. }
  39543. } // remove empty-circle if it exists
  39544. if (this._emptyCircleSector) {
  39545. group.remove(this._emptyCircleSector);
  39546. } // when all data are filtered, show lightgray empty circle
  39547. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  39548. var sector = new Sector({
  39549. shape: getBasicPieLayout(seriesModel, api)
  39550. });
  39551. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  39552. this._emptyCircleSector = sector;
  39553. group.add(sector);
  39554. }
  39555. data.diff(oldData).add(function (idx) {
  39556. var piePiece = new PiePiece(data, idx, startAngle);
  39557. data.setItemGraphicEl(idx, piePiece);
  39558. group.add(piePiece);
  39559. }).update(function (newIdx, oldIdx) {
  39560. var piePiece = oldData.getItemGraphicEl(oldIdx);
  39561. piePiece.updateData(data, newIdx, startAngle);
  39562. piePiece.off('click');
  39563. group.add(piePiece);
  39564. data.setItemGraphicEl(newIdx, piePiece);
  39565. }).remove(function (idx) {
  39566. var piePiece = oldData.getItemGraphicEl(idx);
  39567. removeElementWithFadeOut(piePiece, seriesModel, idx);
  39568. }).execute();
  39569. pieLabelLayout(seriesModel); // Always use initial animation.
  39570. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  39571. this._data = data;
  39572. }
  39573. };
  39574. PieView.prototype.dispose = function () {};
  39575. PieView.prototype.containPoint = function (point, seriesModel) {
  39576. var data = seriesModel.getData();
  39577. var itemLayout = data.getItemLayout(0);
  39578. if (itemLayout) {
  39579. var dx = point[0] - itemLayout.cx;
  39580. var dy = point[1] - itemLayout.cy;
  39581. var radius = Math.sqrt(dx * dx + dy * dy);
  39582. return radius <= itemLayout.r && radius >= itemLayout.r0;
  39583. }
  39584. };
  39585. PieView.type = 'pie';
  39586. return PieView;
  39587. }(ChartView);
  39588. /**
  39589. * [Usage]:
  39590. * (1)
  39591. * createListSimply(seriesModel, ['value']);
  39592. * (2)
  39593. * createListSimply(seriesModel, {
  39594. * coordDimensions: ['value'],
  39595. * dimensionsCount: 5
  39596. * });
  39597. */
  39598. function createSeriesDataSimply(seriesModel, opt, nameList) {
  39599. opt = isArray(opt) && {
  39600. coordDimensions: opt
  39601. } || extend({
  39602. encodeDefine: seriesModel.getEncode()
  39603. }, opt);
  39604. var source = seriesModel.getSource();
  39605. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  39606. var list = new SeriesData(dimensions, seriesModel);
  39607. list.initData(source, nameList);
  39608. return list;
  39609. }
  39610. /*
  39611. * Licensed to the Apache Software Foundation (ASF) under one
  39612. * or more contributor license agreements. See the NOTICE file
  39613. * distributed with this work for additional information
  39614. * regarding copyright ownership. The ASF licenses this file
  39615. * to you under the Apache License, Version 2.0 (the
  39616. * "License"); you may not use this file except in compliance
  39617. * with the License. You may obtain a copy of the License at
  39618. *
  39619. * http://www.apache.org/licenses/LICENSE-2.0
  39620. *
  39621. * Unless required by applicable law or agreed to in writing,
  39622. * software distributed under the License is distributed on an
  39623. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39624. * KIND, either express or implied. See the License for the
  39625. * specific language governing permissions and limitations
  39626. * under the License.
  39627. */
  39628. /**
  39629. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39630. */
  39631. /*
  39632. * Licensed to the Apache Software Foundation (ASF) under one
  39633. * or more contributor license agreements. See the NOTICE file
  39634. * distributed with this work for additional information
  39635. * regarding copyright ownership. The ASF licenses this file
  39636. * to you under the Apache License, Version 2.0 (the
  39637. * "License"); you may not use this file except in compliance
  39638. * with the License. You may obtain a copy of the License at
  39639. *
  39640. * http://www.apache.org/licenses/LICENSE-2.0
  39641. *
  39642. * Unless required by applicable law or agreed to in writing,
  39643. * software distributed under the License is distributed on an
  39644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39645. * KIND, either express or implied. See the License for the
  39646. * specific language governing permissions and limitations
  39647. * under the License.
  39648. */
  39649. /**
  39650. * LegendVisualProvider is an bridge that pick encoded color from data and
  39651. * provide to the legend component.
  39652. */
  39653. var LegendVisualProvider =
  39654. /** @class */
  39655. function () {
  39656. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  39657. getDataWithEncodedVisual, // Function to get raw data before filtered.
  39658. getRawData) {
  39659. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  39660. this._getRawData = getRawData;
  39661. }
  39662. LegendVisualProvider.prototype.getAllNames = function () {
  39663. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  39664. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  39665. return rawData.mapArray(rawData.getName);
  39666. };
  39667. LegendVisualProvider.prototype.containName = function (name) {
  39668. var rawData = this._getRawData();
  39669. return rawData.indexOfName(name) >= 0;
  39670. };
  39671. LegendVisualProvider.prototype.indexOfName = function (name) {
  39672. // Only get data when necessary.
  39673. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  39674. // Invoking Series#getData immediately will throw an error.
  39675. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  39676. return dataWithEncodedVisual.indexOfName(name);
  39677. };
  39678. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  39679. // Get encoded visual properties from final filtered data.
  39680. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  39681. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  39682. };
  39683. return LegendVisualProvider;
  39684. }();
  39685. var PieSeriesModel =
  39686. /** @class */
  39687. function (_super) {
  39688. __extends(PieSeriesModel, _super);
  39689. function PieSeriesModel() {
  39690. return _super !== null && _super.apply(this, arguments) || this;
  39691. }
  39692. /**
  39693. * @overwrite
  39694. */
  39695. PieSeriesModel.prototype.init = function (option) {
  39696. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  39697. // Use a function instead of direct access because data reference may changed
  39698. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  39699. this._defaultLabelLine(option);
  39700. };
  39701. /**
  39702. * @overwrite
  39703. */
  39704. PieSeriesModel.prototype.mergeOption = function () {
  39705. _super.prototype.mergeOption.apply(this, arguments);
  39706. };
  39707. /**
  39708. * @overwrite
  39709. */
  39710. PieSeriesModel.prototype.getInitialData = function () {
  39711. return createSeriesDataSimply(this, {
  39712. coordDimensions: ['value'],
  39713. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  39714. });
  39715. };
  39716. /**
  39717. * @overwrite
  39718. */
  39719. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  39720. var data = this.getData();
  39721. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  39722. var valueList = [];
  39723. data.each(data.mapDimension('value'), function (value) {
  39724. valueList.push(value);
  39725. });
  39726. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  39727. params.$vars.push('percent');
  39728. return params;
  39729. };
  39730. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  39731. // Extend labelLine emphasis
  39732. defaultEmphasis(option, 'labelLine', ['show']);
  39733. var labelLineNormalOpt = option.labelLine;
  39734. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  39735. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  39736. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  39737. };
  39738. PieSeriesModel.type = 'series.pie';
  39739. PieSeriesModel.defaultOption = {
  39740. // zlevel: 0,
  39741. z: 2,
  39742. legendHoverLink: true,
  39743. colorBy: 'data',
  39744. // 默认全局居中
  39745. center: ['50%', '50%'],
  39746. radius: [0, '75%'],
  39747. // 默认顺时针
  39748. clockwise: true,
  39749. startAngle: 90,
  39750. // 最小角度改为0
  39751. minAngle: 0,
  39752. // If the angle of a sector less than `minShowLabelAngle`,
  39753. // the label will not be displayed.
  39754. minShowLabelAngle: 0,
  39755. // 选中时扇区偏移量
  39756. selectedOffset: 10,
  39757. // 选择模式,默认关闭,可选single,multiple
  39758. // selectedMode: false,
  39759. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  39760. // roseType: null,
  39761. percentPrecision: 2,
  39762. // If still show when all data zero.
  39763. stillShowZeroSum: true,
  39764. // cursor: null,
  39765. left: 0,
  39766. top: 0,
  39767. right: 0,
  39768. bottom: 0,
  39769. width: null,
  39770. height: null,
  39771. label: {
  39772. // color: 'inherit',
  39773. // If rotate around circle
  39774. rotate: 0,
  39775. show: true,
  39776. overflow: 'truncate',
  39777. // 'outer', 'inside', 'center'
  39778. position: 'outer',
  39779. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  39780. alignTo: 'none',
  39781. // Closest distance between label and chart edge.
  39782. // Works only position is 'outer' and alignTo is 'edge'.
  39783. edgeDistance: '25%',
  39784. // Works only position is 'outer' and alignTo is not 'edge'.
  39785. bleedMargin: 10,
  39786. // Distance between text and label line.
  39787. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39788. // 默认使用全局文本样式,详见TEXTSTYLE
  39789. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  39790. },
  39791. // Enabled when label.normal.position is 'outer'
  39792. labelLine: {
  39793. show: true,
  39794. // 引导线两段中的第一段长度
  39795. length: 15,
  39796. // 引导线两段中的第二段长度
  39797. length2: 15,
  39798. smooth: false,
  39799. minTurnAngle: 90,
  39800. maxSurfaceAngle: 90,
  39801. lineStyle: {
  39802. // color: 各异,
  39803. width: 1,
  39804. type: 'solid'
  39805. }
  39806. },
  39807. itemStyle: {
  39808. borderWidth: 1,
  39809. borderJoin: 'round'
  39810. },
  39811. showEmptyCircle: true,
  39812. emptyCircleStyle: {
  39813. color: 'lightgray',
  39814. opacity: 1
  39815. },
  39816. labelLayout: {
  39817. // Hide the overlapped label.
  39818. hideOverlap: true
  39819. },
  39820. emphasis: {
  39821. scale: true,
  39822. scaleSize: 5
  39823. },
  39824. // If use strategy to avoid label overlapping
  39825. avoidLabelOverlap: true,
  39826. // Animation type. Valid values: expansion, scale
  39827. animationType: 'expansion',
  39828. animationDuration: 1000,
  39829. // Animation type when update. Valid values: transition, expansion
  39830. animationTypeUpdate: 'transition',
  39831. animationEasingUpdate: 'cubicInOut',
  39832. animationDurationUpdate: 500,
  39833. animationEasing: 'cubicInOut'
  39834. };
  39835. return PieSeriesModel;
  39836. }(SeriesModel);
  39837. function negativeDataFilter(seriesType) {
  39838. return {
  39839. seriesType: seriesType,
  39840. reset: function (seriesModel, ecModel) {
  39841. var data = seriesModel.getData();
  39842. data.filterSelf(function (idx) {
  39843. // handle negative value condition
  39844. var valueDim = data.mapDimension('value');
  39845. var curValue = data.get(valueDim, idx);
  39846. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  39847. return false;
  39848. }
  39849. return true;
  39850. });
  39851. }
  39852. };
  39853. }
  39854. function install$4(registers) {
  39855. registers.registerChartView(PieView);
  39856. registers.registerSeriesModel(PieSeriesModel);
  39857. createLegacyDataSelectAction('pie', registers.registerAction);
  39858. registers.registerLayout(curry(pieLayout, 'pie'));
  39859. registers.registerProcessor(dataFilter('pie'));
  39860. registers.registerProcessor(negativeDataFilter('pie'));
  39861. }
  39862. var ScatterSeriesModel =
  39863. /** @class */
  39864. function (_super) {
  39865. __extends(ScatterSeriesModel, _super);
  39866. function ScatterSeriesModel() {
  39867. var _this = _super !== null && _super.apply(this, arguments) || this;
  39868. _this.type = ScatterSeriesModel.type;
  39869. _this.hasSymbolVisual = true;
  39870. return _this;
  39871. }
  39872. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  39873. return createSeriesData(null, this, {
  39874. useEncodeDefaulter: true
  39875. });
  39876. };
  39877. ScatterSeriesModel.prototype.getProgressive = function () {
  39878. var progressive = this.option.progressive;
  39879. if (progressive == null) {
  39880. // PENDING
  39881. return this.option.large ? 5e3 : this.get('progressive');
  39882. }
  39883. return progressive;
  39884. };
  39885. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  39886. var progressiveThreshold = this.option.progressiveThreshold;
  39887. if (progressiveThreshold == null) {
  39888. // PENDING
  39889. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39890. }
  39891. return progressiveThreshold;
  39892. };
  39893. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  39894. return selectors.point(data.getItemLayout(dataIndex));
  39895. };
  39896. ScatterSeriesModel.prototype.getZLevelKey = function () {
  39897. // Each progressive series has individual key.
  39898. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  39899. };
  39900. ScatterSeriesModel.type = 'series.scatter';
  39901. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  39902. ScatterSeriesModel.defaultOption = {
  39903. coordinateSystem: 'cartesian2d',
  39904. // zlevel: 0,
  39905. z: 2,
  39906. legendHoverLink: true,
  39907. symbolSize: 10,
  39908. // symbolRotate: null, // 图形旋转控制
  39909. large: false,
  39910. // Available when large is true
  39911. largeThreshold: 2000,
  39912. // cursor: null,
  39913. itemStyle: {
  39914. opacity: 0.8 // color: 各异
  39915. },
  39916. emphasis: {
  39917. scale: true
  39918. },
  39919. // If clip the overflow graphics
  39920. // Works on cartesian / polar series
  39921. clip: true,
  39922. select: {
  39923. itemStyle: {
  39924. borderColor: '#212121'
  39925. }
  39926. },
  39927. universalTransition: {
  39928. divideShape: 'clone'
  39929. } // progressive: null
  39930. };
  39931. return ScatterSeriesModel;
  39932. }(SeriesModel);
  39933. var BOOST_SIZE_THRESHOLD = 4;
  39934. var LargeSymbolPathShape =
  39935. /** @class */
  39936. function () {
  39937. function LargeSymbolPathShape() {}
  39938. return LargeSymbolPathShape;
  39939. }();
  39940. var LargeSymbolPath =
  39941. /** @class */
  39942. function (_super) {
  39943. __extends(LargeSymbolPath, _super);
  39944. function LargeSymbolPath(opts) {
  39945. var _this = _super.call(this, opts) || this;
  39946. _this._off = 0;
  39947. _this.hoverDataIdx = -1;
  39948. return _this;
  39949. }
  39950. LargeSymbolPath.prototype.getDefaultShape = function () {
  39951. return new LargeSymbolPathShape();
  39952. };
  39953. LargeSymbolPath.prototype.reset = function () {
  39954. this.notClear = false;
  39955. this._off = 0;
  39956. };
  39957. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  39958. var points = shape.points;
  39959. var size = shape.size;
  39960. var symbolProxy = this.symbolProxy;
  39961. var symbolProxyShape = symbolProxy.shape;
  39962. var ctx = path.getContext ? path.getContext() : path;
  39963. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39964. var softClipShape = this.softClipShape;
  39965. var i; // Do draw in afterBrush.
  39966. if (canBoost) {
  39967. this._ctx = ctx;
  39968. return;
  39969. }
  39970. this._ctx = null;
  39971. for (i = this._off; i < points.length;) {
  39972. var x = points[i++];
  39973. var y = points[i++];
  39974. if (isNaN(x) || isNaN(y)) {
  39975. continue;
  39976. }
  39977. if (softClipShape && !softClipShape.contain(x, y)) {
  39978. continue;
  39979. }
  39980. symbolProxyShape.x = x - size[0] / 2;
  39981. symbolProxyShape.y = y - size[1] / 2;
  39982. symbolProxyShape.width = size[0];
  39983. symbolProxyShape.height = size[1];
  39984. symbolProxy.buildPath(path, symbolProxyShape, true);
  39985. }
  39986. if (this.incremental) {
  39987. this._off = i;
  39988. this.notClear = true;
  39989. }
  39990. };
  39991. LargeSymbolPath.prototype.afterBrush = function () {
  39992. var shape = this.shape;
  39993. var points = shape.points;
  39994. var size = shape.size;
  39995. var ctx = this._ctx;
  39996. var softClipShape = this.softClipShape;
  39997. var i;
  39998. if (!ctx) {
  39999. return;
  40000. } // PENDING If style or other canvas status changed?
  40001. for (i = this._off; i < points.length;) {
  40002. var x = points[i++];
  40003. var y = points[i++];
  40004. if (isNaN(x) || isNaN(y)) {
  40005. continue;
  40006. }
  40007. if (softClipShape && !softClipShape.contain(x, y)) {
  40008. continue;
  40009. } // fillRect is faster than building a rect path and draw.
  40010. // And it support light globalCompositeOperation.
  40011. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  40012. }
  40013. if (this.incremental) {
  40014. this._off = i;
  40015. this.notClear = true;
  40016. }
  40017. };
  40018. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  40019. // TODO ???
  40020. // Consider transform
  40021. var shape = this.shape;
  40022. var points = shape.points;
  40023. var size = shape.size;
  40024. var w = Math.max(size[0], 4);
  40025. var h = Math.max(size[1], 4); // Not consider transform
  40026. // Treat each element as a rect
  40027. // top down traverse
  40028. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  40029. var i = idx * 2;
  40030. var x0 = points[i] - w / 2;
  40031. var y0 = points[i + 1] - h / 2;
  40032. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  40033. return idx;
  40034. }
  40035. }
  40036. return -1;
  40037. };
  40038. LargeSymbolPath.prototype.contain = function (x, y) {
  40039. var localPos = this.transformCoordToLocal(x, y);
  40040. var rect = this.getBoundingRect();
  40041. x = localPos[0];
  40042. y = localPos[1];
  40043. if (rect.contain(x, y)) {
  40044. // Cache found data index.
  40045. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  40046. return dataIdx >= 0;
  40047. }
  40048. this.hoverDataIdx = -1;
  40049. return false;
  40050. };
  40051. LargeSymbolPath.prototype.getBoundingRect = function () {
  40052. // Ignore stroke for large symbol draw.
  40053. var rect = this._rect;
  40054. if (!rect) {
  40055. var shape = this.shape;
  40056. var points = shape.points;
  40057. var size = shape.size;
  40058. var w = size[0];
  40059. var h = size[1];
  40060. var minX = Infinity;
  40061. var minY = Infinity;
  40062. var maxX = -Infinity;
  40063. var maxY = -Infinity;
  40064. for (var i = 0; i < points.length;) {
  40065. var x = points[i++];
  40066. var y = points[i++];
  40067. minX = Math.min(x, minX);
  40068. maxX = Math.max(x, maxX);
  40069. minY = Math.min(y, minY);
  40070. maxY = Math.max(y, maxY);
  40071. }
  40072. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  40073. }
  40074. return rect;
  40075. };
  40076. return LargeSymbolPath;
  40077. }(Path);
  40078. var LargeSymbolDraw =
  40079. /** @class */
  40080. function () {
  40081. function LargeSymbolDraw() {
  40082. this.group = new Group();
  40083. }
  40084. /**
  40085. * Update symbols draw by new data
  40086. */
  40087. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  40088. this._clear();
  40089. var symbolEl = this._create();
  40090. symbolEl.setShape({
  40091. points: data.getLayout('points')
  40092. });
  40093. this._setCommon(symbolEl, data, opt);
  40094. };
  40095. LargeSymbolDraw.prototype.updateLayout = function (data) {
  40096. var points = data.getLayout('points');
  40097. this.group.eachChild(function (child) {
  40098. if (child.startIndex != null) {
  40099. var len = (child.endIndex - child.startIndex) * 2;
  40100. var byteOffset = child.startIndex * 4 * 2;
  40101. points = new Float32Array(points.buffer, byteOffset, len);
  40102. }
  40103. child.setShape('points', points); // Reset draw cursor.
  40104. child.reset();
  40105. });
  40106. };
  40107. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  40108. this._clear();
  40109. };
  40110. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  40111. var lastAdded = this._newAdded[0];
  40112. var points = data.getLayout('points');
  40113. var oldPoints = lastAdded && lastAdded.shape.points; // Merging the exists. Each element has 1e4 points.
  40114. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  40115. if (oldPoints && oldPoints.length < 2e4) {
  40116. var oldLen = oldPoints.length;
  40117. var newPoints = new Float32Array(oldLen + points.length); // Concat two array
  40118. newPoints.set(oldPoints);
  40119. newPoints.set(points, oldLen); // Update endIndex
  40120. lastAdded.endIndex = taskParams.end;
  40121. lastAdded.setShape({
  40122. points: newPoints
  40123. });
  40124. } else {
  40125. // Clear
  40126. this._newAdded = [];
  40127. var symbolEl = this._create();
  40128. symbolEl.startIndex = taskParams.start;
  40129. symbolEl.endIndex = taskParams.end;
  40130. symbolEl.incremental = true;
  40131. symbolEl.setShape({
  40132. points: points
  40133. });
  40134. this._setCommon(symbolEl, data, opt);
  40135. }
  40136. };
  40137. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  40138. this._newAdded[0] && cb(this._newAdded[0]);
  40139. };
  40140. LargeSymbolDraw.prototype._create = function () {
  40141. var symbolEl = new LargeSymbolPath({
  40142. cursor: 'default'
  40143. });
  40144. this.group.add(symbolEl);
  40145. this._newAdded.push(symbolEl);
  40146. return symbolEl;
  40147. };
  40148. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  40149. var hostModel = data.hostModel;
  40150. opt = opt || {};
  40151. var size = data.getVisual('symbolSize');
  40152. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  40153. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  40154. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  40155. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  40156. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  40157. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  40158. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  40159. var globalStyle = data.getVisual('style');
  40160. var visualColor = globalStyle && globalStyle.fill;
  40161. if (visualColor) {
  40162. symbolEl.setColor(visualColor);
  40163. }
  40164. var ecData = getECData(symbolEl); // Enable tooltip
  40165. // PENDING May have performance issue when path is extremely large
  40166. ecData.seriesIndex = hostModel.seriesIndex;
  40167. symbolEl.on('mousemove', function (e) {
  40168. ecData.dataIndex = null;
  40169. var dataIndex = symbolEl.hoverDataIdx;
  40170. if (dataIndex >= 0) {
  40171. // Provide dataIndex for tooltip
  40172. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  40173. }
  40174. });
  40175. };
  40176. LargeSymbolDraw.prototype.remove = function () {
  40177. this._clear();
  40178. };
  40179. LargeSymbolDraw.prototype._clear = function () {
  40180. this._newAdded = [];
  40181. this.group.removeAll();
  40182. };
  40183. return LargeSymbolDraw;
  40184. }();
  40185. var ScatterView =
  40186. /** @class */
  40187. function (_super) {
  40188. __extends(ScatterView, _super);
  40189. function ScatterView() {
  40190. var _this = _super !== null && _super.apply(this, arguments) || this;
  40191. _this.type = ScatterView.type;
  40192. return _this;
  40193. }
  40194. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  40195. var data = seriesModel.getData();
  40196. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40197. symbolDraw.updateData(data, {
  40198. // TODO
  40199. // If this parameter should be a shape or a bounding volume
  40200. // shape will be more general.
  40201. // But bounding volume like bounding rect will be much faster in the contain calculation
  40202. clipShape: this._getClipShape(seriesModel)
  40203. });
  40204. this._finished = true;
  40205. };
  40206. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  40207. var data = seriesModel.getData();
  40208. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40209. symbolDraw.incrementalPrepareUpdate(data);
  40210. this._finished = false;
  40211. };
  40212. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  40213. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  40214. clipShape: this._getClipShape(seriesModel)
  40215. });
  40216. this._finished = taskParams.end === seriesModel.getData().count();
  40217. };
  40218. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  40219. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  40220. // PENDING
  40221. this.group.dirty();
  40222. if (!this._finished || data.count() > 1e4) {
  40223. return {
  40224. update: true
  40225. };
  40226. } else {
  40227. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  40228. if (res.progress) {
  40229. res.progress({
  40230. start: 0,
  40231. end: data.count(),
  40232. count: data.count()
  40233. }, data);
  40234. }
  40235. this._symbolDraw.updateLayout(data);
  40236. }
  40237. };
  40238. ScatterView.prototype.eachRendered = function (cb) {
  40239. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  40240. };
  40241. ScatterView.prototype._getClipShape = function (seriesModel) {
  40242. var coordSys = seriesModel.coordinateSystem;
  40243. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  40244. return seriesModel.get('clip', true) ? clipArea : null;
  40245. };
  40246. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  40247. var symbolDraw = this._symbolDraw;
  40248. var pipelineContext = seriesModel.pipelineContext;
  40249. var isLargeDraw = pipelineContext.large;
  40250. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  40251. symbolDraw && symbolDraw.remove();
  40252. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  40253. this._isLargeDraw = isLargeDraw;
  40254. this.group.removeAll();
  40255. }
  40256. this.group.add(symbolDraw.group);
  40257. return symbolDraw;
  40258. };
  40259. ScatterView.prototype.remove = function (ecModel, api) {
  40260. this._symbolDraw && this._symbolDraw.remove(true);
  40261. this._symbolDraw = null;
  40262. };
  40263. ScatterView.prototype.dispose = function () {};
  40264. ScatterView.type = 'scatter';
  40265. return ScatterView;
  40266. }(ChartView);
  40267. var GridModel =
  40268. /** @class */
  40269. function (_super) {
  40270. __extends(GridModel, _super);
  40271. function GridModel() {
  40272. return _super !== null && _super.apply(this, arguments) || this;
  40273. }
  40274. GridModel.type = 'grid';
  40275. GridModel.dependencies = ['xAxis', 'yAxis'];
  40276. GridModel.layoutMode = 'box';
  40277. GridModel.defaultOption = {
  40278. show: false,
  40279. // zlevel: 0,
  40280. z: 0,
  40281. left: '10%',
  40282. top: 60,
  40283. right: '10%',
  40284. bottom: 70,
  40285. // If grid size contain label
  40286. containLabel: false,
  40287. // width: {totalWidth} - left - right,
  40288. // height: {totalHeight} - top - bottom,
  40289. backgroundColor: 'rgba(0,0,0,0)',
  40290. borderWidth: 1,
  40291. borderColor: '#ccc'
  40292. };
  40293. return GridModel;
  40294. }(ComponentModel);
  40295. var CartesianAxisModel =
  40296. /** @class */
  40297. function (_super) {
  40298. __extends(CartesianAxisModel, _super);
  40299. function CartesianAxisModel() {
  40300. return _super !== null && _super.apply(this, arguments) || this;
  40301. }
  40302. CartesianAxisModel.prototype.getCoordSysModel = function () {
  40303. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  40304. };
  40305. CartesianAxisModel.type = 'cartesian2dAxis';
  40306. return CartesianAxisModel;
  40307. }(ComponentModel);
  40308. mixin(CartesianAxisModel, AxisModelCommonMixin);
  40309. var defaultOption = {
  40310. show: true,
  40311. // zlevel: 0,
  40312. z: 0,
  40313. // Inverse the axis.
  40314. inverse: false,
  40315. // Axis name displayed.
  40316. name: '',
  40317. // 'start' | 'middle' | 'end'
  40318. nameLocation: 'end',
  40319. // By degree. By default auto rotate by nameLocation.
  40320. nameRotate: null,
  40321. nameTruncate: {
  40322. maxWidth: null,
  40323. ellipsis: '...',
  40324. placeholder: '.'
  40325. },
  40326. // Use global text style by default.
  40327. nameTextStyle: {},
  40328. // The gap between axisName and axisLine.
  40329. nameGap: 15,
  40330. // Default `false` to support tooltip.
  40331. silent: false,
  40332. // Default `false` to avoid legacy user event listener fail.
  40333. triggerEvent: false,
  40334. tooltip: {
  40335. show: false
  40336. },
  40337. axisPointer: {},
  40338. axisLine: {
  40339. show: true,
  40340. onZero: true,
  40341. onZeroAxisIndex: null,
  40342. lineStyle: {
  40343. color: '#6E7079',
  40344. width: 1,
  40345. type: 'solid'
  40346. },
  40347. // The arrow at both ends the the axis.
  40348. symbol: ['none', 'none'],
  40349. symbolSize: [10, 15]
  40350. },
  40351. axisTick: {
  40352. show: true,
  40353. // Whether axisTick is inside the grid or outside the grid.
  40354. inside: false,
  40355. // The length of axisTick.
  40356. length: 5,
  40357. lineStyle: {
  40358. width: 1
  40359. }
  40360. },
  40361. axisLabel: {
  40362. show: true,
  40363. // Whether axisLabel is inside the grid or outside the grid.
  40364. inside: false,
  40365. rotate: 0,
  40366. // true | false | null/undefined (auto)
  40367. showMinLabel: null,
  40368. // true | false | null/undefined (auto)
  40369. showMaxLabel: null,
  40370. margin: 8,
  40371. // formatter: null,
  40372. fontSize: 12
  40373. },
  40374. splitLine: {
  40375. show: true,
  40376. lineStyle: {
  40377. color: ['#E0E6F1'],
  40378. width: 1,
  40379. type: 'solid'
  40380. }
  40381. },
  40382. splitArea: {
  40383. show: false,
  40384. areaStyle: {
  40385. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  40386. }
  40387. }
  40388. };
  40389. var categoryAxis = merge({
  40390. // The gap at both ends of the axis. For categoryAxis, boolean.
  40391. boundaryGap: true,
  40392. // Set false to faster category collection.
  40393. deduplication: null,
  40394. // splitArea: {
  40395. // show: false
  40396. // },
  40397. splitLine: {
  40398. show: false
  40399. },
  40400. axisTick: {
  40401. // If tick is align with label when boundaryGap is true
  40402. alignWithLabel: false,
  40403. interval: 'auto'
  40404. },
  40405. axisLabel: {
  40406. interval: 'auto'
  40407. }
  40408. }, defaultOption);
  40409. var valueAxis = merge({
  40410. boundaryGap: [0, 0],
  40411. axisLine: {
  40412. // Not shown when other axis is categoryAxis in cartesian
  40413. show: 'auto'
  40414. },
  40415. axisTick: {
  40416. // Not shown when other axis is categoryAxis in cartesian
  40417. show: 'auto'
  40418. },
  40419. // TODO
  40420. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  40421. splitNumber: 5,
  40422. minorTick: {
  40423. // Minor tick, not available for cateogry axis.
  40424. show: false,
  40425. // Split number of minor ticks. The value should be in range of (0, 100)
  40426. splitNumber: 5,
  40427. // Lenght of minor tick
  40428. length: 3,
  40429. // Line style
  40430. lineStyle: {// Default to be same with axisTick
  40431. }
  40432. },
  40433. minorSplitLine: {
  40434. show: false,
  40435. lineStyle: {
  40436. color: '#F4F7FD',
  40437. width: 1
  40438. }
  40439. }
  40440. }, defaultOption);
  40441. var timeAxis = merge({
  40442. splitNumber: 6,
  40443. axisLabel: {
  40444. // To eliminate labels that are not nice
  40445. showMinLabel: false,
  40446. showMaxLabel: false,
  40447. rich: {
  40448. primary: {
  40449. fontWeight: 'bold'
  40450. }
  40451. }
  40452. },
  40453. splitLine: {
  40454. show: false
  40455. }
  40456. }, valueAxis);
  40457. var logAxis = defaults({
  40458. logBase: 10
  40459. }, valueAxis);
  40460. var axisDefault = {
  40461. category: categoryAxis,
  40462. value: valueAxis,
  40463. time: timeAxis,
  40464. log: logAxis
  40465. };
  40466. /*
  40467. * Licensed to the Apache Software Foundation (ASF) under one
  40468. * or more contributor license agreements. See the NOTICE file
  40469. * distributed with this work for additional information
  40470. * regarding copyright ownership. The ASF licenses this file
  40471. * to you under the Apache License, Version 2.0 (the
  40472. * "License"); you may not use this file except in compliance
  40473. * with the License. You may obtain a copy of the License at
  40474. *
  40475. * http://www.apache.org/licenses/LICENSE-2.0
  40476. *
  40477. * Unless required by applicable law or agreed to in writing,
  40478. * software distributed under the License is distributed on an
  40479. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40480. * KIND, either express or implied. See the License for the
  40481. * specific language governing permissions and limitations
  40482. * under the License.
  40483. */
  40484. /**
  40485. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40486. */
  40487. /*
  40488. * Licensed to the Apache Software Foundation (ASF) under one
  40489. * or more contributor license agreements. See the NOTICE file
  40490. * distributed with this work for additional information
  40491. * regarding copyright ownership. The ASF licenses this file
  40492. * to you under the Apache License, Version 2.0 (the
  40493. * "License"); you may not use this file except in compliance
  40494. * with the License. You may obtain a copy of the License at
  40495. *
  40496. * http://www.apache.org/licenses/LICENSE-2.0
  40497. *
  40498. * Unless required by applicable law or agreed to in writing,
  40499. * software distributed under the License is distributed on an
  40500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40501. * KIND, either express or implied. See the License for the
  40502. * specific language governing permissions and limitations
  40503. * under the License.
  40504. */
  40505. var AXIS_TYPES = {
  40506. value: 1,
  40507. category: 1,
  40508. time: 1,
  40509. log: 1
  40510. };
  40511. /**
  40512. * Generate sub axis model class
  40513. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  40514. */
  40515. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  40516. each(AXIS_TYPES, function (v, axisType) {
  40517. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  40518. var AxisModel =
  40519. /** @class */
  40520. function (_super) {
  40521. __extends(AxisModel, _super);
  40522. function AxisModel() {
  40523. var _this = _super !== null && _super.apply(this, arguments) || this;
  40524. _this.type = axisName + 'Axis.' + axisType;
  40525. return _this;
  40526. }
  40527. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  40528. var layoutMode = fetchLayoutMode(this);
  40529. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  40530. var themeModel = ecModel.getTheme();
  40531. merge(option, themeModel.get(axisType + 'Axis'));
  40532. merge(option, this.getDefaultOption());
  40533. option.type = getAxisType(option);
  40534. if (layoutMode) {
  40535. mergeLayoutParam(option, inputPositionParams, layoutMode);
  40536. }
  40537. };
  40538. AxisModel.prototype.optionUpdated = function () {
  40539. var thisOption = this.option;
  40540. if (thisOption.type === 'category') {
  40541. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  40542. }
  40543. };
  40544. /**
  40545. * Should not be called before all of 'getInitailData' finished.
  40546. * Because categories are collected during initializing data.
  40547. */
  40548. AxisModel.prototype.getCategories = function (rawData) {
  40549. var option = this.option; // FIXME
  40550. // warning if called before all of 'getInitailData' finished.
  40551. if (option.type === 'category') {
  40552. if (rawData) {
  40553. return option.data;
  40554. }
  40555. return this.__ordinalMeta.categories;
  40556. }
  40557. };
  40558. AxisModel.prototype.getOrdinalMeta = function () {
  40559. return this.__ordinalMeta;
  40560. };
  40561. AxisModel.type = axisName + 'Axis.' + axisType;
  40562. AxisModel.defaultOption = defaultOption;
  40563. return AxisModel;
  40564. }(BaseAxisModelClass);
  40565. registers.registerComponentModel(AxisModel);
  40566. });
  40567. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  40568. }
  40569. function getAxisType(option) {
  40570. // Default axis with data is category axis
  40571. return option.type || (option.data ? 'category' : 'value');
  40572. }
  40573. var Cartesian =
  40574. /** @class */
  40575. function () {
  40576. function Cartesian(name) {
  40577. this.type = 'cartesian';
  40578. this._dimList = [];
  40579. this._axes = {};
  40580. this.name = name || '';
  40581. }
  40582. Cartesian.prototype.getAxis = function (dim) {
  40583. return this._axes[dim];
  40584. };
  40585. Cartesian.prototype.getAxes = function () {
  40586. return map(this._dimList, function (dim) {
  40587. return this._axes[dim];
  40588. }, this);
  40589. };
  40590. Cartesian.prototype.getAxesByScale = function (scaleType) {
  40591. scaleType = scaleType.toLowerCase();
  40592. return filter(this.getAxes(), function (axis) {
  40593. return axis.scale.type === scaleType;
  40594. });
  40595. };
  40596. Cartesian.prototype.addAxis = function (axis) {
  40597. var dim = axis.dim;
  40598. this._axes[dim] = axis;
  40599. this._dimList.push(dim);
  40600. };
  40601. return Cartesian;
  40602. }();
  40603. var cartesian2DDimensions = ['x', 'y'];
  40604. function canCalculateAffineTransform(scale) {
  40605. return scale.type === 'interval' || scale.type === 'time';
  40606. }
  40607. var Cartesian2D =
  40608. /** @class */
  40609. function (_super) {
  40610. __extends(Cartesian2D, _super);
  40611. function Cartesian2D() {
  40612. var _this = _super !== null && _super.apply(this, arguments) || this;
  40613. _this.type = 'cartesian2d';
  40614. _this.dimensions = cartesian2DDimensions;
  40615. return _this;
  40616. }
  40617. /**
  40618. * Calculate an affine transform matrix if two axes are time or value.
  40619. * It's mainly for accelartion on the large time series data.
  40620. */
  40621. Cartesian2D.prototype.calcAffineTransform = function () {
  40622. this._transform = this._invTransform = null;
  40623. var xAxisScale = this.getAxis('x').scale;
  40624. var yAxisScale = this.getAxis('y').scale;
  40625. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  40626. return;
  40627. }
  40628. var xScaleExtent = xAxisScale.getExtent();
  40629. var yScaleExtent = yAxisScale.getExtent();
  40630. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  40631. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  40632. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  40633. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  40634. if (!xScaleSpan || !yScaleSpan) {
  40635. return;
  40636. } // Accelerate data to point calculation on the special large time series data.
  40637. var scaleX = (end[0] - start[0]) / xScaleSpan;
  40638. var scaleY = (end[1] - start[1]) / yScaleSpan;
  40639. var translateX = start[0] - xScaleExtent[0] * scaleX;
  40640. var translateY = start[1] - yScaleExtent[0] * scaleY;
  40641. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  40642. this._invTransform = invert([], m);
  40643. };
  40644. /**
  40645. * Base axis will be used on stacking.
  40646. */
  40647. Cartesian2D.prototype.getBaseAxis = function () {
  40648. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  40649. };
  40650. Cartesian2D.prototype.containPoint = function (point) {
  40651. var axisX = this.getAxis('x');
  40652. var axisY = this.getAxis('y');
  40653. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  40654. };
  40655. Cartesian2D.prototype.containData = function (data) {
  40656. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  40657. };
  40658. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  40659. out = out || [];
  40660. var xVal = data[0];
  40661. var yVal = data[1]; // Fast path
  40662. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  40663. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  40664. return applyTransform(out, data, this._transform);
  40665. }
  40666. var xAxis = this.getAxis('x');
  40667. var yAxis = this.getAxis('y');
  40668. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  40669. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  40670. return out;
  40671. };
  40672. Cartesian2D.prototype.clampData = function (data, out) {
  40673. var xScale = this.getAxis('x').scale;
  40674. var yScale = this.getAxis('y').scale;
  40675. var xAxisExtent = xScale.getExtent();
  40676. var yAxisExtent = yScale.getExtent();
  40677. var x = xScale.parse(data[0]);
  40678. var y = yScale.parse(data[1]);
  40679. out = out || [];
  40680. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  40681. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  40682. return out;
  40683. };
  40684. Cartesian2D.prototype.pointToData = function (point, clamp) {
  40685. var out = [];
  40686. if (this._invTransform) {
  40687. return applyTransform(out, point, this._invTransform);
  40688. }
  40689. var xAxis = this.getAxis('x');
  40690. var yAxis = this.getAxis('y');
  40691. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  40692. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  40693. return out;
  40694. };
  40695. Cartesian2D.prototype.getOtherAxis = function (axis) {
  40696. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  40697. };
  40698. /**
  40699. * Get rect area of cartesian.
  40700. * Area will have a contain function to determine if a point is in the coordinate system.
  40701. */
  40702. Cartesian2D.prototype.getArea = function () {
  40703. var xExtent = this.getAxis('x').getGlobalExtent();
  40704. var yExtent = this.getAxis('y').getGlobalExtent();
  40705. var x = Math.min(xExtent[0], xExtent[1]);
  40706. var y = Math.min(yExtent[0], yExtent[1]);
  40707. var width = Math.max(xExtent[0], xExtent[1]) - x;
  40708. var height = Math.max(yExtent[0], yExtent[1]) - y;
  40709. return new BoundingRect(x, y, width, height);
  40710. };
  40711. return Cartesian2D;
  40712. }(Cartesian);
  40713. var Axis2D =
  40714. /** @class */
  40715. function (_super) {
  40716. __extends(Axis2D, _super);
  40717. function Axis2D(dim, scale, coordExtent, axisType, position) {
  40718. var _this = _super.call(this, dim, scale, coordExtent) || this;
  40719. /**
  40720. * Index of axis, can be used as key
  40721. * Injected outside.
  40722. */
  40723. _this.index = 0;
  40724. _this.type = axisType || 'value';
  40725. _this.position = position || 'bottom';
  40726. return _this;
  40727. }
  40728. Axis2D.prototype.isHorizontal = function () {
  40729. var position = this.position;
  40730. return position === 'top' || position === 'bottom';
  40731. };
  40732. /**
  40733. * Each item cooresponds to this.getExtent(), which
  40734. * means globalExtent[0] may greater than globalExtent[1],
  40735. * unless `asc` is input.
  40736. *
  40737. * @param {boolean} [asc]
  40738. * @return {Array.<number>}
  40739. */
  40740. Axis2D.prototype.getGlobalExtent = function (asc) {
  40741. var ret = this.getExtent();
  40742. ret[0] = this.toGlobalCoord(ret[0]);
  40743. ret[1] = this.toGlobalCoord(ret[1]);
  40744. asc && ret[0] > ret[1] && ret.reverse();
  40745. return ret;
  40746. };
  40747. Axis2D.prototype.pointToData = function (point, clamp) {
  40748. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  40749. };
  40750. /**
  40751. * Set ordinalSortInfo
  40752. * @param info new OrdinalSortInfo
  40753. */
  40754. Axis2D.prototype.setCategorySortInfo = function (info) {
  40755. if (this.type !== 'category') {
  40756. return false;
  40757. }
  40758. this.model.option.categorySortInfo = info;
  40759. this.scale.setSortInfo(info);
  40760. };
  40761. return Axis2D;
  40762. }(Axis);
  40763. /**
  40764. * Can only be called after coordinate system creation stage.
  40765. * (Can be called before coordinate system update stage).
  40766. */
  40767. function layout$1(gridModel, axisModel, opt) {
  40768. opt = opt || {};
  40769. var grid = gridModel.coordinateSystem;
  40770. var axis = axisModel.axis;
  40771. var layout = {};
  40772. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  40773. var rawAxisPosition = axis.position;
  40774. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  40775. var axisDim = axis.dim;
  40776. var rect = grid.getRect();
  40777. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  40778. var idx = {
  40779. left: 0,
  40780. right: 1,
  40781. top: 0,
  40782. bottom: 1,
  40783. onZero: 2
  40784. };
  40785. var axisOffset = axisModel.get('offset') || 0;
  40786. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  40787. if (otherAxisOnZeroOf) {
  40788. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  40789. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  40790. } // Axis position
  40791. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  40792. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  40793. var dirMap = {
  40794. top: -1,
  40795. bottom: 1,
  40796. left: -1,
  40797. right: 1
  40798. };
  40799. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  40800. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  40801. if (axisModel.get(['axisTick', 'inside'])) {
  40802. layout.tickDirection = -layout.tickDirection;
  40803. }
  40804. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  40805. layout.labelDirection = -layout.labelDirection;
  40806. } // Special label rotation
  40807. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  40808. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  40809. layout.z2 = 1;
  40810. return layout;
  40811. }
  40812. function isCartesian2DSeries(seriesModel) {
  40813. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  40814. }
  40815. function findAxisModels(seriesModel) {
  40816. var axisModelMap = {
  40817. xAxisModel: null,
  40818. yAxisModel: null
  40819. };
  40820. each(axisModelMap, function (v, key) {
  40821. var axisType = key.replace(/Model$/, '');
  40822. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  40823. if ("development" !== 'production') {
  40824. if (!axisModel) {
  40825. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  40826. }
  40827. }
  40828. axisModelMap[key] = axisModel;
  40829. });
  40830. return axisModelMap;
  40831. }
  40832. var mathLog$1 = Math.log;
  40833. function alignScaleTicks(scale, axisModel, alignToScale) {
  40834. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  40835. // In log scale we store _interval and _extent of exponent value.
  40836. // So if we use the method of InternalScale to set/get these data.
  40837. // It process the exponent value, which is linear and what we want here.
  40838. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  40839. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  40840. var alignToSplitNumber = alignToTicks.length - 1;
  40841. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  40842. var scaleExtent = getScaleExtent(scale, axisModel);
  40843. var rawExtent = scaleExtent.extent;
  40844. var isMinFixed = scaleExtent.fixMin;
  40845. var isMaxFixed = scaleExtent.fixMax;
  40846. if (scale.type === 'log') {
  40847. var logBase = mathLog$1(scale.base);
  40848. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  40849. }
  40850. scale.setExtent(rawExtent[0], rawExtent[1]);
  40851. scale.calcNiceExtent({
  40852. splitNumber: alignToSplitNumber,
  40853. fixMin: isMinFixed,
  40854. fixMax: isMaxFixed
  40855. });
  40856. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  40857. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  40858. if (isMinFixed) {
  40859. rawExtent[0] = extent[0];
  40860. }
  40861. if (isMaxFixed) {
  40862. rawExtent[1] = extent[1];
  40863. }
  40864. var interval = intervalScaleProto.getInterval.call(scale);
  40865. var min = rawExtent[0];
  40866. var max = rawExtent[1];
  40867. if (isMinFixed && isMaxFixed) {
  40868. // User set min, max, divide to get new interval
  40869. interval = (max - min) / alignToSplitNumber;
  40870. } else if (isMinFixed) {
  40871. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  40872. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  40873. interval = increaseInterval(interval);
  40874. max = rawExtent[0] + interval * alignToSplitNumber;
  40875. }
  40876. } else if (isMaxFixed) {
  40877. // User set max, expand extent on the other side
  40878. min = rawExtent[1] - interval * alignToSplitNumber;
  40879. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  40880. interval = increaseInterval(interval);
  40881. min = rawExtent[1] - interval * alignToSplitNumber;
  40882. }
  40883. } else {
  40884. var nicedSplitNumber = scale.getTicks().length - 1;
  40885. if (nicedSplitNumber > alignToSplitNumber) {
  40886. interval = increaseInterval(interval);
  40887. }
  40888. var range = interval * alignToSplitNumber;
  40889. max = Math.ceil(rawExtent[1] / interval) * interval;
  40890. min = round(max - range); // Not change the result that crossing zero.
  40891. if (min < 0 && rawExtent[0] >= 0) {
  40892. min = 0;
  40893. max = round(range);
  40894. } else if (max > 0 && rawExtent[1] <= 0) {
  40895. max = 0;
  40896. min = -round(range);
  40897. }
  40898. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  40899. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  40900. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  40901. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  40902. intervalScaleProto.setInterval.call(scale, interval);
  40903. if (t0 || t1) {
  40904. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  40905. }
  40906. if ("development" !== 'production') {
  40907. var ticks = intervalScaleProto.getTicks.call(scale);
  40908. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  40909. warn( // eslint-disable-next-line
  40910. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  40911. }
  40912. }
  40913. }
  40914. var Grid =
  40915. /** @class */
  40916. function () {
  40917. function Grid(gridModel, ecModel, api) {
  40918. // FIXME:TS where used (different from registered type 'cartesian2d')?
  40919. this.type = 'grid';
  40920. this._coordsMap = {};
  40921. this._coordsList = [];
  40922. this._axesMap = {};
  40923. this._axesList = [];
  40924. this.axisPointerEnabled = true;
  40925. this.dimensions = cartesian2DDimensions;
  40926. this._initCartesian(gridModel, ecModel, api);
  40927. this.model = gridModel;
  40928. }
  40929. Grid.prototype.getRect = function () {
  40930. return this._rect;
  40931. };
  40932. Grid.prototype.update = function (ecModel, api) {
  40933. var axesMap = this._axesMap;
  40934. this._updateScale(ecModel, this.model);
  40935. function updateAxisTicks(axes) {
  40936. var alignTo; // Axis is added in order of axisIndex.
  40937. var axesIndices = keys(axes);
  40938. var len = axesIndices.length;
  40939. if (!len) {
  40940. return;
  40941. }
  40942. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  40943. for (var i = len - 1; i >= 0; i--) {
  40944. var idx = +axesIndices[i]; // Convert to number.
  40945. var axis = axes[idx];
  40946. var model = axis.model;
  40947. var scale = axis.scale;
  40948. if ( // Only value and log axis without interval support alignTicks.
  40949. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  40950. axisNeedsAlign.push(axis);
  40951. } else {
  40952. niceScaleExtent(scale, model);
  40953. if (isIntervalOrLogScale(scale)) {
  40954. // Can only align to interval or log axis.
  40955. alignTo = axis;
  40956. }
  40957. }
  40958. }
  40959. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  40960. if (axisNeedsAlign.length) {
  40961. if (!alignTo) {
  40962. alignTo = axisNeedsAlign.pop();
  40963. niceScaleExtent(alignTo.scale, alignTo.model);
  40964. }
  40965. each(axisNeedsAlign, function (axis) {
  40966. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  40967. });
  40968. }
  40969. }
  40970. updateAxisTicks(axesMap.x);
  40971. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  40972. var onZeroRecords = {};
  40973. each(axesMap.x, function (xAxis) {
  40974. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  40975. });
  40976. each(axesMap.y, function (yAxis) {
  40977. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  40978. }); // Resize again if containLabel is enabled
  40979. // FIXME It may cause getting wrong grid size in data processing stage
  40980. this.resize(this.model, api);
  40981. };
  40982. /**
  40983. * Resize the grid
  40984. */
  40985. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  40986. var boxLayoutParams = gridModel.getBoxLayoutParams();
  40987. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  40988. var gridRect = getLayoutRect(boxLayoutParams, {
  40989. width: api.getWidth(),
  40990. height: api.getHeight()
  40991. });
  40992. this._rect = gridRect;
  40993. var axesList = this._axesList;
  40994. adjustAxes(); // Minus label size
  40995. if (isContainLabel) {
  40996. each(axesList, function (axis) {
  40997. if (!axis.model.get(['axisLabel', 'inside'])) {
  40998. var labelUnionRect = estimateLabelUnionRect(axis);
  40999. if (labelUnionRect) {
  41000. var dim = axis.isHorizontal() ? 'height' : 'width';
  41001. var margin = axis.model.get(['axisLabel', 'margin']);
  41002. gridRect[dim] -= labelUnionRect[dim] + margin;
  41003. if (axis.position === 'top') {
  41004. gridRect.y += labelUnionRect.height + margin;
  41005. } else if (axis.position === 'left') {
  41006. gridRect.x += labelUnionRect.width + margin;
  41007. }
  41008. }
  41009. }
  41010. });
  41011. adjustAxes();
  41012. }
  41013. each(this._coordsList, function (coord) {
  41014. // Calculate affine matrix to accelerate the data to point transform.
  41015. // If all the axes scales are time or value.
  41016. coord.calcAffineTransform();
  41017. });
  41018. function adjustAxes() {
  41019. each(axesList, function (axis) {
  41020. var isHorizontal = axis.isHorizontal();
  41021. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  41022. var idx = axis.inverse ? 1 : 0;
  41023. axis.setExtent(extent[idx], extent[1 - idx]);
  41024. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  41025. });
  41026. }
  41027. };
  41028. Grid.prototype.getAxis = function (dim, axisIndex) {
  41029. var axesMapOnDim = this._axesMap[dim];
  41030. if (axesMapOnDim != null) {
  41031. return axesMapOnDim[axisIndex || 0];
  41032. }
  41033. };
  41034. Grid.prototype.getAxes = function () {
  41035. return this._axesList.slice();
  41036. };
  41037. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  41038. if (xAxisIndex != null && yAxisIndex != null) {
  41039. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  41040. return this._coordsMap[key];
  41041. }
  41042. if (isObject(xAxisIndex)) {
  41043. yAxisIndex = xAxisIndex.yAxisIndex;
  41044. xAxisIndex = xAxisIndex.xAxisIndex;
  41045. }
  41046. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  41047. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  41048. return coordList[i];
  41049. }
  41050. }
  41051. };
  41052. Grid.prototype.getCartesians = function () {
  41053. return this._coordsList.slice();
  41054. };
  41055. /**
  41056. * @implements
  41057. */
  41058. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  41059. var target = this._findConvertTarget(finder);
  41060. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  41061. };
  41062. /**
  41063. * @implements
  41064. */
  41065. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  41066. var target = this._findConvertTarget(finder);
  41067. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  41068. };
  41069. Grid.prototype._findConvertTarget = function (finder) {
  41070. var seriesModel = finder.seriesModel;
  41071. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  41072. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  41073. var gridModel = finder.gridModel;
  41074. var coordsList = this._coordsList;
  41075. var cartesian;
  41076. var axis;
  41077. if (seriesModel) {
  41078. cartesian = seriesModel.coordinateSystem;
  41079. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  41080. } else if (xAxisModel && yAxisModel) {
  41081. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41082. } else if (xAxisModel) {
  41083. axis = this.getAxis('x', xAxisModel.componentIndex);
  41084. } else if (yAxisModel) {
  41085. axis = this.getAxis('y', yAxisModel.componentIndex);
  41086. } // Lowest priority.
  41087. else if (gridModel) {
  41088. var grid = gridModel.coordinateSystem;
  41089. if (grid === this) {
  41090. cartesian = this._coordsList[0];
  41091. }
  41092. }
  41093. return {
  41094. cartesian: cartesian,
  41095. axis: axis
  41096. };
  41097. };
  41098. /**
  41099. * @implements
  41100. */
  41101. Grid.prototype.containPoint = function (point) {
  41102. var coord = this._coordsList[0];
  41103. if (coord) {
  41104. return coord.containPoint(point);
  41105. }
  41106. };
  41107. /**
  41108. * Initialize cartesian coordinate systems
  41109. */
  41110. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  41111. var _this = this;
  41112. var grid = this;
  41113. var axisPositionUsed = {
  41114. left: false,
  41115. right: false,
  41116. top: false,
  41117. bottom: false
  41118. };
  41119. var axesMap = {
  41120. x: {},
  41121. y: {}
  41122. };
  41123. var axesCount = {
  41124. x: 0,
  41125. y: 0
  41126. }; /// Create axis
  41127. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  41128. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  41129. if (!axesCount.x || !axesCount.y) {
  41130. // Roll back when there no either x or y axis
  41131. this._axesMap = {};
  41132. this._axesList = [];
  41133. return;
  41134. }
  41135. this._axesMap = axesMap; /// Create cartesian2d
  41136. each(axesMap.x, function (xAxis, xAxisIndex) {
  41137. each(axesMap.y, function (yAxis, yAxisIndex) {
  41138. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  41139. var cartesian = new Cartesian2D(key);
  41140. cartesian.master = _this;
  41141. cartesian.model = gridModel;
  41142. _this._coordsMap[key] = cartesian;
  41143. _this._coordsList.push(cartesian);
  41144. cartesian.addAxis(xAxis);
  41145. cartesian.addAxis(yAxis);
  41146. });
  41147. });
  41148. function createAxisCreator(dimName) {
  41149. return function (axisModel, idx) {
  41150. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  41151. return;
  41152. }
  41153. var axisPosition = axisModel.get('position');
  41154. if (dimName === 'x') {
  41155. // Fix position
  41156. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  41157. // Default bottom of X
  41158. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  41159. }
  41160. } else {
  41161. // Fix position
  41162. if (axisPosition !== 'left' && axisPosition !== 'right') {
  41163. // Default left of Y
  41164. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  41165. }
  41166. }
  41167. axisPositionUsed[axisPosition] = true;
  41168. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  41169. var isCategory = axis.type === 'category';
  41170. axis.onBand = isCategory && axisModel.get('boundaryGap');
  41171. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  41172. axisModel.axis = axis; // Inject axisModel into axis
  41173. axis.model = axisModel; // Inject grid info axis
  41174. axis.grid = grid; // Index of axis, can be used as key
  41175. axis.index = idx;
  41176. grid._axesList.push(axis);
  41177. axesMap[dimName][idx] = axis;
  41178. axesCount[dimName]++;
  41179. };
  41180. }
  41181. };
  41182. /**
  41183. * Update cartesian properties from series.
  41184. */
  41185. Grid.prototype._updateScale = function (ecModel, gridModel) {
  41186. // Reset scale
  41187. each(this._axesList, function (axis) {
  41188. axis.scale.setExtent(Infinity, -Infinity);
  41189. if (axis.type === 'category') {
  41190. var categorySortInfo = axis.model.get('categorySortInfo');
  41191. axis.scale.setSortInfo(categorySortInfo);
  41192. }
  41193. });
  41194. ecModel.eachSeries(function (seriesModel) {
  41195. if (isCartesian2DSeries(seriesModel)) {
  41196. var axesModelMap = findAxisModels(seriesModel);
  41197. var xAxisModel = axesModelMap.xAxisModel;
  41198. var yAxisModel = axesModelMap.yAxisModel;
  41199. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  41200. return;
  41201. }
  41202. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41203. var data = seriesModel.getData();
  41204. var xAxis = cartesian.getAxis('x');
  41205. var yAxis = cartesian.getAxis('y');
  41206. unionExtent(data, xAxis);
  41207. unionExtent(data, yAxis);
  41208. }
  41209. }, this);
  41210. function unionExtent(data, axis) {
  41211. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  41212. axis.scale.unionExtentFromData(data, dim);
  41213. });
  41214. }
  41215. };
  41216. /**
  41217. * @param dim 'x' or 'y' or 'auto' or null/undefined
  41218. */
  41219. Grid.prototype.getTooltipAxes = function (dim) {
  41220. var baseAxes = [];
  41221. var otherAxes = [];
  41222. each(this.getCartesians(), function (cartesian) {
  41223. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  41224. var otherAxis = cartesian.getOtherAxis(baseAxis);
  41225. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  41226. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  41227. });
  41228. return {
  41229. baseAxes: baseAxes,
  41230. otherAxes: otherAxes
  41231. };
  41232. };
  41233. Grid.create = function (ecModel, api) {
  41234. var grids = [];
  41235. ecModel.eachComponent('grid', function (gridModel, idx) {
  41236. var grid = new Grid(gridModel, ecModel, api);
  41237. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  41238. // should be performed in create stage.
  41239. grid.resize(gridModel, api, true);
  41240. gridModel.coordinateSystem = grid;
  41241. grids.push(grid);
  41242. }); // Inject the coordinateSystems into seriesModel
  41243. ecModel.eachSeries(function (seriesModel) {
  41244. if (!isCartesian2DSeries(seriesModel)) {
  41245. return;
  41246. }
  41247. var axesModelMap = findAxisModels(seriesModel);
  41248. var xAxisModel = axesModelMap.xAxisModel;
  41249. var yAxisModel = axesModelMap.yAxisModel;
  41250. var gridModel = xAxisModel.getCoordSysModel();
  41251. if ("development" !== 'production') {
  41252. if (!gridModel) {
  41253. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  41254. }
  41255. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  41256. throw new Error('xAxis and yAxis must use the same grid');
  41257. }
  41258. }
  41259. var grid = gridModel.coordinateSystem;
  41260. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  41261. });
  41262. return grids;
  41263. }; // For deciding which dimensions to use when creating list data
  41264. Grid.dimensions = cartesian2DDimensions;
  41265. return Grid;
  41266. }();
  41267. /**
  41268. * Check if the axis is used in the specified grid.
  41269. */
  41270. function isAxisUsedInTheGrid(axisModel, gridModel) {
  41271. return axisModel.getCoordSysModel() === gridModel;
  41272. }
  41273. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  41274. onZeroRecords) {
  41275. axis.getAxesOnZeroOf = function () {
  41276. // TODO: onZero of multiple axes.
  41277. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  41278. }; // onZero can not be enabled in these two situations:
  41279. // 1. When any other axis is a category axis.
  41280. // 2. When no axis is cross 0 point.
  41281. var otherAxes = axesMap[otherAxisDim];
  41282. var otherAxisOnZeroOf;
  41283. var axisModel = axis.model;
  41284. var onZero = axisModel.get(['axisLine', 'onZero']);
  41285. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  41286. if (!onZero) {
  41287. return;
  41288. } // If target axis is specified.
  41289. if (onZeroAxisIndex != null) {
  41290. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  41291. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  41292. }
  41293. } else {
  41294. // Find the first available other axis.
  41295. for (var idx in otherAxes) {
  41296. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  41297. // if both onZero, the two Y axes overlap.
  41298. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  41299. otherAxisOnZeroOf = otherAxes[idx];
  41300. break;
  41301. }
  41302. }
  41303. }
  41304. if (otherAxisOnZeroOf) {
  41305. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  41306. }
  41307. function getOnZeroRecordKey(axis) {
  41308. return axis.dim + '_' + axis.index;
  41309. }
  41310. }
  41311. function canOnZeroToAxis(axis) {
  41312. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  41313. }
  41314. function updateAxisTransform(axis, coordBase) {
  41315. var axisExtent = axis.getExtent();
  41316. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  41317. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  41318. return coord + coordBase;
  41319. } : function (coord) {
  41320. return axisExtentSum - coord + coordBase;
  41321. };
  41322. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  41323. return coord - coordBase;
  41324. } : function (coord) {
  41325. return axisExtentSum - coord + coordBase;
  41326. };
  41327. }
  41328. var PI$5 = Math.PI;
  41329. /**
  41330. * A final axis is translated and rotated from a "standard axis".
  41331. * So opt.position and opt.rotation is required.
  41332. *
  41333. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  41334. * for example: (0, 0) ------------> (0, 50)
  41335. *
  41336. * nameDirection or tickDirection or labelDirection is 1 means tick
  41337. * or label is below the standard axis, whereas is -1 means above
  41338. * the standard axis. labelOffset means offset between label and axis,
  41339. * which is useful when 'onZero', where axisLabel is in the grid and
  41340. * label in outside grid.
  41341. *
  41342. * Tips: like always,
  41343. * positive rotation represents anticlockwise, and negative rotation
  41344. * represents clockwise.
  41345. * The direction of position coordinate is the same as the direction
  41346. * of screen coordinate.
  41347. *
  41348. * Do not need to consider axis 'inverse', which is auto processed by
  41349. * axis extent.
  41350. */
  41351. var AxisBuilder =
  41352. /** @class */
  41353. function () {
  41354. function AxisBuilder(axisModel, opt) {
  41355. this.group = new Group();
  41356. this.opt = opt;
  41357. this.axisModel = axisModel; // Default value
  41358. defaults(opt, {
  41359. labelOffset: 0,
  41360. nameDirection: 1,
  41361. tickDirection: 1,
  41362. labelDirection: 1,
  41363. silent: true,
  41364. handleAutoShown: function () {
  41365. return true;
  41366. }
  41367. }); // FIXME Not use a seperate text group?
  41368. var transformGroup = new Group({
  41369. x: opt.position[0],
  41370. y: opt.position[1],
  41371. rotation: opt.rotation
  41372. }); // this.group.add(transformGroup);
  41373. // this._transformGroup = transformGroup;
  41374. transformGroup.updateTransform();
  41375. this._transformGroup = transformGroup;
  41376. }
  41377. AxisBuilder.prototype.hasBuilder = function (name) {
  41378. return !!builders[name];
  41379. };
  41380. AxisBuilder.prototype.add = function (name) {
  41381. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  41382. };
  41383. AxisBuilder.prototype.getGroup = function () {
  41384. return this.group;
  41385. };
  41386. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  41387. var rotationDiff = remRadian(textRotation - axisRotation);
  41388. var textAlign;
  41389. var textVerticalAlign;
  41390. if (isRadianAroundZero(rotationDiff)) {
  41391. // Label is parallel with axis line.
  41392. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  41393. textAlign = 'center';
  41394. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  41395. // Label is inverse parallel with axis line.
  41396. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  41397. textAlign = 'center';
  41398. } else {
  41399. textVerticalAlign = 'middle';
  41400. if (rotationDiff > 0 && rotationDiff < PI$5) {
  41401. textAlign = direction > 0 ? 'right' : 'left';
  41402. } else {
  41403. textAlign = direction > 0 ? 'left' : 'right';
  41404. }
  41405. }
  41406. return {
  41407. rotation: rotationDiff,
  41408. textAlign: textAlign,
  41409. textVerticalAlign: textVerticalAlign
  41410. };
  41411. };
  41412. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  41413. var eventData = {
  41414. componentType: axisModel.mainType,
  41415. componentIndex: axisModel.componentIndex
  41416. };
  41417. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  41418. return eventData;
  41419. };
  41420. AxisBuilder.isLabelSilent = function (axisModel) {
  41421. var tooltipOpt = axisModel.get('tooltip');
  41422. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  41423. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  41424. };
  41425. return AxisBuilder;
  41426. }();
  41427. var builders = {
  41428. axisLine: function (opt, axisModel, group, transformGroup) {
  41429. var shown = axisModel.get(['axisLine', 'show']);
  41430. if (shown === 'auto' && opt.handleAutoShown) {
  41431. shown = opt.handleAutoShown('axisLine');
  41432. }
  41433. if (!shown) {
  41434. return;
  41435. }
  41436. var extent = axisModel.axis.getExtent();
  41437. var matrix = transformGroup.transform;
  41438. var pt1 = [extent[0], 0];
  41439. var pt2 = [extent[1], 0];
  41440. if (matrix) {
  41441. applyTransform(pt1, pt1, matrix);
  41442. applyTransform(pt2, pt2, matrix);
  41443. }
  41444. var lineStyle = extend({
  41445. lineCap: 'round'
  41446. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  41447. var line = new Line({
  41448. // Id for animation
  41449. subPixelOptimize: true,
  41450. shape: {
  41451. x1: pt1[0],
  41452. y1: pt1[1],
  41453. x2: pt2[0],
  41454. y2: pt2[1]
  41455. },
  41456. style: lineStyle,
  41457. strokeContainThreshold: opt.strokeContainThreshold || 5,
  41458. silent: true,
  41459. z2: 1
  41460. });
  41461. line.anid = 'line';
  41462. group.add(line);
  41463. var arrows = axisModel.get(['axisLine', 'symbol']);
  41464. if (arrows != null) {
  41465. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  41466. if (isString(arrows)) {
  41467. // Use the same arrow for start and end point
  41468. arrows = [arrows, arrows];
  41469. }
  41470. if (isString(arrowSize) || isNumber(arrowSize)) {
  41471. // Use the same size for width and height
  41472. arrowSize = [arrowSize, arrowSize];
  41473. }
  41474. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  41475. var symbolWidth_1 = arrowSize[0];
  41476. var symbolHeight_1 = arrowSize[1];
  41477. each([{
  41478. rotate: opt.rotation + Math.PI / 2,
  41479. offset: arrowOffset[0],
  41480. r: 0
  41481. }, {
  41482. rotate: opt.rotation - Math.PI / 2,
  41483. offset: arrowOffset[1],
  41484. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  41485. }], function (point, index) {
  41486. if (arrows[index] !== 'none' && arrows[index] != null) {
  41487. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  41488. var r = point.r + point.offset;
  41489. symbol.attr({
  41490. rotation: point.rotate,
  41491. x: pt1[0] + r * Math.cos(opt.rotation),
  41492. y: pt1[1] - r * Math.sin(opt.rotation),
  41493. silent: true,
  41494. z2: 11
  41495. });
  41496. group.add(symbol);
  41497. }
  41498. });
  41499. }
  41500. },
  41501. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  41502. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  41503. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  41504. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  41505. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  41506. // See https://github.com/apache/echarts/issues/14266 for more.
  41507. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  41508. var labelList = prepareLayoutList(map(labelEls, function (label) {
  41509. return {
  41510. label: label,
  41511. priority: label.z2,
  41512. defaultAttr: {
  41513. ignore: label.ignore
  41514. }
  41515. };
  41516. }));
  41517. hideOverlap(labelList);
  41518. }
  41519. },
  41520. axisName: function (opt, axisModel, group, transformGroup) {
  41521. var name = retrieve(opt.axisName, axisModel.get('name'));
  41522. if (!name) {
  41523. return;
  41524. }
  41525. var nameLocation = axisModel.get('nameLocation');
  41526. var nameDirection = opt.nameDirection;
  41527. var textStyleModel = axisModel.getModel('nameTextStyle');
  41528. var gap = axisModel.get('nameGap') || 0;
  41529. var extent = axisModel.axis.getExtent();
  41530. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  41531. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  41532. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  41533. var labelLayout;
  41534. var nameRotation = axisModel.get('nameRotate');
  41535. if (nameRotation != null) {
  41536. nameRotation = nameRotation * PI$5 / 180; // To radian.
  41537. }
  41538. var axisNameAvailableWidth;
  41539. if (isNameLocationCenter(nameLocation)) {
  41540. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  41541. nameDirection);
  41542. } else {
  41543. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  41544. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  41545. if (axisNameAvailableWidth != null) {
  41546. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  41547. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  41548. }
  41549. }
  41550. var textFont = textStyleModel.getFont();
  41551. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  41552. var ellipsis = truncateOpt.ellipsis;
  41553. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  41554. var textEl = new ZRText({
  41555. x: pos[0],
  41556. y: pos[1],
  41557. rotation: labelLayout.rotation,
  41558. silent: AxisBuilder.isLabelSilent(axisModel),
  41559. style: createTextStyle(textStyleModel, {
  41560. text: name,
  41561. font: textFont,
  41562. overflow: 'truncate',
  41563. width: maxWidth,
  41564. ellipsis: ellipsis,
  41565. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  41566. align: textStyleModel.get('align') || labelLayout.textAlign,
  41567. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  41568. }),
  41569. z2: 1
  41570. });
  41571. setTooltipConfig({
  41572. el: textEl,
  41573. componentModel: axisModel,
  41574. itemName: name
  41575. });
  41576. textEl.__fullText = name; // Id for animation
  41577. textEl.anid = 'name';
  41578. if (axisModel.get('triggerEvent')) {
  41579. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  41580. eventData.targetType = 'axisName';
  41581. eventData.name = name;
  41582. getECData(textEl).eventData = eventData;
  41583. } // FIXME
  41584. transformGroup.add(textEl);
  41585. textEl.updateTransform();
  41586. group.add(textEl);
  41587. textEl.decomposeTransform();
  41588. }
  41589. };
  41590. function endTextLayout(rotation, textPosition, textRotate, extent) {
  41591. var rotationDiff = remRadian(textRotate - rotation);
  41592. var textAlign;
  41593. var textVerticalAlign;
  41594. var inverse = extent[0] > extent[1];
  41595. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  41596. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  41597. textVerticalAlign = onLeft ? 'bottom' : 'top';
  41598. textAlign = 'center';
  41599. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  41600. textVerticalAlign = onLeft ? 'top' : 'bottom';
  41601. textAlign = 'center';
  41602. } else {
  41603. textVerticalAlign = 'middle';
  41604. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  41605. textAlign = onLeft ? 'left' : 'right';
  41606. } else {
  41607. textAlign = onLeft ? 'right' : 'left';
  41608. }
  41609. }
  41610. return {
  41611. rotation: rotationDiff,
  41612. textAlign: textAlign,
  41613. textVerticalAlign: textVerticalAlign
  41614. };
  41615. }
  41616. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  41617. if (shouldShowAllLabels(axisModel.axis)) {
  41618. return;
  41619. } // If min or max are user set, we need to check
  41620. // If the tick on min(max) are overlap on their neighbour tick
  41621. // If they are overlapped, we need to hide the min(max) tick label
  41622. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  41623. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  41624. // Have not consider onBand yet, where tick els is more than label els.
  41625. labelEls = labelEls || [];
  41626. tickEls = tickEls || [];
  41627. var firstLabel = labelEls[0];
  41628. var nextLabel = labelEls[1];
  41629. var lastLabel = labelEls[labelEls.length - 1];
  41630. var prevLabel = labelEls[labelEls.length - 2];
  41631. var firstTick = tickEls[0];
  41632. var nextTick = tickEls[1];
  41633. var lastTick = tickEls[tickEls.length - 1];
  41634. var prevTick = tickEls[tickEls.length - 2];
  41635. if (showMinLabel === false) {
  41636. ignoreEl(firstLabel);
  41637. ignoreEl(firstTick);
  41638. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  41639. if (showMinLabel) {
  41640. ignoreEl(nextLabel);
  41641. ignoreEl(nextTick);
  41642. } else {
  41643. ignoreEl(firstLabel);
  41644. ignoreEl(firstTick);
  41645. }
  41646. }
  41647. if (showMaxLabel === false) {
  41648. ignoreEl(lastLabel);
  41649. ignoreEl(lastTick);
  41650. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  41651. if (showMaxLabel) {
  41652. ignoreEl(prevLabel);
  41653. ignoreEl(prevTick);
  41654. } else {
  41655. ignoreEl(lastLabel);
  41656. ignoreEl(lastTick);
  41657. }
  41658. }
  41659. }
  41660. function ignoreEl(el) {
  41661. el && (el.ignore = true);
  41662. }
  41663. function isTwoLabelOverlapped(current, next) {
  41664. // current and next has the same rotation.
  41665. var firstRect = current && current.getBoundingRect().clone();
  41666. var nextRect = next && next.getBoundingRect().clone();
  41667. if (!firstRect || !nextRect) {
  41668. return;
  41669. } // When checking intersect of two rotated labels, we use mRotationBack
  41670. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  41671. var mRotationBack = identity([]);
  41672. rotate(mRotationBack, mRotationBack, -current.rotation);
  41673. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  41674. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  41675. return firstRect.intersect(nextRect);
  41676. }
  41677. function isNameLocationCenter(nameLocation) {
  41678. return nameLocation === 'middle' || nameLocation === 'center';
  41679. }
  41680. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  41681. var tickEls = [];
  41682. var pt1 = [];
  41683. var pt2 = [];
  41684. for (var i = 0; i < ticksCoords.length; i++) {
  41685. var tickCoord = ticksCoords[i].coord;
  41686. pt1[0] = tickCoord;
  41687. pt1[1] = 0;
  41688. pt2[0] = tickCoord;
  41689. pt2[1] = tickEndCoord;
  41690. if (tickTransform) {
  41691. applyTransform(pt1, pt1, tickTransform);
  41692. applyTransform(pt2, pt2, tickTransform);
  41693. } // Tick line, Not use group transform to have better line draw
  41694. var tickEl = new Line({
  41695. subPixelOptimize: true,
  41696. shape: {
  41697. x1: pt1[0],
  41698. y1: pt1[1],
  41699. x2: pt2[0],
  41700. y2: pt2[1]
  41701. },
  41702. style: tickLineStyle,
  41703. z2: 2,
  41704. autoBatch: true,
  41705. silent: true
  41706. });
  41707. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  41708. tickEls.push(tickEl);
  41709. }
  41710. return tickEls;
  41711. }
  41712. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  41713. var axis = axisModel.axis;
  41714. var tickModel = axisModel.getModel('axisTick');
  41715. var shown = tickModel.get('show');
  41716. if (shown === 'auto' && opt.handleAutoShown) {
  41717. shown = opt.handleAutoShown('axisTick');
  41718. }
  41719. if (!shown || axis.scale.isBlank()) {
  41720. return;
  41721. }
  41722. var lineStyleModel = tickModel.getModel('lineStyle');
  41723. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  41724. var ticksCoords = axis.getTicksCoords();
  41725. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  41726. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  41727. }), 'ticks');
  41728. for (var i = 0; i < ticksEls.length; i++) {
  41729. group.add(ticksEls[i]);
  41730. }
  41731. return ticksEls;
  41732. }
  41733. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  41734. var axis = axisModel.axis;
  41735. var minorTickModel = axisModel.getModel('minorTick');
  41736. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  41737. return;
  41738. }
  41739. var minorTicksCoords = axis.getMinorTicksCoords();
  41740. if (!minorTicksCoords.length) {
  41741. return;
  41742. }
  41743. var lineStyleModel = minorTickModel.getModel('lineStyle');
  41744. var tickEndCoord = tickDirection * minorTickModel.get('length');
  41745. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  41746. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  41747. }));
  41748. for (var i = 0; i < minorTicksCoords.length; i++) {
  41749. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  41750. for (var k = 0; k < minorTicksEls.length; k++) {
  41751. group.add(minorTicksEls[k]);
  41752. }
  41753. }
  41754. }
  41755. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  41756. var axis = axisModel.axis;
  41757. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  41758. if (!show || axis.scale.isBlank()) {
  41759. return;
  41760. }
  41761. var labelModel = axisModel.getModel('axisLabel');
  41762. var labelMargin = labelModel.get('margin');
  41763. var labels = axis.getViewLabels(); // Special label rotate.
  41764. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  41765. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  41766. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  41767. var labelEls = [];
  41768. var silent = AxisBuilder.isLabelSilent(axisModel);
  41769. var triggerEvent = axisModel.get('triggerEvent');
  41770. each(labels, function (labelItem, index) {
  41771. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  41772. var formattedLabel = labelItem.formattedLabel;
  41773. var rawLabel = labelItem.rawLabel;
  41774. var itemLabelModel = labelModel;
  41775. if (rawCategoryData && rawCategoryData[tickValue]) {
  41776. var rawCategoryItem = rawCategoryData[tickValue];
  41777. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  41778. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  41779. }
  41780. }
  41781. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  41782. var tickCoord = axis.dataToCoord(tickValue);
  41783. var textEl = new ZRText({
  41784. x: tickCoord,
  41785. y: opt.labelOffset + opt.labelDirection * labelMargin,
  41786. rotation: labelLayout.rotation,
  41787. silent: silent,
  41788. z2: 10 + (labelItem.level || 0),
  41789. style: createTextStyle(itemLabelModel, {
  41790. text: formattedLabel,
  41791. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  41792. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  41793. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  41794. // index of axis.data. So tick should not be exposed to user
  41795. // in category axis.
  41796. // (2) Compatible with previous version, which always use formatted label as
  41797. // input. But in interval scale the formatted label is like '223,445', which
  41798. // maked user repalce ','. So we modify it to return original val but remain
  41799. // it as 'string' to avoid error in replacing.
  41800. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  41801. })
  41802. });
  41803. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  41804. if (triggerEvent) {
  41805. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  41806. eventData.targetType = 'axisLabel';
  41807. eventData.value = rawLabel;
  41808. eventData.tickIndex = index;
  41809. if (axis.type === 'category') {
  41810. eventData.dataIndex = tickValue;
  41811. }
  41812. getECData(textEl).eventData = eventData;
  41813. } // FIXME
  41814. transformGroup.add(textEl);
  41815. textEl.updateTransform();
  41816. labelEls.push(textEl);
  41817. group.add(textEl);
  41818. textEl.decomposeTransform();
  41819. });
  41820. return labelEls;
  41821. }
  41822. // allAxesInfo should be updated when setOption performed.
  41823. function collect(ecModel, api) {
  41824. var result = {
  41825. /**
  41826. * key: makeKey(axis.model)
  41827. * value: {
  41828. * axis,
  41829. * coordSys,
  41830. * axisPointerModel,
  41831. * triggerTooltip,
  41832. * involveSeries,
  41833. * snap,
  41834. * seriesModels,
  41835. * seriesDataCount
  41836. * }
  41837. */
  41838. axesInfo: {},
  41839. seriesInvolved: false,
  41840. /**
  41841. * key: makeKey(coordSys.model)
  41842. * value: Object: key makeKey(axis.model), value: axisInfo
  41843. */
  41844. coordSysAxesInfo: {},
  41845. coordSysMap: {}
  41846. };
  41847. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  41848. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  41849. return result;
  41850. }
  41851. function collectAxesInfo(result, ecModel, api) {
  41852. var globalTooltipModel = ecModel.getComponent('tooltip');
  41853. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  41854. var linksOption = globalAxisPointerModel.get('link', true) || [];
  41855. var linkGroups = []; // Collect axes info.
  41856. each(api.getCoordinateSystems(), function (coordSys) {
  41857. // Some coordinate system do not support axes, like geo.
  41858. if (!coordSys.axisPointerEnabled) {
  41859. return;
  41860. }
  41861. var coordSysKey = makeKey(coordSys.model);
  41862. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  41863. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  41864. // for user. So we enable seting tooltip on coordSys model.
  41865. var coordSysModel = coordSys.model;
  41866. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  41867. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  41868. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  41869. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  41870. // show but axisPointer will show as normal.
  41871. && baseTooltipModel.get('show')) {
  41872. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  41873. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  41874. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  41875. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  41876. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  41877. if (triggerAxis || cross) {
  41878. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  41879. }
  41880. if (cross) {
  41881. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  41882. }
  41883. } // fromTooltip: true | false | 'cross'
  41884. // triggerTooltip: true | false | null
  41885. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  41886. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  41887. var axisPointerShow = axisPointerModel.get('show');
  41888. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  41889. return;
  41890. }
  41891. if (triggerTooltip == null) {
  41892. triggerTooltip = axisPointerModel.get('triggerTooltip');
  41893. }
  41894. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  41895. var snap = axisPointerModel.get('snap');
  41896. var axisKey = makeKey(axis.model);
  41897. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  41898. var axisInfo = result.axesInfo[axisKey] = {
  41899. key: axisKey,
  41900. axis: axis,
  41901. coordSys: coordSys,
  41902. axisPointerModel: axisPointerModel,
  41903. triggerTooltip: triggerTooltip,
  41904. involveSeries: involveSeries,
  41905. snap: snap,
  41906. useHandle: isHandleTrigger(axisPointerModel),
  41907. seriesModels: [],
  41908. linkGroup: null
  41909. };
  41910. axesInfoInCoordSys[axisKey] = axisInfo;
  41911. result.seriesInvolved = result.seriesInvolved || involveSeries;
  41912. var groupIndex = getLinkGroupIndex(linksOption, axis);
  41913. if (groupIndex != null) {
  41914. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  41915. axesInfo: {}
  41916. });
  41917. linkGroup.axesInfo[axisKey] = axisInfo;
  41918. linkGroup.mapper = linksOption[groupIndex].mapper;
  41919. axisInfo.linkGroup = linkGroup;
  41920. }
  41921. }
  41922. });
  41923. }
  41924. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  41925. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  41926. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  41927. var volatileOption = {};
  41928. each(fields, function (field) {
  41929. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  41930. }); // category axis do not auto snap, otherwise some tick that do not
  41931. // has value can not be hovered. value/time/log axis default snap if
  41932. // triggered from tooltip and trigger tooltip.
  41933. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  41934. // Only these properties can be overrided from tooltip to axisPointer.
  41935. if (tooltipAxisPointerModel.get('type') === 'cross') {
  41936. volatileOption.type = 'line';
  41937. }
  41938. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  41939. labelOption.show == null && (labelOption.show = false);
  41940. if (fromTooltip === 'cross') {
  41941. // When 'cross', both axes show labels.
  41942. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  41943. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  41944. // (cross style is dashed by default)
  41945. if (!triggerTooltip) {
  41946. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  41947. crossStyle && defaults(labelOption, crossStyle.textStyle);
  41948. }
  41949. }
  41950. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  41951. }
  41952. function collectSeriesInfo(result, ecModel) {
  41953. // Prepare data for axis trigger
  41954. ecModel.eachSeries(function (seriesModel) {
  41955. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  41956. var coordSys = seriesModel.coordinateSystem;
  41957. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  41958. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  41959. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  41960. return;
  41961. }
  41962. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  41963. var axis = axisInfo.axis;
  41964. if (coordSys.getAxis(axis.dim) === axis) {
  41965. axisInfo.seriesModels.push(seriesModel);
  41966. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  41967. axisInfo.seriesDataCount += seriesModel.getData().count();
  41968. }
  41969. });
  41970. });
  41971. }
  41972. /**
  41973. * For example:
  41974. * {
  41975. * axisPointer: {
  41976. * links: [{
  41977. * xAxisIndex: [2, 4],
  41978. * yAxisIndex: 'all'
  41979. * }, {
  41980. * xAxisId: ['a5', 'a7'],
  41981. * xAxisName: 'xxx'
  41982. * }]
  41983. * }
  41984. * }
  41985. */
  41986. function getLinkGroupIndex(linksOption, axis) {
  41987. var axisModel = axis.model;
  41988. var dim = axis.dim;
  41989. for (var i = 0; i < linksOption.length; i++) {
  41990. var linkOption = linksOption[i] || {};
  41991. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  41992. return i;
  41993. }
  41994. }
  41995. }
  41996. function checkPropInLink(linkPropValue, axisPropValue) {
  41997. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  41998. }
  41999. function fixValue(axisModel) {
  42000. var axisInfo = getAxisInfo(axisModel);
  42001. if (!axisInfo) {
  42002. return;
  42003. }
  42004. var axisPointerModel = axisInfo.axisPointerModel;
  42005. var scale = axisInfo.axis.scale;
  42006. var option = axisPointerModel.option;
  42007. var status = axisPointerModel.get('status');
  42008. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  42009. if (value != null) {
  42010. value = scale.parse(value);
  42011. }
  42012. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  42013. // and status should be initialized.
  42014. if (status == null) {
  42015. option.status = useHandle ? 'show' : 'hide';
  42016. }
  42017. var extent = scale.getExtent().slice();
  42018. extent[0] > extent[1] && extent.reverse();
  42019. if ( // Pick a value on axis when initializing.
  42020. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  42021. // where we should re-pick a value to keep `handle` displaying normally.
  42022. || value > extent[1]) {
  42023. // Make handle displayed on the end of the axis when init, which looks better.
  42024. value = extent[1];
  42025. }
  42026. if (value < extent[0]) {
  42027. value = extent[0];
  42028. }
  42029. option.value = value;
  42030. if (useHandle) {
  42031. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  42032. }
  42033. }
  42034. function getAxisInfo(axisModel) {
  42035. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  42036. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  42037. }
  42038. function getAxisPointerModel(axisModel) {
  42039. var axisInfo = getAxisInfo(axisModel);
  42040. return axisInfo && axisInfo.axisPointerModel;
  42041. }
  42042. function isHandleTrigger(axisPointerModel) {
  42043. return !!axisPointerModel.get(['handle', 'show']);
  42044. }
  42045. /**
  42046. * @param {module:echarts/model/Model} model
  42047. * @return {string} unique key
  42048. */
  42049. function makeKey(model) {
  42050. return model.type + '||' + model.id;
  42051. }
  42052. var axisPointerClazz = {};
  42053. /**
  42054. * Base class of AxisView.
  42055. */
  42056. var AxisView =
  42057. /** @class */
  42058. function (_super) {
  42059. __extends(AxisView, _super);
  42060. function AxisView() {
  42061. var _this = _super !== null && _super.apply(this, arguments) || this;
  42062. _this.type = AxisView.type;
  42063. return _this;
  42064. }
  42065. /**
  42066. * @override
  42067. */
  42068. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  42069. // FIXME
  42070. // This process should proformed after coordinate systems updated
  42071. // (axis scale updated), and should be performed each time update.
  42072. // So put it here temporarily, although it is not appropriate to
  42073. // put a model-writing procedure in `view`.
  42074. this.axisPointerClass && fixValue(axisModel);
  42075. _super.prototype.render.apply(this, arguments);
  42076. this._doUpdateAxisPointerClass(axisModel, api, true);
  42077. };
  42078. /**
  42079. * Action handler.
  42080. */
  42081. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  42082. this._doUpdateAxisPointerClass(axisModel, api, false);
  42083. };
  42084. /**
  42085. * @override
  42086. */
  42087. AxisView.prototype.remove = function (ecModel, api) {
  42088. var axisPointer = this._axisPointer;
  42089. axisPointer && axisPointer.remove(api);
  42090. };
  42091. /**
  42092. * @override
  42093. */
  42094. AxisView.prototype.dispose = function (ecModel, api) {
  42095. this._disposeAxisPointer(api);
  42096. _super.prototype.dispose.apply(this, arguments);
  42097. };
  42098. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  42099. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  42100. if (!Clazz) {
  42101. return;
  42102. }
  42103. var axisPointerModel = getAxisPointerModel(axisModel);
  42104. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  42105. };
  42106. AxisView.prototype._disposeAxisPointer = function (api) {
  42107. this._axisPointer && this._axisPointer.dispose(api);
  42108. this._axisPointer = null;
  42109. };
  42110. AxisView.registerAxisPointerClass = function (type, clazz) {
  42111. if ("development" !== 'production') {
  42112. if (axisPointerClazz[type]) {
  42113. throw new Error('axisPointer ' + type + ' exists');
  42114. }
  42115. }
  42116. axisPointerClazz[type] = clazz;
  42117. };
  42118. AxisView.getAxisPointerClass = function (type) {
  42119. return type && axisPointerClazz[type];
  42120. };
  42121. AxisView.type = 'axis';
  42122. return AxisView;
  42123. }(ComponentView);
  42124. var inner$6 = makeInner();
  42125. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  42126. var axis = axisModel.axis;
  42127. if (axis.scale.isBlank()) {
  42128. return;
  42129. } // TODO: TYPE
  42130. var splitAreaModel = axisModel.getModel('splitArea');
  42131. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  42132. var areaColors = areaStyleModel.get('color');
  42133. var gridRect = gridModel.coordinateSystem.getRect();
  42134. var ticksCoords = axis.getTicksCoords({
  42135. tickModel: splitAreaModel,
  42136. clamp: true
  42137. });
  42138. if (!ticksCoords.length) {
  42139. return;
  42140. } // For Making appropriate splitArea animation, the color and anid
  42141. // should be corresponding to previous one if possible.
  42142. var areaColorsLen = areaColors.length;
  42143. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  42144. var newSplitAreaColors = createHashMap();
  42145. var colorIndex = 0;
  42146. if (lastSplitAreaColors) {
  42147. for (var i = 0; i < ticksCoords.length; i++) {
  42148. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  42149. if (cIndex != null) {
  42150. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  42151. break;
  42152. }
  42153. }
  42154. }
  42155. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  42156. var areaStyle = areaStyleModel.getAreaStyle();
  42157. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  42158. for (var i = 1; i < ticksCoords.length; i++) {
  42159. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  42160. var x = void 0;
  42161. var y = void 0;
  42162. var width = void 0;
  42163. var height = void 0;
  42164. if (axis.isHorizontal()) {
  42165. x = prev;
  42166. y = gridRect.y;
  42167. width = tickCoord - x;
  42168. height = gridRect.height;
  42169. prev = x + width;
  42170. } else {
  42171. x = gridRect.x;
  42172. y = prev;
  42173. width = gridRect.width;
  42174. height = tickCoord - y;
  42175. prev = y + height;
  42176. }
  42177. var tickValue = ticksCoords[i - 1].tickValue;
  42178. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  42179. axisGroup.add(new Rect({
  42180. anid: tickValue != null ? 'area_' + tickValue : null,
  42181. shape: {
  42182. x: x,
  42183. y: y,
  42184. width: width,
  42185. height: height
  42186. },
  42187. style: defaults({
  42188. fill: areaColors[colorIndex]
  42189. }, areaStyle),
  42190. autoBatch: true,
  42191. silent: true
  42192. }));
  42193. colorIndex = (colorIndex + 1) % areaColorsLen;
  42194. }
  42195. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  42196. }
  42197. function rectCoordAxisHandleRemove(axisView) {
  42198. inner$6(axisView).splitAreaColors = null;
  42199. }
  42200. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  42201. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  42202. var CartesianAxisView =
  42203. /** @class */
  42204. function (_super) {
  42205. __extends(CartesianAxisView, _super);
  42206. function CartesianAxisView() {
  42207. var _this = _super !== null && _super.apply(this, arguments) || this;
  42208. _this.type = CartesianAxisView.type;
  42209. _this.axisPointerClass = 'CartesianAxisPointer';
  42210. return _this;
  42211. }
  42212. /**
  42213. * @override
  42214. */
  42215. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  42216. this.group.removeAll();
  42217. var oldAxisGroup = this._axisGroup;
  42218. this._axisGroup = new Group();
  42219. this.group.add(this._axisGroup);
  42220. if (!axisModel.get('show')) {
  42221. return;
  42222. }
  42223. var gridModel = axisModel.getCoordSysModel();
  42224. var layout = layout$1(gridModel, axisModel);
  42225. var axisBuilder = new AxisBuilder(axisModel, extend({
  42226. handleAutoShown: function (elementType) {
  42227. var cartesians = gridModel.coordinateSystem.getCartesians();
  42228. for (var i = 0; i < cartesians.length; i++) {
  42229. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  42230. // Still show axis tick or axisLine if other axis is value / log
  42231. return true;
  42232. }
  42233. } // Not show axisTick or axisLine if other axis is category / time
  42234. return false;
  42235. }
  42236. }, layout));
  42237. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  42238. this._axisGroup.add(axisBuilder.getGroup());
  42239. each(selfBuilderAttrs, function (name) {
  42240. if (axisModel.get([name, 'show'])) {
  42241. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  42242. }
  42243. }, this); // THIS is a special case for bar racing chart.
  42244. // Update the axis label from the natural initial layout to
  42245. // sorted layout should has no animation.
  42246. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  42247. if (!isInitialSortFromBarRacing) {
  42248. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  42249. }
  42250. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  42251. };
  42252. CartesianAxisView.prototype.remove = function () {
  42253. rectCoordAxisHandleRemove(this);
  42254. };
  42255. CartesianAxisView.type = 'cartesianAxis';
  42256. return CartesianAxisView;
  42257. }(AxisView);
  42258. var axisElementBuilders = {
  42259. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  42260. var axis = axisModel.axis;
  42261. if (axis.scale.isBlank()) {
  42262. return;
  42263. }
  42264. var splitLineModel = axisModel.getModel('splitLine');
  42265. var lineStyleModel = splitLineModel.getModel('lineStyle');
  42266. var lineColors = lineStyleModel.get('color');
  42267. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  42268. var gridRect = gridModel.coordinateSystem.getRect();
  42269. var isHorizontal = axis.isHorizontal();
  42270. var lineCount = 0;
  42271. var ticksCoords = axis.getTicksCoords({
  42272. tickModel: splitLineModel
  42273. });
  42274. var p1 = [];
  42275. var p2 = [];
  42276. var lineStyle = lineStyleModel.getLineStyle();
  42277. for (var i = 0; i < ticksCoords.length; i++) {
  42278. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  42279. if (isHorizontal) {
  42280. p1[0] = tickCoord;
  42281. p1[1] = gridRect.y;
  42282. p2[0] = tickCoord;
  42283. p2[1] = gridRect.y + gridRect.height;
  42284. } else {
  42285. p1[0] = gridRect.x;
  42286. p1[1] = tickCoord;
  42287. p2[0] = gridRect.x + gridRect.width;
  42288. p2[1] = tickCoord;
  42289. }
  42290. var colorIndex = lineCount++ % lineColors.length;
  42291. var tickValue = ticksCoords[i].tickValue;
  42292. axisGroup.add(new Line({
  42293. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  42294. subPixelOptimize: true,
  42295. autoBatch: true,
  42296. shape: {
  42297. x1: p1[0],
  42298. y1: p1[1],
  42299. x2: p2[0],
  42300. y2: p2[1]
  42301. },
  42302. style: defaults({
  42303. stroke: lineColors[colorIndex]
  42304. }, lineStyle),
  42305. silent: true
  42306. }));
  42307. }
  42308. },
  42309. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  42310. var axis = axisModel.axis;
  42311. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  42312. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  42313. var gridRect = gridModel.coordinateSystem.getRect();
  42314. var isHorizontal = axis.isHorizontal();
  42315. var minorTicksCoords = axis.getMinorTicksCoords();
  42316. if (!minorTicksCoords.length) {
  42317. return;
  42318. }
  42319. var p1 = [];
  42320. var p2 = [];
  42321. var lineStyle = lineStyleModel.getLineStyle();
  42322. for (var i = 0; i < minorTicksCoords.length; i++) {
  42323. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  42324. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  42325. if (isHorizontal) {
  42326. p1[0] = tickCoord;
  42327. p1[1] = gridRect.y;
  42328. p2[0] = tickCoord;
  42329. p2[1] = gridRect.y + gridRect.height;
  42330. } else {
  42331. p1[0] = gridRect.x;
  42332. p1[1] = tickCoord;
  42333. p2[0] = gridRect.x + gridRect.width;
  42334. p2[1] = tickCoord;
  42335. }
  42336. axisGroup.add(new Line({
  42337. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  42338. subPixelOptimize: true,
  42339. autoBatch: true,
  42340. shape: {
  42341. x1: p1[0],
  42342. y1: p1[1],
  42343. x2: p2[0],
  42344. y2: p2[1]
  42345. },
  42346. style: lineStyle,
  42347. silent: true
  42348. }));
  42349. }
  42350. }
  42351. },
  42352. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  42353. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  42354. }
  42355. };
  42356. var CartesianXAxisView =
  42357. /** @class */
  42358. function (_super) {
  42359. __extends(CartesianXAxisView, _super);
  42360. function CartesianXAxisView() {
  42361. var _this = _super !== null && _super.apply(this, arguments) || this;
  42362. _this.type = CartesianXAxisView.type;
  42363. return _this;
  42364. }
  42365. CartesianXAxisView.type = 'xAxis';
  42366. return CartesianXAxisView;
  42367. }(CartesianAxisView);
  42368. var CartesianYAxisView =
  42369. /** @class */
  42370. function (_super) {
  42371. __extends(CartesianYAxisView, _super);
  42372. function CartesianYAxisView() {
  42373. var _this = _super !== null && _super.apply(this, arguments) || this;
  42374. _this.type = CartesianXAxisView.type;
  42375. return _this;
  42376. }
  42377. CartesianYAxisView.type = 'yAxis';
  42378. return CartesianYAxisView;
  42379. }(CartesianAxisView);
  42380. var GridView =
  42381. /** @class */
  42382. function (_super) {
  42383. __extends(GridView, _super);
  42384. function GridView() {
  42385. var _this = _super !== null && _super.apply(this, arguments) || this;
  42386. _this.type = 'grid';
  42387. return _this;
  42388. }
  42389. GridView.prototype.render = function (gridModel, ecModel) {
  42390. this.group.removeAll();
  42391. if (gridModel.get('show')) {
  42392. this.group.add(new Rect({
  42393. shape: gridModel.coordinateSystem.getRect(),
  42394. style: defaults({
  42395. fill: gridModel.get('backgroundColor')
  42396. }, gridModel.getItemStyle()),
  42397. silent: true,
  42398. z2: -1
  42399. }));
  42400. }
  42401. };
  42402. GridView.type = 'grid';
  42403. return GridView;
  42404. }(ComponentView);
  42405. var extraOption = {
  42406. // gridIndex: 0,
  42407. // gridId: '',
  42408. offset: 0
  42409. };
  42410. function install$5(registers) {
  42411. registers.registerComponentView(GridView);
  42412. registers.registerComponentModel(GridModel);
  42413. registers.registerCoordinateSystem('cartesian2d', Grid);
  42414. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  42415. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  42416. registers.registerComponentView(CartesianXAxisView);
  42417. registers.registerComponentView(CartesianYAxisView);
  42418. registers.registerPreprocessor(function (option) {
  42419. // Only create grid when need
  42420. if (option.xAxis && option.yAxis && !option.grid) {
  42421. option.grid = {};
  42422. }
  42423. });
  42424. }
  42425. function install$6(registers) {
  42426. // In case developer forget to include grid component
  42427. use(install$5);
  42428. registers.registerSeriesModel(ScatterSeriesModel);
  42429. registers.registerChartView(ScatterView);
  42430. registers.registerLayout(pointsLayout('scatter'));
  42431. }
  42432. var inner$7 = makeInner();
  42433. var clone$3 = clone;
  42434. var bind$1 = bind;
  42435. /**
  42436. * Base axis pointer class in 2D.
  42437. */
  42438. var BaseAxisPointer =
  42439. /** @class */
  42440. function () {
  42441. function BaseAxisPointer() {
  42442. this._dragging = false;
  42443. /**
  42444. * In px, arbitrary value. Do not set too small,
  42445. * no animation is ok for most cases.
  42446. */
  42447. this.animationThreshold = 15;
  42448. }
  42449. /**
  42450. * @implement
  42451. */
  42452. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  42453. var value = axisPointerModel.get('value');
  42454. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  42455. // be replaced when user calling setOption in not merge mode.
  42456. this._axisModel = axisModel;
  42457. this._axisPointerModel = axisPointerModel;
  42458. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  42459. // So it is power consuming if performing `render` each time,
  42460. // especially on mobile device.
  42461. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  42462. return;
  42463. }
  42464. this._lastValue = value;
  42465. this._lastStatus = status;
  42466. var group = this._group;
  42467. var handle = this._handle;
  42468. if (!status || status === 'hide') {
  42469. // Do not clear here, for animation better.
  42470. group && group.hide();
  42471. handle && handle.hide();
  42472. return;
  42473. }
  42474. group && group.show();
  42475. handle && handle.show(); // Otherwise status is 'show'
  42476. var elOption = {};
  42477. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  42478. var graphicKey = elOption.graphicKey;
  42479. if (graphicKey !== this._lastGraphicKey) {
  42480. this.clear(api);
  42481. }
  42482. this._lastGraphicKey = graphicKey;
  42483. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  42484. if (!group) {
  42485. group = this._group = new Group();
  42486. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  42487. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  42488. api.getZr().add(group);
  42489. } else {
  42490. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  42491. this.updatePointerEl(group, elOption, doUpdateProps);
  42492. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  42493. }
  42494. updateMandatoryProps(group, axisPointerModel, true);
  42495. this._renderHandle(value);
  42496. };
  42497. /**
  42498. * @implement
  42499. */
  42500. BaseAxisPointer.prototype.remove = function (api) {
  42501. this.clear(api);
  42502. };
  42503. /**
  42504. * @implement
  42505. */
  42506. BaseAxisPointer.prototype.dispose = function (api) {
  42507. this.clear(api);
  42508. };
  42509. /**
  42510. * @protected
  42511. */
  42512. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  42513. var animation = axisPointerModel.get('animation');
  42514. var axis = axisModel.axis;
  42515. var isCategoryAxis = axis.type === 'category';
  42516. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  42517. if (!useSnap && !isCategoryAxis) {
  42518. return false;
  42519. }
  42520. if (animation === 'auto' || animation == null) {
  42521. var animationThreshold = this.animationThreshold;
  42522. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  42523. return true;
  42524. } // It is important to auto animation when snap used. Consider if there is
  42525. // a dataZoom, animation will be disabled when too many points exist, while
  42526. // it will be enabled for better visual effect when little points exist.
  42527. if (useSnap) {
  42528. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  42529. var axisExtent = axis.getExtent(); // Approximate band width
  42530. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  42531. }
  42532. return false;
  42533. }
  42534. return animation === true;
  42535. };
  42536. /**
  42537. * add {pointer, label, graphicKey} to elOption
  42538. * @protected
  42539. */
  42540. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  42541. };
  42542. /**
  42543. * @protected
  42544. */
  42545. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  42546. var pointerOption = elOption.pointer;
  42547. if (pointerOption) {
  42548. var pointerEl = inner$7(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  42549. group.add(pointerEl);
  42550. }
  42551. };
  42552. /**
  42553. * @protected
  42554. */
  42555. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  42556. if (elOption.label) {
  42557. var labelEl = inner$7(group).labelEl = new ZRText(clone$3(elOption.label));
  42558. group.add(labelEl);
  42559. updateLabelShowHide(labelEl, axisPointerModel);
  42560. }
  42561. };
  42562. /**
  42563. * @protected
  42564. */
  42565. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  42566. var pointerEl = inner$7(group).pointerEl;
  42567. if (pointerEl && elOption.pointer) {
  42568. pointerEl.setStyle(elOption.pointer.style);
  42569. updateProps(pointerEl, {
  42570. shape: elOption.pointer.shape
  42571. });
  42572. }
  42573. };
  42574. /**
  42575. * @protected
  42576. */
  42577. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  42578. var labelEl = inner$7(group).labelEl;
  42579. if (labelEl) {
  42580. labelEl.setStyle(elOption.label.style);
  42581. updateProps(labelEl, {
  42582. // Consider text length change in vertical axis, animation should
  42583. // be used on shape, otherwise the effect will be weird.
  42584. // TODOTODO
  42585. // shape: elOption.label.shape,
  42586. x: elOption.label.x,
  42587. y: elOption.label.y
  42588. });
  42589. updateLabelShowHide(labelEl, axisPointerModel);
  42590. }
  42591. };
  42592. /**
  42593. * @private
  42594. */
  42595. BaseAxisPointer.prototype._renderHandle = function (value) {
  42596. if (this._dragging || !this.updateHandleTransform) {
  42597. return;
  42598. }
  42599. var axisPointerModel = this._axisPointerModel;
  42600. var zr = this._api.getZr();
  42601. var handle = this._handle;
  42602. var handleModel = axisPointerModel.getModel('handle');
  42603. var status = axisPointerModel.get('status');
  42604. if (!handleModel.get('show') || !status || status === 'hide') {
  42605. handle && zr.remove(handle);
  42606. this._handle = null;
  42607. return;
  42608. }
  42609. var isInit;
  42610. if (!this._handle) {
  42611. isInit = true;
  42612. handle = this._handle = createIcon(handleModel.get('icon'), {
  42613. cursor: 'move',
  42614. draggable: true,
  42615. onmousemove: function (e) {
  42616. // Fot mobile devicem, prevent screen slider on the button.
  42617. stop(e.event);
  42618. },
  42619. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  42620. drift: bind$1(this._onHandleDragMove, this),
  42621. ondragend: bind$1(this._onHandleDragEnd, this)
  42622. });
  42623. zr.add(handle);
  42624. }
  42625. updateMandatoryProps(handle, axisPointerModel, false); // update style
  42626. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  42627. var handleSize = handleModel.get('size');
  42628. if (!isArray(handleSize)) {
  42629. handleSize = [handleSize, handleSize];
  42630. }
  42631. handle.scaleX = handleSize[0] / 2;
  42632. handle.scaleY = handleSize[1] / 2;
  42633. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  42634. this._moveHandleToValue(value, isInit);
  42635. };
  42636. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  42637. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  42638. };
  42639. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  42640. var handle = this._handle;
  42641. if (!handle) {
  42642. return;
  42643. }
  42644. this._dragging = true; // Persistent for throttle.
  42645. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  42646. this._payloadInfo = trans;
  42647. handle.stopAnimation();
  42648. handle.attr(getHandleTransProps(trans));
  42649. inner$7(handle).lastProp = null;
  42650. this._doDispatchAxisPointer();
  42651. };
  42652. /**
  42653. * Throttled method.
  42654. */
  42655. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  42656. var handle = this._handle;
  42657. if (!handle) {
  42658. return;
  42659. }
  42660. var payloadInfo = this._payloadInfo;
  42661. var axisModel = this._axisModel;
  42662. this._api.dispatchAction({
  42663. type: 'updateAxisPointer',
  42664. x: payloadInfo.cursorPoint[0],
  42665. y: payloadInfo.cursorPoint[1],
  42666. tooltipOption: payloadInfo.tooltipOption,
  42667. axesInfo: [{
  42668. axisDim: axisModel.axis.dim,
  42669. axisIndex: axisModel.componentIndex
  42670. }]
  42671. });
  42672. };
  42673. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  42674. this._dragging = false;
  42675. var handle = this._handle;
  42676. if (!handle) {
  42677. return;
  42678. }
  42679. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  42680. // axisPointer. So move handle to align the exact value position when
  42681. // drag ended.
  42682. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  42683. // button, and will be hidden after finger left handle button.
  42684. this._api.dispatchAction({
  42685. type: 'hideTip'
  42686. });
  42687. };
  42688. /**
  42689. * @private
  42690. */
  42691. BaseAxisPointer.prototype.clear = function (api) {
  42692. this._lastValue = null;
  42693. this._lastStatus = null;
  42694. var zr = api.getZr();
  42695. var group = this._group;
  42696. var handle = this._handle;
  42697. if (zr && group) {
  42698. this._lastGraphicKey = null;
  42699. group && zr.remove(group);
  42700. handle && zr.remove(handle);
  42701. this._group = null;
  42702. this._handle = null;
  42703. this._payloadInfo = null;
  42704. }
  42705. clear(this, '_doDispatchAxisPointer');
  42706. };
  42707. /**
  42708. * @protected
  42709. */
  42710. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  42711. };
  42712. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  42713. xDimIndex = xDimIndex || 0;
  42714. return {
  42715. x: xy[xDimIndex],
  42716. y: xy[1 - xDimIndex],
  42717. width: wh[xDimIndex],
  42718. height: wh[1 - xDimIndex]
  42719. };
  42720. };
  42721. return BaseAxisPointer;
  42722. }();
  42723. function updateProps$1(animationModel, moveAnimation, el, props) {
  42724. // Animation optimize.
  42725. if (!propsEqual(inner$7(el).lastProp, props)) {
  42726. inner$7(el).lastProp = props;
  42727. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  42728. }
  42729. }
  42730. function propsEqual(lastProps, newProps) {
  42731. if (isObject(lastProps) && isObject(newProps)) {
  42732. var equals_1 = true;
  42733. each(newProps, function (item, key) {
  42734. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  42735. });
  42736. return !!equals_1;
  42737. } else {
  42738. return lastProps === newProps;
  42739. }
  42740. }
  42741. function updateLabelShowHide(labelEl, axisPointerModel) {
  42742. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  42743. }
  42744. function getHandleTransProps(trans) {
  42745. return {
  42746. x: trans.x || 0,
  42747. y: trans.y || 0,
  42748. rotation: trans.rotation || 0
  42749. };
  42750. }
  42751. function updateMandatoryProps(group, axisPointerModel, silent) {
  42752. var z = axisPointerModel.get('z');
  42753. var zlevel = axisPointerModel.get('zlevel');
  42754. group && group.traverse(function (el) {
  42755. if (el.type !== 'group') {
  42756. z != null && (el.z = z);
  42757. zlevel != null && (el.zlevel = zlevel);
  42758. el.silent = silent;
  42759. }
  42760. });
  42761. }
  42762. function buildElStyle(axisPointerModel) {
  42763. var axisPointerType = axisPointerModel.get('type');
  42764. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  42765. var style;
  42766. if (axisPointerType === 'line') {
  42767. style = styleModel.getLineStyle();
  42768. style.fill = null;
  42769. } else if (axisPointerType === 'shadow') {
  42770. style = styleModel.getAreaStyle();
  42771. style.stroke = null;
  42772. }
  42773. return style;
  42774. }
  42775. /**
  42776. * @param {Function} labelPos {align, verticalAlign, position}
  42777. */
  42778. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  42779. var value = axisPointerModel.get('value');
  42780. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  42781. precision: axisPointerModel.get(['label', 'precision']),
  42782. formatter: axisPointerModel.get(['label', 'formatter'])
  42783. });
  42784. var labelModel = axisPointerModel.getModel('label');
  42785. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  42786. var font = labelModel.getFont();
  42787. var textRect = getBoundingRect(text, font);
  42788. var position = labelPos.position;
  42789. var width = textRect.width + paddings[1] + paddings[3];
  42790. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  42791. var align = labelPos.align;
  42792. align === 'right' && (position[0] -= width);
  42793. align === 'center' && (position[0] -= width / 2);
  42794. var verticalAlign = labelPos.verticalAlign;
  42795. verticalAlign === 'bottom' && (position[1] -= height);
  42796. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  42797. confineInContainer(position, width, height, api);
  42798. var bgColor = labelModel.get('backgroundColor');
  42799. if (!bgColor || bgColor === 'auto') {
  42800. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  42801. }
  42802. elOption.label = {
  42803. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  42804. x: position[0],
  42805. y: position[1],
  42806. style: createTextStyle(labelModel, {
  42807. text: text,
  42808. font: font,
  42809. fill: labelModel.getTextColor(),
  42810. padding: paddings,
  42811. backgroundColor: bgColor
  42812. }),
  42813. // Lable should be over axisPointer.
  42814. z2: 10
  42815. };
  42816. } // Do not overflow ec container
  42817. function confineInContainer(position, width, height, api) {
  42818. var viewWidth = api.getWidth();
  42819. var viewHeight = api.getHeight();
  42820. position[0] = Math.min(position[0] + width, viewWidth) - width;
  42821. position[1] = Math.min(position[1] + height, viewHeight) - height;
  42822. position[0] = Math.max(position[0], 0);
  42823. position[1] = Math.max(position[1], 0);
  42824. }
  42825. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  42826. value = axis.scale.parse(value);
  42827. var text = axis.scale.getLabel({
  42828. value: value
  42829. }, {
  42830. // If `precision` is set, width can be fixed (like '12.00500'), which
  42831. // helps to debounce when when moving label.
  42832. precision: opt.precision
  42833. });
  42834. var formatter = opt.formatter;
  42835. if (formatter) {
  42836. var params_1 = {
  42837. value: getAxisRawValue(axis, {
  42838. value: value
  42839. }),
  42840. axisDimension: axis.dim,
  42841. axisIndex: axis.index,
  42842. seriesData: []
  42843. };
  42844. each(seriesDataIndices, function (idxItem) {
  42845. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  42846. var dataIndex = idxItem.dataIndexInside;
  42847. var dataParams = series && series.getDataParams(dataIndex);
  42848. dataParams && params_1.seriesData.push(dataParams);
  42849. });
  42850. if (isString(formatter)) {
  42851. text = formatter.replace('{value}', text);
  42852. } else if (isFunction(formatter)) {
  42853. text = formatter(params_1);
  42854. }
  42855. }
  42856. return text;
  42857. }
  42858. function getTransformedPosition(axis, value, layoutInfo) {
  42859. var transform = create$1();
  42860. rotate(transform, transform, layoutInfo.rotation);
  42861. translate(transform, transform, layoutInfo.position);
  42862. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  42863. }
  42864. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  42865. // @ts-ignore
  42866. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  42867. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  42868. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  42869. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  42870. align: textLayout.textAlign,
  42871. verticalAlign: textLayout.textVerticalAlign
  42872. });
  42873. }
  42874. function makeLineShape(p1, p2, xDimIndex) {
  42875. xDimIndex = xDimIndex || 0;
  42876. return {
  42877. x1: p1[xDimIndex],
  42878. y1: p1[1 - xDimIndex],
  42879. x2: p2[xDimIndex],
  42880. y2: p2[1 - xDimIndex]
  42881. };
  42882. }
  42883. function makeRectShape(xy, wh, xDimIndex) {
  42884. xDimIndex = xDimIndex || 0;
  42885. return {
  42886. x: xy[xDimIndex],
  42887. y: xy[1 - xDimIndex],
  42888. width: wh[xDimIndex],
  42889. height: wh[1 - xDimIndex]
  42890. };
  42891. }
  42892. var CartesianAxisPointer =
  42893. /** @class */
  42894. function (_super) {
  42895. __extends(CartesianAxisPointer, _super);
  42896. function CartesianAxisPointer() {
  42897. return _super !== null && _super.apply(this, arguments) || this;
  42898. }
  42899. /**
  42900. * @override
  42901. */
  42902. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  42903. var axis = axisModel.axis;
  42904. var grid = axis.grid;
  42905. var axisPointerType = axisPointerModel.get('type');
  42906. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42907. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  42908. if (axisPointerType && axisPointerType !== 'none') {
  42909. var elStyle = buildElStyle(axisPointerModel);
  42910. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  42911. pointerOption.style = elStyle;
  42912. elOption.graphicKey = pointerOption.type;
  42913. elOption.pointer = pointerOption;
  42914. }
  42915. var layoutInfo = layout$1(grid.model, axisModel);
  42916. buildCartesianSingleLabelElOption( // @ts-ignore
  42917. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  42918. };
  42919. /**
  42920. * @override
  42921. */
  42922. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  42923. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  42924. labelInside: false
  42925. }); // @ts-ignore
  42926. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  42927. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  42928. return {
  42929. x: pos[0],
  42930. y: pos[1],
  42931. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  42932. };
  42933. };
  42934. /**
  42935. * @override
  42936. */
  42937. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  42938. var axis = axisModel.axis;
  42939. var grid = axis.grid;
  42940. var axisExtent = axis.getGlobalExtent(true);
  42941. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42942. var dimIndex = axis.dim === 'x' ? 0 : 1;
  42943. var currPosition = [transform.x, transform.y];
  42944. currPosition[dimIndex] += delta[dimIndex];
  42945. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  42946. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  42947. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  42948. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  42949. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  42950. var tooltipOptions = [{
  42951. verticalAlign: 'middle'
  42952. }, {
  42953. align: 'center'
  42954. }];
  42955. return {
  42956. x: currPosition[0],
  42957. y: currPosition[1],
  42958. rotation: transform.rotation,
  42959. cursorPoint: cursorPoint,
  42960. tooltipOption: tooltipOptions[dimIndex]
  42961. };
  42962. };
  42963. return CartesianAxisPointer;
  42964. }(BaseAxisPointer);
  42965. function getCartesian(grid, axis) {
  42966. var opt = {};
  42967. opt[axis.dim + 'AxisIndex'] = axis.index;
  42968. return grid.getCartesian(opt);
  42969. }
  42970. var pointerShapeBuilder = {
  42971. line: function (axis, pixelValue, otherExtent) {
  42972. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  42973. return {
  42974. type: 'Line',
  42975. subPixelOptimize: true,
  42976. shape: targetShape
  42977. };
  42978. },
  42979. shadow: function (axis, pixelValue, otherExtent) {
  42980. var bandWidth = Math.max(1, axis.getBandWidth());
  42981. var span = otherExtent[1] - otherExtent[0];
  42982. return {
  42983. type: 'Rect',
  42984. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  42985. };
  42986. }
  42987. };
  42988. function getAxisDimIndex(axis) {
  42989. return axis.dim === 'x' ? 0 : 1;
  42990. }
  42991. var AxisPointerModel =
  42992. /** @class */
  42993. function (_super) {
  42994. __extends(AxisPointerModel, _super);
  42995. function AxisPointerModel() {
  42996. var _this = _super !== null && _super.apply(this, arguments) || this;
  42997. _this.type = AxisPointerModel.type;
  42998. return _this;
  42999. }
  43000. AxisPointerModel.type = 'axisPointer';
  43001. AxisPointerModel.defaultOption = {
  43002. // 'auto' means that show when triggered by tooltip or handle.
  43003. show: 'auto',
  43004. // zlevel: 0,
  43005. z: 50,
  43006. type: 'line',
  43007. // axispointer triggered by tootip determine snap automatically,
  43008. // see `modelHelper`.
  43009. snap: false,
  43010. triggerTooltip: true,
  43011. value: null,
  43012. status: null,
  43013. link: [],
  43014. // Do not set 'auto' here, otherwise global animation: false
  43015. // will not effect at this axispointer.
  43016. animation: null,
  43017. animationDurationUpdate: 200,
  43018. lineStyle: {
  43019. color: '#B9BEC9',
  43020. width: 1,
  43021. type: 'dashed'
  43022. },
  43023. shadowStyle: {
  43024. color: 'rgba(210,219,238,0.2)'
  43025. },
  43026. label: {
  43027. show: true,
  43028. formatter: null,
  43029. precision: 'auto',
  43030. margin: 3,
  43031. color: '#fff',
  43032. padding: [5, 7, 5, 7],
  43033. backgroundColor: 'auto',
  43034. borderColor: null,
  43035. borderWidth: 0,
  43036. borderRadius: 3
  43037. },
  43038. handle: {
  43039. show: false,
  43040. // eslint-disable-next-line
  43041. 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',
  43042. size: 45,
  43043. // handle margin is from symbol center to axis, which is stable when circular move.
  43044. margin: 50,
  43045. // color: '#1b8bbd'
  43046. // color: '#2f4554'
  43047. color: '#333',
  43048. shadowBlur: 3,
  43049. shadowColor: '#aaa',
  43050. shadowOffsetX: 0,
  43051. shadowOffsetY: 2,
  43052. // For mobile performance
  43053. throttle: 40
  43054. }
  43055. };
  43056. return AxisPointerModel;
  43057. }(ComponentModel);
  43058. var inner$8 = makeInner();
  43059. var each$3 = each;
  43060. /**
  43061. * @param {string} key
  43062. * @param {module:echarts/ExtensionAPI} api
  43063. * @param {Function} handler
  43064. * param: {string} currTrigger
  43065. * param: {Array.<number>} point
  43066. */
  43067. function register(key, api, handler) {
  43068. if (env.node) {
  43069. return;
  43070. }
  43071. var zr = api.getZr();
  43072. inner$8(zr).records || (inner$8(zr).records = {});
  43073. initGlobalListeners(zr, api);
  43074. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  43075. record.handler = handler;
  43076. }
  43077. function initGlobalListeners(zr, api) {
  43078. if (inner$8(zr).initialized) {
  43079. return;
  43080. }
  43081. inner$8(zr).initialized = true;
  43082. useHandler('click', curry(doEnter, 'click'));
  43083. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  43084. useHandler('globalout', onLeave);
  43085. function useHandler(eventType, cb) {
  43086. zr.on(eventType, function (e) {
  43087. var dis = makeDispatchAction(api);
  43088. each$3(inner$8(zr).records, function (record) {
  43089. record && cb(record, e, dis.dispatchAction);
  43090. });
  43091. dispatchTooltipFinally(dis.pendings, api);
  43092. });
  43093. }
  43094. }
  43095. function dispatchTooltipFinally(pendings, api) {
  43096. var showLen = pendings.showTip.length;
  43097. var hideLen = pendings.hideTip.length;
  43098. var actuallyPayload;
  43099. if (showLen) {
  43100. actuallyPayload = pendings.showTip[showLen - 1];
  43101. } else if (hideLen) {
  43102. actuallyPayload = pendings.hideTip[hideLen - 1];
  43103. }
  43104. if (actuallyPayload) {
  43105. actuallyPayload.dispatchAction = null;
  43106. api.dispatchAction(actuallyPayload);
  43107. }
  43108. }
  43109. function onLeave(record, e, dispatchAction) {
  43110. record.handler('leave', null, dispatchAction);
  43111. }
  43112. function doEnter(currTrigger, record, e, dispatchAction) {
  43113. record.handler(currTrigger, e, dispatchAction);
  43114. }
  43115. function makeDispatchAction(api) {
  43116. var pendings = {
  43117. showTip: [],
  43118. hideTip: []
  43119. }; // FIXME
  43120. // better approach?
  43121. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  43122. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  43123. // So we have to add "final stage" to merge those dispatched actions.
  43124. var dispatchAction = function (payload) {
  43125. var pendingList = pendings[payload.type];
  43126. if (pendingList) {
  43127. pendingList.push(payload);
  43128. } else {
  43129. payload.dispatchAction = dispatchAction;
  43130. api.dispatchAction(payload);
  43131. }
  43132. };
  43133. return {
  43134. dispatchAction: dispatchAction,
  43135. pendings: pendings
  43136. };
  43137. }
  43138. function unregister(key, api) {
  43139. if (env.node) {
  43140. return;
  43141. }
  43142. var zr = api.getZr();
  43143. var record = (inner$8(zr).records || {})[key];
  43144. if (record) {
  43145. inner$8(zr).records[key] = null;
  43146. }
  43147. }
  43148. var AxisPointerView =
  43149. /** @class */
  43150. function (_super) {
  43151. __extends(AxisPointerView, _super);
  43152. function AxisPointerView() {
  43153. var _this = _super !== null && _super.apply(this, arguments) || this;
  43154. _this.type = AxisPointerView.type;
  43155. return _this;
  43156. }
  43157. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  43158. var globalTooltipModel = ecModel.getComponent('tooltip');
  43159. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  43160. // AxisPointerView to be independent to Tooltip.
  43161. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  43162. // If 'none', it is not controlled by mouse totally.
  43163. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  43164. dispatchAction({
  43165. type: 'updateAxisPointer',
  43166. currTrigger: currTrigger,
  43167. x: e && e.offsetX,
  43168. y: e && e.offsetY
  43169. });
  43170. }
  43171. });
  43172. };
  43173. AxisPointerView.prototype.remove = function (ecModel, api) {
  43174. unregister('axisPointer', api);
  43175. };
  43176. AxisPointerView.prototype.dispose = function (ecModel, api) {
  43177. unregister('axisPointer', api);
  43178. };
  43179. AxisPointerView.type = 'axisPointer';
  43180. return AxisPointerView;
  43181. }(ComponentView);
  43182. /**
  43183. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  43184. * @param ecModel
  43185. * @return {point: [x, y], el: ...} point Will not be null.
  43186. */
  43187. function findPointFromSeries(finder, ecModel) {
  43188. var point = [];
  43189. var seriesIndex = finder.seriesIndex;
  43190. var seriesModel;
  43191. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  43192. return {
  43193. point: []
  43194. };
  43195. }
  43196. var data = seriesModel.getData();
  43197. var dataIndex = queryDataIndex(data, finder);
  43198. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  43199. return {
  43200. point: []
  43201. };
  43202. }
  43203. var el = data.getItemGraphicEl(dataIndex);
  43204. var coordSys = seriesModel.coordinateSystem;
  43205. if (seriesModel.getTooltipPosition) {
  43206. point = seriesModel.getTooltipPosition(dataIndex) || [];
  43207. } else if (coordSys && coordSys.dataToPoint) {
  43208. if (finder.isStacked) {
  43209. var baseAxis = coordSys.getBaseAxis();
  43210. var valueAxis = coordSys.getOtherAxis(baseAxis);
  43211. var valueAxisDim = valueAxis.dim;
  43212. var baseAxisDim = baseAxis.dim;
  43213. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  43214. var baseDim = data.mapDimension(baseAxisDim);
  43215. var stackedData = [];
  43216. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  43217. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  43218. point = coordSys.dataToPoint(stackedData) || [];
  43219. } else {
  43220. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  43221. return data.mapDimension(dim);
  43222. }), dataIndex)) || [];
  43223. }
  43224. } else if (el) {
  43225. // Use graphic bounding rect
  43226. var rect = el.getBoundingRect().clone();
  43227. rect.applyTransform(el.transform);
  43228. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  43229. }
  43230. return {
  43231. point: point,
  43232. el: el
  43233. };
  43234. }
  43235. var inner$9 = makeInner();
  43236. /**
  43237. * Basic logic: check all axis, if they do not demand show/highlight,
  43238. * then hide/downplay them.
  43239. *
  43240. * @return content of event obj for echarts.connect.
  43241. */
  43242. function axisTrigger(payload, ecModel, api) {
  43243. var currTrigger = payload.currTrigger;
  43244. var point = [payload.x, payload.y];
  43245. var finder = payload;
  43246. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  43247. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  43248. // See #6121. But we are not able to reproduce it yet.
  43249. if (!coordSysAxesInfo) {
  43250. return;
  43251. }
  43252. if (illegalPoint(point)) {
  43253. // Used in the default behavior of `connection`: use the sample seriesIndex
  43254. // and dataIndex. And also used in the tooltipView trigger.
  43255. point = findPointFromSeries({
  43256. seriesIndex: finder.seriesIndex,
  43257. // Do not use dataIndexInside from other ec instance.
  43258. // FIXME: auto detect it?
  43259. dataIndex: finder.dataIndex
  43260. }, ecModel).point;
  43261. }
  43262. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  43263. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  43264. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  43265. // and dataIndex.
  43266. var inputAxesInfo = finder.axesInfo;
  43267. var axesInfo = coordSysAxesInfo.axesInfo;
  43268. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  43269. var outputPayload = {};
  43270. var showValueMap = {};
  43271. var dataByCoordSys = {
  43272. list: [],
  43273. map: {}
  43274. };
  43275. var updaters = {
  43276. showPointer: curry(showPointer, showValueMap),
  43277. showTooltip: curry(showTooltip, dataByCoordSys)
  43278. }; // Process for triggered axes.
  43279. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  43280. // If a point given, it must be contained by the coordinate system.
  43281. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  43282. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  43283. var axis = axisInfo.axis;
  43284. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  43285. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  43286. var val = inputAxisInfo && inputAxisInfo.value;
  43287. if (val == null && !isIllegalPoint) {
  43288. val = axis.pointToData(point);
  43289. }
  43290. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  43291. }
  43292. });
  43293. }); // Process for linked axes.
  43294. var linkTriggers = {};
  43295. each(axesInfo, function (tarAxisInfo, tarKey) {
  43296. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  43297. if (linkGroup && !showValueMap[tarKey]) {
  43298. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  43299. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  43300. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  43301. var val = srcValItem.value;
  43302. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  43303. linkTriggers[tarAxisInfo.key] = val;
  43304. }
  43305. });
  43306. }
  43307. });
  43308. each(linkTriggers, function (val, tarKey) {
  43309. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  43310. });
  43311. updateModelActually(showValueMap, axesInfo, outputPayload);
  43312. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  43313. dispatchHighDownActually(axesInfo, dispatchAction, api);
  43314. return outputPayload;
  43315. }
  43316. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  43317. var axis = axisInfo.axis;
  43318. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  43319. return;
  43320. }
  43321. if (!axisInfo.involveSeries) {
  43322. updaters.showPointer(axisInfo, newValue);
  43323. return;
  43324. } // Heavy calculation. So put it after axis.containData checking.
  43325. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  43326. var payloadBatch = payloadInfo.payloadBatch;
  43327. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  43328. // By default use the first involved series data as a sample to connect.
  43329. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  43330. extend(outputFinder, payloadBatch[0]);
  43331. } // If no linkSource input, this process is for collecting link
  43332. // target, where snap should not be accepted.
  43333. if (!noSnap && axisInfo.snap) {
  43334. if (axis.containData(snapToValue) && snapToValue != null) {
  43335. newValue = snapToValue;
  43336. }
  43337. }
  43338. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  43339. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  43340. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  43341. }
  43342. function buildPayloadsBySeries(value, axisInfo) {
  43343. var axis = axisInfo.axis;
  43344. var dim = axis.dim;
  43345. var snapToValue = value;
  43346. var payloadBatch = [];
  43347. var minDist = Number.MAX_VALUE;
  43348. var minDiff = -1;
  43349. each(axisInfo.seriesModels, function (series, idx) {
  43350. var dataDim = series.getData().mapDimensionsAll(dim);
  43351. var seriesNestestValue;
  43352. var dataIndices;
  43353. if (series.getAxisTooltipData) {
  43354. var result = series.getAxisTooltipData(dataDim, value, axis);
  43355. dataIndices = result.dataIndices;
  43356. seriesNestestValue = result.nestestValue;
  43357. } else {
  43358. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  43359. // when data length is not same.
  43360. // false,
  43361. axis.type === 'category' ? 0.5 : null);
  43362. if (!dataIndices.length) {
  43363. return;
  43364. }
  43365. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  43366. }
  43367. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  43368. return;
  43369. }
  43370. var diff = value - seriesNestestValue;
  43371. var dist = Math.abs(diff); // Consider category case
  43372. if (dist <= minDist) {
  43373. if (dist < minDist || diff >= 0 && minDiff < 0) {
  43374. minDist = dist;
  43375. minDiff = diff;
  43376. snapToValue = seriesNestestValue;
  43377. payloadBatch.length = 0;
  43378. }
  43379. each(dataIndices, function (dataIndex) {
  43380. payloadBatch.push({
  43381. seriesIndex: series.seriesIndex,
  43382. dataIndexInside: dataIndex,
  43383. dataIndex: series.getData().getRawIndex(dataIndex)
  43384. });
  43385. });
  43386. }
  43387. });
  43388. return {
  43389. payloadBatch: payloadBatch,
  43390. snapToValue: snapToValue
  43391. };
  43392. }
  43393. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  43394. showValueMap[axisInfo.key] = {
  43395. value: value,
  43396. payloadBatch: payloadBatch
  43397. };
  43398. }
  43399. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  43400. var payloadBatch = payloadInfo.payloadBatch;
  43401. var axis = axisInfo.axis;
  43402. var axisModel = axis.model;
  43403. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  43404. // whose length will be used to judge whether dispatch action.
  43405. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  43406. return;
  43407. }
  43408. var coordSysModel = axisInfo.coordSys.model;
  43409. var coordSysKey = makeKey(coordSysModel);
  43410. var coordSysItem = dataByCoordSys.map[coordSysKey];
  43411. if (!coordSysItem) {
  43412. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  43413. coordSysId: coordSysModel.id,
  43414. coordSysIndex: coordSysModel.componentIndex,
  43415. coordSysType: coordSysModel.type,
  43416. coordSysMainType: coordSysModel.mainType,
  43417. dataByAxis: []
  43418. };
  43419. dataByCoordSys.list.push(coordSysItem);
  43420. }
  43421. coordSysItem.dataByAxis.push({
  43422. axisDim: axis.dim,
  43423. axisIndex: axisModel.componentIndex,
  43424. axisType: axisModel.type,
  43425. axisId: axisModel.id,
  43426. value: value,
  43427. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  43428. // depends that all models have been updated. So it should not be performed
  43429. // here. Considering axisPointerModel used here is volatile, which is hard
  43430. // to be retrieve in TooltipView, we prepare parameters here.
  43431. valueLabelOpt: {
  43432. precision: axisPointerModel.get(['label', 'precision']),
  43433. formatter: axisPointerModel.get(['label', 'formatter'])
  43434. },
  43435. seriesDataIndices: payloadBatch.slice()
  43436. });
  43437. }
  43438. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  43439. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  43440. each(axesInfo, function (axisInfo, key) {
  43441. var option = axisInfo.axisPointerModel.option;
  43442. var valItem = showValueMap[key];
  43443. if (valItem) {
  43444. !axisInfo.useHandle && (option.status = 'show');
  43445. option.value = valItem.value; // For label formatter param and highlight.
  43446. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  43447. } // When always show (e.g., handle used), remain
  43448. // original value and status.
  43449. else {
  43450. // If hide, value still need to be set, consider
  43451. // click legend to toggle axis blank.
  43452. !axisInfo.useHandle && (option.status = 'hide');
  43453. } // If status is 'hide', should be no info in payload.
  43454. option.status === 'show' && outputAxesInfo.push({
  43455. axisDim: axisInfo.axis.dim,
  43456. axisIndex: axisInfo.axis.model.componentIndex,
  43457. value: option.value
  43458. });
  43459. });
  43460. }
  43461. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  43462. // Basic logic: If no showTip required, hideTip will be dispatched.
  43463. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  43464. dispatchAction({
  43465. type: 'hideTip'
  43466. });
  43467. return;
  43468. } // In most case only one axis (or event one series is used). It is
  43469. // convinient to fetch payload.seriesIndex and payload.dataIndex
  43470. // dirtectly. So put the first seriesIndex and dataIndex of the first
  43471. // axis on the payload.
  43472. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  43473. dispatchAction({
  43474. type: 'showTip',
  43475. escapeConnect: true,
  43476. x: point[0],
  43477. y: point[1],
  43478. tooltipOption: payload.tooltipOption,
  43479. position: payload.position,
  43480. dataIndexInside: sampleItem.dataIndexInside,
  43481. dataIndex: sampleItem.dataIndex,
  43482. seriesIndex: sampleItem.seriesIndex,
  43483. dataByCoordSys: dataByCoordSys.list
  43484. });
  43485. }
  43486. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  43487. // FIXME
  43488. // highlight status modification shoule be a stage of main process?
  43489. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  43490. var zr = api.getZr();
  43491. var highDownKey = 'axisPointerLastHighlights';
  43492. var lastHighlights = inner$9(zr)[highDownKey] || {};
  43493. var newHighlights = inner$9(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  43494. // Build hash map and remove duplicate incidentally.
  43495. each(axesInfo, function (axisInfo, key) {
  43496. var option = axisInfo.axisPointerModel.option;
  43497. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  43498. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  43499. newHighlights[key] = batchItem;
  43500. });
  43501. }); // Diff.
  43502. var toHighlight = [];
  43503. var toDownplay = [];
  43504. each(lastHighlights, function (batchItem, key) {
  43505. !newHighlights[key] && toDownplay.push(batchItem);
  43506. });
  43507. each(newHighlights, function (batchItem, key) {
  43508. !lastHighlights[key] && toHighlight.push(batchItem);
  43509. });
  43510. toDownplay.length && api.dispatchAction({
  43511. type: 'downplay',
  43512. escapeConnect: true,
  43513. // Not blur others when highlight in axisPointer.
  43514. notBlur: true,
  43515. batch: toDownplay
  43516. });
  43517. toHighlight.length && api.dispatchAction({
  43518. type: 'highlight',
  43519. escapeConnect: true,
  43520. // Not blur others when highlight in axisPointer.
  43521. notBlur: true,
  43522. batch: toHighlight
  43523. });
  43524. }
  43525. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  43526. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  43527. var inputAxisInfo = inputAxesInfo[i];
  43528. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  43529. return inputAxisInfo;
  43530. }
  43531. }
  43532. }
  43533. function makeMapperParam(axisInfo) {
  43534. var axisModel = axisInfo.axis.model;
  43535. var item = {};
  43536. var dim = item.axisDim = axisInfo.axis.dim;
  43537. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  43538. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  43539. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  43540. return item;
  43541. }
  43542. function illegalPoint(point) {
  43543. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  43544. }
  43545. function install$7(registers) {
  43546. // CartesianAxisPointer is not supposed to be required here. But consider
  43547. // echarts.simple.js and online build tooltip, which only require gridSimple,
  43548. // CartesianAxisPointer should be able to required somewhere.
  43549. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  43550. registers.registerComponentModel(AxisPointerModel);
  43551. registers.registerComponentView(AxisPointerView);
  43552. registers.registerPreprocessor(function (option) {
  43553. // Always has a global axisPointerModel for default setting.
  43554. if (option) {
  43555. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  43556. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  43557. // is not set, remain null/undefined, otherwise it will
  43558. // override existent link setting.
  43559. if (link && !isArray(link)) {
  43560. option.axisPointer.link = [link];
  43561. }
  43562. }
  43563. }); // This process should proformed after coordinate systems created
  43564. // and series data processed. So put it on statistic processing stage.
  43565. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  43566. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  43567. // allAxesInfo should be updated when setOption performed.
  43568. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  43569. }); // Broadcast to all views.
  43570. registers.registerAction({
  43571. type: 'updateAxisPointer',
  43572. event: 'updateAxisPointer',
  43573. update: ':updateAxisPointer'
  43574. }, axisTrigger);
  43575. }
  43576. function install$8(registers) {
  43577. use(install$5);
  43578. use(install$7);
  43579. }
  43580. function setKeyInfoToNewElOption(resultItem, newElOption) {
  43581. var existElOption = resultItem.existing; // Set id and type after id assigned.
  43582. newElOption.id = resultItem.keyInfo.id;
  43583. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  43584. if (newElOption.parentId == null) {
  43585. var newElParentOption = newElOption.parentOption;
  43586. if (newElParentOption) {
  43587. newElOption.parentId = newElParentOption.id;
  43588. } else if (existElOption) {
  43589. newElOption.parentId = existElOption.parentId;
  43590. }
  43591. } // Clear
  43592. newElOption.parentOption = null;
  43593. }
  43594. function isSetLoc(obj, props) {
  43595. var isSet;
  43596. each(props, function (prop) {
  43597. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  43598. });
  43599. return isSet;
  43600. }
  43601. function mergeNewElOptionToExist(existList, index, newElOption) {
  43602. // Update existing options, for `getOption` feature.
  43603. var newElOptCopy = extend({}, newElOption);
  43604. var existElOption = existList[index];
  43605. var $action = newElOption.$action || 'merge';
  43606. if ($action === 'merge') {
  43607. if (existElOption) {
  43608. if ("development" !== 'production') {
  43609. var newType = newElOption.type;
  43610. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  43611. } // We can ensure that newElOptCopy and existElOption are not
  43612. // the same object, so `merge` will not change newElOptCopy.
  43613. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  43614. mergeLayoutParam(existElOption, newElOptCopy, {
  43615. ignoreSize: true
  43616. }); // Will be used in render.
  43617. copyLayoutParams(newElOption, existElOption); // Copy transition info to new option so it can be used in the transition.
  43618. // DO IT AFTER merge
  43619. copyTransitionInfo(newElOption, existElOption);
  43620. copyTransitionInfo(newElOption, existElOption, 'shape');
  43621. copyTransitionInfo(newElOption, existElOption, 'style');
  43622. copyTransitionInfo(newElOption, existElOption, 'extra'); // Copy clipPath
  43623. newElOption.clipPath = existElOption.clipPath;
  43624. } else {
  43625. existList[index] = newElOptCopy;
  43626. }
  43627. } else if ($action === 'replace') {
  43628. existList[index] = newElOptCopy;
  43629. } else if ($action === 'remove') {
  43630. // null will be cleaned later.
  43631. existElOption && (existList[index] = null);
  43632. }
  43633. }
  43634. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  43635. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  43636. function copyTransitionInfo(target, source, targetProp) {
  43637. if (targetProp) {
  43638. if (!target[targetProp] && source[targetProp]) {
  43639. // TODO avoid creating this empty object when there is no transition configuration.
  43640. target[targetProp] = {};
  43641. }
  43642. target = target[targetProp];
  43643. source = source[targetProp];
  43644. }
  43645. if (!target || !source) {
  43646. return;
  43647. }
  43648. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  43649. for (var i = 0; i < props.length; i++) {
  43650. var prop = props[i];
  43651. if (target[prop] == null && source[prop] != null) {
  43652. target[prop] = source[prop];
  43653. }
  43654. }
  43655. }
  43656. function setLayoutInfoToExist(existItem, newElOption) {
  43657. if (!existItem) {
  43658. return;
  43659. }
  43660. existItem.hv = newElOption.hv = [// Rigid body, dont care `width`.
  43661. isSetLoc(newElOption, ['left', 'right']), // Rigid body, dont care `height`.
  43662. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  43663. if (existItem.type === 'group') {
  43664. var existingGroupOpt = existItem;
  43665. var newGroupOpt = newElOption;
  43666. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  43667. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  43668. }
  43669. }
  43670. var GraphicComponentModel =
  43671. /** @class */
  43672. function (_super) {
  43673. __extends(GraphicComponentModel, _super);
  43674. function GraphicComponentModel() {
  43675. var _this = _super !== null && _super.apply(this, arguments) || this;
  43676. _this.type = GraphicComponentModel.type;
  43677. _this.preventAutoZ = true;
  43678. return _this;
  43679. }
  43680. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  43681. // Prevent default merge to elements
  43682. var elements = this.option.elements;
  43683. this.option.elements = null;
  43684. _super.prototype.mergeOption.call(this, option, ecModel);
  43685. this.option.elements = elements;
  43686. };
  43687. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  43688. var thisOption = this.option;
  43689. var newList = (isInit ? thisOption : newOption).elements;
  43690. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  43691. var flattenedList = [];
  43692. this._flatten(newList, flattenedList, null);
  43693. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  43694. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  43695. each(mappingResult, function (resultItem, index) {
  43696. var newElOption = resultItem.newOption;
  43697. if ("development" !== 'production') {
  43698. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  43699. }
  43700. if (!newElOption) {
  43701. return;
  43702. }
  43703. elOptionsToUpdate.push(newElOption);
  43704. setKeyInfoToNewElOption(resultItem, newElOption);
  43705. mergeNewElOptionToExist(existList, index, newElOption);
  43706. setLayoutInfoToExist(existList[index], newElOption);
  43707. }, this); // Clean
  43708. thisOption.elements = filter(existList, function (item) {
  43709. // $action should be volatile, otherwise option gotten from
  43710. // `getOption` will contain unexpected $action.
  43711. item && delete item.$action;
  43712. return item != null;
  43713. });
  43714. };
  43715. /**
  43716. * Convert
  43717. * [{
  43718. * type: 'group',
  43719. * id: 'xx',
  43720. * children: [{type: 'circle'}, {type: 'polygon'}]
  43721. * }]
  43722. * to
  43723. * [
  43724. * {type: 'group', id: 'xx'},
  43725. * {type: 'circle', parentId: 'xx'},
  43726. * {type: 'polygon', parentId: 'xx'}
  43727. * ]
  43728. */
  43729. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  43730. each(optionList, function (option) {
  43731. if (!option) {
  43732. return;
  43733. }
  43734. if (parentOption) {
  43735. option.parentOption = parentOption;
  43736. }
  43737. result.push(option);
  43738. var children = option.children;
  43739. if (option.type === 'group' && children) {
  43740. this._flatten(children, result, option);
  43741. } // Deleting for JSON output, and for not affecting group creation.
  43742. delete option.children;
  43743. }, this);
  43744. }; // FIXME
  43745. // Pass to view using payload? setOption has a payload?
  43746. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  43747. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  43748. this._elOptionsToUpdate = null;
  43749. return els;
  43750. };
  43751. GraphicComponentModel.type = 'graphic';
  43752. GraphicComponentModel.defaultOption = {
  43753. elements: [] // parentId: null
  43754. };
  43755. return GraphicComponentModel;
  43756. }(ComponentModel);
  43757. /**
  43758. * Whether need to call `convertEC4CompatibleStyle`.
  43759. */
  43760. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  43761. // Since echarts5, `RectText` is separated from its host element and style.text
  43762. // does not exist any more. The compat work brings some extra burden on performance.
  43763. // So we provide:
  43764. // `legacy: true` force make compat.
  43765. // `legacy: false`, force do not compat.
  43766. // `legacy` not set: auto detect wheter legacy.
  43767. // But in this case we do not compat (difficult to detect and rare case):
  43768. // Becuse custom series and graphic component support "merge", users may firstly
  43769. // only set `textStrokeWidth` style or secondly only set `text`.
  43770. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  43771. && (elType === 'text' || hasOwn(style, 'text')));
  43772. }
  43773. /**
  43774. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  43775. * @param hostStyle The properties might be modified.
  43776. * @return If be text el, `textContentStyle` and `textConfig` will not be retured.
  43777. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  43778. * retried from the `hostStyle`.
  43779. */
  43780. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  43781. var srcStyle = hostStyle;
  43782. var textConfig;
  43783. var textContent;
  43784. var textContentStyle;
  43785. if (elType === 'text') {
  43786. textContentStyle = srcStyle;
  43787. } else {
  43788. textContentStyle = {};
  43789. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  43790. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  43791. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  43792. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  43793. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  43794. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  43795. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  43796. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  43797. textContent = {
  43798. type: 'text',
  43799. style: textContentStyle,
  43800. // ec4 do not support rectText trigger.
  43801. // And when text postion is different in normal and emphasis
  43802. // => hover text trigger emphasis;
  43803. // => text position changed, leave mouse pointer immediately;
  43804. // That might cause state incorrect.
  43805. silent: true
  43806. };
  43807. textConfig = {};
  43808. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  43809. if (isNormal) {
  43810. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  43811. } else {
  43812. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  43813. }
  43814. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  43815. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  43816. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  43817. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  43818. }
  43819. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  43820. each(textContentStyle.rich, function (richItem) {
  43821. convertEC4CompatibleRichItem(richItem, richItem);
  43822. });
  43823. return {
  43824. textConfig: textConfig,
  43825. textContent: textContent
  43826. };
  43827. }
  43828. /**
  43829. * The result will be set to `out`.
  43830. */
  43831. function convertEC4CompatibleRichItem(out, richItem) {
  43832. if (!richItem) {
  43833. return;
  43834. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  43835. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  43836. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  43837. // richText in ec5.
  43838. // (2) `out === richItem` if and only if `out` is text el or rich item.
  43839. // So we can overwite existing props in `out` since textXXX has higher priority.
  43840. richItem.font = richItem.textFont || richItem.font;
  43841. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  43842. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  43843. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  43844. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  43845. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  43846. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  43847. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  43848. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  43849. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  43850. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  43851. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  43852. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  43853. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  43854. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  43855. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  43856. }
  43857. var LEGACY_TRANSFORM_PROPS_MAP = {
  43858. position: ['x', 'y'],
  43859. scale: ['scaleX', 'scaleY'],
  43860. origin: ['originX', 'originY']
  43861. };
  43862. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  43863. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  43864. obj[key] = 1;
  43865. return obj;
  43866. }, {});
  43867. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', '); // '' means root
  43868. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  43869. var transitionInnerStore = makeInner();
  43870. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  43871. var animationProp = animationType + "Animation";
  43872. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  43873. var userDuring = transitionInnerStore(el).userDuring; // Only set when duration is > 0 and it's need to be animated.
  43874. if (config.duration > 0) {
  43875. // For simplicity, if during not specified, the previous during will not work any more.
  43876. config.during = userDuring ? bind(duringCall, {
  43877. el: el,
  43878. userDuring: userDuring
  43879. }) : null;
  43880. config.setToFinal = true;
  43881. config.scope = animationType;
  43882. }
  43883. extend(config, elOption[animationProp]);
  43884. return config;
  43885. }
  43886. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  43887. opts = opts || {};
  43888. var dataIndex = opts.dataIndex,
  43889. isInit = opts.isInit,
  43890. clearStyle = opts.clearStyle;
  43891. var hasAnimation = animatableModel.isAnimationEnabled(); // Save the meta info for further morphing. Like apply on the sub morphing elements.
  43892. var store = transitionInnerStore(el);
  43893. var styleOpt = elOption.style;
  43894. store.userDuring = elOption.during;
  43895. var transFromProps = {};
  43896. var propsToSet = {};
  43897. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  43898. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  43899. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  43900. if (!isInit && hasAnimation) {
  43901. prepareTransformTransitionFrom(el, elOption, transFromProps);
  43902. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  43903. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  43904. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  43905. }
  43906. propsToSet.style = styleOpt;
  43907. applyPropsDirectly(el, propsToSet, clearStyle);
  43908. applyMiscProps(el, elOption);
  43909. if (hasAnimation) {
  43910. if (isInit) {
  43911. var enterFromProps_1 = {};
  43912. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  43913. var prop = propName ? elOption[propName] : elOption;
  43914. if (prop && prop.enterFrom) {
  43915. if (propName) {
  43916. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  43917. }
  43918. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  43919. }
  43920. });
  43921. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  43922. if (config.duration > 0) {
  43923. el.animateFrom(enterFromProps_1, config);
  43924. }
  43925. } else {
  43926. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  43927. }
  43928. } // Store leave to be used in leave transition.
  43929. updateLeaveTo(el, elOption);
  43930. styleOpt ? el.dirty() : el.markRedraw();
  43931. }
  43932. function updateLeaveTo(el, elOption) {
  43933. // Try merge to previous set leaveTo
  43934. var leaveToProps = transitionInnerStore(el).leaveToProps;
  43935. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  43936. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  43937. var prop = propName ? elOption[propName] : elOption;
  43938. if (prop && prop.leaveTo) {
  43939. if (!leaveToProps) {
  43940. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  43941. }
  43942. if (propName) {
  43943. leaveToProps[propName] = leaveToProps[propName] || {};
  43944. }
  43945. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  43946. }
  43947. }
  43948. }
  43949. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  43950. if (el) {
  43951. var parent_1 = el.parent;
  43952. var leaveToProps = transitionInnerStore(el).leaveToProps;
  43953. if (leaveToProps) {
  43954. // TODO TODO use leave after leaveAnimation in series is introduced
  43955. // TODO Data index?
  43956. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  43957. config.done = function () {
  43958. parent_1.remove(el);
  43959. onRemove && onRemove();
  43960. };
  43961. el.animateTo(leaveToProps, config);
  43962. } else {
  43963. parent_1.remove(el);
  43964. onRemove && onRemove();
  43965. }
  43966. }
  43967. }
  43968. function isTransitionAll(transition) {
  43969. return transition === 'all';
  43970. }
  43971. function applyPropsDirectly(el, // Can be null/undefined
  43972. allPropsFinal, clearStyle) {
  43973. var styleOpt = allPropsFinal.style;
  43974. if (!el.isGroup && styleOpt) {
  43975. if (clearStyle) {
  43976. el.useStyle({}); // When style object changed, how to trade the existing animation?
  43977. // It is probably complicated and not needed to cover all the cases.
  43978. // But still need consider the case:
  43979. // (1) When using init animation on `style.opacity`, and before the animation
  43980. // ended users triggers an update by mousewhel. At that time the init
  43981. // animation should better be continued rather than terminated.
  43982. // So after `useStyle` called, we should change the animation target manually
  43983. // to continue the effect of the init animation.
  43984. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  43985. // to update the value to `val2` and no animation declared, should be terminate
  43986. // the previous animation or just modify the target of the animation?
  43987. // Therotically That will happen not only on `style` but also on `shape` and
  43988. // `transfrom` props. But we haven't handle this case at present yet.
  43989. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  43990. var animators = el.animators;
  43991. for (var i = 0; i < animators.length; i++) {
  43992. var animator = animators[i]; // targetName is the "topKey".
  43993. if (animator.targetName === 'style') {
  43994. animator.changeTarget(el.style);
  43995. }
  43996. }
  43997. }
  43998. el.setStyle(styleOpt);
  43999. }
  44000. if (allPropsFinal) {
  44001. // Not set style here.
  44002. allPropsFinal.style = null; // Set el to the final state firstly.
  44003. allPropsFinal && el.attr(allPropsFinal);
  44004. allPropsFinal.style = styleOpt;
  44005. }
  44006. }
  44007. function applyPropsTransition(el, elOption, dataIndex, model, // Can be null/undefined
  44008. transFromProps) {
  44009. if (transFromProps) {
  44010. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  44011. if (config.duration > 0) {
  44012. el.animateFrom(transFromProps, config);
  44013. }
  44014. }
  44015. }
  44016. function applyMiscProps(el, elOption) {
  44017. // Merge by default.
  44018. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  44019. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  44020. if (el instanceof Displayable) {
  44021. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  44022. }
  44023. if (el instanceof Path) {
  44024. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  44025. }
  44026. } // Use it to avoid it be exposed to user.
  44027. var tmpDuringScope = {};
  44028. var transitionDuringAPI = {
  44029. // Usually other props do not need to be changed in animation during.
  44030. setTransform: function (key, val) {
  44031. if ("development" !== 'production') {
  44032. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  44033. }
  44034. tmpDuringScope.el[key] = val;
  44035. return this;
  44036. },
  44037. getTransform: function (key) {
  44038. if ("development" !== 'production') {
  44039. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  44040. }
  44041. return tmpDuringScope.el[key];
  44042. },
  44043. setShape: function (key, val) {
  44044. if ("development" !== 'production') {
  44045. assertNotReserved(key);
  44046. }
  44047. var el = tmpDuringScope.el;
  44048. var shape = el.shape || (el.shape = {});
  44049. shape[key] = val;
  44050. el.dirtyShape && el.dirtyShape();
  44051. return this;
  44052. },
  44053. getShape: function (key) {
  44054. if ("development" !== 'production') {
  44055. assertNotReserved(key);
  44056. }
  44057. var shape = tmpDuringScope.el.shape;
  44058. if (shape) {
  44059. return shape[key];
  44060. }
  44061. },
  44062. setStyle: function (key, val) {
  44063. if ("development" !== 'production') {
  44064. assertNotReserved(key);
  44065. }
  44066. var el = tmpDuringScope.el;
  44067. var style = el.style;
  44068. if (style) {
  44069. if ("development" !== 'production') {
  44070. if (eqNaN(val)) {
  44071. warn('style.' + key + ' must not be assigned with NaN.');
  44072. }
  44073. }
  44074. style[key] = val;
  44075. el.dirtyStyle && el.dirtyStyle();
  44076. }
  44077. return this;
  44078. },
  44079. getStyle: function (key) {
  44080. if ("development" !== 'production') {
  44081. assertNotReserved(key);
  44082. }
  44083. var style = tmpDuringScope.el.style;
  44084. if (style) {
  44085. return style[key];
  44086. }
  44087. },
  44088. setExtra: function (key, val) {
  44089. if ("development" !== 'production') {
  44090. assertNotReserved(key);
  44091. }
  44092. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  44093. extra[key] = val;
  44094. return this;
  44095. },
  44096. getExtra: function (key) {
  44097. if ("development" !== 'production') {
  44098. assertNotReserved(key);
  44099. }
  44100. var extra = tmpDuringScope.el.extra;
  44101. if (extra) {
  44102. return extra[key];
  44103. }
  44104. }
  44105. };
  44106. function assertNotReserved(key) {
  44107. if ("development" !== 'production') {
  44108. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  44109. throw new Error('key must not be "' + key + '"');
  44110. }
  44111. }
  44112. }
  44113. function duringCall() {
  44114. // Do not provide "percent" until some requirements come.
  44115. // Because consider thies case:
  44116. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  44117. // And enter duration is different from update duration.
  44118. // Thus it might be confused about the meaning of "percent" in during callback.
  44119. var scope = this;
  44120. var el = scope.el;
  44121. if (!el) {
  44122. return;
  44123. } // If el is remove from zr by reason like legend, during still need to called,
  44124. // becuase el will be added back to zr and the prop value should not be incorrect.
  44125. var latestUserDuring = transitionInnerStore(el).userDuring;
  44126. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  44127. // If a during is called multiple times in one frame, maybe some users' calulation logic
  44128. // might be wrong (not sure whether this usage exists).
  44129. // The case of a during might be called twice can be: by default there is a animator for
  44130. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  44131. // another animators for 'style'/'shape'/'extra'.
  44132. if (latestUserDuring !== scopeUserDuring) {
  44133. // release
  44134. scope.el = scope.userDuring = null;
  44135. return;
  44136. }
  44137. tmpDuringScope.el = el; // Give no `this` to user in "during" calling.
  44138. scopeUserDuring(transitionDuringAPI); // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  44139. // consider the issue that the prop might be incorrect when return to "normal" state.
  44140. }
  44141. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  44142. var attrOpt = elOption[mainAttr];
  44143. if (!attrOpt) {
  44144. return;
  44145. }
  44146. var elPropsInAttr = fromEl[mainAttr];
  44147. var transFromPropsInAttr;
  44148. if (elPropsInAttr) {
  44149. var transition = elOption.transition;
  44150. var attrTransition = attrOpt.transition;
  44151. if (attrTransition) {
  44152. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  44153. if (isTransitionAll(attrTransition)) {
  44154. extend(transFromPropsInAttr, elPropsInAttr);
  44155. } else {
  44156. var transitionKeys = normalizeToArray(attrTransition);
  44157. for (var i = 0; i < transitionKeys.length; i++) {
  44158. var key = transitionKeys[i];
  44159. var elVal = elPropsInAttr[key];
  44160. transFromPropsInAttr[key] = elVal;
  44161. }
  44162. }
  44163. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  44164. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  44165. var elPropsInAttrKeys = keys(elPropsInAttr);
  44166. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  44167. var key = elPropsInAttrKeys[i];
  44168. var elVal = elPropsInAttr[key];
  44169. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  44170. transFromPropsInAttr[key] = elVal;
  44171. }
  44172. }
  44173. }
  44174. }
  44175. }
  44176. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  44177. var attrOpt = elOption[mainAttr];
  44178. if (!attrOpt) {
  44179. return;
  44180. }
  44181. var allPropsInAttr = allProps[mainAttr] = {};
  44182. var keysInAttr = keys(attrOpt);
  44183. for (var i = 0; i < keysInAttr.length; i++) {
  44184. var key = keysInAttr[i]; // To avoid share one object with different element, and
  44185. // to avoid user modify the object inexpectedly, have to clone.
  44186. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  44187. }
  44188. }
  44189. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  44190. var transition = elOption.transition;
  44191. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  44192. for (var i = 0; i < transitionKeys.length; i++) {
  44193. var key = transitionKeys[i];
  44194. if (key === 'style' || key === 'shape' || key === 'extra') {
  44195. continue;
  44196. }
  44197. var elVal = el[key];
  44198. if ("development" !== 'production') {
  44199. checkTransformPropRefer(key, 'el.transition');
  44200. } // Do not clone, animator will perform that clone.
  44201. transFromProps[key] = elVal;
  44202. }
  44203. }
  44204. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  44205. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  44206. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  44207. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  44208. var legacyArr = elOption[legacyName];
  44209. if (legacyArr) {
  44210. allProps[xyName[0]] = legacyArr[0];
  44211. allProps[xyName[1]] = legacyArr[1];
  44212. }
  44213. }
  44214. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  44215. var key = TRANSFORMABLE_PROPS[i];
  44216. if (elOption[key] != null) {
  44217. allProps[key] = elOption[key];
  44218. }
  44219. }
  44220. }
  44221. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  44222. if (!styleOpt) {
  44223. return;
  44224. }
  44225. var fromElStyle = fromEl.style;
  44226. var transFromStyleProps;
  44227. if (fromElStyle) {
  44228. var styleTransition = styleOpt.transition;
  44229. var elTransition = elOption.transition;
  44230. if (styleTransition && !isTransitionAll(styleTransition)) {
  44231. var transitionKeys = normalizeToArray(styleTransition);
  44232. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  44233. for (var i = 0; i < transitionKeys.length; i++) {
  44234. var key = transitionKeys[i];
  44235. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  44236. transFromStyleProps[key] = elVal;
  44237. }
  44238. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  44239. var animationProps = fromEl.getAnimationStyleProps();
  44240. var animationStyleProps = animationProps ? animationProps.style : null;
  44241. if (animationStyleProps) {
  44242. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  44243. var styleKeys = keys(styleOpt);
  44244. for (var i = 0; i < styleKeys.length; i++) {
  44245. var key = styleKeys[i];
  44246. if (animationStyleProps[key]) {
  44247. var elVal = fromElStyle[key];
  44248. transFromStyleProps[key] = elVal;
  44249. }
  44250. }
  44251. }
  44252. }
  44253. }
  44254. }
  44255. function isNonStyleTransitionEnabled(optVal, elVal) {
  44256. // The same as `checkNonStyleTansitionRefer`.
  44257. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  44258. }
  44259. var checkTransformPropRefer;
  44260. if ("development" !== 'production') {
  44261. checkTransformPropRefer = function (key, usedIn) {
  44262. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  44263. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  44264. }
  44265. };
  44266. }
  44267. var getStateToRestore = makeInner();
  44268. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  44269. /**
  44270. * Stop previous keyframe animation and restore the attributes.
  44271. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  44272. */
  44273. function stopPreviousKeyframeAnimationAndRestore(el) {
  44274. // Stop previous keyframe animation.
  44275. el.stopAnimation('keyframe'); // Restore
  44276. el.attr(getStateToRestore(el));
  44277. }
  44278. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  44279. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  44280. return;
  44281. }
  44282. if (isArray(animationOpts)) {
  44283. each(animationOpts, function (singleAnimationOpts) {
  44284. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  44285. });
  44286. return;
  44287. }
  44288. var keyframes = animationOpts.keyframes;
  44289. var duration = animationOpts.duration;
  44290. if (animatableModel && duration == null) {
  44291. // Default to use duration of config.
  44292. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  44293. var config = getAnimationConfig('enter', animatableModel, 0);
  44294. duration = config && config.duration;
  44295. }
  44296. if (!keyframes || !duration) {
  44297. return;
  44298. }
  44299. var stateToRestore = getStateToRestore(el);
  44300. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  44301. if (targetPropName && !el[targetPropName]) {
  44302. return;
  44303. }
  44304. var animator;
  44305. var endFrameIsSet = false; // Sort keyframes by percent.
  44306. keyframes.sort(function (a, b) {
  44307. return a.percent - b.percent;
  44308. });
  44309. each(keyframes, function (kf) {
  44310. // Stop current animation.
  44311. var animators = el.animators;
  44312. var kfValues = targetPropName ? kf[targetPropName] : kf;
  44313. if ("development" !== 'production') {
  44314. if (kf.percent >= 1) {
  44315. endFrameIsSet = true;
  44316. }
  44317. }
  44318. if (!kfValues) {
  44319. return;
  44320. }
  44321. var propKeys = keys(kfValues);
  44322. if (!targetPropName) {
  44323. // PENDING performance?
  44324. propKeys = filter(propKeys, function (key) {
  44325. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  44326. });
  44327. }
  44328. if (!propKeys.length) {
  44329. return;
  44330. }
  44331. if (!animator) {
  44332. animator = el.animate(targetPropName, animationOpts.loop, true);
  44333. animator.scope = 'keyframe';
  44334. }
  44335. for (var i = 0; i < animators.length; i++) {
  44336. // Stop all other animation that is not keyframe.
  44337. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  44338. animators[i].stopTracks(propKeys);
  44339. }
  44340. }
  44341. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  44342. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  44343. each(propKeys, function (key) {
  44344. // Save original value.
  44345. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  44346. });
  44347. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  44348. });
  44349. if (!animator) {
  44350. return;
  44351. }
  44352. if ("development" !== 'production') {
  44353. if (!endFrameIsSet) {
  44354. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  44355. }
  44356. }
  44357. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  44358. });
  44359. }
  44360. var nonShapeGraphicElements = {
  44361. // Reserved but not supported in graphic component.
  44362. path: null,
  44363. compoundPath: null,
  44364. // Supported in graphic component.
  44365. group: Group,
  44366. image: ZRImage,
  44367. text: ZRText
  44368. };
  44369. var inner$a = makeInner(); // ------------------------
  44370. // View
  44371. // ------------------------
  44372. var GraphicComponentView =
  44373. /** @class */
  44374. function (_super) {
  44375. __extends(GraphicComponentView, _super);
  44376. function GraphicComponentView() {
  44377. var _this = _super !== null && _super.apply(this, arguments) || this;
  44378. _this.type = GraphicComponentView.type;
  44379. return _this;
  44380. }
  44381. GraphicComponentView.prototype.init = function () {
  44382. this._elMap = createHashMap();
  44383. };
  44384. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  44385. // Having leveraged between use cases and algorithm complexity, a very
  44386. // simple layout mechanism is used:
  44387. // The size(width/height) can be determined by itself or its parent (not
  44388. // implemented yet), but can not by its children. (Top-down travel)
  44389. // The location(x/y) can be determined by the bounding rect of itself
  44390. // (can including its descendants or not) and the size of its parent.
  44391. // (Bottom-up travel)
  44392. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  44393. // view will be reused.
  44394. if (graphicModel !== this._lastGraphicModel) {
  44395. this._clear();
  44396. }
  44397. this._lastGraphicModel = graphicModel;
  44398. this._updateElements(graphicModel);
  44399. this._relocate(graphicModel, api);
  44400. };
  44401. /**
  44402. * Update graphic elements.
  44403. */
  44404. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  44405. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  44406. if (!elOptionsToUpdate) {
  44407. return;
  44408. }
  44409. var elMap = this._elMap;
  44410. var rootGroup = this.group;
  44411. var globalZ = graphicModel.get('z');
  44412. var globalZLevel = graphicModel.get('zlevel'); // Top-down tranverse to assign graphic settings to each elements.
  44413. each(elOptionsToUpdate, function (elOption) {
  44414. var id = convertOptionIdName(elOption.id, null);
  44415. var elExisting = id != null ? elMap.get(id) : null;
  44416. var parentId = convertOptionIdName(elOption.parentId, null);
  44417. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  44418. var elType = elOption.type;
  44419. var elOptionStyle = elOption.style;
  44420. if (elType === 'text' && elOptionStyle) {
  44421. // In top/bottom mode, textVerticalAlign should not be used, which cause
  44422. // inaccurately locating.
  44423. if (elOption.hv && elOption.hv[1]) {
  44424. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  44425. }
  44426. }
  44427. var textContentOption = elOption.textContent;
  44428. var textConfig = elOption.textConfig;
  44429. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  44430. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  44431. if (!textConfig && convertResult.textConfig) {
  44432. textConfig = elOption.textConfig = convertResult.textConfig;
  44433. }
  44434. if (!textContentOption && convertResult.textContent) {
  44435. textContentOption = convertResult.textContent;
  44436. }
  44437. } // Remove unnecessary props to avoid potential problems.
  44438. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  44439. if ("development" !== 'production') {
  44440. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  44441. }
  44442. var $action = elOption.$action || 'merge';
  44443. var isMerge = $action === 'merge';
  44444. var isReplace = $action === 'replace';
  44445. if (isMerge) {
  44446. var isInit = !elExisting;
  44447. var el_1 = elExisting;
  44448. if (isInit) {
  44449. el_1 = createEl(id, targetElParent, elOption.type, elMap);
  44450. } else {
  44451. el_1 && (inner$a(el_1).isNew = false); // Stop and restore before update any other attributes.
  44452. stopPreviousKeyframeAnimationAndRestore(el_1);
  44453. }
  44454. if (el_1) {
  44455. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  44456. isInit: isInit
  44457. });
  44458. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  44459. }
  44460. } else if (isReplace) {
  44461. removeEl(elExisting, elOption, elMap, graphicModel);
  44462. var el_2 = createEl(id, targetElParent, elOption.type, elMap);
  44463. if (el_2) {
  44464. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  44465. isInit: true
  44466. });
  44467. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  44468. }
  44469. } else if ($action === 'remove') {
  44470. updateLeaveTo(elExisting, elOption);
  44471. removeEl(elExisting, elOption, elMap, graphicModel);
  44472. }
  44473. var el = elMap.get(id);
  44474. if (el && textContentOption) {
  44475. if (isMerge) {
  44476. var textContentExisting = el.getTextContent();
  44477. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  44478. } else if (isReplace) {
  44479. el.setTextContent(new ZRText(textContentOption));
  44480. }
  44481. }
  44482. if (el) {
  44483. var clipPathOption = elOption.clipPath;
  44484. if (clipPathOption) {
  44485. var clipPathType = clipPathOption.type;
  44486. var clipPath = void 0;
  44487. var isInit = false;
  44488. if (isMerge) {
  44489. var oldClipPath = el.getClipPath();
  44490. isInit = !oldClipPath || inner$a(oldClipPath).type !== clipPathType;
  44491. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  44492. } else if (isReplace) {
  44493. isInit = true;
  44494. clipPath = newEl(clipPathType);
  44495. }
  44496. el.setClipPath(clipPath);
  44497. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  44498. isInit: isInit
  44499. });
  44500. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  44501. }
  44502. var elInner = inner$a(el);
  44503. el.setTextConfig(textConfig);
  44504. elInner.option = elOption;
  44505. setEventData(el, graphicModel, elOption);
  44506. setTooltipConfig({
  44507. el: el,
  44508. componentModel: graphicModel,
  44509. itemName: el.name,
  44510. itemTooltipOption: elOption.tooltip
  44511. });
  44512. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  44513. }
  44514. });
  44515. };
  44516. /**
  44517. * Locate graphic elements.
  44518. */
  44519. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  44520. var elOptions = graphicModel.option.elements;
  44521. var rootGroup = this.group;
  44522. var elMap = this._elMap;
  44523. var apiWidth = api.getWidth();
  44524. var apiHeight = api.getHeight();
  44525. var xy = ['x', 'y']; // Top-down to calculate percentage width/height of group
  44526. for (var i = 0; i < elOptions.length; i++) {
  44527. var elOption = elOptions[i];
  44528. var id = convertOptionIdName(elOption.id, null);
  44529. var el = id != null ? elMap.get(id) : null;
  44530. if (!el || !el.isGroup) {
  44531. continue;
  44532. }
  44533. var parentEl = el.parent;
  44534. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  44535. var elInner = inner$a(el);
  44536. var parentElInner = inner$a(parentEl);
  44537. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  44538. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  44539. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  44540. for (var i = elOptions.length - 1; i >= 0; i--) {
  44541. var elOption = elOptions[i];
  44542. var id = convertOptionIdName(elOption.id, null);
  44543. var el = id != null ? elMap.get(id) : null;
  44544. if (!el) {
  44545. continue;
  44546. }
  44547. var parentEl = el.parent;
  44548. var parentElInner = inner$a(parentEl);
  44549. var containerInfo = parentEl === rootGroup ? {
  44550. width: apiWidth,
  44551. height: apiHeight
  44552. } : {
  44553. width: parentElInner.width,
  44554. height: parentElInner.height
  44555. }; // PENDING
  44556. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  44557. // does not include the rect of [0, 0, group.width, group.height], which
  44558. // is probably weird for users. Should we make a break change for it?
  44559. var layoutPos = {};
  44560. var layouted = positionElement(el, elOption, containerInfo, null, {
  44561. hv: elOption.hv,
  44562. boundingMode: elOption.bounding
  44563. }, layoutPos);
  44564. if (!inner$a(el).isNew && layouted) {
  44565. var transition = elOption.transition;
  44566. var animatePos = {};
  44567. for (var k = 0; k < xy.length; k++) {
  44568. var key = xy[k];
  44569. var val = layoutPos[key];
  44570. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  44571. animatePos[key] = val;
  44572. } else {
  44573. el[key] = val;
  44574. }
  44575. }
  44576. updateProps(el, animatePos, graphicModel, 0);
  44577. } else {
  44578. el.attr(layoutPos);
  44579. }
  44580. }
  44581. };
  44582. /**
  44583. * Clear all elements.
  44584. */
  44585. GraphicComponentView.prototype._clear = function () {
  44586. var _this = this;
  44587. var elMap = this._elMap;
  44588. elMap.each(function (el) {
  44589. removeEl(el, inner$a(el).option, elMap, _this._lastGraphicModel);
  44590. });
  44591. this._elMap = createHashMap();
  44592. };
  44593. GraphicComponentView.prototype.dispose = function () {
  44594. this._clear();
  44595. };
  44596. GraphicComponentView.type = 'graphic';
  44597. return GraphicComponentView;
  44598. }(ComponentView);
  44599. function newEl(graphicType) {
  44600. if ("development" !== 'production') {
  44601. assert(graphicType, 'graphic type MUST be set');
  44602. }
  44603. var Clz = hasOwn(nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  44604. // overwritten by users, so do them first.
  44605. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  44606. if ("development" !== 'production') {
  44607. assert(Clz, "graphic type " + graphicType + " can not be found");
  44608. }
  44609. var el = new Clz({});
  44610. inner$a(el).type = graphicType;
  44611. return el;
  44612. }
  44613. function createEl(id, targetElParent, graphicType, elMap) {
  44614. var el = newEl(graphicType);
  44615. targetElParent.add(el);
  44616. elMap.set(id, el);
  44617. inner$a(el).id = id;
  44618. inner$a(el).isNew = true;
  44619. return el;
  44620. }
  44621. function removeEl(elExisting, elOption, elMap, graphicModel) {
  44622. var existElParent = elExisting && elExisting.parent;
  44623. if (existElParent) {
  44624. elExisting.type === 'group' && elExisting.traverse(function (el) {
  44625. removeEl(el, elOption, elMap, graphicModel);
  44626. });
  44627. applyLeaveTransition(elExisting, elOption, graphicModel);
  44628. elMap.removeKey(inner$a(elExisting).id);
  44629. }
  44630. }
  44631. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  44632. if (!el.isGroup) {
  44633. var elDisplayable = el;
  44634. elDisplayable.cursor = retrieve2(elOption.cursor, Displayable.prototype.cursor); // We should not support configure z and zlevel in the element level.
  44635. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  44636. elDisplayable.z = retrieve2(elOption.z, defaultZ || 0);
  44637. elDisplayable.zlevel = retrieve2(elOption.zlevel, defaultZlevel || 0); // z2 must not be null/undefined, otherwise sort error may occur.
  44638. var optZ2 = elOption.z2;
  44639. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  44640. }
  44641. each(keys(elOption), function (key) {
  44642. var val = elOption[key]; // Assign event handlers.
  44643. // PENDING: should enumerate all event names or use pattern matching?
  44644. if (key.indexOf('on') === 0 && isFunction(val)) {
  44645. el[key] = val;
  44646. }
  44647. });
  44648. el.draggable = elOption.draggable; // Other attributes
  44649. elOption.name != null && (el.name = elOption.name);
  44650. elOption.id != null && (el.id = elOption.id);
  44651. } // Remove unnecessary props to avoid potential problems.
  44652. function getCleanedElOption(elOption) {
  44653. elOption = extend({}, elOption);
  44654. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  44655. delete elOption[name];
  44656. });
  44657. return elOption;
  44658. }
  44659. function setEventData(el, graphicModel, elOption) {
  44660. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  44661. if (!el.silent && !el.ignore && !eventData) {
  44662. eventData = getECData(el).eventData = {
  44663. componentType: 'graphic',
  44664. componentIndex: graphicModel.componentIndex,
  44665. name: el.name
  44666. };
  44667. } // `elOption.info` enables user to mount some info on
  44668. // elements and use them in event handlers.
  44669. if (eventData) {
  44670. eventData.info = elOption.info;
  44671. }
  44672. }
  44673. function install$9(registers) {
  44674. registers.registerComponentModel(GraphicComponentModel);
  44675. registers.registerComponentView(GraphicComponentView);
  44676. registers.registerPreprocessor(function (option) {
  44677. var graphicOption = option.graphic; // Convert
  44678. // {graphic: [{left: 10, type: 'circle'}, ...]}
  44679. // or
  44680. // {graphic: {left: 10, type: 'circle'}}
  44681. // to
  44682. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  44683. if (isArray(graphicOption)) {
  44684. if (!graphicOption[0] || !graphicOption[0].elements) {
  44685. option.graphic = [{
  44686. elements: graphicOption
  44687. }];
  44688. } else {
  44689. // Only one graphic instance can be instantiated. (We dont
  44690. // want that too many views are created in echarts._viewMap)
  44691. option.graphic = [option.graphic[0]];
  44692. }
  44693. } else if (graphicOption && !graphicOption.elements) {
  44694. option.graphic = [{
  44695. elements: [graphicOption]
  44696. }];
  44697. }
  44698. });
  44699. }
  44700. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  44701. // FIXME: polar has been broken (but rarely used).
  44702. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  44703. function isCoordSupported(seriesModel) {
  44704. var coordType = seriesModel.get('coordinateSystem');
  44705. return indexOf(SERIES_COORDS, coordType) >= 0;
  44706. }
  44707. function getAxisMainType(axisDim) {
  44708. if ("development" !== 'production') {
  44709. assert(axisDim);
  44710. }
  44711. return axisDim + 'Axis';
  44712. }
  44713. /**
  44714. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  44715. * This function finds all linked dataZoomModels start from the given payload.
  44716. */
  44717. function findEffectedDataZooms(ecModel, payload) {
  44718. // Key: `DataZoomAxisDimension`
  44719. var axisRecords = createHashMap();
  44720. var effectedModels = []; // Key: uid of dataZoomModel
  44721. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  44722. ecModel.eachComponent({
  44723. mainType: 'dataZoom',
  44724. query: payload
  44725. }, function (dataZoomModel) {
  44726. if (!effectedModelMap.get(dataZoomModel.uid)) {
  44727. addToEffected(dataZoomModel);
  44728. }
  44729. }); // Start from the given dataZoomModels, travel the graph to find
  44730. // all of the linked dataZoom models.
  44731. var foundNewLink;
  44732. do {
  44733. foundNewLink = false;
  44734. ecModel.eachComponent('dataZoom', processSingle);
  44735. } while (foundNewLink);
  44736. function processSingle(dataZoomModel) {
  44737. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  44738. addToEffected(dataZoomModel);
  44739. foundNewLink = true;
  44740. }
  44741. }
  44742. function addToEffected(dataZoom) {
  44743. effectedModelMap.set(dataZoom.uid, true);
  44744. effectedModels.push(dataZoom);
  44745. markAxisControlled(dataZoom);
  44746. }
  44747. function isLinked(dataZoomModel) {
  44748. var isLink = false;
  44749. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  44750. var axisIdxArr = axisRecords.get(axisDim);
  44751. if (axisIdxArr && axisIdxArr[axisIndex]) {
  44752. isLink = true;
  44753. }
  44754. });
  44755. return isLink;
  44756. }
  44757. function markAxisControlled(dataZoomModel) {
  44758. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  44759. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  44760. });
  44761. }
  44762. return effectedModels;
  44763. }
  44764. /**
  44765. * Find the first target coordinate system.
  44766. * Available after model built.
  44767. *
  44768. * @return Like {
  44769. * grid: [
  44770. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  44771. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  44772. * ...
  44773. * ], // cartesians must not be null/undefined.
  44774. * polar: [
  44775. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  44776. * ...
  44777. * ], // polars must not be null/undefined.
  44778. * singleAxis: [
  44779. * {model: coord0, axisModels: [], coordIndex: 0}
  44780. * ]
  44781. * }
  44782. */
  44783. function collectReferCoordSysModelInfo(dataZoomModel) {
  44784. var ecModel = dataZoomModel.ecModel;
  44785. var coordSysInfoWrap = {
  44786. infoList: [],
  44787. infoMap: createHashMap()
  44788. };
  44789. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  44790. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  44791. if (!axisModel) {
  44792. return;
  44793. }
  44794. var coordSysModel = axisModel.getCoordSysModel();
  44795. if (!coordSysModel) {
  44796. return;
  44797. }
  44798. var coordSysUid = coordSysModel.uid;
  44799. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  44800. if (!coordSysInfo) {
  44801. coordSysInfo = {
  44802. model: coordSysModel,
  44803. axisModels: []
  44804. };
  44805. coordSysInfoWrap.infoList.push(coordSysInfo);
  44806. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  44807. }
  44808. coordSysInfo.axisModels.push(axisModel);
  44809. });
  44810. return coordSysInfoWrap;
  44811. }
  44812. var DataZoomAxisInfo =
  44813. /** @class */
  44814. function () {
  44815. function DataZoomAxisInfo() {
  44816. this.indexList = [];
  44817. this.indexMap = [];
  44818. }
  44819. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  44820. // Remove duplication.
  44821. if (!this.indexMap[axisCmptIdx]) {
  44822. this.indexList.push(axisCmptIdx);
  44823. this.indexMap[axisCmptIdx] = true;
  44824. }
  44825. };
  44826. return DataZoomAxisInfo;
  44827. }();
  44828. var DataZoomModel =
  44829. /** @class */
  44830. function (_super) {
  44831. __extends(DataZoomModel, _super);
  44832. function DataZoomModel() {
  44833. var _this = _super !== null && _super.apply(this, arguments) || this;
  44834. _this.type = DataZoomModel.type;
  44835. _this._autoThrottle = true;
  44836. _this._noTarget = true;
  44837. /**
  44838. * It is `[rangeModeForMin, rangeModeForMax]`.
  44839. * The optional values for `rangeMode`:
  44840. * + `'value'` mode: the axis extent will always be determined by
  44841. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  44842. * how data like and how `axis.min` and `axis.max` are.
  44843. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  44844. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  44845. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  44846. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  44847. *
  44848. * For example, when users are using dynamic data (update data periodically via `setOption`),
  44849. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  44850. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  44851. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  44852. */
  44853. _this._rangePropMode = ['percent', 'percent'];
  44854. return _this;
  44855. }
  44856. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  44857. var inputRawOption = retrieveRawOption(option);
  44858. /**
  44859. * Suppose a "main process" start at the point that model prepared (that is,
  44860. * model initialized or merged or method called in `action`).
  44861. * We should keep the `main process` idempotent, that is, given a set of values
  44862. * on `option`, we get the same result.
  44863. *
  44864. * But sometimes, values on `option` will be updated for providing users
  44865. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  44866. * should not be the base/input of the `main process`.
  44867. *
  44868. * So in that case we should save and keep the input of the `main process`
  44869. * separately, called `settledOption`.
  44870. *
  44871. * For example, consider the case:
  44872. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  44873. * where the original input `option.startValue`, `option.endValue` are earsed by
  44874. * calculated value.
  44875. * (Step)2) click the legend to hide and show a series,
  44876. * where the new range is calculated by the earsed `startValue` and `endValue`,
  44877. * which brings incorrect result.
  44878. */
  44879. this.settledOption = inputRawOption;
  44880. this.mergeDefaultAndTheme(option, ecModel);
  44881. this._doInit(inputRawOption);
  44882. };
  44883. DataZoomModel.prototype.mergeOption = function (newOption) {
  44884. var inputRawOption = retrieveRawOption(newOption); //FIX #2591
  44885. merge(this.option, newOption, true);
  44886. merge(this.settledOption, inputRawOption, true);
  44887. this._doInit(inputRawOption);
  44888. };
  44889. DataZoomModel.prototype._doInit = function (inputRawOption) {
  44890. var thisOption = this.option;
  44891. this._setDefaultThrottle(inputRawOption);
  44892. this._updateRangeUse(inputRawOption);
  44893. var settledOption = this.settledOption;
  44894. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  44895. // start/end has higher priority over startValue/endValue if they
  44896. // both set, but we should make chart.setOption({endValue: 1000})
  44897. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  44898. if (this._rangePropMode[index] === 'value') {
  44899. thisOption[names[0]] = settledOption[names[0]] = null;
  44900. } // Otherwise do nothing and use the merge result.
  44901. }, this);
  44902. this._resetTarget();
  44903. };
  44904. DataZoomModel.prototype._resetTarget = function () {
  44905. var optionOrient = this.get('orient', true);
  44906. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  44907. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  44908. if (hasAxisSpecified) {
  44909. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  44910. } else {
  44911. this._orient = optionOrient || 'horizontal';
  44912. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  44913. }
  44914. this._noTarget = true;
  44915. targetAxisIndexMap.each(function (axisInfo) {
  44916. if (axisInfo.indexList.length) {
  44917. this._noTarget = false;
  44918. }
  44919. }, this);
  44920. };
  44921. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  44922. var hasAxisSpecified = false;
  44923. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  44924. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  44925. // but do not want use auto mode. Because empty array may be encountered when
  44926. // some error occured.
  44927. if (!refering.specified) {
  44928. return;
  44929. }
  44930. hasAxisSpecified = true;
  44931. var axisInfo = new DataZoomAxisInfo();
  44932. each(refering.models, function (axisModel) {
  44933. axisInfo.add(axisModel.componentIndex);
  44934. });
  44935. targetAxisIndexMap.set(axisDim, axisInfo);
  44936. }, this);
  44937. return hasAxisSpecified;
  44938. };
  44939. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  44940. var ecModel = this.ecModel;
  44941. var needAuto = true; // Find axis that parallel to dataZoom as default.
  44942. if (needAuto) {
  44943. var axisDim = orient === 'vertical' ? 'y' : 'x';
  44944. var axisModels = ecModel.findComponents({
  44945. mainType: axisDim + 'Axis'
  44946. });
  44947. setParallelAxis(axisModels, axisDim);
  44948. } // Find axis that parallel to dataZoom as default.
  44949. if (needAuto) {
  44950. var axisModels = ecModel.findComponents({
  44951. mainType: 'singleAxis',
  44952. filter: function (axisModel) {
  44953. return axisModel.get('orient', true) === orient;
  44954. }
  44955. });
  44956. setParallelAxis(axisModels, 'single');
  44957. }
  44958. function setParallelAxis(axisModels, axisDim) {
  44959. // At least use the first parallel axis as the target axis.
  44960. var axisModel = axisModels[0];
  44961. if (!axisModel) {
  44962. return;
  44963. }
  44964. var axisInfo = new DataZoomAxisInfo();
  44965. axisInfo.add(axisModel.componentIndex);
  44966. targetAxisIndexMap.set(axisDim, axisInfo);
  44967. needAuto = false; // Find parallel axes in the same grid.
  44968. if (axisDim === 'x' || axisDim === 'y') {
  44969. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  44970. gridModel_1 && each(axisModels, function (axModel) {
  44971. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  44972. axisInfo.add(axModel.componentIndex);
  44973. }
  44974. });
  44975. }
  44976. }
  44977. if (needAuto) {
  44978. // If no parallel axis, find the first category axis as default. (Also consider polar).
  44979. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  44980. if (!needAuto) {
  44981. return;
  44982. }
  44983. var axisModels = ecModel.findComponents({
  44984. mainType: getAxisMainType(axisDim),
  44985. filter: function (axisModel) {
  44986. return axisModel.get('type', true) === 'category';
  44987. }
  44988. });
  44989. if (axisModels[0]) {
  44990. var axisInfo = new DataZoomAxisInfo();
  44991. axisInfo.add(axisModels[0].componentIndex);
  44992. targetAxisIndexMap.set(axisDim, axisInfo);
  44993. needAuto = false;
  44994. }
  44995. }, this);
  44996. }
  44997. };
  44998. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  44999. var dim; // Find the first axis
  45000. this.eachTargetAxis(function (axisDim) {
  45001. !dim && (dim = axisDim);
  45002. }, this);
  45003. return dim === 'y' ? 'vertical' : 'horizontal';
  45004. };
  45005. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  45006. // When first time user set throttle, auto throttle ends.
  45007. if (inputRawOption.hasOwnProperty('throttle')) {
  45008. this._autoThrottle = false;
  45009. }
  45010. if (this._autoThrottle) {
  45011. var globalOption = this.ecModel.option;
  45012. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  45013. }
  45014. };
  45015. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  45016. var rangePropMode = this._rangePropMode;
  45017. var rangeModeInOption = this.get('rangeMode');
  45018. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  45019. var percentSpecified = inputRawOption[names[0]] != null;
  45020. var valueSpecified = inputRawOption[names[1]] != null;
  45021. if (percentSpecified && !valueSpecified) {
  45022. rangePropMode[index] = 'percent';
  45023. } else if (!percentSpecified && valueSpecified) {
  45024. rangePropMode[index] = 'value';
  45025. } else if (rangeModeInOption) {
  45026. rangePropMode[index] = rangeModeInOption[index];
  45027. } else if (percentSpecified) {
  45028. // percentSpecified && valueSpecified
  45029. rangePropMode[index] = 'percent';
  45030. } // else remain its original setting.
  45031. });
  45032. };
  45033. DataZoomModel.prototype.noTarget = function () {
  45034. return this._noTarget;
  45035. };
  45036. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  45037. var firstAxisModel;
  45038. this.eachTargetAxis(function (axisDim, axisIndex) {
  45039. if (firstAxisModel == null) {
  45040. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45041. }
  45042. }, this);
  45043. return firstAxisModel;
  45044. };
  45045. /**
  45046. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  45047. */
  45048. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  45049. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  45050. each(axisInfo.indexList, function (axisIndex) {
  45051. callback.call(context, axisDim, axisIndex);
  45052. });
  45053. });
  45054. };
  45055. /**
  45056. * @return If not found, return null/undefined.
  45057. */
  45058. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  45059. var axisModel = this.getAxisModel(axisDim, axisIndex);
  45060. if (axisModel) {
  45061. return axisModel.__dzAxisProxy;
  45062. }
  45063. };
  45064. /**
  45065. * @return If not found, return null/undefined.
  45066. */
  45067. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  45068. if ("development" !== 'production') {
  45069. assert(axisDim && axisIndex != null);
  45070. }
  45071. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  45072. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  45073. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45074. }
  45075. };
  45076. /**
  45077. * If not specified, set to undefined.
  45078. */
  45079. DataZoomModel.prototype.setRawRange = function (opt) {
  45080. var thisOption = this.option;
  45081. var settledOption = this.settledOption;
  45082. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  45083. // Consider the pair <start, startValue>:
  45084. // If one has value and the other one is `null/undefined`, we both set them
  45085. // to `settledOption`. This strategy enables the feature to clear the original
  45086. // value in `settledOption` to `null/undefined`.
  45087. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  45088. // and keep `settledOption` with the original value. This strategy enables users to
  45089. // only set <end or endValue> but not set <start or startValue> when calling
  45090. // `dispatchAction`.
  45091. // The pair <end, endValue> is treated in the same way.
  45092. if (opt[names[0]] != null || opt[names[1]] != null) {
  45093. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  45094. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  45095. }
  45096. }, this);
  45097. this._updateRangeUse(opt);
  45098. };
  45099. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  45100. var option = this.option;
  45101. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  45102. option[name] = opt[name];
  45103. });
  45104. };
  45105. DataZoomModel.prototype.getPercentRange = function () {
  45106. var axisProxy = this.findRepresentativeAxisProxy();
  45107. if (axisProxy) {
  45108. return axisProxy.getDataPercentWindow();
  45109. }
  45110. };
  45111. /**
  45112. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  45113. *
  45114. * @return [startValue, endValue] value can only be '-' or finite number.
  45115. */
  45116. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  45117. if (axisDim == null && axisIndex == null) {
  45118. var axisProxy = this.findRepresentativeAxisProxy();
  45119. if (axisProxy) {
  45120. return axisProxy.getDataValueWindow();
  45121. }
  45122. } else {
  45123. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  45124. }
  45125. };
  45126. /**
  45127. * @param axisModel If axisModel given, find axisProxy
  45128. * corresponding to the axisModel
  45129. */
  45130. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  45131. if (axisModel) {
  45132. return axisModel.__dzAxisProxy;
  45133. } // Find the first hosted axisProxy
  45134. var firstProxy;
  45135. var axisDimList = this._targetAxisInfoMap.keys();
  45136. for (var i = 0; i < axisDimList.length; i++) {
  45137. var axisDim = axisDimList[i];
  45138. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  45139. for (var j = 0; j < axisInfo.indexList.length; j++) {
  45140. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  45141. if (proxy.hostedBy(this)) {
  45142. return proxy;
  45143. }
  45144. if (!firstProxy) {
  45145. firstProxy = proxy;
  45146. }
  45147. }
  45148. } // If no hosted proxy found, still need to return a proxy.
  45149. // This case always happens in toolbox dataZoom, where axes are all hosted by
  45150. // other dataZooms.
  45151. return firstProxy;
  45152. };
  45153. DataZoomModel.prototype.getRangePropMode = function () {
  45154. return this._rangePropMode.slice();
  45155. };
  45156. DataZoomModel.prototype.getOrient = function () {
  45157. if ("development" !== 'production') {
  45158. // Should not be called before initialized.
  45159. assert(this._orient);
  45160. }
  45161. return this._orient;
  45162. };
  45163. DataZoomModel.type = 'dataZoom';
  45164. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  45165. DataZoomModel.defaultOption = {
  45166. // zlevel: 0,
  45167. z: 4,
  45168. filterMode: 'filter',
  45169. start: 0,
  45170. end: 100
  45171. };
  45172. return DataZoomModel;
  45173. }(ComponentModel);
  45174. /**
  45175. * Retrieve the those raw params from option, which will be cached separately.
  45176. * becasue they will be overwritten by normalized/calculated values in the main
  45177. * process.
  45178. */
  45179. function retrieveRawOption(option) {
  45180. var ret = {};
  45181. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  45182. option.hasOwnProperty(name) && (ret[name] = option[name]);
  45183. });
  45184. return ret;
  45185. }
  45186. var SelectDataZoomModel =
  45187. /** @class */
  45188. function (_super) {
  45189. __extends(SelectDataZoomModel, _super);
  45190. function SelectDataZoomModel() {
  45191. var _this = _super !== null && _super.apply(this, arguments) || this;
  45192. _this.type = SelectDataZoomModel.type;
  45193. return _this;
  45194. }
  45195. SelectDataZoomModel.type = 'dataZoom.select';
  45196. return SelectDataZoomModel;
  45197. }(DataZoomModel);
  45198. var DataZoomView =
  45199. /** @class */
  45200. function (_super) {
  45201. __extends(DataZoomView, _super);
  45202. function DataZoomView() {
  45203. var _this = _super !== null && _super.apply(this, arguments) || this;
  45204. _this.type = DataZoomView.type;
  45205. return _this;
  45206. }
  45207. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  45208. this.dataZoomModel = dataZoomModel;
  45209. this.ecModel = ecModel;
  45210. this.api = api;
  45211. };
  45212. DataZoomView.type = 'dataZoom';
  45213. return DataZoomView;
  45214. }(ComponentView);
  45215. var SelectDataZoomView =
  45216. /** @class */
  45217. function (_super) {
  45218. __extends(SelectDataZoomView, _super);
  45219. function SelectDataZoomView() {
  45220. var _this = _super !== null && _super.apply(this, arguments) || this;
  45221. _this.type = SelectDataZoomView.type;
  45222. return _this;
  45223. }
  45224. SelectDataZoomView.type = 'dataZoom.select';
  45225. return SelectDataZoomView;
  45226. }(DataZoomView);
  45227. /*
  45228. * Licensed to the Apache Software Foundation (ASF) under one
  45229. * or more contributor license agreements. See the NOTICE file
  45230. * distributed with this work for additional information
  45231. * regarding copyright ownership. The ASF licenses this file
  45232. * to you under the Apache License, Version 2.0 (the
  45233. * "License"); you may not use this file except in compliance
  45234. * with the License. You may obtain a copy of the License at
  45235. *
  45236. * http://www.apache.org/licenses/LICENSE-2.0
  45237. *
  45238. * Unless required by applicable law or agreed to in writing,
  45239. * software distributed under the License is distributed on an
  45240. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45241. * KIND, either express or implied. See the License for the
  45242. * specific language governing permissions and limitations
  45243. * under the License.
  45244. */
  45245. /**
  45246. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45247. */
  45248. /*
  45249. * Licensed to the Apache Software Foundation (ASF) under one
  45250. * or more contributor license agreements. See the NOTICE file
  45251. * distributed with this work for additional information
  45252. * regarding copyright ownership. The ASF licenses this file
  45253. * to you under the Apache License, Version 2.0 (the
  45254. * "License"); you may not use this file except in compliance
  45255. * with the License. You may obtain a copy of the License at
  45256. *
  45257. * http://www.apache.org/licenses/LICENSE-2.0
  45258. *
  45259. * Unless required by applicable law or agreed to in writing,
  45260. * software distributed under the License is distributed on an
  45261. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45262. * KIND, either express or implied. See the License for the
  45263. * specific language governing permissions and limitations
  45264. * under the License.
  45265. */
  45266. /**
  45267. * Calculate slider move result.
  45268. * Usage:
  45269. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  45270. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  45271. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  45272. *
  45273. * @param delta Move length.
  45274. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  45275. * handleEnds will be modified in this method.
  45276. * @param extent handleEnds is restricted by extent.
  45277. * extent[0] should less or equals than extent[1].
  45278. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  45279. * @param minSpan The range of dataZoom can not be smaller than that.
  45280. * If not set, handle0 and cross handle1. If set as a non-negative
  45281. * number (including `0`), handles will push each other when reaching
  45282. * the minSpan.
  45283. * @param maxSpan The range of dataZoom can not be larger than that.
  45284. * @return The input handleEnds.
  45285. */
  45286. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  45287. delta = delta || 0;
  45288. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  45289. if (minSpan != null) {
  45290. minSpan = restrict(minSpan, [0, extentSpan]);
  45291. }
  45292. if (maxSpan != null) {
  45293. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  45294. }
  45295. if (handleIndex === 'all') {
  45296. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  45297. handleSpan = restrict(handleSpan, [0, extentSpan]);
  45298. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  45299. handleIndex = 0;
  45300. }
  45301. handleEnds[0] = restrict(handleEnds[0], extent);
  45302. handleEnds[1] = restrict(handleEnds[1], extent);
  45303. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  45304. handleEnds[handleIndex] += delta; // Restrict in extent.
  45305. var extentMinSpan = minSpan || 0;
  45306. var realExtent = extent.slice();
  45307. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  45308. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  45309. var currDistSign;
  45310. currDistSign = getSpanSign(handleEnds, handleIndex);
  45311. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  45312. // If minSpan exists, 'cross' is forbidden.
  45313. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  45314. } // Shrink span.
  45315. currDistSign = getSpanSign(handleEnds, handleIndex);
  45316. if (maxSpan != null && currDistSign.span > maxSpan) {
  45317. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  45318. }
  45319. return handleEnds;
  45320. }
  45321. function getSpanSign(handleEnds, handleIndex) {
  45322. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  45323. // is at left of handleEnds[1] for non-cross case.
  45324. return {
  45325. span: Math.abs(dist),
  45326. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  45327. };
  45328. }
  45329. function restrict(value, extend) {
  45330. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  45331. }
  45332. var each$4 = each;
  45333. var asc$1 = asc;
  45334. /**
  45335. * Operate single axis.
  45336. * One axis can only operated by one axis operator.
  45337. * Different dataZoomModels may be defined to operate the same axis.
  45338. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  45339. * So dataZoomModels share one axisProxy in that case.
  45340. */
  45341. var AxisProxy =
  45342. /** @class */
  45343. function () {
  45344. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  45345. this._dimName = dimName;
  45346. this._axisIndex = axisIndex;
  45347. this.ecModel = ecModel;
  45348. this._dataZoomModel = dataZoomModel; // /**
  45349. // * @readOnly
  45350. // * @private
  45351. // */
  45352. // this.hasSeriesStacked;
  45353. }
  45354. /**
  45355. * Whether the axisProxy is hosted by dataZoomModel.
  45356. */
  45357. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  45358. return this._dataZoomModel === dataZoomModel;
  45359. };
  45360. /**
  45361. * @return Value can only be NaN or finite value.
  45362. */
  45363. AxisProxy.prototype.getDataValueWindow = function () {
  45364. return this._valueWindow.slice();
  45365. };
  45366. /**
  45367. * @return {Array.<number>}
  45368. */
  45369. AxisProxy.prototype.getDataPercentWindow = function () {
  45370. return this._percentWindow.slice();
  45371. };
  45372. AxisProxy.prototype.getTargetSeriesModels = function () {
  45373. var seriesModels = [];
  45374. this.ecModel.eachSeries(function (seriesModel) {
  45375. if (isCoordSupported(seriesModel)) {
  45376. var axisMainType = getAxisMainType(this._dimName);
  45377. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  45378. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  45379. seriesModels.push(seriesModel);
  45380. }
  45381. }
  45382. }, this);
  45383. return seriesModels;
  45384. };
  45385. AxisProxy.prototype.getAxisModel = function () {
  45386. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  45387. };
  45388. AxisProxy.prototype.getMinMaxSpan = function () {
  45389. return clone(this._minMaxSpan);
  45390. };
  45391. /**
  45392. * Only calculate by given range and this._dataExtent, do not change anything.
  45393. */
  45394. AxisProxy.prototype.calculateDataWindow = function (opt) {
  45395. var dataExtent = this._dataExtent;
  45396. var axisModel = this.getAxisModel();
  45397. var scale = axisModel.axis.scale;
  45398. var rangePropMode = this._dataZoomModel.getRangePropMode();
  45399. var percentExtent = [0, 100];
  45400. var percentWindow = [];
  45401. var valueWindow = [];
  45402. var hasPropModeValue;
  45403. each$4(['start', 'end'], function (prop, idx) {
  45404. var boundPercent = opt[prop];
  45405. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  45406. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  45407. // but not min/max of axis, which will be calculated by data window then).
  45408. // The former one is suitable for cases that a dataZoom component controls multiple
  45409. // axes with different unit or extent, and the latter one is suitable for accurate
  45410. // zoom by pixel (e.g., in dataZoomSelect).
  45411. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  45412. // only when setOption or dispatchAction, otherwise it remains its original value.
  45413. // (Why not only record `percentProp` and always map to `valueProp`? Because
  45414. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  45415. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  45416. // data extent. All of values that are overflow the `dataExtent` will be calculated
  45417. // to percent '100%').
  45418. if (rangePropMode[idx] === 'percent') {
  45419. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  45420. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  45421. } else {
  45422. hasPropModeValue = true;
  45423. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  45424. // This calculation can not be inversed, because all of values that
  45425. // are overflow the `dataExtent` will be calculated to percent '100%'
  45426. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  45427. } // valueWindow[idx] = round(boundValue);
  45428. // percentWindow[idx] = round(boundPercent);
  45429. valueWindow[idx] = boundValue;
  45430. percentWindow[idx] = boundPercent;
  45431. });
  45432. asc$1(valueWindow);
  45433. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  45434. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  45435. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  45436. // where API is able to initialize/modify the window size even though `zoomLock`
  45437. // specified.
  45438. var spans = this._minMaxSpan;
  45439. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  45440. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  45441. var suffix = toValue ? 'Span' : 'ValueSpan';
  45442. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  45443. for (var i = 0; i < 2; i++) {
  45444. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  45445. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  45446. }
  45447. }
  45448. return {
  45449. valueWindow: valueWindow,
  45450. percentWindow: percentWindow
  45451. };
  45452. };
  45453. /**
  45454. * Notice: reset should not be called before series.restoreData() called,
  45455. * so it is recommanded to be called in "process stage" but not "model init
  45456. * stage".
  45457. */
  45458. AxisProxy.prototype.reset = function (dataZoomModel) {
  45459. if (dataZoomModel !== this._dataZoomModel) {
  45460. return;
  45461. }
  45462. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  45463. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  45464. this._updateMinMaxSpan();
  45465. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  45466. this._valueWindow = dataWindow.valueWindow;
  45467. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  45468. this._setAxisModel();
  45469. };
  45470. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  45471. if (dataZoomModel !== this._dataZoomModel) {
  45472. return;
  45473. }
  45474. var axisDim = this._dimName;
  45475. var seriesModels = this.getTargetSeriesModels();
  45476. var filterMode = dataZoomModel.get('filterMode');
  45477. var valueWindow = this._valueWindow;
  45478. if (filterMode === 'none') {
  45479. return;
  45480. } // FIXME
  45481. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  45482. // with NaN data, NaN will be filtered and stack will be wrong.
  45483. // So we need to force the mode to be set empty.
  45484. // In fect, it is not a big deal that do not support filterMode-'filter'
  45485. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  45486. // selection" some day, which might need "adapt to data extent on the
  45487. // otherAxis", which is disabled by filterMode-'empty'.
  45488. // But currently, stack has been fixed to based on value but not index,
  45489. // so this is not an issue any more.
  45490. // let otherAxisModel = this.getOtherAxisModel();
  45491. // if (dataZoomModel.get('$fromToolbox')
  45492. // && otherAxisModel
  45493. // && otherAxisModel.hasSeriesStacked
  45494. // ) {
  45495. // filterMode = 'empty';
  45496. // }
  45497. // TODO
  45498. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  45499. each$4(seriesModels, function (seriesModel) {
  45500. var seriesData = seriesModel.getData();
  45501. var dataDims = seriesData.mapDimensionsAll(axisDim);
  45502. if (!dataDims.length) {
  45503. return;
  45504. }
  45505. if (filterMode === 'weakFilter') {
  45506. var store_1 = seriesData.getStore();
  45507. var dataDimIndices_1 = map(dataDims, function (dim) {
  45508. return seriesData.getDimensionIndex(dim);
  45509. }, seriesData);
  45510. seriesData.filterSelf(function (dataIndex) {
  45511. var leftOut;
  45512. var rightOut;
  45513. var hasValue;
  45514. for (var i = 0; i < dataDims.length; i++) {
  45515. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  45516. var thisHasValue = !isNaN(value);
  45517. var thisLeftOut = value < valueWindow[0];
  45518. var thisRightOut = value > valueWindow[1];
  45519. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  45520. return true;
  45521. }
  45522. thisHasValue && (hasValue = true);
  45523. thisLeftOut && (leftOut = true);
  45524. thisRightOut && (rightOut = true);
  45525. } // If both left out and right out, do not filter.
  45526. return hasValue && leftOut && rightOut;
  45527. });
  45528. } else {
  45529. each$4(dataDims, function (dim) {
  45530. if (filterMode === 'empty') {
  45531. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  45532. return !isInWindow(value) ? NaN : value;
  45533. }));
  45534. } else {
  45535. var range = {};
  45536. range[dim] = valueWindow; // console.time('select');
  45537. seriesData.selectRange(range); // console.timeEnd('select');
  45538. }
  45539. });
  45540. }
  45541. each$4(dataDims, function (dim) {
  45542. seriesData.setApproximateExtent(valueWindow, dim);
  45543. });
  45544. });
  45545. function isInWindow(value) {
  45546. return value >= valueWindow[0] && value <= valueWindow[1];
  45547. }
  45548. };
  45549. AxisProxy.prototype._updateMinMaxSpan = function () {
  45550. var minMaxSpan = this._minMaxSpan = {};
  45551. var dataZoomModel = this._dataZoomModel;
  45552. var dataExtent = this._dataExtent;
  45553. each$4(['min', 'max'], function (minMax) {
  45554. var percentSpan = dataZoomModel.get(minMax + 'Span');
  45555. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  45556. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  45557. if (valueSpan != null) {
  45558. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  45559. } else if (percentSpan != null) {
  45560. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  45561. }
  45562. minMaxSpan[minMax + 'Span'] = percentSpan;
  45563. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  45564. }, this);
  45565. };
  45566. AxisProxy.prototype._setAxisModel = function () {
  45567. var axisModel = this.getAxisModel();
  45568. var percentWindow = this._percentWindow;
  45569. var valueWindow = this._valueWindow;
  45570. if (!percentWindow) {
  45571. return;
  45572. } // [0, 500]: arbitrary value, guess axis extent.
  45573. var precision = getPixelPrecision(valueWindow, [0, 500]);
  45574. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  45575. // by series data, which may be a little different from the extent calculated by
  45576. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  45577. // little when zooming. So it will not be fixed until some users require it strongly.
  45578. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  45579. if (percentWindow[0] !== 0) {
  45580. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  45581. }
  45582. if (percentWindow[1] !== 100) {
  45583. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  45584. }
  45585. rawExtentInfo.freeze();
  45586. };
  45587. return AxisProxy;
  45588. }();
  45589. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  45590. var dataExtent = [Infinity, -Infinity];
  45591. each$4(seriesModels, function (seriesModel) {
  45592. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  45593. }); // It is important to get "consistent" extent when more then one axes is
  45594. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  45595. // when zooming. But it is difficult to know what is "consistent", considering
  45596. // axes have different type or even different meanings (For example, two
  45597. // time axes are used to compare data of the same date in different years).
  45598. // So basically dataZoom just obtains extent by series.data (in category axis
  45599. // extent can be obtained from axis.data).
  45600. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  45601. // consistent.
  45602. var axisModel = axisProxy.getAxisModel();
  45603. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  45604. return [rawExtentResult.min, rawExtentResult.max];
  45605. }
  45606. var dataZoomProcessor = {
  45607. // `dataZoomProcessor` will only be performed in needed series. Consider if
  45608. // there is a line series and a pie series, it is better not to update the
  45609. // line series if only pie series is needed to be updated.
  45610. getTargetSeries: function (ecModel) {
  45611. function eachAxisModel(cb) {
  45612. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45613. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45614. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  45615. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  45616. });
  45617. });
  45618. } // FIXME: it brings side-effect to `getTargetSeries`.
  45619. // Prepare axis proxies.
  45620. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  45621. // dispose all last axis proxy, in case that some axis are deleted.
  45622. axisModel.__dzAxisProxy = null;
  45623. });
  45624. var proxyList = [];
  45625. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  45626. // Different dataZooms may constrol the same axis. In that case,
  45627. // an axisProxy serves both of them.
  45628. if (!axisModel.__dzAxisProxy) {
  45629. // Use the first dataZoomModel as the main model of axisProxy.
  45630. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  45631. proxyList.push(axisModel.__dzAxisProxy);
  45632. }
  45633. });
  45634. var seriesModelMap = createHashMap();
  45635. each(proxyList, function (axisProxy) {
  45636. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  45637. seriesModelMap.set(seriesModel.uid, seriesModel);
  45638. });
  45639. });
  45640. return seriesModelMap;
  45641. },
  45642. // Consider appendData, where filter should be performed. Because data process is
  45643. // in block mode currently, it is not need to worry about that the overallProgress
  45644. // execute every frame.
  45645. overallReset: function (ecModel, api) {
  45646. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45647. // We calculate window and reset axis here but not in model
  45648. // init stage and not after action dispatch handler, because
  45649. // reset should be called after seriesData.restoreData.
  45650. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45651. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  45652. }); // Caution: data zoom filtering is order sensitive when using
  45653. // percent range and no min/max/scale set on axis.
  45654. // For example, we have dataZoom definition:
  45655. // [
  45656. // {xAxisIndex: 0, start: 30, end: 70},
  45657. // {yAxisIndex: 0, start: 20, end: 80}
  45658. // ]
  45659. // In this case, [20, 80] of y-dataZoom should be based on data
  45660. // that have filtered by x-dataZoom using range of [30, 70],
  45661. // but should not be based on full raw data. Thus sliding
  45662. // x-dataZoom will change both ranges of xAxis and yAxis,
  45663. // while sliding y-dataZoom will only change the range of yAxis.
  45664. // So we should filter x-axis after reset x-axis immediately,
  45665. // and then reset y-axis and filter y-axis.
  45666. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  45667. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  45668. });
  45669. });
  45670. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  45671. // Fullfill all of the range props so that user
  45672. // is able to get them from chart.getOption().
  45673. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  45674. if (axisProxy) {
  45675. var percentRange = axisProxy.getDataPercentWindow();
  45676. var valueRange = axisProxy.getDataValueWindow();
  45677. dataZoomModel.setCalculatedRange({
  45678. start: percentRange[0],
  45679. end: percentRange[1],
  45680. startValue: valueRange[0],
  45681. endValue: valueRange[1]
  45682. });
  45683. }
  45684. });
  45685. }
  45686. };
  45687. function installDataZoomAction(registers) {
  45688. registers.registerAction('dataZoom', function (payload, ecModel) {
  45689. var effectedModels = findEffectedDataZooms(ecModel, payload);
  45690. each(effectedModels, function (dataZoomModel) {
  45691. dataZoomModel.setRawRange({
  45692. start: payload.start,
  45693. end: payload.end,
  45694. startValue: payload.startValue,
  45695. endValue: payload.endValue
  45696. });
  45697. });
  45698. });
  45699. }
  45700. var installed = false;
  45701. function installCommon(registers) {
  45702. if (installed) {
  45703. return;
  45704. }
  45705. installed = true;
  45706. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  45707. installDataZoomAction(registers);
  45708. registers.registerSubTypeDefaulter('dataZoom', function () {
  45709. // Default 'slider' when no type specified.
  45710. return 'slider';
  45711. });
  45712. }
  45713. function install$a(registers) {
  45714. registers.registerComponentModel(SelectDataZoomModel);
  45715. registers.registerComponentView(SelectDataZoomView);
  45716. installCommon(registers);
  45717. }
  45718. /*
  45719. * Licensed to the Apache Software Foundation (ASF) under one
  45720. * or more contributor license agreements. See the NOTICE file
  45721. * distributed with this work for additional information
  45722. * regarding copyright ownership. The ASF licenses this file
  45723. * to you under the Apache License, Version 2.0 (the
  45724. * "License"); you may not use this file except in compliance
  45725. * with the License. You may obtain a copy of the License at
  45726. *
  45727. * http://www.apache.org/licenses/LICENSE-2.0
  45728. *
  45729. * Unless required by applicable law or agreed to in writing,
  45730. * software distributed under the License is distributed on an
  45731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45732. * KIND, either express or implied. See the License for the
  45733. * specific language governing permissions and limitations
  45734. * under the License.
  45735. */
  45736. /**
  45737. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45738. */
  45739. var ToolboxFeature =
  45740. /** @class */
  45741. function () {
  45742. function ToolboxFeature() {}
  45743. return ToolboxFeature;
  45744. }();
  45745. var features = {};
  45746. function registerFeature(name, ctor) {
  45747. features[name] = ctor;
  45748. }
  45749. function getFeature(name) {
  45750. return features[name];
  45751. }
  45752. var ToolboxModel =
  45753. /** @class */
  45754. function (_super) {
  45755. __extends(ToolboxModel, _super);
  45756. function ToolboxModel() {
  45757. var _this = _super !== null && _super.apply(this, arguments) || this;
  45758. _this.type = ToolboxModel.type;
  45759. return _this;
  45760. }
  45761. ToolboxModel.prototype.optionUpdated = function () {
  45762. _super.prototype.optionUpdated.apply(this, arguments);
  45763. var ecModel = this.ecModel;
  45764. each(this.option.feature, function (featureOpt, featureName) {
  45765. var Feature = getFeature(featureName);
  45766. if (Feature) {
  45767. if (Feature.getDefaultOption) {
  45768. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  45769. }
  45770. merge(featureOpt, Feature.defaultOption);
  45771. }
  45772. });
  45773. };
  45774. ToolboxModel.type = 'toolbox';
  45775. ToolboxModel.layoutMode = {
  45776. type: 'box',
  45777. ignoreSize: true
  45778. };
  45779. ToolboxModel.defaultOption = {
  45780. show: true,
  45781. z: 6,
  45782. // zlevel: 0,
  45783. orient: 'horizontal',
  45784. left: 'right',
  45785. top: 'top',
  45786. // right
  45787. // bottom
  45788. backgroundColor: 'transparent',
  45789. borderColor: '#ccc',
  45790. borderRadius: 0,
  45791. borderWidth: 0,
  45792. padding: 5,
  45793. itemSize: 15,
  45794. itemGap: 8,
  45795. showTitle: true,
  45796. iconStyle: {
  45797. borderColor: '#666',
  45798. color: 'none'
  45799. },
  45800. emphasis: {
  45801. iconStyle: {
  45802. borderColor: '#3E98C5'
  45803. }
  45804. },
  45805. // textStyle: {},
  45806. // feature
  45807. tooltip: {
  45808. show: false,
  45809. position: 'bottom'
  45810. }
  45811. };
  45812. return ToolboxModel;
  45813. }(ComponentModel);
  45814. /**
  45815. * Layout list like component.
  45816. * It will box layout each items in group of component and then position the whole group in the viewport
  45817. * @param {module:zrender/group/Group} group
  45818. * @param {module:echarts/model/Component} componentModel
  45819. * @param {module:echarts/ExtensionAPI}
  45820. */
  45821. function layout$2(group, componentModel, api) {
  45822. var boxLayoutParams = componentModel.getBoxLayoutParams();
  45823. var padding = componentModel.get('padding');
  45824. var viewportSize = {
  45825. width: api.getWidth(),
  45826. height: api.getHeight()
  45827. };
  45828. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  45829. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  45830. positionElement(group, boxLayoutParams, viewportSize, padding);
  45831. }
  45832. function makeBackground(rect, componentModel) {
  45833. var padding = normalizeCssArray$1(componentModel.get('padding'));
  45834. var style = componentModel.getItemStyle(['color', 'opacity']);
  45835. style.fill = componentModel.get('backgroundColor');
  45836. rect = new Rect({
  45837. shape: {
  45838. x: rect.x - padding[3],
  45839. y: rect.y - padding[0],
  45840. width: rect.width + padding[1] + padding[3],
  45841. height: rect.height + padding[0] + padding[2],
  45842. r: componentModel.get('borderRadius')
  45843. },
  45844. style: style,
  45845. silent: true,
  45846. z2: -1
  45847. }); // FIXME
  45848. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  45849. // and background rect when setting like `left: 0`, `top: 0`.
  45850. // graphic.subPixelOptimizeRect(rect);
  45851. return rect;
  45852. }
  45853. var ToolboxView =
  45854. /** @class */
  45855. function (_super) {
  45856. __extends(ToolboxView, _super);
  45857. function ToolboxView() {
  45858. return _super !== null && _super.apply(this, arguments) || this;
  45859. }
  45860. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  45861. var group = this.group;
  45862. group.removeAll();
  45863. if (!toolboxModel.get('show')) {
  45864. return;
  45865. }
  45866. var itemSize = +toolboxModel.get('itemSize');
  45867. var isVertical = toolboxModel.get('orient') === 'vertical';
  45868. var featureOpts = toolboxModel.get('feature') || {};
  45869. var features = this._features || (this._features = {});
  45870. var featureNames = [];
  45871. each(featureOpts, function (opt, name) {
  45872. featureNames.push(name);
  45873. });
  45874. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  45875. this._featureNames = featureNames;
  45876. function processFeature(newIndex, oldIndex) {
  45877. var featureName = featureNames[newIndex];
  45878. var oldName = featureNames[oldIndex];
  45879. var featureOpt = featureOpts[featureName];
  45880. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  45881. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  45882. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  45883. featureOpt.title = payload.newTitle;
  45884. }
  45885. if (featureName && !oldName) {
  45886. // Create
  45887. if (isUserFeatureName(featureName)) {
  45888. feature = {
  45889. onclick: featureModel.option.onclick,
  45890. featureName: featureName
  45891. };
  45892. } else {
  45893. var Feature = getFeature(featureName);
  45894. if (!Feature) {
  45895. return;
  45896. }
  45897. feature = new Feature();
  45898. }
  45899. features[featureName] = feature;
  45900. } else {
  45901. feature = features[oldName]; // If feature does not exsit.
  45902. if (!feature) {
  45903. return;
  45904. }
  45905. }
  45906. feature.uid = getUID('toolbox-feature');
  45907. feature.model = featureModel;
  45908. feature.ecModel = ecModel;
  45909. feature.api = api;
  45910. var isToolboxFeature = feature instanceof ToolboxFeature;
  45911. if (!featureName && oldName) {
  45912. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  45913. return;
  45914. }
  45915. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  45916. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  45917. return;
  45918. }
  45919. createIconPaths(featureModel, feature, featureName);
  45920. featureModel.setIconStatus = function (iconName, status) {
  45921. var option = this.option;
  45922. var iconPaths = this.iconPaths;
  45923. option.iconStatus = option.iconStatus || {};
  45924. option.iconStatus[iconName] = status;
  45925. if (iconPaths[iconName]) {
  45926. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  45927. }
  45928. };
  45929. if (feature instanceof ToolboxFeature) {
  45930. if (feature.render) {
  45931. feature.render(featureModel, ecModel, api, payload);
  45932. }
  45933. }
  45934. }
  45935. function createIconPaths(featureModel, feature, featureName) {
  45936. var iconStyleModel = featureModel.getModel('iconStyle');
  45937. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has mutiple icon. they are orginaized as
  45938. // {
  45939. // icon: {
  45940. // foo: '',
  45941. // bar: ''
  45942. // },
  45943. // title: {
  45944. // foo: '',
  45945. // bar: ''
  45946. // }
  45947. // }
  45948. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  45949. var titles = featureModel.get('title') || {};
  45950. var iconsMap;
  45951. var titlesMap;
  45952. if (isString(icons)) {
  45953. iconsMap = {};
  45954. iconsMap[featureName] = icons;
  45955. } else {
  45956. iconsMap = icons;
  45957. }
  45958. if (isString(titles)) {
  45959. titlesMap = {};
  45960. titlesMap[featureName] = titles;
  45961. } else {
  45962. titlesMap = titles;
  45963. }
  45964. var iconPaths = featureModel.iconPaths = {};
  45965. each(iconsMap, function (iconStr, iconName) {
  45966. var path = createIcon(iconStr, {}, {
  45967. x: -itemSize / 2,
  45968. y: -itemSize / 2,
  45969. width: itemSize,
  45970. height: itemSize
  45971. }); // TODO handling image
  45972. path.setStyle(iconStyleModel.getItemStyle());
  45973. var pathEmphasisState = path.ensureState('emphasis');
  45974. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  45975. var textContent = new ZRText({
  45976. style: {
  45977. text: titlesMap[iconName],
  45978. align: iconStyleEmphasisModel.get('textAlign'),
  45979. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  45980. padding: iconStyleEmphasisModel.get('textPadding'),
  45981. fill: null
  45982. },
  45983. ignore: true
  45984. });
  45985. path.setTextContent(textContent);
  45986. setTooltipConfig({
  45987. el: path,
  45988. componentModel: toolboxModel,
  45989. itemName: iconName,
  45990. formatterParamsExtra: {
  45991. title: titlesMap[iconName]
  45992. }
  45993. });
  45994. path.__title = titlesMap[iconName];
  45995. path.on('mouseover', function () {
  45996. // Should not reuse above hoverStyle, which might be modified.
  45997. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  45998. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  45999. textContent.setStyle({
  46000. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  46001. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  46002. });
  46003. path.setTextConfig({
  46004. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  46005. });
  46006. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  46007. // There are flags managed by the echarts.
  46008. api.enterEmphasis(this);
  46009. }).on('mouseout', function () {
  46010. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  46011. api.leaveEmphasis(this);
  46012. }
  46013. textContent.hide();
  46014. });
  46015. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  46016. group.add(path);
  46017. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  46018. iconPaths[iconName] = path;
  46019. });
  46020. }
  46021. layout$2(group, toolboxModel, api); // Render background after group is layout
  46022. // FIXME
  46023. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  46024. isVertical || group.eachChild(function (icon) {
  46025. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  46026. // TODO simplify code?
  46027. var emphasisState = icon.ensureState('emphasis');
  46028. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  46029. var textContent = icon.getTextContent();
  46030. var emphasisTextState = textContent && textContent.ensureState('emphasis'); // May be background element
  46031. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  46032. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  46033. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  46034. var offsetX = icon.x + group.x;
  46035. var offsetY = icon.y + group.y + itemSize;
  46036. var needPutOnTop = false;
  46037. if (offsetY + rect.height > api.getHeight()) {
  46038. emphasisTextConfig.position = 'top';
  46039. needPutOnTop = true;
  46040. }
  46041. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  46042. if (offsetX + rect.width / 2 > api.getWidth()) {
  46043. emphasisTextConfig.position = ['100%', topOffset];
  46044. emphasisTextStyle.align = 'right';
  46045. } else if (offsetX - rect.width / 2 < 0) {
  46046. emphasisTextConfig.position = [0, topOffset];
  46047. emphasisTextStyle.align = 'left';
  46048. }
  46049. }
  46050. });
  46051. };
  46052. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  46053. each(this._features, function (feature) {
  46054. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  46055. });
  46056. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  46057. // zrUtil.each(this._features, function (feature) {
  46058. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  46059. // });
  46060. // },
  46061. ToolboxView.prototype.remove = function (ecModel, api) {
  46062. each(this._features, function (feature) {
  46063. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  46064. });
  46065. this.group.removeAll();
  46066. };
  46067. ToolboxView.prototype.dispose = function (ecModel, api) {
  46068. each(this._features, function (feature) {
  46069. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  46070. });
  46071. };
  46072. ToolboxView.type = 'toolbox';
  46073. return ToolboxView;
  46074. }(ComponentView);
  46075. function isUserFeatureName(featureName) {
  46076. return featureName.indexOf('my') === 0;
  46077. }
  46078. /* global window, document */
  46079. var SaveAsImage =
  46080. /** @class */
  46081. function (_super) {
  46082. __extends(SaveAsImage, _super);
  46083. function SaveAsImage() {
  46084. return _super !== null && _super.apply(this, arguments) || this;
  46085. }
  46086. SaveAsImage.prototype.onclick = function (ecModel, api) {
  46087. var model = this.model;
  46088. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  46089. var isSvg = api.getZr().painter.getType() === 'svg';
  46090. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  46091. var url = api.getConnectedDataURL({
  46092. type: type,
  46093. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  46094. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  46095. excludeComponents: model.get('excludeComponents'),
  46096. pixelRatio: model.get('pixelRatio')
  46097. });
  46098. var browser = env.browser; // Chrome, Firefox, New Edge
  46099. if (isFunction(MouseEvent) && (browser.newEdge || !browser.ie && !browser.edge)) {
  46100. var $a = document.createElement('a');
  46101. $a.download = title + '.' + type;
  46102. $a.target = '_blank';
  46103. $a.href = url;
  46104. var evt = new MouseEvent('click', {
  46105. // some micro front-end framework, window maybe is a Proxy
  46106. view: document.defaultView,
  46107. bubbles: true,
  46108. cancelable: false
  46109. });
  46110. $a.dispatchEvent(evt);
  46111. } // IE or old Edge
  46112. else {
  46113. // @ts-ignore
  46114. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  46115. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  46116. var base64Encoded = parts[0].indexOf('base64') > -1;
  46117. var bstr = isSvg // should decode the svg data uri first
  46118. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  46119. // otherwise, like `svg` data uri exported by zrender,
  46120. // there will be an error, for it's not encoded with base64.
  46121. // (just a url-encoded string through `encodeURIComponent`)
  46122. base64Encoded && (bstr = window.atob(bstr));
  46123. var filename = title + '.' + type; // @ts-ignore
  46124. if (window.navigator.msSaveOrOpenBlob) {
  46125. var n = bstr.length;
  46126. var u8arr = new Uint8Array(n);
  46127. while (n--) {
  46128. u8arr[n] = bstr.charCodeAt(n);
  46129. }
  46130. var blob = new Blob([u8arr]); // @ts-ignore
  46131. window.navigator.msSaveOrOpenBlob(blob, filename);
  46132. } else {
  46133. var frame = document.createElement('iframe');
  46134. document.body.appendChild(frame);
  46135. var cw = frame.contentWindow;
  46136. var doc = cw.document;
  46137. doc.open('image/svg+xml', 'replace');
  46138. doc.write(bstr);
  46139. doc.close();
  46140. cw.focus();
  46141. doc.execCommand('SaveAs', true, filename);
  46142. document.body.removeChild(frame);
  46143. }
  46144. } else {
  46145. var lang = model.get('lang');
  46146. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  46147. var tab = window.open();
  46148. tab.document.write(html);
  46149. tab.document.title = title;
  46150. }
  46151. }
  46152. };
  46153. SaveAsImage.getDefaultOption = function (ecModel) {
  46154. var defaultOption = {
  46155. show: true,
  46156. 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',
  46157. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  46158. type: 'png',
  46159. // Default use option.backgroundColor
  46160. // backgroundColor: '#fff',
  46161. connectedBackgroundColor: '#fff',
  46162. name: '',
  46163. excludeComponents: ['toolbox'],
  46164. // use current pixel ratio of device by default
  46165. // pixelRatio: 1,
  46166. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  46167. };
  46168. return defaultOption;
  46169. };
  46170. return SaveAsImage;
  46171. }(ToolboxFeature);
  46172. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  46173. var radioTypes = [['line', 'bar'], ['stack']];
  46174. var MagicType =
  46175. /** @class */
  46176. function (_super) {
  46177. __extends(MagicType, _super);
  46178. function MagicType() {
  46179. return _super !== null && _super.apply(this, arguments) || this;
  46180. }
  46181. MagicType.prototype.getIcons = function () {
  46182. var model = this.model;
  46183. var availableIcons = model.get('icon');
  46184. var icons = {};
  46185. each(model.get('type'), function (type) {
  46186. if (availableIcons[type]) {
  46187. icons[type] = availableIcons[type];
  46188. }
  46189. });
  46190. return icons;
  46191. };
  46192. MagicType.getDefaultOption = function (ecModel) {
  46193. var defaultOption = {
  46194. show: true,
  46195. type: [],
  46196. // Icon group
  46197. icon: {
  46198. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  46199. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  46200. // eslint-disable-next-line
  46201. 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
  46202. },
  46203. // `line`, `bar`, `stack`, `tiled`
  46204. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  46205. option: {},
  46206. seriesIndex: {}
  46207. };
  46208. return defaultOption;
  46209. };
  46210. MagicType.prototype.onclick = function (ecModel, api, type) {
  46211. var model = this.model;
  46212. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  46213. if (!seriesOptGenreator[type]) {
  46214. return;
  46215. }
  46216. var newOption = {
  46217. series: []
  46218. };
  46219. var generateNewSeriesTypes = function (seriesModel) {
  46220. var seriesType = seriesModel.subType;
  46221. var seriesId = seriesModel.id;
  46222. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  46223. if (newSeriesOpt) {
  46224. // PENDING If merge original option?
  46225. defaults(newSeriesOpt, seriesModel.option);
  46226. newOption.series.push(newSeriesOpt);
  46227. } // Modify boundaryGap
  46228. var coordSys = seriesModel.coordinateSystem;
  46229. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  46230. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  46231. if (categoryAxis) {
  46232. var axisDim = categoryAxis.dim;
  46233. var axisType = axisDim + 'Axis';
  46234. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  46235. var axisIndex = axisModel.componentIndex;
  46236. newOption[axisType] = newOption[axisType] || [];
  46237. for (var i = 0; i <= axisIndex; i++) {
  46238. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  46239. }
  46240. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  46241. }
  46242. }
  46243. };
  46244. each(radioTypes, function (radio) {
  46245. if (indexOf(radio, type) >= 0) {
  46246. each(radio, function (item) {
  46247. model.setIconStatus(item, 'normal');
  46248. });
  46249. }
  46250. });
  46251. model.setIconStatus(type, 'emphasis');
  46252. ecModel.eachComponent({
  46253. mainType: 'series',
  46254. query: seriesIndex == null ? null : {
  46255. seriesIndex: seriesIndex
  46256. }
  46257. }, generateNewSeriesTypes);
  46258. var newTitle;
  46259. var currentType = type; // Change title of stack
  46260. if (type === 'stack') {
  46261. // use titles in model instead of ecModel
  46262. // as stack and tiled appears in pair, just flip them
  46263. // no need of checking stack state
  46264. newTitle = merge({
  46265. stack: model.option.title.tiled,
  46266. tiled: model.option.title.stack
  46267. }, model.option.title);
  46268. if (model.get(['iconStatus', type]) !== 'emphasis') {
  46269. currentType = 'tiled';
  46270. }
  46271. }
  46272. api.dispatchAction({
  46273. type: 'changeMagicType',
  46274. currentType: currentType,
  46275. newOption: newOption,
  46276. newTitle: newTitle,
  46277. featureName: 'magicType'
  46278. });
  46279. };
  46280. return MagicType;
  46281. }(ToolboxFeature);
  46282. var seriesOptGenreator = {
  46283. 'line': function (seriesType, seriesId, seriesModel, model) {
  46284. if (seriesType === 'bar') {
  46285. return merge({
  46286. id: seriesId,
  46287. type: 'line',
  46288. // Preserve data related option
  46289. data: seriesModel.get('data'),
  46290. stack: seriesModel.get('stack'),
  46291. markPoint: seriesModel.get('markPoint'),
  46292. markLine: seriesModel.get('markLine')
  46293. }, model.get(['option', 'line']) || {}, true);
  46294. }
  46295. },
  46296. 'bar': function (seriesType, seriesId, seriesModel, model) {
  46297. if (seriesType === 'line') {
  46298. return merge({
  46299. id: seriesId,
  46300. type: 'bar',
  46301. // Preserve data related option
  46302. data: seriesModel.get('data'),
  46303. stack: seriesModel.get('stack'),
  46304. markPoint: seriesModel.get('markPoint'),
  46305. markLine: seriesModel.get('markLine')
  46306. }, model.get(['option', 'bar']) || {}, true);
  46307. }
  46308. },
  46309. 'stack': function (seriesType, seriesId, seriesModel, model) {
  46310. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  46311. if (seriesType === 'line' || seriesType === 'bar') {
  46312. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  46313. return merge({
  46314. id: seriesId,
  46315. stack: isStack ? '' : INNER_STACK_KEYWORD
  46316. }, model.get(['option', 'stack']) || {}, true);
  46317. }
  46318. }
  46319. }; // TODO: SELF REGISTERED.
  46320. registerAction({
  46321. type: 'changeMagicType',
  46322. event: 'magicTypeChanged',
  46323. update: 'prepareAndUpdate'
  46324. }, function (payload, ecModel) {
  46325. ecModel.mergeOption(payload.newOption);
  46326. });
  46327. /* global document */
  46328. var BLOCK_SPLITER = new Array(60).join('-');
  46329. var ITEM_SPLITER = '\t';
  46330. /**
  46331. * Group series into two types
  46332. * 1. on category axis, like line, bar
  46333. * 2. others, like scatter, pie
  46334. */
  46335. function groupSeries(ecModel) {
  46336. var seriesGroupByCategoryAxis = {};
  46337. var otherSeries = [];
  46338. var meta = [];
  46339. ecModel.eachRawSeries(function (seriesModel) {
  46340. var coordSys = seriesModel.coordinateSystem;
  46341. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  46342. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  46343. var baseAxis = coordSys.getBaseAxis();
  46344. if (baseAxis.type === 'category') {
  46345. var key = baseAxis.dim + '_' + baseAxis.index;
  46346. if (!seriesGroupByCategoryAxis[key]) {
  46347. seriesGroupByCategoryAxis[key] = {
  46348. categoryAxis: baseAxis,
  46349. valueAxis: coordSys.getOtherAxis(baseAxis),
  46350. series: []
  46351. };
  46352. meta.push({
  46353. axisDim: baseAxis.dim,
  46354. axisIndex: baseAxis.index
  46355. });
  46356. }
  46357. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  46358. } else {
  46359. otherSeries.push(seriesModel);
  46360. }
  46361. } else {
  46362. otherSeries.push(seriesModel);
  46363. }
  46364. });
  46365. return {
  46366. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  46367. other: otherSeries,
  46368. meta: meta
  46369. };
  46370. }
  46371. /**
  46372. * Assemble content of series on cateogory axis
  46373. * @inner
  46374. */
  46375. function assembleSeriesWithCategoryAxis(groups) {
  46376. var tables = [];
  46377. each(groups, function (group, key) {
  46378. var categoryAxis = group.categoryAxis;
  46379. var valueAxis = group.valueAxis;
  46380. var valueAxisDim = valueAxis.dim;
  46381. var headers = [' '].concat(map(group.series, function (series) {
  46382. return series.name;
  46383. })); // @ts-ignore TODO Polar
  46384. var columns = [categoryAxis.model.getCategories()];
  46385. each(group.series, function (series) {
  46386. var rawData = series.getRawData();
  46387. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  46388. return val;
  46389. }));
  46390. }); // Assemble table content
  46391. var lines = [headers.join(ITEM_SPLITER)];
  46392. for (var i = 0; i < columns[0].length; i++) {
  46393. var items = [];
  46394. for (var j = 0; j < columns.length; j++) {
  46395. items.push(columns[j][i]);
  46396. }
  46397. lines.push(items.join(ITEM_SPLITER));
  46398. }
  46399. tables.push(lines.join('\n'));
  46400. });
  46401. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  46402. }
  46403. /**
  46404. * Assemble content of other series
  46405. */
  46406. function assembleOtherSeries(series) {
  46407. return map(series, function (series) {
  46408. var data = series.getRawData();
  46409. var lines = [series.name];
  46410. var vals = [];
  46411. data.each(data.dimensions, function () {
  46412. var argLen = arguments.length;
  46413. var dataIndex = arguments[argLen - 1];
  46414. var name = data.getName(dataIndex);
  46415. for (var i = 0; i < argLen - 1; i++) {
  46416. vals[i] = arguments[i];
  46417. }
  46418. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  46419. });
  46420. return lines.join('\n');
  46421. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  46422. }
  46423. function getContentFromModel(ecModel) {
  46424. var result = groupSeries(ecModel);
  46425. return {
  46426. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  46427. return !!str.replace(/[\n\t\s]/g, '');
  46428. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  46429. meta: result.meta
  46430. };
  46431. }
  46432. function trim$1(str) {
  46433. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  46434. }
  46435. /**
  46436. * If a block is tsv format
  46437. */
  46438. function isTSVFormat(block) {
  46439. // Simple method to find out if a block is tsv format
  46440. var firstLine = block.slice(0, block.indexOf('\n'));
  46441. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  46442. return true;
  46443. }
  46444. }
  46445. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  46446. /**
  46447. * @param {string} tsv
  46448. * @return {Object}
  46449. */
  46450. function parseTSVContents(tsv) {
  46451. var tsvLines = tsv.split(/\n+/g);
  46452. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  46453. var categories = [];
  46454. var series = map(headers, function (header) {
  46455. return {
  46456. name: header,
  46457. data: []
  46458. };
  46459. });
  46460. for (var i = 0; i < tsvLines.length; i++) {
  46461. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  46462. categories.push(items.shift());
  46463. for (var j = 0; j < items.length; j++) {
  46464. series[j] && (series[j].data[i] = items[j]);
  46465. }
  46466. }
  46467. return {
  46468. series: series,
  46469. categories: categories
  46470. };
  46471. }
  46472. function parseListContents(str) {
  46473. var lines = str.split(/\n+/g);
  46474. var seriesName = trim$1(lines.shift());
  46475. var data = [];
  46476. for (var i = 0; i < lines.length; i++) {
  46477. // if line is empty, ignore it.
  46478. // there is a case that a user forgot to delete `\n`.
  46479. var line = trim$1(lines[i]);
  46480. if (!line) {
  46481. continue;
  46482. }
  46483. var items = line.split(itemSplitRegex);
  46484. var name_1 = '';
  46485. var value = void 0;
  46486. var hasName = false;
  46487. if (isNaN(items[0])) {
  46488. // First item is name
  46489. hasName = true;
  46490. name_1 = items[0];
  46491. items = items.slice(1);
  46492. data[i] = {
  46493. name: name_1,
  46494. value: []
  46495. };
  46496. value = data[i].value;
  46497. } else {
  46498. value = data[i] = [];
  46499. }
  46500. for (var j = 0; j < items.length; j++) {
  46501. value.push(+items[j]);
  46502. }
  46503. if (value.length === 1) {
  46504. hasName ? data[i].value = value[0] : data[i] = value[0];
  46505. }
  46506. }
  46507. return {
  46508. name: seriesName,
  46509. data: data
  46510. };
  46511. }
  46512. function parseContents(str, blockMetaList) {
  46513. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  46514. var newOption = {
  46515. series: []
  46516. };
  46517. each(blocks, function (block, idx) {
  46518. if (isTSVFormat(block)) {
  46519. var result = parseTSVContents(block);
  46520. var blockMeta = blockMetaList[idx];
  46521. var axisKey = blockMeta.axisDim + 'Axis';
  46522. if (blockMeta) {
  46523. newOption[axisKey] = newOption[axisKey] || [];
  46524. newOption[axisKey][blockMeta.axisIndex] = {
  46525. data: result.categories
  46526. };
  46527. newOption.series = newOption.series.concat(result.series);
  46528. }
  46529. } else {
  46530. var result = parseListContents(block);
  46531. newOption.series.push(result);
  46532. }
  46533. });
  46534. return newOption;
  46535. }
  46536. var DataView =
  46537. /** @class */
  46538. function (_super) {
  46539. __extends(DataView, _super);
  46540. function DataView() {
  46541. return _super !== null && _super.apply(this, arguments) || this;
  46542. }
  46543. DataView.prototype.onclick = function (ecModel, api) {
  46544. // FIXME: better way?
  46545. setTimeout(function () {
  46546. api.dispatchAction({
  46547. type: 'hideTip'
  46548. });
  46549. });
  46550. var container = api.getDom();
  46551. var model = this.model;
  46552. if (this._dom) {
  46553. container.removeChild(this._dom);
  46554. }
  46555. var root = document.createElement('div'); // use padding to avoid 5px whitespace
  46556. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  46557. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  46558. var header = document.createElement('h4');
  46559. var lang = model.get('lang') || [];
  46560. header.innerHTML = lang[0] || model.get('title');
  46561. header.style.cssText = 'margin:10px 20px';
  46562. header.style.color = model.get('textColor');
  46563. var viewMain = document.createElement('div');
  46564. var textarea = document.createElement('textarea');
  46565. viewMain.style.cssText = 'overflow:auto';
  46566. var optionToContent = model.get('optionToContent');
  46567. var contentToOption = model.get('contentToOption');
  46568. var result = getContentFromModel(ecModel);
  46569. if (isFunction(optionToContent)) {
  46570. var htmlOrDom = optionToContent(api.getOption());
  46571. if (isString(htmlOrDom)) {
  46572. viewMain.innerHTML = htmlOrDom;
  46573. } else if (isDom(htmlOrDom)) {
  46574. viewMain.appendChild(htmlOrDom);
  46575. }
  46576. } else {
  46577. // Use default textarea
  46578. textarea.readOnly = model.get('readOnly');
  46579. var style = textarea.style; // eslint-disable-next-line max-len
  46580. 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';
  46581. style.color = model.get('textColor');
  46582. style.borderColor = model.get('textareaBorderColor');
  46583. style.backgroundColor = model.get('textareaColor');
  46584. textarea.value = result.value;
  46585. viewMain.appendChild(textarea);
  46586. }
  46587. var blockMetaList = result.meta;
  46588. var buttonContainer = document.createElement('div');
  46589. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0'; // eslint-disable-next-line max-len
  46590. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  46591. var closeButton = document.createElement('div');
  46592. var refreshButton = document.createElement('div');
  46593. buttonStyle += ';background-color:' + model.get('buttonColor');
  46594. buttonStyle += ';color:' + model.get('buttonTextColor');
  46595. var self = this;
  46596. function close() {
  46597. container.removeChild(root);
  46598. self._dom = null;
  46599. }
  46600. addEventListener(closeButton, 'click', close);
  46601. addEventListener(refreshButton, 'click', function () {
  46602. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  46603. if ("development" !== 'production') {
  46604. // eslint-disable-next-line
  46605. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  46606. }
  46607. close();
  46608. return;
  46609. }
  46610. var newOption;
  46611. try {
  46612. if (isFunction(contentToOption)) {
  46613. newOption = contentToOption(viewMain, api.getOption());
  46614. } else {
  46615. newOption = parseContents(textarea.value, blockMetaList);
  46616. }
  46617. } catch (e) {
  46618. close();
  46619. throw new Error('Data view format error ' + e);
  46620. }
  46621. if (newOption) {
  46622. api.dispatchAction({
  46623. type: 'changeDataView',
  46624. newOption: newOption
  46625. });
  46626. }
  46627. close();
  46628. });
  46629. closeButton.innerHTML = lang[1];
  46630. refreshButton.innerHTML = lang[2];
  46631. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  46632. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  46633. buttonContainer.appendChild(closeButton);
  46634. root.appendChild(header);
  46635. root.appendChild(viewMain);
  46636. root.appendChild(buttonContainer);
  46637. viewMain.style.height = container.clientHeight - 80 + 'px';
  46638. container.appendChild(root);
  46639. this._dom = root;
  46640. };
  46641. DataView.prototype.remove = function (ecModel, api) {
  46642. this._dom && api.getDom().removeChild(this._dom);
  46643. };
  46644. DataView.prototype.dispose = function (ecModel, api) {
  46645. this.remove(ecModel, api);
  46646. };
  46647. DataView.getDefaultOption = function (ecModel) {
  46648. var defaultOption = {
  46649. show: true,
  46650. readOnly: false,
  46651. optionToContent: null,
  46652. contentToOption: null,
  46653. // eslint-disable-next-line
  46654. 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',
  46655. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  46656. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  46657. backgroundColor: '#fff',
  46658. textColor: '#000',
  46659. textareaColor: '#fff',
  46660. textareaBorderColor: '#333',
  46661. buttonColor: '#c23531',
  46662. buttonTextColor: '#fff'
  46663. };
  46664. return defaultOption;
  46665. };
  46666. return DataView;
  46667. }(ToolboxFeature);
  46668. /**
  46669. * @inner
  46670. */
  46671. function tryMergeDataOption(newData, originalData) {
  46672. return map(newData, function (newVal, idx) {
  46673. var original = originalData && originalData[idx];
  46674. if (isObject(original) && !isArray(original)) {
  46675. var newValIsObject = isObject(newVal) && !isArray(newVal);
  46676. if (!newValIsObject) {
  46677. newVal = {
  46678. value: newVal
  46679. };
  46680. } // original data has name but new data has no name
  46681. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  46682. newVal = defaults(newVal, original);
  46683. shouldDeleteName && delete newVal.name;
  46684. return newVal;
  46685. } else {
  46686. return newVal;
  46687. }
  46688. });
  46689. } // TODO: SELF REGISTERED.
  46690. registerAction({
  46691. type: 'changeDataView',
  46692. event: 'dataViewChanged',
  46693. update: 'prepareAndUpdate'
  46694. }, function (payload, ecModel) {
  46695. var newSeriesOptList = [];
  46696. each(payload.newOption.series, function (seriesOpt) {
  46697. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  46698. if (!seriesModel) {
  46699. // New created series
  46700. // Geuss the series type
  46701. newSeriesOptList.push(extend({
  46702. // Default is scatter
  46703. type: 'scatter'
  46704. }, seriesOpt));
  46705. } else {
  46706. var originalData = seriesModel.get('data');
  46707. newSeriesOptList.push({
  46708. name: seriesOpt.name,
  46709. data: tryMergeDataOption(seriesOpt.data, originalData)
  46710. });
  46711. }
  46712. });
  46713. ecModel.mergeOption(defaults({
  46714. series: newSeriesOptList
  46715. }, payload.newOption));
  46716. });
  46717. var each$5 = each;
  46718. var inner$b = makeInner();
  46719. /**
  46720. * @param ecModel
  46721. * @param newSnapshot key is dataZoomId
  46722. */
  46723. function push(ecModel, newSnapshot) {
  46724. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  46725. // complete an range with current range.
  46726. each$5(newSnapshot, function (batchItem, dataZoomId) {
  46727. var i = storedSnapshots.length - 1;
  46728. for (; i >= 0; i--) {
  46729. var snapshot = storedSnapshots[i];
  46730. if (snapshot[dataZoomId]) {
  46731. break;
  46732. }
  46733. }
  46734. if (i < 0) {
  46735. // No origin range set, create one by current range.
  46736. var dataZoomModel = ecModel.queryComponents({
  46737. mainType: 'dataZoom',
  46738. subType: 'select',
  46739. id: dataZoomId
  46740. })[0];
  46741. if (dataZoomModel) {
  46742. var percentRange = dataZoomModel.getPercentRange();
  46743. storedSnapshots[0][dataZoomId] = {
  46744. dataZoomId: dataZoomId,
  46745. start: percentRange[0],
  46746. end: percentRange[1]
  46747. };
  46748. }
  46749. }
  46750. });
  46751. storedSnapshots.push(newSnapshot);
  46752. }
  46753. function pop(ecModel) {
  46754. var storedSnapshots = getStoreSnapshots(ecModel);
  46755. var head = storedSnapshots[storedSnapshots.length - 1];
  46756. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  46757. var snapshot = {};
  46758. each$5(head, function (batchItem, dataZoomId) {
  46759. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  46760. batchItem = storedSnapshots[i][dataZoomId];
  46761. if (batchItem) {
  46762. snapshot[dataZoomId] = batchItem;
  46763. break;
  46764. }
  46765. }
  46766. });
  46767. return snapshot;
  46768. }
  46769. function clear$1(ecModel) {
  46770. inner$b(ecModel).snapshots = null;
  46771. }
  46772. function count(ecModel) {
  46773. return getStoreSnapshots(ecModel).length;
  46774. }
  46775. /**
  46776. * History length of each dataZoom may be different.
  46777. * this._history[0] is used to store origin range.
  46778. */
  46779. function getStoreSnapshots(ecModel) {
  46780. var store = inner$b(ecModel);
  46781. if (!store.snapshots) {
  46782. store.snapshots = [{}];
  46783. }
  46784. return store.snapshots;
  46785. }
  46786. var RestoreOption =
  46787. /** @class */
  46788. function (_super) {
  46789. __extends(RestoreOption, _super);
  46790. function RestoreOption() {
  46791. return _super !== null && _super.apply(this, arguments) || this;
  46792. }
  46793. RestoreOption.prototype.onclick = function (ecModel, api) {
  46794. clear$1(ecModel);
  46795. api.dispatchAction({
  46796. type: 'restore',
  46797. from: this.uid
  46798. });
  46799. };
  46800. RestoreOption.getDefaultOption = function (ecModel) {
  46801. var defaultOption = {
  46802. show: true,
  46803. // eslint-disable-next-line
  46804. 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',
  46805. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  46806. };
  46807. return defaultOption;
  46808. };
  46809. return RestoreOption;
  46810. }(ToolboxFeature); // TODO: SELF REGISTERED.
  46811. registerAction({
  46812. type: 'restore',
  46813. event: 'restore',
  46814. update: 'prepareAndUpdate'
  46815. }, function (payload, ecModel) {
  46816. ecModel.resetOption('recreate');
  46817. });
  46818. var ATTR = '\0_ec_interaction_mutex';
  46819. function take(zr, resourceKey, userKey) {
  46820. var store = getStore(zr);
  46821. store[resourceKey] = userKey;
  46822. }
  46823. function release(zr, resourceKey, userKey) {
  46824. var store = getStore(zr);
  46825. var uKey = store[resourceKey];
  46826. if (uKey === userKey) {
  46827. store[resourceKey] = null;
  46828. }
  46829. }
  46830. function isTaken(zr, resourceKey) {
  46831. return !!getStore(zr)[resourceKey];
  46832. }
  46833. function getStore(zr) {
  46834. return zr[ATTR] || (zr[ATTR] = {});
  46835. }
  46836. /**
  46837. * payload: {
  46838. * type: 'takeGlobalCursor',
  46839. * key: 'dataZoomSelect', or 'brush', or ...,
  46840. * If no userKey, release global cursor.
  46841. * }
  46842. */
  46843. // TODO: SELF REGISTERED.
  46844. registerAction({
  46845. type: 'takeGlobalCursor',
  46846. event: 'globalCursorTaken',
  46847. update: 'update'
  46848. }, noop);
  46849. var BRUSH_PANEL_GLOBAL = true;
  46850. var mathMin$7 = Math.min;
  46851. var mathMax$7 = Math.max;
  46852. var mathPow$2 = Math.pow;
  46853. var COVER_Z = 10000;
  46854. var UNSELECT_THRESHOLD = 6;
  46855. var MIN_RESIZE_LINE_WIDTH = 6;
  46856. var MUTEX_RESOURCE_KEY = 'globalPan';
  46857. var DIRECTION_MAP = {
  46858. w: [0, 0],
  46859. e: [0, 1],
  46860. n: [1, 0],
  46861. s: [1, 1]
  46862. };
  46863. var CURSOR_MAP = {
  46864. w: 'ew',
  46865. e: 'ew',
  46866. n: 'ns',
  46867. s: 'ns',
  46868. ne: 'nesw',
  46869. sw: 'nesw',
  46870. nw: 'nwse',
  46871. se: 'nwse'
  46872. };
  46873. var DEFAULT_BRUSH_OPT = {
  46874. brushStyle: {
  46875. lineWidth: 2,
  46876. stroke: 'rgba(210,219,238,0.3)',
  46877. fill: '#D2DBEE'
  46878. },
  46879. transformable: true,
  46880. brushMode: 'single',
  46881. removeOnClick: false
  46882. };
  46883. var baseUID = 0;
  46884. /**
  46885. * params:
  46886. * areas: Array.<Array>, coord relates to container group,
  46887. * If no container specified, to global.
  46888. * opt {
  46889. * isEnd: boolean,
  46890. * removeOnClick: boolean
  46891. * }
  46892. */
  46893. var BrushController =
  46894. /** @class */
  46895. function (_super) {
  46896. __extends(BrushController, _super);
  46897. function BrushController(zr) {
  46898. var _this = _super.call(this) || this;
  46899. /**
  46900. * @internal
  46901. */
  46902. _this._track = [];
  46903. /**
  46904. * @internal
  46905. */
  46906. _this._covers = [];
  46907. _this._handlers = {};
  46908. if ("development" !== 'production') {
  46909. assert(zr);
  46910. }
  46911. _this._zr = zr;
  46912. _this.group = new Group();
  46913. _this._uid = 'brushController_' + baseUID++;
  46914. each(pointerHandlers, function (handler, eventName) {
  46915. this._handlers[eventName] = bind(handler, this);
  46916. }, _this);
  46917. return _this;
  46918. }
  46919. /**
  46920. * If set to `false`, select disabled.
  46921. */
  46922. BrushController.prototype.enableBrush = function (brushOption) {
  46923. if ("development" !== 'production') {
  46924. assert(this._mounted);
  46925. }
  46926. this._brushType && this._doDisableBrush();
  46927. brushOption.brushType && this._doEnableBrush(brushOption);
  46928. return this;
  46929. };
  46930. BrushController.prototype._doEnableBrush = function (brushOption) {
  46931. var zr = this._zr; // Consider roam, which takes globalPan too.
  46932. if (!this._enableGlobalPan) {
  46933. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  46934. }
  46935. each(this._handlers, function (handler, eventName) {
  46936. zr.on(eventName, handler);
  46937. });
  46938. this._brushType = brushOption.brushType;
  46939. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  46940. };
  46941. BrushController.prototype._doDisableBrush = function () {
  46942. var zr = this._zr;
  46943. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  46944. each(this._handlers, function (handler, eventName) {
  46945. zr.off(eventName, handler);
  46946. });
  46947. this._brushType = this._brushOption = null;
  46948. };
  46949. /**
  46950. * @param panelOpts If not pass, it is global brush.
  46951. */
  46952. BrushController.prototype.setPanels = function (panelOpts) {
  46953. if (panelOpts && panelOpts.length) {
  46954. var panels_1 = this._panels = {};
  46955. each(panelOpts, function (panelOpts) {
  46956. panels_1[panelOpts.panelId] = clone(panelOpts);
  46957. });
  46958. } else {
  46959. this._panels = null;
  46960. }
  46961. return this;
  46962. };
  46963. BrushController.prototype.mount = function (opt) {
  46964. opt = opt || {};
  46965. if ("development" !== 'production') {
  46966. this._mounted = true; // should be at first.
  46967. }
  46968. this._enableGlobalPan = opt.enableGlobalPan;
  46969. var thisGroup = this.group;
  46970. this._zr.add(thisGroup);
  46971. thisGroup.attr({
  46972. x: opt.x || 0,
  46973. y: opt.y || 0,
  46974. rotation: opt.rotation || 0,
  46975. scaleX: opt.scaleX || 1,
  46976. scaleY: opt.scaleY || 1
  46977. });
  46978. this._transform = thisGroup.getLocalTransform();
  46979. return this;
  46980. }; // eachCover(cb, context): void {
  46981. // each(this._covers, cb, context);
  46982. // }
  46983. /**
  46984. * Update covers.
  46985. * @param coverConfigList
  46986. * If coverConfigList is null/undefined, all covers removed.
  46987. */
  46988. BrushController.prototype.updateCovers = function (coverConfigList) {
  46989. if ("development" !== 'production') {
  46990. assert(this._mounted);
  46991. }
  46992. coverConfigList = map(coverConfigList, function (coverConfig) {
  46993. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  46994. });
  46995. var tmpIdPrefix = '\0-brush-index-';
  46996. var oldCovers = this._covers;
  46997. var newCovers = this._covers = [];
  46998. var controller = this;
  46999. var creatingCover = this._creatingCover;
  47000. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  47001. return this;
  47002. function getKey(brushOption, index) {
  47003. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  47004. }
  47005. function oldGetKey(cover, index) {
  47006. return getKey(cover.__brushOption, index);
  47007. }
  47008. function addOrUpdate(newIndex, oldIndex) {
  47009. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  47010. // where updating cover when creating should be forbiden.
  47011. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  47012. newCovers[newIndex] = oldCovers[oldIndex];
  47013. } else {
  47014. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  47015. updateCoverAfterCreation(controller, cover);
  47016. }
  47017. }
  47018. function remove(oldIndex) {
  47019. if (oldCovers[oldIndex] !== creatingCover) {
  47020. controller.group.remove(oldCovers[oldIndex]);
  47021. }
  47022. }
  47023. };
  47024. BrushController.prototype.unmount = function () {
  47025. if ("development" !== 'production') {
  47026. if (!this._mounted) {
  47027. return;
  47028. }
  47029. }
  47030. this.enableBrush(false); // container may 'removeAll' outside.
  47031. clearCovers(this);
  47032. this._zr.remove(this.group);
  47033. if ("development" !== 'production') {
  47034. this._mounted = false; // should be at last.
  47035. }
  47036. return this;
  47037. };
  47038. BrushController.prototype.dispose = function () {
  47039. this.unmount();
  47040. this.off();
  47041. };
  47042. return BrushController;
  47043. }(Eventful);
  47044. function createCover(controller, brushOption) {
  47045. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  47046. cover.__brushOption = brushOption;
  47047. updateZ(cover, brushOption);
  47048. controller.group.add(cover);
  47049. return cover;
  47050. }
  47051. function endCreating(controller, creatingCover) {
  47052. var coverRenderer = getCoverRenderer(creatingCover);
  47053. if (coverRenderer.endCreating) {
  47054. coverRenderer.endCreating(controller, creatingCover);
  47055. updateZ(creatingCover, creatingCover.__brushOption);
  47056. }
  47057. return creatingCover;
  47058. }
  47059. function updateCoverShape(controller, cover) {
  47060. var brushOption = cover.__brushOption;
  47061. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  47062. }
  47063. function updateZ(cover, brushOption) {
  47064. var z = brushOption.z;
  47065. z == null && (z = COVER_Z);
  47066. cover.traverse(function (el) {
  47067. el.z = z;
  47068. el.z2 = z; // Consider in given container.
  47069. });
  47070. }
  47071. function updateCoverAfterCreation(controller, cover) {
  47072. getCoverRenderer(cover).updateCommon(controller, cover);
  47073. updateCoverShape(controller, cover);
  47074. }
  47075. function getCoverRenderer(cover) {
  47076. return coverRenderers[cover.__brushOption.brushType];
  47077. } // return target panel or `true` (means global panel)
  47078. function getPanelByPoint(controller, e, localCursorPoint) {
  47079. var panels = controller._panels;
  47080. if (!panels) {
  47081. return BRUSH_PANEL_GLOBAL; // Global panel
  47082. }
  47083. var panel;
  47084. var transform = controller._transform;
  47085. each(panels, function (pn) {
  47086. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  47087. });
  47088. return panel;
  47089. } // Return a panel or true
  47090. function getPanelByCover(controller, cover) {
  47091. var panels = controller._panels;
  47092. if (!panels) {
  47093. return BRUSH_PANEL_GLOBAL; // Global panel
  47094. }
  47095. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  47096. // which is then treated as global panel.
  47097. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  47098. }
  47099. function clearCovers(controller) {
  47100. var covers = controller._covers;
  47101. var originalLength = covers.length;
  47102. each(covers, function (cover) {
  47103. controller.group.remove(cover);
  47104. }, controller);
  47105. covers.length = 0;
  47106. return !!originalLength;
  47107. }
  47108. function trigger(controller, opt) {
  47109. var areas = map(controller._covers, function (cover) {
  47110. var brushOption = cover.__brushOption;
  47111. var range = clone(brushOption.range);
  47112. return {
  47113. brushType: brushOption.brushType,
  47114. panelId: brushOption.panelId,
  47115. range: range
  47116. };
  47117. });
  47118. controller.trigger('brush', {
  47119. areas: areas,
  47120. isEnd: !!opt.isEnd,
  47121. removeOnClick: !!opt.removeOnClick
  47122. });
  47123. }
  47124. function shouldShowCover(controller) {
  47125. var track = controller._track;
  47126. if (!track.length) {
  47127. return false;
  47128. }
  47129. var p2 = track[track.length - 1];
  47130. var p1 = track[0];
  47131. var dx = p2[0] - p1[0];
  47132. var dy = p2[1] - p1[1];
  47133. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  47134. return dist > UNSELECT_THRESHOLD;
  47135. }
  47136. function getTrackEnds(track) {
  47137. var tail = track.length - 1;
  47138. tail < 0 && (tail = 0);
  47139. return [track[0], track[tail]];
  47140. }
  47141. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  47142. var cover = new Group();
  47143. cover.add(new Rect({
  47144. name: 'main',
  47145. style: makeStyle(brushOption),
  47146. silent: true,
  47147. draggable: true,
  47148. cursor: 'move',
  47149. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  47150. ondragend: curry(trigger, controller, {
  47151. isEnd: true
  47152. })
  47153. }));
  47154. each(edgeNameSequences, function (nameSequence) {
  47155. cover.add(new Rect({
  47156. name: nameSequence.join(''),
  47157. style: {
  47158. opacity: 0
  47159. },
  47160. draggable: true,
  47161. silent: true,
  47162. invisible: true,
  47163. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  47164. ondragend: curry(trigger, controller, {
  47165. isEnd: true
  47166. })
  47167. }));
  47168. });
  47169. return cover;
  47170. }
  47171. function updateBaseRect(controller, cover, localRange, brushOption) {
  47172. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  47173. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  47174. var x = localRange[0][0];
  47175. var y = localRange[1][0];
  47176. var xa = x - lineWidth / 2;
  47177. var ya = y - lineWidth / 2;
  47178. var x2 = localRange[0][1];
  47179. var y2 = localRange[1][1];
  47180. var x2a = x2 - handleSize + lineWidth / 2;
  47181. var y2a = y2 - handleSize + lineWidth / 2;
  47182. var width = x2 - x;
  47183. var height = y2 - y;
  47184. var widtha = width + lineWidth;
  47185. var heighta = height + lineWidth;
  47186. updateRectShape(controller, cover, 'main', x, y, width, height);
  47187. if (brushOption.transformable) {
  47188. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  47189. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  47190. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  47191. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  47192. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  47193. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  47194. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  47195. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  47196. }
  47197. }
  47198. function updateCommon(controller, cover) {
  47199. var brushOption = cover.__brushOption;
  47200. var transformable = brushOption.transformable;
  47201. var mainEl = cover.childAt(0);
  47202. mainEl.useStyle(makeStyle(brushOption));
  47203. mainEl.attr({
  47204. silent: !transformable,
  47205. cursor: transformable ? 'move' : 'default'
  47206. });
  47207. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  47208. var el = cover.childOfName(nameSequence.join(''));
  47209. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  47210. el && el.attr({
  47211. silent: !transformable,
  47212. invisible: !transformable,
  47213. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  47214. });
  47215. });
  47216. }
  47217. function updateRectShape(controller, cover, name, x, y, w, h) {
  47218. var el = cover.childOfName(name);
  47219. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  47220. }
  47221. function makeStyle(brushOption) {
  47222. return defaults({
  47223. strokeNoScale: true
  47224. }, brushOption.brushStyle);
  47225. }
  47226. function formatRectRange(x, y, x2, y2) {
  47227. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  47228. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  47229. return [[min[0], max[0]], [min[1], max[1]] // y range
  47230. ];
  47231. }
  47232. function getTransform$1(controller) {
  47233. return getTransform(controller.group);
  47234. }
  47235. function getGlobalDirection1(controller, localDirName) {
  47236. var map = {
  47237. w: 'left',
  47238. e: 'right',
  47239. n: 'top',
  47240. s: 'bottom'
  47241. };
  47242. var inverseMap = {
  47243. left: 'w',
  47244. right: 'e',
  47245. top: 'n',
  47246. bottom: 's'
  47247. };
  47248. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  47249. return inverseMap[dir];
  47250. }
  47251. function getGlobalDirection2(controller, localDirNameSeq) {
  47252. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  47253. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  47254. return globalDir.join('');
  47255. }
  47256. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  47257. var brushOption = cover.__brushOption;
  47258. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  47259. var localDelta = toLocalDelta(controller, dx, dy);
  47260. each(dirNameSequence, function (dirName) {
  47261. var ind = DIRECTION_MAP[dirName];
  47262. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  47263. });
  47264. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  47265. updateCoverAfterCreation(controller, cover);
  47266. trigger(controller, {
  47267. isEnd: false
  47268. });
  47269. }
  47270. function driftPolygon(controller, cover, dx, dy) {
  47271. var range = cover.__brushOption.range;
  47272. var localDelta = toLocalDelta(controller, dx, dy);
  47273. each(range, function (point) {
  47274. point[0] += localDelta[0];
  47275. point[1] += localDelta[1];
  47276. });
  47277. updateCoverAfterCreation(controller, cover);
  47278. trigger(controller, {
  47279. isEnd: false
  47280. });
  47281. }
  47282. function toLocalDelta(controller, dx, dy) {
  47283. var thisGroup = controller.group;
  47284. var localD = thisGroup.transformCoordToLocal(dx, dy);
  47285. var localZero = thisGroup.transformCoordToLocal(0, 0);
  47286. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  47287. }
  47288. function clipByPanel(controller, cover, data) {
  47289. var panel = getPanelByCover(controller, cover);
  47290. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  47291. }
  47292. function pointsToRect(points) {
  47293. var xmin = mathMin$7(points[0][0], points[1][0]);
  47294. var ymin = mathMin$7(points[0][1], points[1][1]);
  47295. var xmax = mathMax$7(points[0][0], points[1][0]);
  47296. var ymax = mathMax$7(points[0][1], points[1][1]);
  47297. return {
  47298. x: xmin,
  47299. y: ymin,
  47300. width: xmax - xmin,
  47301. height: ymax - ymin
  47302. };
  47303. }
  47304. function resetCursor(controller, e, localCursorPoint) {
  47305. if ( // Check active
  47306. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  47307. // but not called when mouse is out of zr area to avoid bad influence
  47308. // if `mousemove`, `mouseup` are triggered from `document` event.
  47309. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  47310. return;
  47311. }
  47312. var zr = controller._zr;
  47313. var covers = controller._covers;
  47314. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  47315. if (!controller._dragging) {
  47316. for (var i = 0; i < covers.length; i++) {
  47317. var brushOption = covers[i].__brushOption;
  47318. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  47319. // Use cursor style set on cover.
  47320. return;
  47321. }
  47322. }
  47323. }
  47324. currPanel && zr.setCursorStyle('crosshair');
  47325. }
  47326. function preventDefault(e) {
  47327. var rawE = e.event;
  47328. rawE.preventDefault && rawE.preventDefault();
  47329. }
  47330. function mainShapeContain(cover, x, y) {
  47331. return cover.childOfName('main').contain(x, y);
  47332. }
  47333. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  47334. var creatingCover = controller._creatingCover;
  47335. var panel = controller._creatingPanel;
  47336. var thisBrushOption = controller._brushOption;
  47337. var eventParams;
  47338. controller._track.push(localCursorPoint.slice());
  47339. if (shouldShowCover(controller) || creatingCover) {
  47340. if (panel && !creatingCover) {
  47341. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  47342. var brushOption = clone(thisBrushOption);
  47343. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  47344. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  47345. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  47346. controller._covers.push(creatingCover);
  47347. }
  47348. if (creatingCover) {
  47349. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  47350. var coverBrushOption = creatingCover.__brushOption;
  47351. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  47352. if (isEnd) {
  47353. endCreating(controller, creatingCover);
  47354. coverRenderer.updateCommon(controller, creatingCover);
  47355. }
  47356. updateCoverShape(controller, creatingCover);
  47357. eventParams = {
  47358. isEnd: isEnd
  47359. };
  47360. }
  47361. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  47362. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  47363. // But a single click do not clear covers, because user may have casual
  47364. // clicks (for example, click on other component and do not expect covers
  47365. // disappear).
  47366. // Only some cover removed, trigger action, but not every click trigger action.
  47367. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  47368. eventParams = {
  47369. isEnd: isEnd,
  47370. removeOnClick: true
  47371. };
  47372. }
  47373. }
  47374. return eventParams;
  47375. }
  47376. function determineBrushType(brushType, panel) {
  47377. if (brushType === 'auto') {
  47378. if ("development" !== 'production') {
  47379. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  47380. }
  47381. return panel.defaultBrushType;
  47382. }
  47383. return brushType;
  47384. }
  47385. var pointerHandlers = {
  47386. mousedown: function (e) {
  47387. if (this._dragging) {
  47388. // In case some browser do not support globalOut,
  47389. // and release mouse out side the browser.
  47390. handleDragEnd(this, e);
  47391. } else if (!e.target || !e.target.draggable) {
  47392. preventDefault(e);
  47393. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  47394. this._creatingCover = null;
  47395. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  47396. if (panel) {
  47397. this._dragging = true;
  47398. this._track = [localCursorPoint.slice()];
  47399. }
  47400. }
  47401. },
  47402. mousemove: function (e) {
  47403. var x = e.offsetX;
  47404. var y = e.offsetY;
  47405. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  47406. resetCursor(this, e, localCursorPoint);
  47407. if (this._dragging) {
  47408. preventDefault(e);
  47409. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  47410. eventParams && trigger(this, eventParams);
  47411. }
  47412. },
  47413. mouseup: function (e) {
  47414. handleDragEnd(this, e);
  47415. }
  47416. };
  47417. function handleDragEnd(controller, e) {
  47418. if (controller._dragging) {
  47419. preventDefault(e);
  47420. var x = e.offsetX;
  47421. var y = e.offsetY;
  47422. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  47423. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  47424. controller._dragging = false;
  47425. controller._track = [];
  47426. controller._creatingCover = null; // trigger event shoule be at final, after procedure will be nested.
  47427. eventParams && trigger(controller, eventParams);
  47428. }
  47429. }
  47430. function isOutsideZrArea(controller, x, y) {
  47431. var zr = controller._zr;
  47432. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  47433. }
  47434. /**
  47435. * key: brushType
  47436. */
  47437. var coverRenderers = {
  47438. lineX: getLineRenderer(0),
  47439. lineY: getLineRenderer(1),
  47440. rect: {
  47441. createCover: function (controller, brushOption) {
  47442. function returnInput(range) {
  47443. return range;
  47444. }
  47445. return createBaseRectCover({
  47446. toRectRange: returnInput,
  47447. fromRectRange: returnInput
  47448. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  47449. },
  47450. getCreatingRange: function (localTrack) {
  47451. var ends = getTrackEnds(localTrack);
  47452. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  47453. },
  47454. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47455. updateBaseRect(controller, cover, localRange, brushOption);
  47456. },
  47457. updateCommon: updateCommon,
  47458. contain: mainShapeContain
  47459. },
  47460. polygon: {
  47461. createCover: function (controller, brushOption) {
  47462. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  47463. // border of the shape when drawing, which is a better experience for user.
  47464. cover.add(new Polyline({
  47465. name: 'main',
  47466. style: makeStyle(brushOption),
  47467. silent: true
  47468. }));
  47469. return cover;
  47470. },
  47471. getCreatingRange: function (localTrack) {
  47472. return localTrack;
  47473. },
  47474. endCreating: function (controller, cover) {
  47475. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  47476. cover.add(new Polygon({
  47477. name: 'main',
  47478. draggable: true,
  47479. drift: curry(driftPolygon, controller, cover),
  47480. ondragend: curry(trigger, controller, {
  47481. isEnd: true
  47482. })
  47483. }));
  47484. },
  47485. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47486. cover.childAt(0).setShape({
  47487. points: clipByPanel(controller, cover, localRange)
  47488. });
  47489. },
  47490. updateCommon: updateCommon,
  47491. contain: mainShapeContain
  47492. }
  47493. };
  47494. function getLineRenderer(xyIndex) {
  47495. return {
  47496. createCover: function (controller, brushOption) {
  47497. return createBaseRectCover({
  47498. toRectRange: function (range) {
  47499. var rectRange = [range, [0, 100]];
  47500. xyIndex && rectRange.reverse();
  47501. return rectRange;
  47502. },
  47503. fromRectRange: function (rectRange) {
  47504. return rectRange[xyIndex];
  47505. }
  47506. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  47507. },
  47508. getCreatingRange: function (localTrack) {
  47509. var ends = getTrackEnds(localTrack);
  47510. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  47511. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  47512. return [min, max];
  47513. },
  47514. updateCoverShape: function (controller, cover, localRange, brushOption) {
  47515. var otherExtent; // If brushWidth not specified, fit the panel.
  47516. var panel = getPanelByCover(controller, cover);
  47517. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  47518. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  47519. } else {
  47520. var zr = controller._zr;
  47521. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  47522. }
  47523. var rectRange = [localRange, otherExtent];
  47524. xyIndex && rectRange.reverse();
  47525. updateBaseRect(controller, cover, rectRange, brushOption);
  47526. },
  47527. updateCommon: updateCommon,
  47528. contain: mainShapeContain
  47529. };
  47530. }
  47531. /*
  47532. * Licensed to the Apache Software Foundation (ASF) under one
  47533. * or more contributor license agreements. See the NOTICE file
  47534. * distributed with this work for additional information
  47535. * regarding copyright ownership. The ASF licenses this file
  47536. * to you under the Apache License, Version 2.0 (the
  47537. * "License"); you may not use this file except in compliance
  47538. * with the License. You may obtain a copy of the License at
  47539. *
  47540. * http://www.apache.org/licenses/LICENSE-2.0
  47541. *
  47542. * Unless required by applicable law or agreed to in writing,
  47543. * software distributed under the License is distributed on an
  47544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47545. * KIND, either express or implied. See the License for the
  47546. * specific language governing permissions and limitations
  47547. * under the License.
  47548. */
  47549. /**
  47550. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47551. */
  47552. /*
  47553. * Licensed to the Apache Software Foundation (ASF) under one
  47554. * or more contributor license agreements. See the NOTICE file
  47555. * distributed with this work for additional information
  47556. * regarding copyright ownership. The ASF licenses this file
  47557. * to you under the Apache License, Version 2.0 (the
  47558. * "License"); you may not use this file except in compliance
  47559. * with the License. You may obtain a copy of the License at
  47560. *
  47561. * http://www.apache.org/licenses/LICENSE-2.0
  47562. *
  47563. * Unless required by applicable law or agreed to in writing,
  47564. * software distributed under the License is distributed on an
  47565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47566. * KIND, either express or implied. See the License for the
  47567. * specific language governing permissions and limitations
  47568. * under the License.
  47569. */
  47570. var IRRELEVANT_EXCLUDES = {
  47571. 'axisPointer': 1,
  47572. 'tooltip': 1,
  47573. 'brush': 1
  47574. };
  47575. /**
  47576. * Avoid that: mouse click on a elements that is over geo or graph,
  47577. * but roam is triggered.
  47578. */
  47579. function onIrrelevantElement(e, api, targetCoordSysModel) {
  47580. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  47581. var coordSys = model && model.coordinateSystem;
  47582. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  47583. }
  47584. function makeRectPanelClipPath(rect) {
  47585. rect = normalizeRect(rect);
  47586. return function (localPoints) {
  47587. return clipPointsByRect(localPoints, rect);
  47588. };
  47589. }
  47590. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  47591. rect = normalizeRect(rect);
  47592. return function (xyIndex) {
  47593. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  47594. var brushWidth = idx ? rect.width : rect.height;
  47595. var base = idx ? rect.x : rect.y;
  47596. return [base, base + (brushWidth || 0)];
  47597. };
  47598. }
  47599. function makeRectIsTargetByCursor(rect, api, targetModel) {
  47600. var boundingRect = normalizeRect(rect);
  47601. return function (e, localCursorPoint) {
  47602. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  47603. };
  47604. } // Consider width/height is negative.
  47605. function normalizeRect(rect) {
  47606. return BoundingRect.create(rect);
  47607. }
  47608. // how to genarialize to more coordinate systems.
  47609. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  47610. var BrushTargetManager =
  47611. /** @class */
  47612. function () {
  47613. /**
  47614. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  47615. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  47616. * @param opt.include include coordinate system types.
  47617. */
  47618. function BrushTargetManager(finder, ecModel, opt) {
  47619. var _this = this;
  47620. this._targetInfoList = [];
  47621. var foundCpts = parseFinder$1(ecModel, finder);
  47622. each(targetInfoBuilders, function (builder, type) {
  47623. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  47624. builder(foundCpts, _this._targetInfoList);
  47625. }
  47626. });
  47627. }
  47628. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  47629. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  47630. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  47631. if (!area.coordRange) {
  47632. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  47633. // rebuild range by coordRange accrately, which may bring trouble when
  47634. // brushing only one item. So we use __rangeOffset to rebuilding range
  47635. // by coordRange. And this it only used in brush component so it is no
  47636. // need to be adapted to coordRanges.
  47637. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  47638. area.__rangeOffset = {
  47639. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  47640. xyMinMax: result.xyMinMax
  47641. };
  47642. }
  47643. });
  47644. return areas;
  47645. };
  47646. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  47647. each(areas, function (area) {
  47648. var targetInfo = this.findTargetInfo(area, ecModel);
  47649. if (targetInfo && targetInfo !== true) {
  47650. each(targetInfo.coordSyses, function (coordSys) {
  47651. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  47652. cb(area, result.values, coordSys, ecModel);
  47653. });
  47654. }
  47655. }, this);
  47656. };
  47657. /**
  47658. * the `areas` is `BrushModel.areas`.
  47659. * Called in layout stage.
  47660. * convert `area.coordRange` to global range and set panelId to `area.range`.
  47661. */
  47662. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  47663. each(areas, function (area) {
  47664. var targetInfo = this.findTargetInfo(area, ecModel);
  47665. if ("development" !== 'production') {
  47666. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  47667. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  47668. }
  47669. area.range = area.range || []; // convert coordRange to global range and set panelId.
  47670. if (targetInfo && targetInfo !== true) {
  47671. area.panelId = targetInfo.panelId; // (1) area.range shoule always be calculate from coordRange but does
  47672. // not keep its original value, for the sake of the dataZoom scenario,
  47673. // where area.coordRange remains unchanged but area.range may be changed.
  47674. // (2) Only support converting one coordRange to pixel range in brush
  47675. // component. So do not consider `coordRanges`.
  47676. // (3) About __rangeOffset, see comment above.
  47677. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  47678. var rangeOffset = area.__rangeOffset;
  47679. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  47680. }
  47681. }, this);
  47682. };
  47683. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  47684. return map(this._targetInfoList, function (targetInfo) {
  47685. var rect = targetInfo.getPanelRect();
  47686. return {
  47687. panelId: targetInfo.panelId,
  47688. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  47689. clipPath: makeRectPanelClipPath(rect),
  47690. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  47691. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  47692. };
  47693. });
  47694. };
  47695. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  47696. // Check whether area is bound in coord, and series do not belong to that coord.
  47697. // If do not do this check, some brush (like lineX) will controll all axes.
  47698. var targetInfo = this.findTargetInfo(area, ecModel);
  47699. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  47700. };
  47701. /**
  47702. * If return Object, a coord found.
  47703. * If reutrn true, global found.
  47704. * Otherwise nothing found.
  47705. */
  47706. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  47707. var targetInfoList = this._targetInfoList;
  47708. var foundCpts = parseFinder$1(ecModel, area);
  47709. for (var i = 0; i < targetInfoList.length; i++) {
  47710. var targetInfo = targetInfoList[i];
  47711. var areaPanelId = area.panelId;
  47712. if (areaPanelId) {
  47713. if (targetInfo.panelId === areaPanelId) {
  47714. return targetInfo;
  47715. }
  47716. } else {
  47717. for (var j = 0; j < targetInfoMatchers.length; j++) {
  47718. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  47719. return targetInfo;
  47720. }
  47721. }
  47722. }
  47723. }
  47724. return true;
  47725. };
  47726. return BrushTargetManager;
  47727. }();
  47728. function formatMinMax(minMax) {
  47729. minMax[0] > minMax[1] && minMax.reverse();
  47730. return minMax;
  47731. }
  47732. function parseFinder$1(ecModel, finder) {
  47733. return parseFinder(ecModel, finder, {
  47734. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  47735. });
  47736. }
  47737. var targetInfoBuilders = {
  47738. grid: function (foundCpts, targetInfoList) {
  47739. var xAxisModels = foundCpts.xAxisModels;
  47740. var yAxisModels = foundCpts.yAxisModels;
  47741. var gridModels = foundCpts.gridModels; // Remove duplicated.
  47742. var gridModelMap = createHashMap();
  47743. var xAxesHas = {};
  47744. var yAxesHas = {};
  47745. if (!xAxisModels && !yAxisModels && !gridModels) {
  47746. return;
  47747. }
  47748. each(xAxisModels, function (axisModel) {
  47749. var gridModel = axisModel.axis.grid.model;
  47750. gridModelMap.set(gridModel.id, gridModel);
  47751. xAxesHas[gridModel.id] = true;
  47752. });
  47753. each(yAxisModels, function (axisModel) {
  47754. var gridModel = axisModel.axis.grid.model;
  47755. gridModelMap.set(gridModel.id, gridModel);
  47756. yAxesHas[gridModel.id] = true;
  47757. });
  47758. each(gridModels, function (gridModel) {
  47759. gridModelMap.set(gridModel.id, gridModel);
  47760. xAxesHas[gridModel.id] = true;
  47761. yAxesHas[gridModel.id] = true;
  47762. });
  47763. gridModelMap.each(function (gridModel) {
  47764. var grid = gridModel.coordinateSystem;
  47765. var cartesians = [];
  47766. each(grid.getCartesians(), function (cartesian, index) {
  47767. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  47768. cartesians.push(cartesian);
  47769. }
  47770. });
  47771. targetInfoList.push({
  47772. panelId: 'grid--' + gridModel.id,
  47773. gridModel: gridModel,
  47774. coordSysModel: gridModel,
  47775. // Use the first one as the representitive coordSys.
  47776. coordSys: cartesians[0],
  47777. coordSyses: cartesians,
  47778. getPanelRect: panelRectBuilders.grid,
  47779. xAxisDeclared: xAxesHas[gridModel.id],
  47780. yAxisDeclared: yAxesHas[gridModel.id]
  47781. });
  47782. });
  47783. },
  47784. geo: function (foundCpts, targetInfoList) {
  47785. each(foundCpts.geoModels, function (geoModel) {
  47786. var coordSys = geoModel.coordinateSystem;
  47787. targetInfoList.push({
  47788. panelId: 'geo--' + geoModel.id,
  47789. geoModel: geoModel,
  47790. coordSysModel: geoModel,
  47791. coordSys: coordSys,
  47792. coordSyses: [coordSys],
  47793. getPanelRect: panelRectBuilders.geo
  47794. });
  47795. });
  47796. }
  47797. };
  47798. var targetInfoMatchers = [// grid
  47799. function (foundCpts, targetInfo) {
  47800. var xAxisModel = foundCpts.xAxisModel;
  47801. var yAxisModel = foundCpts.yAxisModel;
  47802. var gridModel = foundCpts.gridModel;
  47803. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  47804. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  47805. return gridModel && gridModel === targetInfo.gridModel;
  47806. }, // geo
  47807. function (foundCpts, targetInfo) {
  47808. var geoModel = foundCpts.geoModel;
  47809. return geoModel && geoModel === targetInfo.geoModel;
  47810. }];
  47811. var panelRectBuilders = {
  47812. grid: function () {
  47813. // grid is not Transformable.
  47814. return this.coordSys.master.getRect().clone();
  47815. },
  47816. geo: function () {
  47817. var coordSys = this.coordSys;
  47818. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  47819. rect.applyTransform(getTransform(coordSys));
  47820. return rect;
  47821. }
  47822. };
  47823. var coordConvert = {
  47824. lineX: curry(axisConvert, 0),
  47825. lineY: curry(axisConvert, 1),
  47826. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  47827. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  47828. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  47829. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  47830. return {
  47831. values: values,
  47832. xyMinMax: values
  47833. };
  47834. },
  47835. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  47836. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  47837. var values = map(rangeOrCoordRange, function (item) {
  47838. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  47839. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  47840. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  47841. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  47842. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  47843. return p;
  47844. });
  47845. return {
  47846. values: values,
  47847. xyMinMax: xyMinMax
  47848. };
  47849. }
  47850. };
  47851. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  47852. if ("development" !== 'production') {
  47853. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  47854. }
  47855. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  47856. var values = formatMinMax(map([0, 1], function (i) {
  47857. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  47858. }));
  47859. var xyMinMax = [];
  47860. xyMinMax[axisNameIndex] = values;
  47861. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  47862. return {
  47863. values: values,
  47864. xyMinMax: xyMinMax
  47865. };
  47866. }
  47867. var diffProcessor = {
  47868. lineX: curry(axisDiffProcessor, 0),
  47869. lineY: curry(axisDiffProcessor, 1),
  47870. rect: function (values, refer, scales) {
  47871. 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]]];
  47872. },
  47873. polygon: function (values, refer, scales) {
  47874. return map(values, function (item, idx) {
  47875. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  47876. });
  47877. }
  47878. };
  47879. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  47880. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  47881. } // We have to process scale caused by dataZoom manually,
  47882. // although it might be not accurate.
  47883. // Return [0~1, 0~1]
  47884. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  47885. var sizeCurr = getSize$1(xyMinMaxCurr);
  47886. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  47887. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  47888. isNaN(scales[0]) && (scales[0] = 1);
  47889. isNaN(scales[1]) && (scales[1] = 1);
  47890. return scales;
  47891. }
  47892. function getSize$1(xyMinMax) {
  47893. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  47894. }
  47895. var each$6 = each;
  47896. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  47897. var DataZoomFeature =
  47898. /** @class */
  47899. function (_super) {
  47900. __extends(DataZoomFeature, _super);
  47901. function DataZoomFeature() {
  47902. return _super !== null && _super.apply(this, arguments) || this;
  47903. }
  47904. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  47905. if (!this._brushController) {
  47906. this._brushController = new BrushController(api.getZr());
  47907. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  47908. }
  47909. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  47910. updateBackBtnStatus(featureModel, ecModel);
  47911. };
  47912. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  47913. handlers[type].call(this);
  47914. };
  47915. DataZoomFeature.prototype.remove = function (ecModel, api) {
  47916. this._brushController && this._brushController.unmount();
  47917. };
  47918. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  47919. this._brushController && this._brushController.dispose();
  47920. };
  47921. DataZoomFeature.prototype._onBrush = function (eventParam) {
  47922. var areas = eventParam.areas;
  47923. if (!eventParam.isEnd || !areas.length) {
  47924. return;
  47925. }
  47926. var snapshot = {};
  47927. var ecModel = this.ecModel;
  47928. this._brushController.updateCovers([]); // remove cover
  47929. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  47930. include: ['grid']
  47931. });
  47932. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  47933. if (coordSys.type !== 'cartesian2d') {
  47934. return;
  47935. }
  47936. var brushType = area.brushType;
  47937. if (brushType === 'rect') {
  47938. setBatch('x', coordSys, coordRange[0]);
  47939. setBatch('y', coordSys, coordRange[1]);
  47940. } else {
  47941. setBatch({
  47942. lineX: 'x',
  47943. lineY: 'y'
  47944. }[brushType], coordSys, coordRange);
  47945. }
  47946. });
  47947. push(ecModel, snapshot);
  47948. this._dispatchZoomAction(snapshot);
  47949. function setBatch(dimName, coordSys, minMax) {
  47950. var axis = coordSys.getAxis(dimName);
  47951. var axisModel = axis.model;
  47952. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  47953. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  47954. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  47955. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  47956. }
  47957. dataZoomModel && (snapshot[dataZoomModel.id] = {
  47958. dataZoomId: dataZoomModel.id,
  47959. startValue: minMax[0],
  47960. endValue: minMax[1]
  47961. });
  47962. }
  47963. function findDataZoom(dimName, axisModel, ecModel) {
  47964. var found;
  47965. ecModel.eachComponent({
  47966. mainType: 'dataZoom',
  47967. subType: 'select'
  47968. }, function (dzModel) {
  47969. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  47970. has && (found = dzModel);
  47971. });
  47972. return found;
  47973. }
  47974. };
  47975. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  47976. var batch = []; // Convert from hash map to array.
  47977. each$6(snapshot, function (batchItem, dataZoomId) {
  47978. batch.push(clone(batchItem));
  47979. });
  47980. batch.length && this.api.dispatchAction({
  47981. type: 'dataZoom',
  47982. from: this.uid,
  47983. batch: batch
  47984. });
  47985. };
  47986. DataZoomFeature.getDefaultOption = function (ecModel) {
  47987. var defaultOption = {
  47988. show: true,
  47989. filterMode: 'filter',
  47990. // Icon group
  47991. icon: {
  47992. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  47993. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  47994. },
  47995. // `zoom`, `back`
  47996. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  47997. brushStyle: {
  47998. borderWidth: 0,
  47999. color: 'rgba(210,219,238,0.2)'
  48000. }
  48001. };
  48002. return defaultOption;
  48003. };
  48004. return DataZoomFeature;
  48005. }(ToolboxFeature);
  48006. var handlers = {
  48007. zoom: function () {
  48008. var nextActive = !this._isZoomActive;
  48009. this.api.dispatchAction({
  48010. type: 'takeGlobalCursor',
  48011. key: 'dataZoomSelect',
  48012. dataZoomSelectActive: nextActive
  48013. });
  48014. },
  48015. back: function () {
  48016. this._dispatchZoomAction(pop(this.ecModel));
  48017. }
  48018. };
  48019. function makeAxisFinder(dzFeatureModel) {
  48020. var setting = {
  48021. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  48022. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  48023. xAxisId: dzFeatureModel.get('xAxisId', true),
  48024. yAxisId: dzFeatureModel.get('yAxisId', true)
  48025. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  48026. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  48027. // Some old cases set like this below to close yAxis control but leave xAxis control:
  48028. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  48029. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  48030. setting.xAxisIndex = 'all';
  48031. }
  48032. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  48033. setting.yAxisIndex = 'all';
  48034. }
  48035. return setting;
  48036. }
  48037. function updateBackBtnStatus(featureModel, ecModel) {
  48038. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  48039. }
  48040. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  48041. var zoomActive = view._isZoomActive;
  48042. if (payload && payload.type === 'takeGlobalCursor') {
  48043. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  48044. }
  48045. view._isZoomActive = zoomActive;
  48046. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  48047. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  48048. include: ['grid']
  48049. });
  48050. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  48051. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  48052. });
  48053. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  48054. brushType: 'auto',
  48055. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  48056. } : false);
  48057. }
  48058. registerInternalOptionCreator('dataZoom', function (ecModel) {
  48059. var toolboxModel = ecModel.getComponent('toolbox', 0);
  48060. var featureDataZoomPath = ['feature', 'dataZoom'];
  48061. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  48062. return;
  48063. }
  48064. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  48065. var dzOptions = [];
  48066. var finder = makeAxisFinder(dzFeatureModel);
  48067. var finderResult = parseFinder(ecModel, finder);
  48068. each$6(finderResult.xAxisModels, function (axisModel) {
  48069. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  48070. });
  48071. each$6(finderResult.yAxisModels, function (axisModel) {
  48072. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  48073. });
  48074. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  48075. var axisIndex = axisModel.componentIndex;
  48076. var newOpt = {
  48077. type: 'select',
  48078. $fromToolbox: true,
  48079. // Default to be filter
  48080. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  48081. // Id for merge mapping.
  48082. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  48083. };
  48084. newOpt[axisIndexPropName] = axisIndex;
  48085. dzOptions.push(newOpt);
  48086. }
  48087. return dzOptions;
  48088. });
  48089. function install$b(registers) {
  48090. registers.registerComponentModel(ToolboxModel);
  48091. registers.registerComponentView(ToolboxView);
  48092. registerFeature('saveAsImage', SaveAsImage);
  48093. registerFeature('magicType', MagicType);
  48094. registerFeature('dataView', DataView);
  48095. registerFeature('dataZoom', DataZoomFeature);
  48096. registerFeature('restore', RestoreOption);
  48097. use(install$a);
  48098. }
  48099. var TooltipModel =
  48100. /** @class */
  48101. function (_super) {
  48102. __extends(TooltipModel, _super);
  48103. function TooltipModel() {
  48104. var _this = _super !== null && _super.apply(this, arguments) || this;
  48105. _this.type = TooltipModel.type;
  48106. return _this;
  48107. }
  48108. TooltipModel.type = 'tooltip';
  48109. TooltipModel.dependencies = ['axisPointer'];
  48110. TooltipModel.defaultOption = {
  48111. // zlevel: 0,
  48112. z: 60,
  48113. show: true,
  48114. // tooltip main content
  48115. showContent: true,
  48116. // 'trigger' only works on coordinate system.
  48117. // 'item' | 'axis' | 'none'
  48118. trigger: 'item',
  48119. // 'click' | 'mousemove' | 'none'
  48120. triggerOn: 'mousemove|click',
  48121. alwaysShowContent: false,
  48122. displayMode: 'single',
  48123. renderMode: 'auto',
  48124. // whether restraint content inside viewRect.
  48125. // If renderMode: 'richText', default true.
  48126. // If renderMode: 'html', defaut false (for backward compat).
  48127. confine: null,
  48128. showDelay: 0,
  48129. hideDelay: 100,
  48130. // Animation transition time, unit is second
  48131. transitionDuration: 0.4,
  48132. enterable: false,
  48133. backgroundColor: '#fff',
  48134. // box shadow
  48135. shadowBlur: 10,
  48136. shadowColor: 'rgba(0, 0, 0, .2)',
  48137. shadowOffsetX: 1,
  48138. shadowOffsetY: 2,
  48139. // tooltip border radius, unit is px, default is 4
  48140. borderRadius: 4,
  48141. // tooltip border width, unit is px, default is 0 (no border)
  48142. borderWidth: 1,
  48143. // Tooltip inside padding, default is 5 for all direction
  48144. // Array is allowed to set up, right, bottom, left, same with css
  48145. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  48146. padding: null,
  48147. // Extra css text
  48148. extraCssText: '',
  48149. // axis indicator, trigger by axis
  48150. axisPointer: {
  48151. // default is line
  48152. // legal values: 'line' | 'shadow' | 'cross'
  48153. type: 'line',
  48154. // Valid when type is line, appoint tooltip line locate on which line. Optional
  48155. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  48156. // default is 'auto', chose the axis which type is category.
  48157. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  48158. axis: 'auto',
  48159. animation: 'auto',
  48160. animationDurationUpdate: 200,
  48161. animationEasingUpdate: 'exponentialOut',
  48162. crossStyle: {
  48163. color: '#999',
  48164. width: 1,
  48165. type: 'dashed',
  48166. // TODO formatter
  48167. textStyle: {}
  48168. } // lineStyle and shadowStyle should not be specified here,
  48169. // otherwise it will always override those styles on option.axisPointer.
  48170. },
  48171. textStyle: {
  48172. color: '#666',
  48173. fontSize: 14
  48174. }
  48175. };
  48176. return TooltipModel;
  48177. }(ComponentModel);
  48178. /* global document */
  48179. function shouldTooltipConfine(tooltipModel) {
  48180. var confineOption = tooltipModel.get('confine');
  48181. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  48182. : tooltipModel.get('renderMode') === 'richText';
  48183. }
  48184. function testStyle(styleProps) {
  48185. if (!env.domSupported) {
  48186. return;
  48187. }
  48188. var style = document.documentElement.style;
  48189. for (var i = 0, len = styleProps.length; i < len; i++) {
  48190. if (styleProps[i] in style) {
  48191. return styleProps[i];
  48192. }
  48193. }
  48194. }
  48195. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  48196. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  48197. function toCSSVendorPrefix(styleVendor, styleProp) {
  48198. if (!styleVendor) {
  48199. return styleProp;
  48200. }
  48201. styleProp = toCamelCase(styleProp, true);
  48202. var idx = styleVendor.indexOf(styleProp);
  48203. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  48204. return styleVendor.toLowerCase();
  48205. }
  48206. function getComputedStyle(el, style) {
  48207. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  48208. return stl ? style ? stl[style] : stl : null;
  48209. }
  48210. /* global document, window */
  48211. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  48212. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  48213. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  48214. function mirrorPos(pos) {
  48215. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  48216. return pos;
  48217. }
  48218. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  48219. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  48220. return '';
  48221. }
  48222. var backgroundColor = tooltipModel.get('backgroundColor');
  48223. var borderWidth = tooltipModel.get('borderWidth');
  48224. borderColor = convertToColorString(borderColor);
  48225. var arrowPos = mirrorPos(arrowPosition);
  48226. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  48227. var positionStyle = '';
  48228. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  48229. var rotateDeg;
  48230. if (indexOf(['left', 'right'], arrowPos) > -1) {
  48231. positionStyle += 'top:50%';
  48232. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  48233. } else {
  48234. positionStyle += 'left:50%';
  48235. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  48236. }
  48237. var rotateRadian = rotateDeg * Math.PI / 180;
  48238. var arrowWH = arrowSize + borderWidth;
  48239. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  48240. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  48241. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  48242. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  48243. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  48244. return "<div style=\"" + styleCss.join('') + "\"></div>";
  48245. }
  48246. function assembleTransition(duration, onlyFade) {
  48247. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  48248. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  48249. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  48250. if (!onlyFade) {
  48251. transitionOption = " " + duration + "s " + transitionCurve;
  48252. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  48253. }
  48254. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  48255. }
  48256. function assembleTransform(x, y, toString) {
  48257. // If using float on style, the final width of the dom might
  48258. // keep changing slightly while mouse move. So `toFixed(0)` them.
  48259. var x0 = x.toFixed(0) + 'px';
  48260. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  48261. if (!env.transformSupported) {
  48262. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  48263. } // support transform
  48264. var is3d = env.transform3dSupported;
  48265. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  48266. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  48267. }
  48268. /**
  48269. * @param {Object} textStyle
  48270. * @return {string}
  48271. * @inner
  48272. */
  48273. function assembleFont(textStyleModel) {
  48274. var cssText = [];
  48275. var fontSize = textStyleModel.get('fontSize');
  48276. var color = textStyleModel.getTextColor();
  48277. color && cssText.push('color:' + color);
  48278. cssText.push('font:' + textStyleModel.getFont());
  48279. fontSize // @ts-ignore, leave it to the tooltip refactor.
  48280. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  48281. var shadowColor = textStyleModel.get('textShadowColor');
  48282. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  48283. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  48284. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  48285. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  48286. each(['decoration', 'align'], function (name) {
  48287. var val = textStyleModel.get(name);
  48288. val && cssText.push('text-' + name + ':' + val);
  48289. });
  48290. return cssText.join(';');
  48291. }
  48292. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  48293. var cssText = [];
  48294. var transitionDuration = tooltipModel.get('transitionDuration');
  48295. var backgroundColor = tooltipModel.get('backgroundColor');
  48296. var shadowBlur = tooltipModel.get('shadowBlur');
  48297. var shadowColor = tooltipModel.get('shadowColor');
  48298. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  48299. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  48300. var textStyleModel = tooltipModel.getModel('textStyle');
  48301. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  48302. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  48303. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  48304. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  48305. if (backgroundColor) {
  48306. cssText.push('background-color:' + backgroundColor);
  48307. } // Border style
  48308. each(['width', 'color', 'radius'], function (name) {
  48309. var borderName = 'border-' + name;
  48310. var camelCase = toCamelCase(borderName);
  48311. var val = tooltipModel.get(camelCase);
  48312. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  48313. }); // Text style
  48314. cssText.push(assembleFont(textStyleModel)); // Padding
  48315. if (padding != null) {
  48316. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  48317. }
  48318. return cssText.join(';') + ';';
  48319. } // If not able to make, do not modify the input `out`.
  48320. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  48321. var zrPainter = zr && zr.painter;
  48322. if (appendToBody) {
  48323. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  48324. if (zrViewportRoot) {
  48325. // Some APPs might use scale on body, so we support CSS transform here.
  48326. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  48327. }
  48328. } else {
  48329. out[0] = zrX;
  48330. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  48331. // the sibling of canvas root. So padding of ec container
  48332. // should be considered here.
  48333. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  48334. if (viewportRootOffset) {
  48335. out[0] += viewportRootOffset.offsetLeft;
  48336. out[1] += viewportRootOffset.offsetTop;
  48337. }
  48338. }
  48339. out[2] = out[0] / zr.getWidth();
  48340. out[3] = out[1] / zr.getHeight();
  48341. }
  48342. var TooltipHTMLContent =
  48343. /** @class */
  48344. function () {
  48345. function TooltipHTMLContent(container, api, opt) {
  48346. this._show = false;
  48347. this._styleCoord = [0, 0, 0, 0];
  48348. this._enterable = true;
  48349. this._firstShow = true;
  48350. this._longHide = true;
  48351. if (env.wxa) {
  48352. return null;
  48353. }
  48354. var el = document.createElement('div'); // TODO: TYPE
  48355. el.domBelongToZr = true;
  48356. this.el = el;
  48357. var zr = this._zr = api.getZr();
  48358. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  48359. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  48360. if (appendToBody) {
  48361. document.body.appendChild(el);
  48362. } else {
  48363. container.appendChild(el);
  48364. }
  48365. this._container = container; // FIXME
  48366. // Is it needed to trigger zr event manually if
  48367. // the browser do not support `pointer-events: none`.
  48368. var self = this;
  48369. el.onmouseenter = function () {
  48370. // clear the timeout in hideLater and keep showing tooltip
  48371. if (self._enterable) {
  48372. clearTimeout(self._hideTimeout);
  48373. self._show = true;
  48374. }
  48375. self._inContent = true;
  48376. };
  48377. el.onmousemove = function (e) {
  48378. e = e || window.event;
  48379. if (!self._enterable) {
  48380. // `pointer-events: none` is set to tooltip content div
  48381. // if `enterable` is set as `false`, and `el.onmousemove`
  48382. // can not be triggered. But in browser that do not
  48383. // support `pointer-events`, we need to do this:
  48384. // Try trigger zrender event to avoid mouse
  48385. // in and out shape too frequently
  48386. var handler = zr.handler;
  48387. var zrViewportRoot = zr.painter.getViewportRoot();
  48388. normalizeEvent(zrViewportRoot, e, true);
  48389. handler.dispatch('mousemove', e);
  48390. }
  48391. };
  48392. el.onmouseleave = function () {
  48393. // set `_inContent` to `false` before `hideLater`
  48394. self._inContent = false;
  48395. if (self._enterable) {
  48396. if (self._show) {
  48397. self.hideLater(self._hideDelay);
  48398. }
  48399. }
  48400. };
  48401. }
  48402. /**
  48403. * Update when tooltip is rendered
  48404. */
  48405. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  48406. // FIXME
  48407. // Move this logic to ec main?
  48408. var container = this._container;
  48409. var position = getComputedStyle(container, 'position');
  48410. var domStyle = container.style;
  48411. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  48412. domStyle.position = 'relative';
  48413. } // move tooltip if chart resized
  48414. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  48415. alwaysShowContent && this._moveIfResized(); // update className
  48416. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  48417. // PENDING
  48418. // this.hide();
  48419. };
  48420. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  48421. clearTimeout(this._hideTimeout);
  48422. clearTimeout(this._longHideTimeout);
  48423. var el = this.el;
  48424. var style = el.style;
  48425. var styleCoord = this._styleCoord;
  48426. if (!el.innerHTML) {
  48427. style.display = 'none';
  48428. } else {
  48429. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  48430. + 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
  48431. // triggered by canvas, and cause some unexpectable result like dragging
  48432. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  48433. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  48434. // scenario.
  48435. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  48436. }
  48437. this._show = true;
  48438. this._firstShow = false;
  48439. this._longHide = false;
  48440. };
  48441. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  48442. var el = this.el;
  48443. if (content == null) {
  48444. el.innerHTML = '';
  48445. return;
  48446. }
  48447. var arrow = '';
  48448. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  48449. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  48450. }
  48451. if (isString(content)) {
  48452. el.innerHTML = content + arrow;
  48453. } else if (content) {
  48454. // Clear previous
  48455. el.innerHTML = '';
  48456. if (!isArray(content)) {
  48457. content = [content];
  48458. }
  48459. for (var i = 0; i < content.length; i++) {
  48460. if (isDom(content[i]) && content[i].parentNode !== el) {
  48461. el.appendChild(content[i]);
  48462. }
  48463. } // no arrow if empty
  48464. if (arrow && el.childNodes.length) {
  48465. // no need to create a new parent element, but it's not supported by IE 10 and older.
  48466. // const arrowEl = document.createRange().createContextualFragment(arrow);
  48467. var arrowEl = document.createElement('div');
  48468. arrowEl.innerHTML = arrow;
  48469. el.appendChild(arrowEl);
  48470. }
  48471. }
  48472. };
  48473. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  48474. this._enterable = enterable;
  48475. };
  48476. TooltipHTMLContent.prototype.getSize = function () {
  48477. var el = this.el;
  48478. return [el.offsetWidth, el.offsetHeight];
  48479. };
  48480. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  48481. var styleCoord = this._styleCoord;
  48482. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  48483. if (styleCoord[0] != null && styleCoord[1] != null) {
  48484. var style_1 = this.el.style;
  48485. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  48486. each(transforms, function (transform) {
  48487. style_1[transform[0]] = transform[1];
  48488. });
  48489. }
  48490. };
  48491. /**
  48492. * when `alwaysShowContent` is true,
  48493. * move the tooltip after chart resized
  48494. */
  48495. TooltipHTMLContent.prototype._moveIfResized = function () {
  48496. // The ratio of left to width
  48497. var ratioX = this._styleCoord[2]; // The ratio of top to height
  48498. var ratioY = this._styleCoord[3];
  48499. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  48500. };
  48501. TooltipHTMLContent.prototype.hide = function () {
  48502. var _this = this;
  48503. var style = this.el.style;
  48504. style.visibility = 'hidden';
  48505. style.opacity = '0';
  48506. env.transform3dSupported && (style.willChange = '');
  48507. this._show = false;
  48508. this._longHideTimeout = setTimeout(function () {
  48509. return _this._longHide = true;
  48510. }, 500);
  48511. };
  48512. TooltipHTMLContent.prototype.hideLater = function (time) {
  48513. if (this._show && !(this._inContent && this._enterable)) {
  48514. if (time) {
  48515. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  48516. this._show = false;
  48517. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  48518. } else {
  48519. this.hide();
  48520. }
  48521. }
  48522. };
  48523. TooltipHTMLContent.prototype.isShow = function () {
  48524. return this._show;
  48525. };
  48526. TooltipHTMLContent.prototype.dispose = function () {
  48527. this.el.parentNode.removeChild(this.el);
  48528. };
  48529. return TooltipHTMLContent;
  48530. }();
  48531. var TooltipRichContent =
  48532. /** @class */
  48533. function () {
  48534. function TooltipRichContent(api) {
  48535. this._show = false;
  48536. this._styleCoord = [0, 0, 0, 0];
  48537. this._enterable = true;
  48538. this._zr = api.getZr();
  48539. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  48540. }
  48541. /**
  48542. * Update when tooltip is rendered
  48543. */
  48544. TooltipRichContent.prototype.update = function (tooltipModel) {
  48545. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  48546. alwaysShowContent && this._moveIfResized();
  48547. };
  48548. TooltipRichContent.prototype.show = function () {
  48549. if (this._hideTimeout) {
  48550. clearTimeout(this._hideTimeout);
  48551. }
  48552. this.el.show();
  48553. this._show = true;
  48554. };
  48555. /**
  48556. * Set tooltip content
  48557. */
  48558. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  48559. var _this = this;
  48560. if (isObject(content)) {
  48561. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  48562. }
  48563. if (this.el) {
  48564. this._zr.remove(this.el);
  48565. }
  48566. var textStyleModel = tooltipModel.getModel('textStyle');
  48567. this.el = new ZRText({
  48568. style: {
  48569. rich: markupStyleCreator.richTextStyles,
  48570. text: content,
  48571. lineHeight: 22,
  48572. borderWidth: 1,
  48573. borderColor: borderColor,
  48574. textShadowColor: textStyleModel.get('textShadowColor'),
  48575. fill: tooltipModel.get(['textStyle', 'color']),
  48576. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  48577. verticalAlign: 'top',
  48578. align: 'left'
  48579. },
  48580. z: tooltipModel.get('z')
  48581. });
  48582. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  48583. _this.el.style[propName] = tooltipModel.get(propName);
  48584. });
  48585. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  48586. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  48587. });
  48588. this._zr.add(this.el);
  48589. var self = this;
  48590. this.el.on('mouseover', function () {
  48591. // clear the timeout in hideLater and keep showing tooltip
  48592. if (self._enterable) {
  48593. clearTimeout(self._hideTimeout);
  48594. self._show = true;
  48595. }
  48596. self._inContent = true;
  48597. });
  48598. this.el.on('mouseout', function () {
  48599. if (self._enterable) {
  48600. if (self._show) {
  48601. self.hideLater(self._hideDelay);
  48602. }
  48603. }
  48604. self._inContent = false;
  48605. });
  48606. };
  48607. TooltipRichContent.prototype.setEnterable = function (enterable) {
  48608. this._enterable = enterable;
  48609. };
  48610. TooltipRichContent.prototype.getSize = function () {
  48611. var el = this.el;
  48612. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  48613. // if overflow, it will be cut. So calculate them accurately.
  48614. var shadowOuterSize = calcShadowOuterSize(el.style);
  48615. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  48616. };
  48617. TooltipRichContent.prototype.moveTo = function (x, y) {
  48618. var el = this.el;
  48619. if (el) {
  48620. var styleCoord = this._styleCoord;
  48621. makeStyleCoord$1(styleCoord, this._zr, x, y);
  48622. x = styleCoord[0];
  48623. y = styleCoord[1];
  48624. var style = el.style;
  48625. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  48626. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  48627. el.x = x + borderWidth + shadowOuterSize.left;
  48628. el.y = y + borderWidth + shadowOuterSize.top;
  48629. el.markRedraw();
  48630. }
  48631. };
  48632. /**
  48633. * when `alwaysShowContent` is true,
  48634. * move the tooltip after chart resized
  48635. */
  48636. TooltipRichContent.prototype._moveIfResized = function () {
  48637. // The ratio of left to width
  48638. var ratioX = this._styleCoord[2]; // The ratio of top to height
  48639. var ratioY = this._styleCoord[3];
  48640. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  48641. };
  48642. TooltipRichContent.prototype.hide = function () {
  48643. if (this.el) {
  48644. this.el.hide();
  48645. }
  48646. this._show = false;
  48647. };
  48648. TooltipRichContent.prototype.hideLater = function (time) {
  48649. if (this._show && !(this._inContent && this._enterable)) {
  48650. if (time) {
  48651. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  48652. this._show = false;
  48653. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  48654. } else {
  48655. this.hide();
  48656. }
  48657. }
  48658. };
  48659. TooltipRichContent.prototype.isShow = function () {
  48660. return this._show;
  48661. };
  48662. TooltipRichContent.prototype.dispose = function () {
  48663. this._zr.remove(this.el);
  48664. };
  48665. return TooltipRichContent;
  48666. }();
  48667. function mathMaxWith0(val) {
  48668. return Math.max(0, val);
  48669. }
  48670. function calcShadowOuterSize(style) {
  48671. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  48672. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  48673. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  48674. return {
  48675. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  48676. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  48677. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  48678. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  48679. };
  48680. }
  48681. function makeStyleCoord$1(out, zr, zrX, zrY) {
  48682. out[0] = zrX;
  48683. out[1] = zrY;
  48684. out[2] = out[0] / zr.getWidth();
  48685. out[3] = out[1] / zr.getHeight();
  48686. }
  48687. var proxyRect = new Rect({
  48688. shape: {
  48689. x: -1,
  48690. y: -1,
  48691. width: 2,
  48692. height: 2
  48693. }
  48694. });
  48695. var TooltipView =
  48696. /** @class */
  48697. function (_super) {
  48698. __extends(TooltipView, _super);
  48699. function TooltipView() {
  48700. var _this = _super !== null && _super.apply(this, arguments) || this;
  48701. _this.type = TooltipView.type;
  48702. return _this;
  48703. }
  48704. TooltipView.prototype.init = function (ecModel, api) {
  48705. if (env.node || !api.getDom()) {
  48706. return;
  48707. }
  48708. var tooltipModel = ecModel.getComponent('tooltip');
  48709. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  48710. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  48711. appendToBody: tooltipModel.get('appendToBody', true)
  48712. });
  48713. };
  48714. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  48715. if (env.node || !api.getDom()) {
  48716. return;
  48717. } // Reset
  48718. this.group.removeAll();
  48719. this._tooltipModel = tooltipModel;
  48720. this._ecModel = ecModel;
  48721. this._api = api;
  48722. /**
  48723. * @private
  48724. * @type {boolean}
  48725. */
  48726. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  48727. var tooltipContent = this._tooltipContent;
  48728. tooltipContent.update(tooltipModel);
  48729. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  48730. this._initGlobalListener();
  48731. this._keepShow(); // PENDING
  48732. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  48733. // which causes that the `updatePosition` function was also called frequently.
  48734. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  48735. // To avoid frequent triggering,
  48736. // consider throttling it in 50ms when transition is enabled
  48737. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  48738. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  48739. } else {
  48740. clear(this, '_updatePosition');
  48741. }
  48742. };
  48743. TooltipView.prototype._initGlobalListener = function () {
  48744. var tooltipModel = this._tooltipModel;
  48745. var triggerOn = tooltipModel.get('triggerOn');
  48746. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  48747. // If 'none', it is not controlled by mouse totally.
  48748. if (triggerOn !== 'none') {
  48749. if (triggerOn.indexOf(currTrigger) >= 0) {
  48750. this._tryShow(e, dispatchAction);
  48751. } else if (currTrigger === 'leave') {
  48752. this._hide(dispatchAction);
  48753. }
  48754. }
  48755. }, this));
  48756. };
  48757. TooltipView.prototype._keepShow = function () {
  48758. var tooltipModel = this._tooltipModel;
  48759. var ecModel = this._ecModel;
  48760. var api = this._api; // Try to keep the tooltip show when refreshing
  48761. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  48762. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  48763. // which is not expected.
  48764. && tooltipModel.get('triggerOn') !== 'none') {
  48765. var self_1 = this;
  48766. clearTimeout(this._refreshUpdateTimeout);
  48767. this._refreshUpdateTimeout = setTimeout(function () {
  48768. // Show tip next tick after other charts are rendered
  48769. // In case highlight action has wrong result
  48770. // FIXME
  48771. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  48772. x: self_1._lastX,
  48773. y: self_1._lastY,
  48774. dataByCoordSys: self_1._lastDataByCoordSys
  48775. });
  48776. });
  48777. }
  48778. };
  48779. /**
  48780. * Show tip manually by
  48781. * dispatchAction({
  48782. * type: 'showTip',
  48783. * x: 10,
  48784. * y: 10
  48785. * });
  48786. * Or
  48787. * dispatchAction({
  48788. * type: 'showTip',
  48789. * seriesIndex: 0,
  48790. * dataIndex or dataIndexInside or name
  48791. * });
  48792. *
  48793. * TODO Batch
  48794. */
  48795. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  48796. if (payload.from === this.uid || env.node || !api.getDom()) {
  48797. return;
  48798. }
  48799. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  48800. this._ticket = ''; // When triggered from axisPointer.
  48801. var dataByCoordSys = payload.dataByCoordSys;
  48802. var cmptRef = findComponentReference(payload, ecModel, api);
  48803. if (cmptRef) {
  48804. var rect = cmptRef.el.getBoundingRect().clone();
  48805. rect.applyTransform(cmptRef.el.transform);
  48806. this._tryShow({
  48807. offsetX: rect.x + rect.width / 2,
  48808. offsetY: rect.y + rect.height / 2,
  48809. target: cmptRef.el,
  48810. position: payload.position,
  48811. // When manully trigger, the mouse is not on the el, so we'd better to
  48812. // position tooltip on the bottom of the el and display arrow is possible.
  48813. positionDefault: 'bottom'
  48814. }, dispatchAction);
  48815. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  48816. var el = proxyRect;
  48817. el.x = payload.x;
  48818. el.y = payload.y;
  48819. el.update();
  48820. getECData(el).tooltipConfig = {
  48821. name: null,
  48822. option: payload.tooltip
  48823. }; // Manually show tooltip while view is not using zrender elements.
  48824. this._tryShow({
  48825. offsetX: payload.x,
  48826. offsetY: payload.y,
  48827. target: el
  48828. }, dispatchAction);
  48829. } else if (dataByCoordSys) {
  48830. this._tryShow({
  48831. offsetX: payload.x,
  48832. offsetY: payload.y,
  48833. position: payload.position,
  48834. dataByCoordSys: dataByCoordSys,
  48835. tooltipOption: payload.tooltipOption
  48836. }, dispatchAction);
  48837. } else if (payload.seriesIndex != null) {
  48838. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  48839. return;
  48840. }
  48841. var pointInfo = findPointFromSeries(payload, ecModel);
  48842. var cx = pointInfo.point[0];
  48843. var cy = pointInfo.point[1];
  48844. if (cx != null && cy != null) {
  48845. this._tryShow({
  48846. offsetX: cx,
  48847. offsetY: cy,
  48848. target: pointInfo.el,
  48849. position: payload.position,
  48850. // When manully trigger, the mouse is not on the el, so we'd better to
  48851. // position tooltip on the bottom of the el and display arrow is possible.
  48852. positionDefault: 'bottom'
  48853. }, dispatchAction);
  48854. }
  48855. } else if (payload.x != null && payload.y != null) {
  48856. // FIXME
  48857. // should wrap dispatchAction like `axisPointer/globalListener` ?
  48858. api.dispatchAction({
  48859. type: 'updateAxisPointer',
  48860. x: payload.x,
  48861. y: payload.y
  48862. });
  48863. this._tryShow({
  48864. offsetX: payload.x,
  48865. offsetY: payload.y,
  48866. position: payload.position,
  48867. target: api.getZr().findHover(payload.x, payload.y).target
  48868. }, dispatchAction);
  48869. }
  48870. };
  48871. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  48872. var tooltipContent = this._tooltipContent;
  48873. if (!this._alwaysShowContent && this._tooltipModel) {
  48874. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  48875. }
  48876. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  48877. if (payload.from !== this.uid) {
  48878. this._hide(makeDispatchAction$1(payload, api));
  48879. }
  48880. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  48881. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  48882. // and tooltip.
  48883. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  48884. var seriesIndex = payload.seriesIndex;
  48885. var dataIndex = payload.dataIndex; // @ts-ignore
  48886. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  48887. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  48888. return;
  48889. }
  48890. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  48891. if (!seriesModel) {
  48892. return;
  48893. }
  48894. var data = seriesModel.getData();
  48895. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  48896. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  48897. return;
  48898. }
  48899. api.dispatchAction({
  48900. type: 'updateAxisPointer',
  48901. seriesIndex: seriesIndex,
  48902. dataIndex: dataIndex,
  48903. position: payload.position
  48904. });
  48905. return true;
  48906. };
  48907. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  48908. var el = e.target;
  48909. var tooltipModel = this._tooltipModel;
  48910. if (!tooltipModel) {
  48911. return;
  48912. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  48913. this._lastX = e.offsetX;
  48914. this._lastY = e.offsetY;
  48915. var dataByCoordSys = e.dataByCoordSys;
  48916. if (dataByCoordSys && dataByCoordSys.length) {
  48917. this._showAxisTooltip(dataByCoordSys, e);
  48918. } else if (el) {
  48919. this._lastDataByCoordSys = null;
  48920. var seriesDispatcher_1;
  48921. var cmptDispatcher_1;
  48922. findEventDispatcher(el, function (target) {
  48923. // Always show item tooltip if mouse is on the element with dataIndex
  48924. if (getECData(target).dataIndex != null) {
  48925. seriesDispatcher_1 = target;
  48926. return true;
  48927. } // Tooltip provided directly. Like legend.
  48928. if (getECData(target).tooltipConfig != null) {
  48929. cmptDispatcher_1 = target;
  48930. return true;
  48931. }
  48932. }, true);
  48933. if (seriesDispatcher_1) {
  48934. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  48935. } else if (cmptDispatcher_1) {
  48936. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  48937. } else {
  48938. this._hide(dispatchAction);
  48939. }
  48940. } else {
  48941. this._lastDataByCoordSys = null;
  48942. this._hide(dispatchAction);
  48943. }
  48944. };
  48945. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  48946. // showDelay is used in this case: tooltip.enterable is set
  48947. // as true. User intent to move mouse into tooltip and click
  48948. // something. `showDelay` makes it easier to enter the content
  48949. // but tooltip do not move immediately.
  48950. var delay = tooltipModel.get('showDelay');
  48951. cb = bind(cb, this);
  48952. clearTimeout(this._showTimout);
  48953. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  48954. };
  48955. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  48956. var ecModel = this._ecModel;
  48957. var globalTooltipModel = this._tooltipModel;
  48958. var point = [e.offsetX, e.offsetY];
  48959. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  48960. var renderMode = this._renderMode;
  48961. var cbParamsList = [];
  48962. var articleMarkup = createTooltipMarkup('section', {
  48963. blocks: [],
  48964. noHeader: true
  48965. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  48966. var markupTextArrLegacy = [];
  48967. var markupStyleCreator = new TooltipMarkupStyleCreator();
  48968. each(dataByCoordSys, function (itemCoordSys) {
  48969. each(itemCoordSys.dataByAxis, function (axisItem) {
  48970. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  48971. var axisValue = axisItem.value;
  48972. if (!axisModel || axisValue == null) {
  48973. return;
  48974. }
  48975. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  48976. var axisSectionMarkup = createTooltipMarkup('section', {
  48977. header: axisValueLabel,
  48978. noHeader: !trim(axisValueLabel),
  48979. sortBlocks: true,
  48980. blocks: []
  48981. });
  48982. articleMarkup.blocks.push(axisSectionMarkup);
  48983. each(axisItem.seriesDataIndices, function (idxItem) {
  48984. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  48985. var dataIndex = idxItem.dataIndexInside;
  48986. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  48987. if (cbParams.dataIndex < 0) {
  48988. return;
  48989. }
  48990. cbParams.axisDim = axisItem.axisDim;
  48991. cbParams.axisIndex = axisItem.axisIndex;
  48992. cbParams.axisType = axisItem.axisType;
  48993. cbParams.axisId = axisItem.axisId;
  48994. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  48995. value: axisValue
  48996. });
  48997. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  48998. // text in `formatter` callback and use those markers style.
  48999. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  49000. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  49001. var frag = seriesTooltipResult.frag;
  49002. if (frag) {
  49003. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  49004. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  49005. valueFormatter: valueFormatter
  49006. }, frag) : frag);
  49007. }
  49008. if (seriesTooltipResult.text) {
  49009. markupTextArrLegacy.push(seriesTooltipResult.text);
  49010. }
  49011. cbParamsList.push(cbParams);
  49012. });
  49013. });
  49014. }); // In most cases, the second axis is displays upper on the first one.
  49015. // So we reverse it to look better.
  49016. articleMarkup.blocks.reverse();
  49017. markupTextArrLegacy.reverse();
  49018. var positionExpr = e.position;
  49019. var orderMode = singleTooltipModel.get('order');
  49020. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  49021. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  49022. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  49023. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  49024. this._showOrMove(singleTooltipModel, function () {
  49025. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  49026. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  49027. } else {
  49028. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  49029. }
  49030. }); // Do not trigger events here, because this branch only be entered
  49031. // from dispatchAction.
  49032. };
  49033. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  49034. var ecModel = this._ecModel;
  49035. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  49036. // Used when mouseover on a element like markPoint or edge
  49037. // In which case, the data is not main data in series.
  49038. var seriesIndex = ecData.seriesIndex;
  49039. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  49040. var dataModel = ecData.dataModel || seriesModel;
  49041. var dataIndex = ecData.dataIndex;
  49042. var dataType = ecData.dataType;
  49043. var data = dataModel.getData(dataType);
  49044. var renderMode = this._renderMode;
  49045. var positionDefault = e.positionDefault;
  49046. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  49047. position: positionDefault
  49048. } : null);
  49049. var tooltipTrigger = tooltipModel.get('trigger');
  49050. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  49051. return;
  49052. }
  49053. var params = dataModel.getDataParams(dataIndex, dataType);
  49054. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  49055. // text in `formatter` callback and use those markers style.
  49056. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  49057. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  49058. var orderMode = tooltipModel.get('order');
  49059. var valueFormatter = tooltipModel.get('valueFormatter');
  49060. var frag = seriesTooltipResult.frag;
  49061. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  49062. valueFormatter: valueFormatter
  49063. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  49064. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  49065. this._showOrMove(tooltipModel, function () {
  49066. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  49067. }); // FIXME
  49068. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  49069. dispatchAction({
  49070. type: 'showTip',
  49071. dataIndexInside: dataIndex,
  49072. dataIndex: data.getRawIndex(dataIndex),
  49073. seriesIndex: seriesIndex,
  49074. from: this.uid
  49075. });
  49076. };
  49077. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  49078. var ecData = getECData(el);
  49079. var tooltipConfig = ecData.tooltipConfig;
  49080. var tooltipOpt = tooltipConfig.option || {};
  49081. if (isString(tooltipOpt)) {
  49082. var content = tooltipOpt;
  49083. tooltipOpt = {
  49084. content: content,
  49085. // Fixed formatter
  49086. formatter: content
  49087. };
  49088. }
  49089. var tooltipModelCascade = [tooltipOpt];
  49090. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  49091. if (cmpt) {
  49092. tooltipModelCascade.push(cmpt);
  49093. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  49094. // so that they can not share the same formatter. Since the global tooltip formatter is used for series
  49095. // by convension, we do not use it as the default formatter for component.
  49096. tooltipModelCascade.push({
  49097. formatter: tooltipOpt.content
  49098. });
  49099. var positionDefault = e.positionDefault;
  49100. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  49101. position: positionDefault
  49102. } : null);
  49103. var defaultHtml = subTooltipModel.get('content');
  49104. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  49105. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  49106. // only works on coordinate system. In fact, we have not found case
  49107. // that requires setting `trigger` nothing on component yet.
  49108. this._showOrMove(subTooltipModel, function () {
  49109. // Use formatterParams from element defined in component
  49110. // Avoid users modify it.
  49111. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  49112. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  49113. }); // If not dispatch showTip, tip may be hide triggered by axis.
  49114. dispatchAction({
  49115. type: 'showTip',
  49116. from: this.uid
  49117. });
  49118. };
  49119. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  49120. // Instead of top level tooltip.
  49121. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  49122. // Reset ticket
  49123. this._ticket = '';
  49124. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  49125. return;
  49126. }
  49127. var tooltipContent = this._tooltipContent;
  49128. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  49129. var formatter = tooltipModel.get('formatter');
  49130. positionExpr = positionExpr || tooltipModel.get('position');
  49131. var html = defaultHtml;
  49132. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  49133. var nearPointColor = nearPoint.color;
  49134. if (formatter) {
  49135. if (isString(formatter)) {
  49136. var useUTC = tooltipModel.ecModel.get('useUTC');
  49137. var params0 = isArray(params) ? params[0] : params;
  49138. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  49139. html = formatter;
  49140. if (isTimeAxis) {
  49141. html = format(params0.axisValue, html, useUTC);
  49142. }
  49143. html = formatTpl(html, params, true);
  49144. } else if (isFunction(formatter)) {
  49145. var callback = bind(function (cbTicket, html) {
  49146. if (cbTicket === this._ticket) {
  49147. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  49148. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  49149. }
  49150. }, this);
  49151. this._ticket = asyncTicket;
  49152. html = formatter(params, asyncTicket, callback);
  49153. } else {
  49154. html = formatter;
  49155. }
  49156. }
  49157. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  49158. tooltipContent.show(tooltipModel, nearPointColor);
  49159. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  49160. };
  49161. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  49162. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  49163. return {
  49164. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  49165. };
  49166. }
  49167. if (!isArray(tooltipDataParams)) {
  49168. return {
  49169. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  49170. };
  49171. }
  49172. };
  49173. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  49174. y, // Mouse y
  49175. content, params, el) {
  49176. var viewWidth = this._api.getWidth();
  49177. var viewHeight = this._api.getHeight();
  49178. positionExpr = positionExpr || tooltipModel.get('position');
  49179. var contentSize = content.getSize();
  49180. var align = tooltipModel.get('align');
  49181. var vAlign = tooltipModel.get('verticalAlign');
  49182. var rect = el && el.getBoundingRect().clone();
  49183. el && rect.applyTransform(el.transform);
  49184. if (isFunction(positionExpr)) {
  49185. // Callback of position can be an array or a string specify the position
  49186. positionExpr = positionExpr([x, y], params, content.el, rect, {
  49187. viewSize: [viewWidth, viewHeight],
  49188. contentSize: contentSize.slice()
  49189. });
  49190. }
  49191. if (isArray(positionExpr)) {
  49192. x = parsePercent$1(positionExpr[0], viewWidth);
  49193. y = parsePercent$1(positionExpr[1], viewHeight);
  49194. } else if (isObject(positionExpr)) {
  49195. var boxLayoutPosition = positionExpr;
  49196. boxLayoutPosition.width = contentSize[0];
  49197. boxLayoutPosition.height = contentSize[1];
  49198. var layoutRect = getLayoutRect(boxLayoutPosition, {
  49199. width: viewWidth,
  49200. height: viewHeight
  49201. });
  49202. x = layoutRect.x;
  49203. y = layoutRect.y;
  49204. align = null; // When positionExpr is left/top/right/bottom,
  49205. // align and verticalAlign will not work.
  49206. vAlign = null;
  49207. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  49208. else if (isString(positionExpr) && el) {
  49209. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  49210. x = pos[0];
  49211. y = pos[1];
  49212. } else {
  49213. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  49214. x = pos[0];
  49215. y = pos[1];
  49216. }
  49217. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  49218. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  49219. if (shouldTooltipConfine(tooltipModel)) {
  49220. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  49221. x = pos[0];
  49222. y = pos[1];
  49223. }
  49224. content.moveTo(x, y);
  49225. }; // FIXME
  49226. // Should we remove this but leave this to user?
  49227. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  49228. var lastCoordSys = this._lastDataByCoordSys;
  49229. var lastCbParamsList = this._cbParamsList;
  49230. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  49231. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  49232. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  49233. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  49234. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  49235. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  49236. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  49237. var thisItem = thisDataByAxis[indexAxis] || {};
  49238. var lastIndices = lastItem.seriesDataIndices || [];
  49239. var newIndices = thisItem.seriesDataIndices || [];
  49240. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  49241. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  49242. var newIdxItem = newIndices[j];
  49243. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  49244. }); // check is cbParams data value changed
  49245. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  49246. var seriesIdx = idxItem.seriesIndex;
  49247. var cbParams = cbParamsList[seriesIdx];
  49248. var lastCbParams = lastCbParamsList[seriesIdx];
  49249. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  49250. contentNotChanged = false;
  49251. }
  49252. });
  49253. });
  49254. });
  49255. this._lastDataByCoordSys = dataByCoordSys;
  49256. this._cbParamsList = cbParamsList;
  49257. return !!contentNotChanged;
  49258. };
  49259. TooltipView.prototype._hide = function (dispatchAction) {
  49260. // Do not directly hideLater here, because this behavior may be prevented
  49261. // in dispatchAction when showTip is dispatched.
  49262. // FIXME
  49263. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  49264. this._lastDataByCoordSys = null;
  49265. dispatchAction({
  49266. type: 'hideTip',
  49267. from: this.uid
  49268. });
  49269. };
  49270. TooltipView.prototype.dispose = function (ecModel, api) {
  49271. if (env.node || !api.getDom()) {
  49272. return;
  49273. }
  49274. clear(this, '_updatePosition');
  49275. this._tooltipContent.dispose();
  49276. unregister('itemTooltip', api);
  49277. };
  49278. TooltipView.type = 'tooltip';
  49279. return TooltipView;
  49280. }(ComponentView);
  49281. /**
  49282. * From top to bottom. (the last one should be globalTooltipModel);
  49283. */
  49284. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  49285. // Last is always tooltip model.
  49286. var ecModel = globalTooltipModel.ecModel;
  49287. var resultModel;
  49288. if (defaultTooltipOption) {
  49289. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  49290. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  49291. } else {
  49292. resultModel = globalTooltipModel;
  49293. }
  49294. for (var i = modelCascade.length - 1; i >= 0; i--) {
  49295. var tooltipOpt = modelCascade[i];
  49296. if (tooltipOpt) {
  49297. if (tooltipOpt instanceof Model) {
  49298. tooltipOpt = tooltipOpt.get('tooltip', true);
  49299. } // In each data item tooltip can be simply write:
  49300. // {
  49301. // value: 10,
  49302. // tooltip: 'Something you need to know'
  49303. // }
  49304. if (isString(tooltipOpt)) {
  49305. tooltipOpt = {
  49306. formatter: tooltipOpt
  49307. };
  49308. }
  49309. if (tooltipOpt) {
  49310. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  49311. }
  49312. }
  49313. }
  49314. return resultModel;
  49315. }
  49316. function makeDispatchAction$1(payload, api) {
  49317. return payload.dispatchAction || bind(api.dispatchAction, api);
  49318. }
  49319. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  49320. var size = content.getSize();
  49321. var width = size[0];
  49322. var height = size[1];
  49323. if (gapH != null) {
  49324. // Add extra 2 pixels for this case:
  49325. // At present the "values" in defaut tooltip are using CSS `float: right`.
  49326. // When the right edge of the tooltip box is on the right side of the
  49327. // viewport, the `float` layout might push the "values" to the second line.
  49328. if (x + width + gapH + 2 > viewWidth) {
  49329. x -= width + gapH;
  49330. } else {
  49331. x += gapH;
  49332. }
  49333. }
  49334. if (gapV != null) {
  49335. if (y + height + gapV > viewHeight) {
  49336. y -= height + gapV;
  49337. } else {
  49338. y += gapV;
  49339. }
  49340. }
  49341. return [x, y];
  49342. }
  49343. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  49344. var size = content.getSize();
  49345. var width = size[0];
  49346. var height = size[1];
  49347. x = Math.min(x + width, viewWidth) - width;
  49348. y = Math.min(y + height, viewHeight) - height;
  49349. x = Math.max(x, 0);
  49350. y = Math.max(y, 0);
  49351. return [x, y];
  49352. }
  49353. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  49354. var domWidth = contentSize[0];
  49355. var domHeight = contentSize[1];
  49356. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  49357. var x = 0;
  49358. var y = 0;
  49359. var rectWidth = rect.width;
  49360. var rectHeight = rect.height;
  49361. switch (position) {
  49362. case 'inside':
  49363. x = rect.x + rectWidth / 2 - domWidth / 2;
  49364. y = rect.y + rectHeight / 2 - domHeight / 2;
  49365. break;
  49366. case 'top':
  49367. x = rect.x + rectWidth / 2 - domWidth / 2;
  49368. y = rect.y - domHeight - offset;
  49369. break;
  49370. case 'bottom':
  49371. x = rect.x + rectWidth / 2 - domWidth / 2;
  49372. y = rect.y + rectHeight + offset;
  49373. break;
  49374. case 'left':
  49375. x = rect.x - domWidth - offset;
  49376. y = rect.y + rectHeight / 2 - domHeight / 2;
  49377. break;
  49378. case 'right':
  49379. x = rect.x + rectWidth + offset;
  49380. y = rect.y + rectHeight / 2 - domHeight / 2;
  49381. }
  49382. return [x, y];
  49383. }
  49384. function isCenterAlign(align) {
  49385. return align === 'center' || align === 'middle';
  49386. }
  49387. /**
  49388. * Find target component by payload like:
  49389. * ```js
  49390. * { legendId: 'some_id', name: 'xxx' }
  49391. * { toolboxIndex: 1, name: 'xxx' }
  49392. * { geoName: 'some_name', name: 'xxx' }
  49393. * ```
  49394. * PENDING: at present only
  49395. *
  49396. * If not found, return null/undefined.
  49397. */
  49398. function findComponentReference(payload, ecModel, api) {
  49399. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  49400. var componentMainType = queryOptionMap.keys()[0];
  49401. if (!componentMainType || componentMainType === 'series') {
  49402. return;
  49403. }
  49404. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  49405. useDefault: false,
  49406. enableAll: false,
  49407. enableNone: false
  49408. });
  49409. var model = queryResult.models[0];
  49410. if (!model) {
  49411. return;
  49412. }
  49413. var view = api.getViewOfComponentModel(model);
  49414. var el;
  49415. view.group.traverse(function (subEl) {
  49416. var tooltipConfig = getECData(subEl).tooltipConfig;
  49417. if (tooltipConfig && tooltipConfig.name === payload.name) {
  49418. el = subEl;
  49419. return true; // stop
  49420. }
  49421. });
  49422. if (el) {
  49423. return {
  49424. componentMainType: componentMainType,
  49425. componentIndex: model.componentIndex,
  49426. el: el
  49427. };
  49428. }
  49429. }
  49430. function install$c(registers) {
  49431. use(install$7);
  49432. registers.registerComponentModel(TooltipModel);
  49433. registers.registerComponentView(TooltipView);
  49434. /**
  49435. * @action
  49436. * @property {string} type
  49437. * @property {number} seriesIndex
  49438. * @property {number} dataIndex
  49439. * @property {number} [x]
  49440. * @property {number} [y]
  49441. */
  49442. registers.registerAction({
  49443. type: 'showTip',
  49444. event: 'showTip',
  49445. update: 'tooltip:manuallyShowTip'
  49446. }, noop);
  49447. registers.registerAction({
  49448. type: 'hideTip',
  49449. event: 'hideTip',
  49450. update: 'tooltip:manuallyHideTip'
  49451. }, noop);
  49452. }
  49453. var TitleModel =
  49454. /** @class */
  49455. function (_super) {
  49456. __extends(TitleModel, _super);
  49457. function TitleModel() {
  49458. var _this = _super !== null && _super.apply(this, arguments) || this;
  49459. _this.type = TitleModel.type;
  49460. _this.layoutMode = {
  49461. type: 'box',
  49462. ignoreSize: true
  49463. };
  49464. return _this;
  49465. }
  49466. TitleModel.type = 'title';
  49467. TitleModel.defaultOption = {
  49468. // zlevel: 0,
  49469. z: 6,
  49470. show: true,
  49471. text: '',
  49472. target: 'blank',
  49473. subtext: '',
  49474. subtarget: 'blank',
  49475. left: 0,
  49476. top: 0,
  49477. backgroundColor: 'rgba(0,0,0,0)',
  49478. borderColor: '#ccc',
  49479. borderWidth: 0,
  49480. padding: 5,
  49481. itemGap: 10,
  49482. textStyle: {
  49483. fontSize: 18,
  49484. fontWeight: 'bold',
  49485. color: '#464646'
  49486. },
  49487. subtextStyle: {
  49488. fontSize: 12,
  49489. color: '#6E7079'
  49490. }
  49491. };
  49492. return TitleModel;
  49493. }(ComponentModel); // View
  49494. var TitleView =
  49495. /** @class */
  49496. function (_super) {
  49497. __extends(TitleView, _super);
  49498. function TitleView() {
  49499. var _this = _super !== null && _super.apply(this, arguments) || this;
  49500. _this.type = TitleView.type;
  49501. return _this;
  49502. }
  49503. TitleView.prototype.render = function (titleModel, ecModel, api) {
  49504. this.group.removeAll();
  49505. if (!titleModel.get('show')) {
  49506. return;
  49507. }
  49508. var group = this.group;
  49509. var textStyleModel = titleModel.getModel('textStyle');
  49510. var subtextStyleModel = titleModel.getModel('subtextStyle');
  49511. var textAlign = titleModel.get('textAlign');
  49512. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  49513. var textEl = new ZRText({
  49514. style: createTextStyle(textStyleModel, {
  49515. text: titleModel.get('text'),
  49516. fill: textStyleModel.getTextColor()
  49517. }, {
  49518. disableBox: true
  49519. }),
  49520. z2: 10
  49521. });
  49522. var textRect = textEl.getBoundingRect();
  49523. var subText = titleModel.get('subtext');
  49524. var subTextEl = new ZRText({
  49525. style: createTextStyle(subtextStyleModel, {
  49526. text: subText,
  49527. fill: subtextStyleModel.getTextColor(),
  49528. y: textRect.height + titleModel.get('itemGap'),
  49529. verticalAlign: 'top'
  49530. }, {
  49531. disableBox: true
  49532. }),
  49533. z2: 10
  49534. });
  49535. var link = titleModel.get('link');
  49536. var sublink = titleModel.get('sublink');
  49537. var triggerEvent = titleModel.get('triggerEvent', true);
  49538. textEl.silent = !link && !triggerEvent;
  49539. subTextEl.silent = !sublink && !triggerEvent;
  49540. if (link) {
  49541. textEl.on('click', function () {
  49542. windowOpen(link, '_' + titleModel.get('target'));
  49543. });
  49544. }
  49545. if (sublink) {
  49546. subTextEl.on('click', function () {
  49547. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  49548. });
  49549. }
  49550. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  49551. componentType: 'title',
  49552. componentIndex: titleModel.componentIndex
  49553. } : null;
  49554. group.add(textEl);
  49555. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  49556. var groupRect = group.getBoundingRect();
  49557. var layoutOption = titleModel.getBoxLayoutParams();
  49558. layoutOption.width = groupRect.width;
  49559. layoutOption.height = groupRect.height;
  49560. var layoutRect = getLayoutRect(layoutOption, {
  49561. width: api.getWidth(),
  49562. height: api.getHeight()
  49563. }, titleModel.get('padding')); // Adjust text align based on position
  49564. if (!textAlign) {
  49565. // Align left if title is on the left. center and right is same
  49566. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  49567. if (textAlign === 'middle') {
  49568. textAlign = 'center';
  49569. } // Adjust layout by text align
  49570. if (textAlign === 'right') {
  49571. layoutRect.x += layoutRect.width;
  49572. } else if (textAlign === 'center') {
  49573. layoutRect.x += layoutRect.width / 2;
  49574. }
  49575. }
  49576. if (!textVerticalAlign) {
  49577. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  49578. if (textVerticalAlign === 'center') {
  49579. textVerticalAlign = 'middle';
  49580. }
  49581. if (textVerticalAlign === 'bottom') {
  49582. layoutRect.y += layoutRect.height;
  49583. } else if (textVerticalAlign === 'middle') {
  49584. layoutRect.y += layoutRect.height / 2;
  49585. }
  49586. textVerticalAlign = textVerticalAlign || 'top';
  49587. }
  49588. group.x = layoutRect.x;
  49589. group.y = layoutRect.y;
  49590. group.markRedraw();
  49591. var alignStyle = {
  49592. align: textAlign,
  49593. verticalAlign: textVerticalAlign
  49594. };
  49595. textEl.setStyle(alignStyle);
  49596. subTextEl.setStyle(alignStyle); // Render background
  49597. // Get groupRect again because textAlign has been changed
  49598. groupRect = group.getBoundingRect();
  49599. var padding = layoutRect.margin;
  49600. var style = titleModel.getItemStyle(['color', 'opacity']);
  49601. style.fill = titleModel.get('backgroundColor');
  49602. var rect = new Rect({
  49603. shape: {
  49604. x: groupRect.x - padding[3],
  49605. y: groupRect.y - padding[0],
  49606. width: groupRect.width + padding[1] + padding[3],
  49607. height: groupRect.height + padding[0] + padding[2],
  49608. r: titleModel.get('borderRadius')
  49609. },
  49610. style: style,
  49611. subPixelOptimize: true,
  49612. silent: true
  49613. });
  49614. group.add(rect);
  49615. };
  49616. TitleView.type = 'title';
  49617. return TitleView;
  49618. }(ComponentView);
  49619. function install$d(registers) {
  49620. registers.registerComponentModel(TitleModel);
  49621. registers.registerComponentView(TitleView);
  49622. }
  49623. function checkMarkerInSeries(seriesOpts, markerType) {
  49624. if (!seriesOpts) {
  49625. return false;
  49626. }
  49627. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  49628. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  49629. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  49630. return true;
  49631. }
  49632. }
  49633. return false;
  49634. }
  49635. function fillLabel(opt) {
  49636. defaultEmphasis(opt, 'label', ['show']);
  49637. } // { [componentType]: MarkerModel }
  49638. var inner$c = makeInner();
  49639. var MarkerModel =
  49640. /** @class */
  49641. function (_super) {
  49642. __extends(MarkerModel, _super);
  49643. function MarkerModel() {
  49644. var _this = _super !== null && _super.apply(this, arguments) || this;
  49645. _this.type = MarkerModel.type;
  49646. /**
  49647. * If marker model is created by self from series
  49648. */
  49649. _this.createdBySelf = false;
  49650. return _this;
  49651. }
  49652. /**
  49653. * @overrite
  49654. */
  49655. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  49656. if ("development" !== 'production') {
  49657. if (this.type === 'marker') {
  49658. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  49659. }
  49660. }
  49661. this.mergeDefaultAndTheme(option, ecModel);
  49662. this._mergeOption(option, ecModel, false, true);
  49663. };
  49664. MarkerModel.prototype.isAnimationEnabled = function () {
  49665. if (env.node) {
  49666. return false;
  49667. }
  49668. var hostSeries = this.__hostSeries;
  49669. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  49670. };
  49671. /**
  49672. * @overrite
  49673. */
  49674. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  49675. this._mergeOption(newOpt, ecModel, false, false);
  49676. };
  49677. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  49678. var componentType = this.mainType;
  49679. if (!createdBySelf) {
  49680. ecModel.eachSeries(function (seriesModel) {
  49681. // mainType can be markPoint, markLine, markArea
  49682. var markerOpt = seriesModel.get(this.mainType, true);
  49683. var markerModel = inner$c(seriesModel)[componentType];
  49684. if (!markerOpt || !markerOpt.data) {
  49685. inner$c(seriesModel)[componentType] = null;
  49686. return;
  49687. }
  49688. if (!markerModel) {
  49689. if (isInit) {
  49690. // Default label emphasis `position` and `show`
  49691. fillLabel(markerOpt);
  49692. }
  49693. each(markerOpt.data, function (item) {
  49694. // FIXME Overwrite fillLabel method ?
  49695. if (item instanceof Array) {
  49696. fillLabel(item[0]);
  49697. fillLabel(item[1]);
  49698. } else {
  49699. fillLabel(item);
  49700. }
  49701. });
  49702. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  49703. // markerOpt, this, ecModel
  49704. // );
  49705. extend(markerModel, {
  49706. mainType: this.mainType,
  49707. // Use the same series index and name
  49708. seriesIndex: seriesModel.seriesIndex,
  49709. name: seriesModel.name,
  49710. createdBySelf: true
  49711. });
  49712. markerModel.__hostSeries = seriesModel;
  49713. } else {
  49714. markerModel._mergeOption(markerOpt, ecModel, true);
  49715. }
  49716. inner$c(seriesModel)[componentType] = markerModel;
  49717. }, this);
  49718. }
  49719. };
  49720. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49721. var data = this.getData();
  49722. var value = this.getRawValue(dataIndex);
  49723. var itemName = data.getName(dataIndex);
  49724. return createTooltipMarkup('section', {
  49725. header: this.name,
  49726. blocks: [createTooltipMarkup('nameValue', {
  49727. name: itemName,
  49728. value: value,
  49729. noName: !itemName,
  49730. noValue: value == null
  49731. })]
  49732. });
  49733. };
  49734. MarkerModel.prototype.getData = function () {
  49735. return this._data;
  49736. };
  49737. MarkerModel.prototype.setData = function (data) {
  49738. this._data = data;
  49739. };
  49740. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  49741. componentType) {
  49742. return inner$c(seriesModel)[componentType];
  49743. };
  49744. MarkerModel.type = 'marker';
  49745. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  49746. return MarkerModel;
  49747. }(ComponentModel);
  49748. mixin(MarkerModel, DataFormatMixin.prototype);
  49749. var MarkPointModel =
  49750. /** @class */
  49751. function (_super) {
  49752. __extends(MarkPointModel, _super);
  49753. function MarkPointModel() {
  49754. var _this = _super !== null && _super.apply(this, arguments) || this;
  49755. _this.type = MarkPointModel.type;
  49756. return _this;
  49757. }
  49758. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  49759. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  49760. };
  49761. MarkPointModel.type = 'markPoint';
  49762. MarkPointModel.defaultOption = {
  49763. // zlevel: 0,
  49764. z: 5,
  49765. symbol: 'pin',
  49766. symbolSize: 50,
  49767. //symbolRotate: 0,
  49768. //symbolOffset: [0, 0]
  49769. tooltip: {
  49770. trigger: 'item'
  49771. },
  49772. label: {
  49773. show: true,
  49774. position: 'inside'
  49775. },
  49776. itemStyle: {
  49777. borderWidth: 2
  49778. },
  49779. emphasis: {
  49780. label: {
  49781. show: true
  49782. }
  49783. }
  49784. };
  49785. return MarkPointModel;
  49786. }(MarkerModel);
  49787. function hasXOrY(item) {
  49788. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  49789. }
  49790. function hasXAndY(item) {
  49791. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  49792. }
  49793. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  49794. var coordArr = [];
  49795. var stacked = isDimensionStacked(data, targetDataDim
  49796. /*, otherDataDim*/
  49797. );
  49798. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  49799. var value = numCalculate(data, calcDataDim, markerType);
  49800. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  49801. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  49802. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  49803. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  49804. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  49805. precision = Math.min(precision, 20);
  49806. if (precision >= 0) {
  49807. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  49808. }
  49809. return [coordArr, coordArrValue];
  49810. } // TODO Specified percent
  49811. var markerTypeCalculator = {
  49812. min: curry(markerTypeCalculatorWithExtent, 'min'),
  49813. max: curry(markerTypeCalculatorWithExtent, 'max'),
  49814. average: curry(markerTypeCalculatorWithExtent, 'average'),
  49815. median: curry(markerTypeCalculatorWithExtent, 'median')
  49816. };
  49817. /**
  49818. * Transform markPoint data item to format used in List by do the following
  49819. * 1. Calculate statistic like `max`, `min`, `average`
  49820. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  49821. */
  49822. function dataTransform(seriesModel, item) {
  49823. var data = seriesModel.getData();
  49824. var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly
  49825. // 2. If `coord` is not a data array. Which uses `xAxis`,
  49826. // `yAxis` to specify the coord on each dimension
  49827. // parseFloat first because item.x and item.y can be percent string like '20%'
  49828. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  49829. var dims = coordSys.dimensions;
  49830. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  49831. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  49832. item = clone(item);
  49833. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  49834. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  49835. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  49836. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  49837. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  49838. // let item use the value without stack.
  49839. item.value = coordInfo[1];
  49840. } else {
  49841. // FIXME Only has one of xAxis and yAxis.
  49842. var coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis]; // Each coord support max, min, average
  49843. for (var i = 0; i < 2; i++) {
  49844. if (markerTypeCalculator[coord[i]]) {
  49845. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  49846. }
  49847. }
  49848. item.coord = coord;
  49849. }
  49850. }
  49851. return item;
  49852. }
  49853. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  49854. var ret = {};
  49855. if (item.valueIndex != null || item.valueDim != null) {
  49856. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  49857. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  49858. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  49859. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  49860. } else {
  49861. ret.baseAxis = seriesModel.getBaseAxis();
  49862. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  49863. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  49864. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  49865. }
  49866. return ret;
  49867. }
  49868. function dataDimToCoordDim(seriesModel, dataDim) {
  49869. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  49870. return dimItem && dimItem.coordDim;
  49871. }
  49872. /**
  49873. * Filter data which is out of coordinateSystem range
  49874. * [dataFilter description]
  49875. */
  49876. function dataFilter$1( // Currently only polar and cartesian has containData.
  49877. coordSys, item) {
  49878. // Alwalys return true if there is no coordSys
  49879. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  49880. }
  49881. function createMarkerDimValueGetter(inCoordSys, dims) {
  49882. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  49883. var rawVal = dimIndex < 2 // x, y, radius, angle
  49884. ? item.coord && item.coord[dimIndex] : item.value;
  49885. return parseDataValue(rawVal, dims[dimIndex]);
  49886. } : function (item, dimName, dataIndex, dimIndex) {
  49887. return parseDataValue(item.value, dims[dimIndex]);
  49888. };
  49889. }
  49890. function numCalculate(data, valueDataDim, type) {
  49891. if (type === 'average') {
  49892. var sum_1 = 0;
  49893. var count_1 = 0;
  49894. data.each(valueDataDim, function (val, idx) {
  49895. if (!isNaN(val)) {
  49896. sum_1 += val;
  49897. count_1++;
  49898. }
  49899. });
  49900. return sum_1 / count_1;
  49901. } else if (type === 'median') {
  49902. return data.getMedian(valueDataDim);
  49903. } else {
  49904. // max & min
  49905. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  49906. }
  49907. }
  49908. var inner$d = makeInner();
  49909. var MarkerView =
  49910. /** @class */
  49911. function (_super) {
  49912. __extends(MarkerView, _super);
  49913. function MarkerView() {
  49914. var _this = _super !== null && _super.apply(this, arguments) || this;
  49915. _this.type = MarkerView.type;
  49916. return _this;
  49917. }
  49918. MarkerView.prototype.init = function () {
  49919. this.markerGroupMap = createHashMap();
  49920. };
  49921. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  49922. var _this = this;
  49923. var markerGroupMap = this.markerGroupMap;
  49924. markerGroupMap.each(function (item) {
  49925. inner$d(item).keep = false;
  49926. });
  49927. ecModel.eachSeries(function (seriesModel) {
  49928. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  49929. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  49930. });
  49931. markerGroupMap.each(function (item) {
  49932. !inner$d(item).keep && _this.group.remove(item.group);
  49933. });
  49934. };
  49935. MarkerView.prototype.markKeep = function (drawGroup) {
  49936. inner$d(drawGroup).keep = true;
  49937. };
  49938. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  49939. var _this = this;
  49940. each(seriesModelList, function (seriesModel) {
  49941. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  49942. if (markerModel) {
  49943. var data = markerModel.getData();
  49944. data.eachItemGraphicEl(function (el) {
  49945. if (el) {
  49946. isBlur ? enterBlur(el) : leaveBlur(el);
  49947. }
  49948. });
  49949. }
  49950. });
  49951. };
  49952. MarkerView.type = 'marker';
  49953. return MarkerView;
  49954. }(ComponentView);
  49955. function updateMarkerLayout(mpData, seriesModel, api) {
  49956. var coordSys = seriesModel.coordinateSystem;
  49957. mpData.each(function (idx) {
  49958. var itemModel = mpData.getItemModel(idx);
  49959. var point;
  49960. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  49961. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  49962. if (!isNaN(xPx) && !isNaN(yPx)) {
  49963. point = [xPx, yPx];
  49964. } // Chart like bar may have there own marker positioning logic
  49965. else if (seriesModel.getMarkerPosition) {
  49966. // Use the getMarkerPoisition
  49967. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  49968. } else if (coordSys) {
  49969. var x = mpData.get(coordSys.dimensions[0], idx);
  49970. var y = mpData.get(coordSys.dimensions[1], idx);
  49971. point = coordSys.dataToPoint([x, y]);
  49972. } // Use x, y if has any
  49973. if (!isNaN(xPx)) {
  49974. point[0] = xPx;
  49975. }
  49976. if (!isNaN(yPx)) {
  49977. point[1] = yPx;
  49978. }
  49979. mpData.setItemLayout(idx, point);
  49980. });
  49981. }
  49982. var MarkPointView =
  49983. /** @class */
  49984. function (_super) {
  49985. __extends(MarkPointView, _super);
  49986. function MarkPointView() {
  49987. var _this = _super !== null && _super.apply(this, arguments) || this;
  49988. _this.type = MarkPointView.type;
  49989. return _this;
  49990. }
  49991. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  49992. ecModel.eachSeries(function (seriesModel) {
  49993. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  49994. if (mpModel) {
  49995. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  49996. this.markerGroupMap.get(seriesModel.id).updateLayout();
  49997. }
  49998. }, this);
  49999. };
  50000. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  50001. var coordSys = seriesModel.coordinateSystem;
  50002. var seriesId = seriesModel.id;
  50003. var seriesData = seriesModel.getData();
  50004. var symbolDrawMap = this.markerGroupMap;
  50005. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  50006. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  50007. mpModel.setData(mpData);
  50008. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  50009. mpData.each(function (idx) {
  50010. var itemModel = mpData.getItemModel(idx);
  50011. var symbol = itemModel.getShallow('symbol');
  50012. var symbolSize = itemModel.getShallow('symbolSize');
  50013. var symbolRotate = itemModel.getShallow('symbolRotate');
  50014. var symbolOffset = itemModel.getShallow('symbolOffset');
  50015. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  50016. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  50017. var rawIdx = mpModel.getRawValue(idx);
  50018. var dataParams = mpModel.getDataParams(idx);
  50019. if (isFunction(symbol)) {
  50020. symbol = symbol(rawIdx, dataParams);
  50021. }
  50022. if (isFunction(symbolSize)) {
  50023. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  50024. symbolSize = symbolSize(rawIdx, dataParams);
  50025. }
  50026. if (isFunction(symbolRotate)) {
  50027. symbolRotate = symbolRotate(rawIdx, dataParams);
  50028. }
  50029. if (isFunction(symbolOffset)) {
  50030. symbolOffset = symbolOffset(rawIdx, dataParams);
  50031. }
  50032. }
  50033. var style = itemModel.getModel('itemStyle').getItemStyle();
  50034. var color = getVisualFromData(seriesData, 'color');
  50035. if (!style.fill) {
  50036. style.fill = color;
  50037. }
  50038. mpData.setItemVisual(idx, {
  50039. symbol: symbol,
  50040. symbolSize: symbolSize,
  50041. symbolRotate: symbolRotate,
  50042. symbolOffset: symbolOffset,
  50043. symbolKeepAspect: symbolKeepAspect,
  50044. style: style
  50045. });
  50046. }); // TODO Text are wrong
  50047. symbolDraw.updateData(mpData);
  50048. this.group.add(symbolDraw.group); // Set host model for tooltip
  50049. // FIXME
  50050. mpData.eachItemGraphicEl(function (el) {
  50051. el.traverse(function (child) {
  50052. getECData(child).dataModel = mpModel;
  50053. });
  50054. });
  50055. this.markKeep(symbolDraw);
  50056. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  50057. };
  50058. MarkPointView.type = 'markPoint';
  50059. return MarkPointView;
  50060. }(MarkerView);
  50061. function createData(coordSys, seriesModel, mpModel) {
  50062. var coordDimsInfos;
  50063. if (coordSys) {
  50064. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  50065. 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
  50066. return extend(extend({}, info), {
  50067. name: coordDim,
  50068. // DON'T use ordinalMeta to parse and collect ordinal.
  50069. ordinalMeta: null
  50070. });
  50071. });
  50072. } else {
  50073. coordDimsInfos = [{
  50074. name: 'value',
  50075. type: 'float'
  50076. }];
  50077. }
  50078. var mpData = new SeriesData(coordDimsInfos, mpModel);
  50079. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  50080. if (coordSys) {
  50081. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  50082. }
  50083. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  50084. mpData.initData(dataOpt, null, dimValueGetter);
  50085. return mpData;
  50086. }
  50087. function install$e(registers) {
  50088. registers.registerComponentModel(MarkPointModel);
  50089. registers.registerComponentView(MarkPointView);
  50090. registers.registerPreprocessor(function (opt) {
  50091. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  50092. // Make sure markPoint component is enabled
  50093. opt.markPoint = opt.markPoint || {};
  50094. }
  50095. });
  50096. }
  50097. var MarkLineModel =
  50098. /** @class */
  50099. function (_super) {
  50100. __extends(MarkLineModel, _super);
  50101. function MarkLineModel() {
  50102. var _this = _super !== null && _super.apply(this, arguments) || this;
  50103. _this.type = MarkLineModel.type;
  50104. return _this;
  50105. }
  50106. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  50107. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  50108. };
  50109. MarkLineModel.type = 'markLine';
  50110. MarkLineModel.defaultOption = {
  50111. // zlevel: 0,
  50112. z: 5,
  50113. symbol: ['circle', 'arrow'],
  50114. symbolSize: [8, 16],
  50115. //symbolRotate: 0,
  50116. symbolOffset: 0,
  50117. precision: 2,
  50118. tooltip: {
  50119. trigger: 'item'
  50120. },
  50121. label: {
  50122. show: true,
  50123. position: 'end',
  50124. distance: 5
  50125. },
  50126. lineStyle: {
  50127. type: 'dashed'
  50128. },
  50129. emphasis: {
  50130. label: {
  50131. show: true
  50132. },
  50133. lineStyle: {
  50134. width: 3
  50135. }
  50136. },
  50137. animationEasing: 'linear'
  50138. };
  50139. return MarkLineModel;
  50140. }(MarkerModel);
  50141. var straightLineProto = Line.prototype;
  50142. var bezierCurveProto = BezierCurve.prototype;
  50143. var StraightLineShape =
  50144. /** @class */
  50145. function () {
  50146. function StraightLineShape() {
  50147. // Start point
  50148. this.x1 = 0;
  50149. this.y1 = 0; // End point
  50150. this.x2 = 0;
  50151. this.y2 = 0;
  50152. this.percent = 1;
  50153. }
  50154. return StraightLineShape;
  50155. }();
  50156. var CurveShape =
  50157. /** @class */
  50158. function (_super) {
  50159. __extends(CurveShape, _super);
  50160. function CurveShape() {
  50161. return _super !== null && _super.apply(this, arguments) || this;
  50162. }
  50163. return CurveShape;
  50164. }(StraightLineShape);
  50165. function isStraightLine(shape) {
  50166. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  50167. }
  50168. var ECLinePath =
  50169. /** @class */
  50170. function (_super) {
  50171. __extends(ECLinePath, _super);
  50172. function ECLinePath(opts) {
  50173. var _this = _super.call(this, opts) || this;
  50174. _this.type = 'ec-line';
  50175. return _this;
  50176. }
  50177. ECLinePath.prototype.getDefaultStyle = function () {
  50178. return {
  50179. stroke: '#000',
  50180. fill: null
  50181. };
  50182. };
  50183. ECLinePath.prototype.getDefaultShape = function () {
  50184. return new StraightLineShape();
  50185. };
  50186. ECLinePath.prototype.buildPath = function (ctx, shape) {
  50187. if (isStraightLine(shape)) {
  50188. straightLineProto.buildPath.call(this, ctx, shape);
  50189. } else {
  50190. bezierCurveProto.buildPath.call(this, ctx, shape);
  50191. }
  50192. };
  50193. ECLinePath.prototype.pointAt = function (t) {
  50194. if (isStraightLine(this.shape)) {
  50195. return straightLineProto.pointAt.call(this, t);
  50196. } else {
  50197. return bezierCurveProto.pointAt.call(this, t);
  50198. }
  50199. };
  50200. ECLinePath.prototype.tangentAt = function (t) {
  50201. var shape = this.shape;
  50202. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  50203. return normalize(p, p);
  50204. };
  50205. return ECLinePath;
  50206. }(Path);
  50207. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  50208. function makeSymbolTypeKey(symbolCategory) {
  50209. return '_' + symbolCategory + 'Type';
  50210. }
  50211. /**
  50212. * @inner
  50213. */
  50214. function createSymbol$1(name, lineData, idx) {
  50215. var symbolType = lineData.getItemVisual(idx, name);
  50216. if (!symbolType || symbolType === 'none') {
  50217. return;
  50218. }
  50219. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  50220. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  50221. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  50222. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  50223. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  50224. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  50225. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  50226. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  50227. symbolPath.name = name;
  50228. return symbolPath;
  50229. }
  50230. function createLine(points) {
  50231. var line = new ECLinePath({
  50232. name: 'line',
  50233. subPixelOptimize: true
  50234. });
  50235. setLinePoints(line.shape, points);
  50236. return line;
  50237. }
  50238. function setLinePoints(targetShape, points) {
  50239. targetShape.x1 = points[0][0];
  50240. targetShape.y1 = points[0][1];
  50241. targetShape.x2 = points[1][0];
  50242. targetShape.y2 = points[1][1];
  50243. targetShape.percent = 1;
  50244. var cp1 = points[2];
  50245. if (cp1) {
  50246. targetShape.cpx1 = cp1[0];
  50247. targetShape.cpy1 = cp1[1];
  50248. } else {
  50249. targetShape.cpx1 = NaN;
  50250. targetShape.cpy1 = NaN;
  50251. }
  50252. }
  50253. var Line$1 =
  50254. /** @class */
  50255. function (_super) {
  50256. __extends(Line, _super);
  50257. function Line(lineData, idx, seriesScope) {
  50258. var _this = _super.call(this) || this;
  50259. _this._createLine(lineData, idx, seriesScope);
  50260. return _this;
  50261. }
  50262. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  50263. var seriesModel = lineData.hostModel;
  50264. var linePoints = lineData.getItemLayout(idx);
  50265. var line = createLine(linePoints);
  50266. line.shape.percent = 0;
  50267. initProps(line, {
  50268. shape: {
  50269. percent: 1
  50270. }
  50271. }, seriesModel, idx);
  50272. this.add(line);
  50273. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50274. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  50275. // it will be updated after line#update.
  50276. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  50277. this.add(symbol);
  50278. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  50279. }, this);
  50280. this._updateCommonStl(lineData, idx, seriesScope);
  50281. }; // TODO More strict on the List type in parameters?
  50282. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  50283. var seriesModel = lineData.hostModel;
  50284. var line = this.childOfName('line');
  50285. var linePoints = lineData.getItemLayout(idx);
  50286. var target = {
  50287. shape: {}
  50288. };
  50289. setLinePoints(target.shape, linePoints);
  50290. updateProps(line, target, seriesModel, idx);
  50291. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50292. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  50293. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  50294. if (this[key] !== symbolType) {
  50295. this.remove(this.childOfName(symbolCategory));
  50296. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  50297. this.add(symbol);
  50298. }
  50299. this[key] = symbolType;
  50300. }, this);
  50301. this._updateCommonStl(lineData, idx, seriesScope);
  50302. };
  50303. Line.prototype.getLinePath = function () {
  50304. return this.childAt(0);
  50305. };
  50306. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  50307. var seriesModel = lineData.hostModel;
  50308. var line = this.childOfName('line');
  50309. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  50310. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  50311. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  50312. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  50313. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  50314. var focus = seriesScope && seriesScope.focus;
  50315. var blurScope = seriesScope && seriesScope.blurScope; // Optimization for large dataset
  50316. if (!seriesScope || lineData.hasItemOption) {
  50317. var itemModel = lineData.getItemModel(idx);
  50318. var emphasisModel = itemModel.getModel('emphasis');
  50319. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  50320. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  50321. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  50322. emphasisDisabled = emphasisModel.get('disabled');
  50323. focus = emphasisModel.get('focus');
  50324. blurScope = emphasisModel.get('blurScope');
  50325. labelStatesModels = getLabelStatesModels(itemModel);
  50326. }
  50327. var lineStyle = lineData.getItemVisual(idx, 'style');
  50328. var visualColor = lineStyle.stroke;
  50329. line.useStyle(lineStyle);
  50330. line.style.fill = null;
  50331. line.style.strokeNoScale = true;
  50332. line.ensureState('emphasis').style = emphasisLineStyle;
  50333. line.ensureState('blur').style = blurLineStyle;
  50334. line.ensureState('select').style = selectLineStyle; // Update symbol
  50335. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  50336. var symbol = this.childOfName(symbolCategory);
  50337. if (symbol) {
  50338. // Share opacity and color with line.
  50339. symbol.setColor(visualColor);
  50340. symbol.style.opacity = lineStyle.opacity;
  50341. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  50342. var stateName = SPECIAL_STATES[i];
  50343. var lineState = line.getState(stateName);
  50344. if (lineState) {
  50345. var lineStateStyle = lineState.style || {};
  50346. var state = symbol.ensureState(stateName);
  50347. var stateStyle = state.style || (state.style = {});
  50348. if (lineStateStyle.stroke != null) {
  50349. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  50350. }
  50351. if (lineStateStyle.opacity != null) {
  50352. stateStyle.opacity = lineStateStyle.opacity;
  50353. }
  50354. }
  50355. }
  50356. symbol.markRedraw();
  50357. }
  50358. }, this);
  50359. var rawVal = seriesModel.getRawValue(idx);
  50360. setLabelStyle(this, labelStatesModels, {
  50361. labelDataIndex: idx,
  50362. labelFetcher: {
  50363. getFormattedLabel: function (dataIndex, stateName) {
  50364. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  50365. }
  50366. },
  50367. inheritColor: visualColor || '#000',
  50368. defaultOpacity: lineStyle.opacity,
  50369. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  50370. });
  50371. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  50372. // values have to be set on `normalStyle`.
  50373. if (label) {
  50374. var labelNormalModel = labelStatesModels.normal;
  50375. label.__align = label.style.align;
  50376. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  50377. label.__position = labelNormalModel.get('position') || 'middle';
  50378. var distance = labelNormalModel.get('distance');
  50379. if (!isArray(distance)) {
  50380. distance = [distance, distance];
  50381. }
  50382. label.__labelDistance = distance;
  50383. }
  50384. this.setTextConfig({
  50385. position: null,
  50386. local: true,
  50387. inside: false // Can't be inside for stroke element.
  50388. });
  50389. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  50390. };
  50391. Line.prototype.highlight = function () {
  50392. enterEmphasis(this);
  50393. };
  50394. Line.prototype.downplay = function () {
  50395. leaveEmphasis(this);
  50396. };
  50397. Line.prototype.updateLayout = function (lineData, idx) {
  50398. this.setLinePoints(lineData.getItemLayout(idx));
  50399. };
  50400. Line.prototype.setLinePoints = function (points) {
  50401. var linePath = this.childOfName('line');
  50402. setLinePoints(linePath.shape, points);
  50403. linePath.dirty();
  50404. };
  50405. Line.prototype.beforeUpdate = function () {
  50406. var lineGroup = this;
  50407. var symbolFrom = lineGroup.childOfName('fromSymbol');
  50408. var symbolTo = lineGroup.childOfName('toSymbol');
  50409. var label = lineGroup.getTextContent(); // Quick reject
  50410. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  50411. return;
  50412. }
  50413. var invScale = 1;
  50414. var parentNode = this.parent;
  50415. while (parentNode) {
  50416. if (parentNode.scaleX) {
  50417. invScale /= parentNode.scaleX;
  50418. }
  50419. parentNode = parentNode.parent;
  50420. }
  50421. var line = lineGroup.childOfName('line'); // If line not changed
  50422. // FIXME Parent scale changed
  50423. if (!this.__dirty && !line.__dirty) {
  50424. return;
  50425. }
  50426. var percent = line.shape.percent;
  50427. var fromPos = line.pointAt(0);
  50428. var toPos = line.pointAt(percent);
  50429. var d = sub([], toPos, fromPos);
  50430. normalize(d, d);
  50431. function setSymbolRotation(symbol, percent) {
  50432. // Fix #12388
  50433. // when symbol is set to be 'arrow' in markLine,
  50434. // symbolRotate value will be ignored, and compulsively use tangent angle.
  50435. // rotate by default if symbol rotation is not specified
  50436. var specifiedRotation = symbol.__specifiedRotation;
  50437. if (specifiedRotation == null) {
  50438. var tangent = line.tangentAt(percent);
  50439. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  50440. } else {
  50441. symbol.attr('rotation', specifiedRotation);
  50442. }
  50443. }
  50444. if (symbolFrom) {
  50445. symbolFrom.setPosition(fromPos);
  50446. setSymbolRotation(symbolFrom, 0);
  50447. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  50448. symbolFrom.markRedraw();
  50449. }
  50450. if (symbolTo) {
  50451. symbolTo.setPosition(toPos);
  50452. setSymbolRotation(symbolTo, 1);
  50453. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  50454. symbolTo.markRedraw();
  50455. }
  50456. if (label && !label.ignore) {
  50457. label.x = label.y = 0;
  50458. label.originX = label.originY = 0;
  50459. var textAlign = void 0;
  50460. var textVerticalAlign = void 0;
  50461. var distance = label.__labelDistance;
  50462. var distanceX = distance[0] * invScale;
  50463. var distanceY = distance[1] * invScale;
  50464. var halfPercent = percent / 2;
  50465. var tangent = line.tangentAt(halfPercent);
  50466. var n = [tangent[1], -tangent[0]];
  50467. var cp = line.pointAt(halfPercent);
  50468. if (n[1] > 0) {
  50469. n[0] = -n[0];
  50470. n[1] = -n[1];
  50471. }
  50472. var dir = tangent[0] < 0 ? -1 : 1;
  50473. if (label.__position !== 'start' && label.__position !== 'end') {
  50474. var rotation = -Math.atan2(tangent[1], tangent[0]);
  50475. if (toPos[0] < fromPos[0]) {
  50476. rotation = Math.PI + rotation;
  50477. }
  50478. label.rotation = rotation;
  50479. }
  50480. var dy = void 0;
  50481. switch (label.__position) {
  50482. case 'insideStartTop':
  50483. case 'insideMiddleTop':
  50484. case 'insideEndTop':
  50485. case 'middle':
  50486. dy = -distanceY;
  50487. textVerticalAlign = 'bottom';
  50488. break;
  50489. case 'insideStartBottom':
  50490. case 'insideMiddleBottom':
  50491. case 'insideEndBottom':
  50492. dy = distanceY;
  50493. textVerticalAlign = 'top';
  50494. break;
  50495. default:
  50496. dy = 0;
  50497. textVerticalAlign = 'middle';
  50498. }
  50499. switch (label.__position) {
  50500. case 'end':
  50501. label.x = d[0] * distanceX + toPos[0];
  50502. label.y = d[1] * distanceY + toPos[1];
  50503. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  50504. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  50505. break;
  50506. case 'start':
  50507. label.x = -d[0] * distanceX + fromPos[0];
  50508. label.y = -d[1] * distanceY + fromPos[1];
  50509. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  50510. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  50511. break;
  50512. case 'insideStartTop':
  50513. case 'insideStart':
  50514. case 'insideStartBottom':
  50515. label.x = distanceX * dir + fromPos[0];
  50516. label.y = fromPos[1] + dy;
  50517. textAlign = tangent[0] < 0 ? 'right' : 'left';
  50518. label.originX = -distanceX * dir;
  50519. label.originY = -dy;
  50520. break;
  50521. case 'insideMiddleTop':
  50522. case 'insideMiddle':
  50523. case 'insideMiddleBottom':
  50524. case 'middle':
  50525. label.x = cp[0];
  50526. label.y = cp[1] + dy;
  50527. textAlign = 'center';
  50528. label.originY = -dy;
  50529. break;
  50530. case 'insideEndTop':
  50531. case 'insideEnd':
  50532. case 'insideEndBottom':
  50533. label.x = -distanceX * dir + toPos[0];
  50534. label.y = toPos[1] + dy;
  50535. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  50536. label.originX = distanceX * dir;
  50537. label.originY = -dy;
  50538. break;
  50539. }
  50540. label.scaleX = label.scaleY = invScale;
  50541. label.setStyle({
  50542. // Use the user specified text align and baseline first
  50543. verticalAlign: label.__verticalAlign || textVerticalAlign,
  50544. align: label.__align || textAlign
  50545. });
  50546. }
  50547. };
  50548. return Line;
  50549. }(Group);
  50550. var LineDraw =
  50551. /** @class */
  50552. function () {
  50553. function LineDraw(LineCtor) {
  50554. this.group = new Group();
  50555. this._LineCtor = LineCtor || Line$1;
  50556. }
  50557. LineDraw.prototype.updateData = function (lineData) {
  50558. var _this = this; // Remove progressive els.
  50559. this._progressiveEls = null;
  50560. var lineDraw = this;
  50561. var group = lineDraw.group;
  50562. var oldLineData = lineDraw._lineData;
  50563. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  50564. // stream mode to normal mode, where previous elements should be removed.
  50565. if (!oldLineData) {
  50566. group.removeAll();
  50567. }
  50568. var seriesScope = makeSeriesScope$1(lineData);
  50569. lineData.diff(oldLineData).add(function (idx) {
  50570. _this._doAdd(lineData, idx, seriesScope);
  50571. }).update(function (newIdx, oldIdx) {
  50572. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  50573. }).remove(function (idx) {
  50574. group.remove(oldLineData.getItemGraphicEl(idx));
  50575. }).execute();
  50576. };
  50577. LineDraw.prototype.updateLayout = function () {
  50578. var lineData = this._lineData; // Do not support update layout in incremental mode.
  50579. if (!lineData) {
  50580. return;
  50581. }
  50582. lineData.eachItemGraphicEl(function (el, idx) {
  50583. el.updateLayout(lineData, idx);
  50584. }, this);
  50585. };
  50586. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  50587. this._seriesScope = makeSeriesScope$1(lineData);
  50588. this._lineData = null;
  50589. this.group.removeAll();
  50590. };
  50591. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  50592. this._progressiveEls = [];
  50593. function updateIncrementalAndHover(el) {
  50594. if (!el.isGroup && !isEffectObject(el)) {
  50595. el.incremental = true;
  50596. el.ensureState('emphasis').hoverLayer = true;
  50597. }
  50598. }
  50599. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  50600. var itemLayout = lineData.getItemLayout(idx);
  50601. if (lineNeedsDraw(itemLayout)) {
  50602. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  50603. el.traverse(updateIncrementalAndHover);
  50604. this.group.add(el);
  50605. lineData.setItemGraphicEl(idx, el);
  50606. this._progressiveEls.push(el);
  50607. }
  50608. }
  50609. };
  50610. LineDraw.prototype.remove = function () {
  50611. this.group.removeAll();
  50612. };
  50613. LineDraw.prototype.eachRendered = function (cb) {
  50614. traverseElements(this._progressiveEls || this.group, cb);
  50615. };
  50616. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  50617. var itemLayout = lineData.getItemLayout(idx);
  50618. if (!lineNeedsDraw(itemLayout)) {
  50619. return;
  50620. }
  50621. var el = new this._LineCtor(lineData, idx, seriesScope);
  50622. lineData.setItemGraphicEl(idx, el);
  50623. this.group.add(el);
  50624. };
  50625. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  50626. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  50627. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  50628. this.group.remove(itemEl);
  50629. return;
  50630. }
  50631. if (!itemEl) {
  50632. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  50633. } else {
  50634. itemEl.updateData(newLineData, newIdx, seriesScope);
  50635. }
  50636. newLineData.setItemGraphicEl(newIdx, itemEl);
  50637. this.group.add(itemEl);
  50638. };
  50639. return LineDraw;
  50640. }();
  50641. function isEffectObject(el) {
  50642. return el.animators && el.animators.length > 0;
  50643. }
  50644. function makeSeriesScope$1(lineData) {
  50645. var hostModel = lineData.hostModel;
  50646. var emphasisModel = hostModel.getModel('emphasis');
  50647. return {
  50648. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  50649. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  50650. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  50651. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  50652. emphasisDisabled: emphasisModel.get('disabled'),
  50653. blurScope: emphasisModel.get('blurScope'),
  50654. focus: emphasisModel.get('focus'),
  50655. labelStatesModels: getLabelStatesModels(hostModel)
  50656. };
  50657. }
  50658. function isPointNaN(pt) {
  50659. return isNaN(pt[0]) || isNaN(pt[1]);
  50660. }
  50661. function lineNeedsDraw(pts) {
  50662. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  50663. }
  50664. var inner$e = makeInner();
  50665. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  50666. var data = seriesModel.getData();
  50667. var itemArray;
  50668. if (!isArray(item)) {
  50669. // Special type markLine like 'min', 'max', 'average', 'median'
  50670. var mlType = item.type;
  50671. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  50672. // data: [{
  50673. // yAxis: 10
  50674. // }]
  50675. || item.xAxis != null || item.yAxis != null) {
  50676. var valueAxis = void 0;
  50677. var value = void 0;
  50678. if (item.yAxis != null || item.xAxis != null) {
  50679. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  50680. value = retrieve(item.yAxis, item.xAxis);
  50681. } else {
  50682. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  50683. valueAxis = axisInfo.valueAxis;
  50684. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  50685. value = numCalculate(data, valueDataDim, mlType);
  50686. }
  50687. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  50688. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  50689. var mlFrom = clone(item);
  50690. var mlTo = {
  50691. coord: []
  50692. };
  50693. mlFrom.type = null;
  50694. mlFrom.coord = [];
  50695. mlFrom.coord[baseIndex] = -Infinity;
  50696. mlTo.coord[baseIndex] = Infinity;
  50697. var precision = mlModel.get('precision');
  50698. if (precision >= 0 && isNumber(value)) {
  50699. value = +value.toFixed(Math.min(precision, 20));
  50700. }
  50701. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  50702. itemArray = [mlFrom, mlTo, {
  50703. type: mlType,
  50704. valueIndex: item.valueIndex,
  50705. // Force to use the value of calculated value.
  50706. value: value
  50707. }];
  50708. } else {
  50709. // Invalid data
  50710. if ("development" !== 'production') {
  50711. logError('Invalid markLine data.');
  50712. }
  50713. itemArray = [];
  50714. }
  50715. } else {
  50716. itemArray = item;
  50717. }
  50718. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  50719. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  50720. merge(normalizedItem[2], normalizedItem[0]);
  50721. merge(normalizedItem[2], normalizedItem[1]);
  50722. return normalizedItem;
  50723. };
  50724. function isInifinity(val) {
  50725. return !isNaN(val) && !isFinite(val);
  50726. } // If a markLine has one dim
  50727. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  50728. var otherDimIndex = 1 - dimIndex;
  50729. var dimName = coordSys.dimensions[dimIndex];
  50730. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  50731. }
  50732. function markLineFilter(coordSys, item) {
  50733. if (coordSys.type === 'cartesian2d') {
  50734. var fromCoord = item[0].coord;
  50735. var toCoord = item[1].coord; // In case
  50736. // {
  50737. // markLine: {
  50738. // data: [{ yAxis: 2 }]
  50739. // }
  50740. // }
  50741. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  50742. return true;
  50743. }
  50744. }
  50745. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  50746. }
  50747. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  50748. var coordSys = seriesModel.coordinateSystem;
  50749. var itemModel = data.getItemModel(idx);
  50750. var point;
  50751. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  50752. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  50753. if (!isNaN(xPx) && !isNaN(yPx)) {
  50754. point = [xPx, yPx];
  50755. } else {
  50756. // Chart like bar may have there own marker positioning logic
  50757. if (seriesModel.getMarkerPosition) {
  50758. // Use the getMarkerPoisition
  50759. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  50760. } else {
  50761. var dims = coordSys.dimensions;
  50762. var x = data.get(dims[0], idx);
  50763. var y = data.get(dims[1], idx);
  50764. point = coordSys.dataToPoint([x, y]);
  50765. } // Expand line to the edge of grid if value on one axis is Inifnity
  50766. // In case
  50767. // markLine: {
  50768. // data: [{
  50769. // yAxis: 2
  50770. // // or
  50771. // type: 'average'
  50772. // }]
  50773. // }
  50774. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  50775. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  50776. var xAxis = coordSys.getAxis('x');
  50777. var yAxis = coordSys.getAxis('y');
  50778. var dims = coordSys.dimensions;
  50779. if (isInifinity(data.get(dims[0], idx))) {
  50780. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  50781. } else if (isInifinity(data.get(dims[1], idx))) {
  50782. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  50783. }
  50784. } // Use x, y if has any
  50785. if (!isNaN(xPx)) {
  50786. point[0] = xPx;
  50787. }
  50788. if (!isNaN(yPx)) {
  50789. point[1] = yPx;
  50790. }
  50791. }
  50792. data.setItemLayout(idx, point);
  50793. }
  50794. var MarkLineView =
  50795. /** @class */
  50796. function (_super) {
  50797. __extends(MarkLineView, _super);
  50798. function MarkLineView() {
  50799. var _this = _super !== null && _super.apply(this, arguments) || this;
  50800. _this.type = MarkLineView.type;
  50801. return _this;
  50802. }
  50803. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  50804. ecModel.eachSeries(function (seriesModel) {
  50805. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  50806. if (mlModel) {
  50807. var mlData_1 = mlModel.getData();
  50808. var fromData_1 = inner$e(mlModel).from;
  50809. var toData_1 = inner$e(mlModel).to; // Update visual and layout of from symbol and to symbol
  50810. fromData_1.each(function (idx) {
  50811. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  50812. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  50813. }); // Update layout of line
  50814. mlData_1.each(function (idx) {
  50815. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  50816. });
  50817. this.markerGroupMap.get(seriesModel.id).updateLayout();
  50818. }
  50819. }, this);
  50820. };
  50821. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  50822. var coordSys = seriesModel.coordinateSystem;
  50823. var seriesId = seriesModel.id;
  50824. var seriesData = seriesModel.getData();
  50825. var lineDrawMap = this.markerGroupMap;
  50826. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  50827. this.group.add(lineDraw.group);
  50828. var mlData = createList$1(coordSys, seriesModel, mlModel);
  50829. var fromData = mlData.from;
  50830. var toData = mlData.to;
  50831. var lineData = mlData.line;
  50832. inner$e(mlModel).from = fromData;
  50833. inner$e(mlModel).to = toData; // Line data for tooltip and formatter
  50834. mlModel.setData(lineData); // TODO
  50835. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  50836. // But the related logic and type definition are not finished yet.
  50837. // Finish it if required
  50838. var symbolType = mlModel.get('symbol');
  50839. var symbolSize = mlModel.get('symbolSize');
  50840. var symbolRotate = mlModel.get('symbolRotate');
  50841. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  50842. if (!isArray(symbolType)) {
  50843. symbolType = [symbolType, symbolType];
  50844. }
  50845. if (!isArray(symbolSize)) {
  50846. symbolSize = [symbolSize, symbolSize];
  50847. }
  50848. if (!isArray(symbolRotate)) {
  50849. symbolRotate = [symbolRotate, symbolRotate];
  50850. }
  50851. if (!isArray(symbolOffset)) {
  50852. symbolOffset = [symbolOffset, symbolOffset];
  50853. } // Update visual and layout of from symbol and to symbol
  50854. mlData.from.each(function (idx) {
  50855. updateDataVisualAndLayout(fromData, idx, true);
  50856. updateDataVisualAndLayout(toData, idx, false);
  50857. }); // Update visual and layout of line
  50858. lineData.each(function (idx) {
  50859. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  50860. // color: lineColor || fromData.getItemVisual(idx, 'color')
  50861. // });
  50862. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  50863. if (lineStyle.stroke == null) {
  50864. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  50865. }
  50866. lineData.setItemVisual(idx, {
  50867. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  50868. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  50869. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  50870. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  50871. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  50872. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  50873. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  50874. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  50875. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  50876. toSymbol: toData.getItemVisual(idx, 'symbol'),
  50877. style: lineStyle
  50878. });
  50879. });
  50880. lineDraw.updateData(lineData); // Set host model for tooltip
  50881. // FIXME
  50882. mlData.line.eachItemGraphicEl(function (el, idx) {
  50883. el.traverse(function (child) {
  50884. getECData(child).dataModel = mlModel;
  50885. });
  50886. });
  50887. function updateDataVisualAndLayout(data, idx, isFrom) {
  50888. var itemModel = data.getItemModel(idx);
  50889. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  50890. var style = itemModel.getModel('itemStyle').getItemStyle();
  50891. if (style.fill == null) {
  50892. style.fill = getVisualFromData(seriesData, 'color');
  50893. }
  50894. data.setItemVisual(idx, {
  50895. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  50896. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  50897. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  50898. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  50899. // TODO: when 2d array is supported, it should ignore parent
  50900. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  50901. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  50902. style: style
  50903. });
  50904. }
  50905. this.markKeep(lineDraw);
  50906. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  50907. };
  50908. MarkLineView.type = 'markLine';
  50909. return MarkLineView;
  50910. }(MarkerView);
  50911. function createList$1(coordSys, seriesModel, mlModel) {
  50912. var coordDimsInfos;
  50913. if (coordSys) {
  50914. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  50915. 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
  50916. return extend(extend({}, info), {
  50917. name: coordDim,
  50918. // DON'T use ordinalMeta to parse and collect ordinal.
  50919. ordinalMeta: null
  50920. });
  50921. });
  50922. } else {
  50923. coordDimsInfos = [{
  50924. name: 'value',
  50925. type: 'float'
  50926. }];
  50927. }
  50928. var fromData = new SeriesData(coordDimsInfos, mlModel);
  50929. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  50930. var lineData = new SeriesData([], mlModel);
  50931. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  50932. if (coordSys) {
  50933. optData = filter(optData, curry(markLineFilter, coordSys));
  50934. }
  50935. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  50936. fromData.initData(map(optData, function (item) {
  50937. return item[0];
  50938. }), null, dimValueGetter);
  50939. toData.initData(map(optData, function (item) {
  50940. return item[1];
  50941. }), null, dimValueGetter);
  50942. lineData.initData(map(optData, function (item) {
  50943. return item[2];
  50944. }));
  50945. lineData.hasItemOption = true;
  50946. return {
  50947. from: fromData,
  50948. to: toData,
  50949. line: lineData
  50950. };
  50951. }
  50952. function install$f(registers) {
  50953. registers.registerComponentModel(MarkLineModel);
  50954. registers.registerComponentView(MarkLineView);
  50955. registers.registerPreprocessor(function (opt) {
  50956. if (checkMarkerInSeries(opt.series, 'markLine')) {
  50957. // Make sure markLine component is enabled
  50958. opt.markLine = opt.markLine || {};
  50959. }
  50960. });
  50961. }
  50962. var MarkAreaModel =
  50963. /** @class */
  50964. function (_super) {
  50965. __extends(MarkAreaModel, _super);
  50966. function MarkAreaModel() {
  50967. var _this = _super !== null && _super.apply(this, arguments) || this;
  50968. _this.type = MarkAreaModel.type;
  50969. return _this;
  50970. }
  50971. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  50972. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  50973. };
  50974. MarkAreaModel.type = 'markArea';
  50975. MarkAreaModel.defaultOption = {
  50976. // zlevel: 0,
  50977. // PENDING
  50978. z: 1,
  50979. tooltip: {
  50980. trigger: 'item'
  50981. },
  50982. // markArea should fixed on the coordinate system
  50983. animation: false,
  50984. label: {
  50985. show: true,
  50986. position: 'top'
  50987. },
  50988. itemStyle: {
  50989. // color and borderColor default to use color from series
  50990. // color: 'auto'
  50991. // borderColor: 'auto'
  50992. borderWidth: 0
  50993. },
  50994. emphasis: {
  50995. label: {
  50996. show: true,
  50997. position: 'top'
  50998. }
  50999. }
  51000. };
  51001. return MarkAreaModel;
  51002. }(MarkerModel);
  51003. var inner$f = makeInner();
  51004. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  51005. var lt = dataTransform(seriesModel, item[0]);
  51006. var rb = dataTransform(seriesModel, item[1]); // FIXME make sure lt is less than rb
  51007. var ltCoord = lt.coord;
  51008. var rbCoord = rb.coord;
  51009. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  51010. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  51011. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  51012. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  51013. var result = mergeAll([{}, lt, rb]);
  51014. result.coord = [lt.coord, rb.coord];
  51015. result.x0 = lt.x;
  51016. result.y0 = lt.y;
  51017. result.x1 = rb.x;
  51018. result.y1 = rb.y;
  51019. return result;
  51020. };
  51021. function isInifinity$1(val) {
  51022. return !isNaN(val) && !isFinite(val);
  51023. } // If a markArea has one dim
  51024. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  51025. var otherDimIndex = 1 - dimIndex;
  51026. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  51027. }
  51028. function markAreaFilter(coordSys, item) {
  51029. var fromCoord = item.coord[0];
  51030. var toCoord = item.coord[1];
  51031. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  51032. // In case
  51033. // {
  51034. // markArea: {
  51035. // data: [{ yAxis: 2 }]
  51036. // }
  51037. // }
  51038. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  51039. return true;
  51040. }
  51041. }
  51042. return dataFilter$1(coordSys, {
  51043. coord: fromCoord,
  51044. x: item.x0,
  51045. y: item.y0
  51046. }) || dataFilter$1(coordSys, {
  51047. coord: toCoord,
  51048. x: item.x1,
  51049. y: item.y1
  51050. });
  51051. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  51052. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  51053. var coordSys = seriesModel.coordinateSystem;
  51054. var itemModel = data.getItemModel(idx);
  51055. var point;
  51056. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  51057. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  51058. if (!isNaN(xPx) && !isNaN(yPx)) {
  51059. point = [xPx, yPx];
  51060. } else {
  51061. // Chart like bar may have there own marker positioning logic
  51062. if (seriesModel.getMarkerPosition) {
  51063. // Use the getMarkerPoisition
  51064. point = seriesModel.getMarkerPosition(data.getValues(dims, idx));
  51065. } else {
  51066. var x = data.get(dims[0], idx);
  51067. var y = data.get(dims[1], idx);
  51068. var pt = [x, y];
  51069. coordSys.clampData && coordSys.clampData(pt, pt);
  51070. point = coordSys.dataToPoint(pt, true);
  51071. }
  51072. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  51073. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  51074. var xAxis = coordSys.getAxis('x');
  51075. var yAxis = coordSys.getAxis('y');
  51076. var x = data.get(dims[0], idx);
  51077. var y = data.get(dims[1], idx);
  51078. if (isInifinity$1(x)) {
  51079. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  51080. } else if (isInifinity$1(y)) {
  51081. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  51082. }
  51083. } // Use x, y if has any
  51084. if (!isNaN(xPx)) {
  51085. point[0] = xPx;
  51086. }
  51087. if (!isNaN(yPx)) {
  51088. point[1] = yPx;
  51089. }
  51090. }
  51091. return point;
  51092. }
  51093. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  51094. var MarkAreaView =
  51095. /** @class */
  51096. function (_super) {
  51097. __extends(MarkAreaView, _super);
  51098. function MarkAreaView() {
  51099. var _this = _super !== null && _super.apply(this, arguments) || this;
  51100. _this.type = MarkAreaView.type;
  51101. return _this;
  51102. }
  51103. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  51104. ecModel.eachSeries(function (seriesModel) {
  51105. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  51106. if (maModel) {
  51107. var areaData_1 = maModel.getData();
  51108. areaData_1.each(function (idx) {
  51109. var points = map(dimPermutations, function (dim) {
  51110. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  51111. }); // Layout
  51112. areaData_1.setItemLayout(idx, points);
  51113. var el = areaData_1.getItemGraphicEl(idx);
  51114. el.setShape('points', points);
  51115. });
  51116. }
  51117. }, this);
  51118. };
  51119. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  51120. var coordSys = seriesModel.coordinateSystem;
  51121. var seriesId = seriesModel.id;
  51122. var seriesData = seriesModel.getData();
  51123. var areaGroupMap = this.markerGroupMap;
  51124. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  51125. group: new Group()
  51126. });
  51127. this.group.add(polygonGroup.group);
  51128. this.markKeep(polygonGroup);
  51129. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  51130. maModel.setData(areaData); // Update visual and layout of line
  51131. areaData.each(function (idx) {
  51132. // Layout
  51133. var points = map(dimPermutations, function (dim) {
  51134. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  51135. });
  51136. var xAxisScale = coordSys.getAxis('x').scale;
  51137. var yAxisScale = coordSys.getAxis('y').scale;
  51138. var xAxisExtent = xAxisScale.getExtent();
  51139. var yAxisExtent = yAxisScale.getExtent();
  51140. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  51141. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  51142. asc(xPointExtent);
  51143. asc(yPointExtent);
  51144. 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
  51145. // in layout so that label will not be displayed. See #12591
  51146. var allClipped = !overlapped;
  51147. areaData.setItemLayout(idx, {
  51148. points: points,
  51149. allClipped: allClipped
  51150. });
  51151. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  51152. var color$1 = getVisualFromData(seriesData, 'color');
  51153. if (!style.fill) {
  51154. style.fill = color$1;
  51155. if (isString(style.fill)) {
  51156. style.fill = modifyAlpha(style.fill, 0.4);
  51157. }
  51158. }
  51159. if (!style.stroke) {
  51160. style.stroke = color$1;
  51161. } // Visual
  51162. areaData.setItemVisual(idx, 'style', style);
  51163. });
  51164. areaData.diff(inner$f(polygonGroup).data).add(function (idx) {
  51165. var layout = areaData.getItemLayout(idx);
  51166. if (!layout.allClipped) {
  51167. var polygon = new Polygon({
  51168. shape: {
  51169. points: layout.points
  51170. }
  51171. });
  51172. areaData.setItemGraphicEl(idx, polygon);
  51173. polygonGroup.group.add(polygon);
  51174. }
  51175. }).update(function (newIdx, oldIdx) {
  51176. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(oldIdx);
  51177. var layout = areaData.getItemLayout(newIdx);
  51178. if (!layout.allClipped) {
  51179. if (polygon) {
  51180. updateProps(polygon, {
  51181. shape: {
  51182. points: layout.points
  51183. }
  51184. }, maModel, newIdx);
  51185. } else {
  51186. polygon = new Polygon({
  51187. shape: {
  51188. points: layout.points
  51189. }
  51190. });
  51191. }
  51192. areaData.setItemGraphicEl(newIdx, polygon);
  51193. polygonGroup.group.add(polygon);
  51194. } else if (polygon) {
  51195. polygonGroup.group.remove(polygon);
  51196. }
  51197. }).remove(function (idx) {
  51198. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(idx);
  51199. polygonGroup.group.remove(polygon);
  51200. }).execute();
  51201. areaData.eachItemGraphicEl(function (polygon, idx) {
  51202. var itemModel = areaData.getItemModel(idx);
  51203. var style = areaData.getItemVisual(idx, 'style');
  51204. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  51205. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  51206. labelFetcher: maModel,
  51207. labelDataIndex: idx,
  51208. defaultText: areaData.getName(idx) || '',
  51209. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  51210. });
  51211. setStatesStylesFromModel(polygon, itemModel);
  51212. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  51213. getECData(polygon).dataModel = maModel;
  51214. });
  51215. inner$f(polygonGroup).data = areaData;
  51216. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  51217. };
  51218. MarkAreaView.type = 'markArea';
  51219. return MarkAreaView;
  51220. }(MarkerView);
  51221. function createList$2(coordSys, seriesModel, maModel) {
  51222. var areaData;
  51223. var dataDims;
  51224. var dims = ['x0', 'y0', 'x1', 'y1'];
  51225. if (coordSys) {
  51226. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  51227. var data = seriesModel.getData();
  51228. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  51229. return extend(extend({}, info), {
  51230. name: coordDim,
  51231. // DON'T use ordinalMeta to parse and collect ordinal.
  51232. ordinalMeta: null
  51233. });
  51234. });
  51235. dataDims = map(dims, function (dim, idx) {
  51236. return {
  51237. name: dim,
  51238. type: coordDimsInfos_1[idx % 2].type
  51239. };
  51240. });
  51241. areaData = new SeriesData(dataDims, maModel);
  51242. } else {
  51243. dataDims = [{
  51244. name: 'value',
  51245. type: 'float'
  51246. }];
  51247. areaData = new SeriesData(dataDims, maModel);
  51248. }
  51249. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  51250. if (coordSys) {
  51251. optData = filter(optData, curry(markAreaFilter, coordSys));
  51252. }
  51253. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  51254. // TODO should convert to ParsedValue?
  51255. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  51256. return parseDataValue(rawVal, dataDims[dimIndex]);
  51257. } : function (item, dimName, dataIndex, dimIndex) {
  51258. return parseDataValue(item.value, dataDims[dimIndex]);
  51259. };
  51260. areaData.initData(optData, null, dimValueGetter);
  51261. areaData.hasItemOption = true;
  51262. return areaData;
  51263. }
  51264. function install$g(registers) {
  51265. registers.registerComponentModel(MarkAreaModel);
  51266. registers.registerComponentView(MarkAreaView);
  51267. registers.registerPreprocessor(function (opt) {
  51268. if (checkMarkerInSeries(opt.series, 'markArea')) {
  51269. // Make sure markArea component is enabled
  51270. opt.markArea = opt.markArea || {};
  51271. }
  51272. });
  51273. }
  51274. var getDefaultSelectorOptions = function (ecModel, type) {
  51275. if (type === 'all') {
  51276. return {
  51277. type: 'all',
  51278. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  51279. };
  51280. } else if (type === 'inverse') {
  51281. return {
  51282. type: 'inverse',
  51283. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  51284. };
  51285. }
  51286. };
  51287. var LegendModel =
  51288. /** @class */
  51289. function (_super) {
  51290. __extends(LegendModel, _super);
  51291. function LegendModel() {
  51292. var _this = _super !== null && _super.apply(this, arguments) || this;
  51293. _this.type = LegendModel.type;
  51294. _this.layoutMode = {
  51295. type: 'box',
  51296. // legend.width/height are maxWidth/maxHeight actually,
  51297. // whereas realy width/height is calculated by its content.
  51298. // (Setting {left: 10, right: 10} does not make sense).
  51299. // So consider the case:
  51300. // `setOption({legend: {left: 10});`
  51301. // then `setOption({legend: {right: 10});`
  51302. // The previous `left` should be cleared by setting `ignoreSize`.
  51303. ignoreSize: true
  51304. };
  51305. return _this;
  51306. }
  51307. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  51308. this.mergeDefaultAndTheme(option, ecModel);
  51309. option.selected = option.selected || {};
  51310. this._updateSelector(option);
  51311. };
  51312. LegendModel.prototype.mergeOption = function (option, ecModel) {
  51313. _super.prototype.mergeOption.call(this, option, ecModel);
  51314. this._updateSelector(option);
  51315. };
  51316. LegendModel.prototype._updateSelector = function (option) {
  51317. var selector = option.selector;
  51318. var ecModel = this.ecModel;
  51319. if (selector === true) {
  51320. selector = option.selector = ['all', 'inverse'];
  51321. }
  51322. if (isArray(selector)) {
  51323. each(selector, function (item, index) {
  51324. isString(item) && (item = {
  51325. type: item
  51326. });
  51327. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  51328. });
  51329. }
  51330. };
  51331. LegendModel.prototype.optionUpdated = function () {
  51332. this._updateData(this.ecModel);
  51333. var legendData = this._data; // If selectedMode is single, try to select one
  51334. if (legendData[0] && this.get('selectedMode') === 'single') {
  51335. var hasSelected = false; // If has any selected in option.selected
  51336. for (var i = 0; i < legendData.length; i++) {
  51337. var name_1 = legendData[i].get('name');
  51338. if (this.isSelected(name_1)) {
  51339. // Force to unselect others
  51340. this.select(name_1);
  51341. hasSelected = true;
  51342. break;
  51343. }
  51344. } // Try select the first if selectedMode is single
  51345. !hasSelected && this.select(legendData[0].get('name'));
  51346. }
  51347. };
  51348. LegendModel.prototype._updateData = function (ecModel) {
  51349. var potentialData = [];
  51350. var availableNames = [];
  51351. ecModel.eachRawSeries(function (seriesModel) {
  51352. var seriesName = seriesModel.name;
  51353. availableNames.push(seriesName);
  51354. var isPotential;
  51355. if (seriesModel.legendVisualProvider) {
  51356. var provider = seriesModel.legendVisualProvider;
  51357. var names = provider.getAllNames();
  51358. if (!ecModel.isSeriesFiltered(seriesModel)) {
  51359. availableNames = availableNames.concat(names);
  51360. }
  51361. if (names.length) {
  51362. potentialData = potentialData.concat(names);
  51363. } else {
  51364. isPotential = true;
  51365. }
  51366. } else {
  51367. isPotential = true;
  51368. }
  51369. if (isPotential && isNameSpecified(seriesModel)) {
  51370. potentialData.push(seriesModel.name);
  51371. }
  51372. });
  51373. /**
  51374. * @type {Array.<string>}
  51375. * @private
  51376. */
  51377. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  51378. // which is convinient for user preparing option.
  51379. var rawData = this.get('data') || potentialData;
  51380. var legendData = map(rawData, function (dataItem) {
  51381. // Can be string or number
  51382. if (isString(dataItem) || isNumber(dataItem)) {
  51383. dataItem = {
  51384. name: dataItem
  51385. };
  51386. }
  51387. return new Model(dataItem, this, this.ecModel);
  51388. }, this);
  51389. /**
  51390. * @type {Array.<module:echarts/model/Model>}
  51391. * @private
  51392. */
  51393. this._data = legendData;
  51394. };
  51395. LegendModel.prototype.getData = function () {
  51396. return this._data;
  51397. };
  51398. LegendModel.prototype.select = function (name) {
  51399. var selected = this.option.selected;
  51400. var selectedMode = this.get('selectedMode');
  51401. if (selectedMode === 'single') {
  51402. var data = this._data;
  51403. each(data, function (dataItem) {
  51404. selected[dataItem.get('name')] = false;
  51405. });
  51406. }
  51407. selected[name] = true;
  51408. };
  51409. LegendModel.prototype.unSelect = function (name) {
  51410. if (this.get('selectedMode') !== 'single') {
  51411. this.option.selected[name] = false;
  51412. }
  51413. };
  51414. LegendModel.prototype.toggleSelected = function (name) {
  51415. var selected = this.option.selected; // Default is true
  51416. if (!selected.hasOwnProperty(name)) {
  51417. selected[name] = true;
  51418. }
  51419. this[selected[name] ? 'unSelect' : 'select'](name);
  51420. };
  51421. LegendModel.prototype.allSelect = function () {
  51422. var data = this._data;
  51423. var selected = this.option.selected;
  51424. each(data, function (dataItem) {
  51425. selected[dataItem.get('name', true)] = true;
  51426. });
  51427. };
  51428. LegendModel.prototype.inverseSelect = function () {
  51429. var data = this._data;
  51430. var selected = this.option.selected;
  51431. each(data, function (dataItem) {
  51432. var name = dataItem.get('name', true); // Initially, default value is true
  51433. if (!selected.hasOwnProperty(name)) {
  51434. selected[name] = true;
  51435. }
  51436. selected[name] = !selected[name];
  51437. });
  51438. };
  51439. LegendModel.prototype.isSelected = function (name) {
  51440. var selected = this.option.selected;
  51441. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  51442. };
  51443. LegendModel.prototype.getOrient = function () {
  51444. return this.get('orient') === 'vertical' ? {
  51445. index: 1,
  51446. name: 'vertical'
  51447. } : {
  51448. index: 0,
  51449. name: 'horizontal'
  51450. };
  51451. };
  51452. LegendModel.type = 'legend.plain';
  51453. LegendModel.dependencies = ['series'];
  51454. LegendModel.defaultOption = {
  51455. // zlevel: 0,
  51456. z: 4,
  51457. show: true,
  51458. orient: 'horizontal',
  51459. left: 'center',
  51460. // right: 'center',
  51461. top: 0,
  51462. // bottom: null,
  51463. align: 'auto',
  51464. backgroundColor: 'rgba(0,0,0,0)',
  51465. borderColor: '#ccc',
  51466. borderRadius: 0,
  51467. borderWidth: 0,
  51468. padding: 5,
  51469. itemGap: 10,
  51470. itemWidth: 25,
  51471. itemHeight: 14,
  51472. symbolRotate: 'inherit',
  51473. symbolKeepAspect: true,
  51474. inactiveColor: '#ccc',
  51475. inactiveBorderColor: '#ccc',
  51476. inactiveBorderWidth: 'auto',
  51477. itemStyle: {
  51478. color: 'inherit',
  51479. opacity: 'inherit',
  51480. borderColor: 'inherit',
  51481. borderWidth: 'auto',
  51482. borderCap: 'inherit',
  51483. borderJoin: 'inherit',
  51484. borderDashOffset: 'inherit',
  51485. borderMiterLimit: 'inherit'
  51486. },
  51487. lineStyle: {
  51488. width: 'auto',
  51489. color: 'inherit',
  51490. inactiveColor: '#ccc',
  51491. inactiveWidth: 2,
  51492. opacity: 'inherit',
  51493. type: 'inherit',
  51494. cap: 'inherit',
  51495. join: 'inherit',
  51496. dashOffset: 'inherit',
  51497. miterLimit: 'inherit'
  51498. },
  51499. textStyle: {
  51500. color: '#333'
  51501. },
  51502. selectedMode: true,
  51503. selector: false,
  51504. selectorLabel: {
  51505. show: true,
  51506. borderRadius: 10,
  51507. padding: [3, 5, 3, 5],
  51508. fontSize: 12,
  51509. fontFamily: 'sans-serif',
  51510. color: '#666',
  51511. borderWidth: 1,
  51512. borderColor: '#666'
  51513. },
  51514. emphasis: {
  51515. selectorLabel: {
  51516. show: true,
  51517. color: '#eee',
  51518. backgroundColor: '#666'
  51519. }
  51520. },
  51521. selectorPosition: 'auto',
  51522. selectorItemGap: 7,
  51523. selectorButtonGap: 10,
  51524. tooltip: {
  51525. show: false
  51526. }
  51527. };
  51528. return LegendModel;
  51529. }(ComponentModel);
  51530. var curry$1 = curry;
  51531. var each$7 = each;
  51532. var Group$1 = Group;
  51533. var LegendView =
  51534. /** @class */
  51535. function (_super) {
  51536. __extends(LegendView, _super);
  51537. function LegendView() {
  51538. var _this = _super !== null && _super.apply(this, arguments) || this;
  51539. _this.type = LegendView.type;
  51540. _this.newlineDisabled = false;
  51541. return _this;
  51542. }
  51543. LegendView.prototype.init = function () {
  51544. this.group.add(this._contentGroup = new Group$1());
  51545. this.group.add(this._selectorGroup = new Group$1());
  51546. this._isFirstRender = true;
  51547. };
  51548. /**
  51549. * @protected
  51550. */
  51551. LegendView.prototype.getContentGroup = function () {
  51552. return this._contentGroup;
  51553. };
  51554. /**
  51555. * @protected
  51556. */
  51557. LegendView.prototype.getSelectorGroup = function () {
  51558. return this._selectorGroup;
  51559. };
  51560. /**
  51561. * @override
  51562. */
  51563. LegendView.prototype.render = function (legendModel, ecModel, api) {
  51564. var isFirstRender = this._isFirstRender;
  51565. this._isFirstRender = false;
  51566. this.resetInner();
  51567. if (!legendModel.get('show', true)) {
  51568. return;
  51569. }
  51570. var itemAlign = legendModel.get('align');
  51571. var orient = legendModel.get('orient');
  51572. if (!itemAlign || itemAlign === 'auto') {
  51573. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  51574. } // selector has been normalized to an array in model
  51575. var selector = legendModel.get('selector', true);
  51576. var selectorPosition = legendModel.get('selectorPosition', true);
  51577. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  51578. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  51579. }
  51580. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  51581. var positionInfo = legendModel.getBoxLayoutParams();
  51582. var viewportSize = {
  51583. width: api.getWidth(),
  51584. height: api.getHeight()
  51585. };
  51586. var padding = legendModel.get('padding');
  51587. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  51588. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  51589. var layoutRect = getLayoutRect(defaults({
  51590. width: mainRect.width,
  51591. height: mainRect.height
  51592. }, positionInfo), viewportSize, padding);
  51593. this.group.x = layoutRect.x - mainRect.x;
  51594. this.group.y = layoutRect.y - mainRect.y;
  51595. this.group.markRedraw(); // Render background after group is layout.
  51596. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  51597. };
  51598. LegendView.prototype.resetInner = function () {
  51599. this.getContentGroup().removeAll();
  51600. this._backgroundEl && this.group.remove(this._backgroundEl);
  51601. this.getSelectorGroup().removeAll();
  51602. };
  51603. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  51604. var contentGroup = this.getContentGroup();
  51605. var legendDrawnMap = createHashMap();
  51606. var selectMode = legendModel.get('selectedMode');
  51607. var excludeSeriesId = [];
  51608. ecModel.eachRawSeries(function (seriesModel) {
  51609. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  51610. });
  51611. each$7(legendModel.getData(), function (legendItemModel, dataIndex) {
  51612. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  51613. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  51614. var g = new Group$1(); // @ts-ignore
  51615. g.newline = true;
  51616. contentGroup.add(g);
  51617. return;
  51618. } // Representitive series.
  51619. var seriesModel = ecModel.getSeriesByName(name)[0];
  51620. if (legendDrawnMap.get(name)) {
  51621. // Have been drawed
  51622. return;
  51623. } // Legend to control series.
  51624. if (seriesModel) {
  51625. var data = seriesModel.getData();
  51626. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  51627. var legendIcon = data.getVisual('legendIcon');
  51628. /**
  51629. * `data.getVisual('style')` may be the color from the register
  51630. * in series. For example, for line series,
  51631. */
  51632. var style = data.getVisual('style');
  51633. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode);
  51634. 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));
  51635. legendDrawnMap.set(name, true);
  51636. } else {
  51637. // Legend to control data. In pie and funnel.
  51638. ecModel.eachRawSeries(function (seriesModel) {
  51639. // In case multiple series has same data name
  51640. if (legendDrawnMap.get(name)) {
  51641. return;
  51642. }
  51643. if (seriesModel.legendVisualProvider) {
  51644. var provider = seriesModel.legendVisualProvider;
  51645. if (!provider.containName(name)) {
  51646. return;
  51647. }
  51648. var idx = provider.indexOfName(name);
  51649. var style = provider.getItemVisual(idx, 'style');
  51650. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  51651. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  51652. // Do not show nothing.
  51653. if (colorArr && colorArr[3] === 0) {
  51654. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  51655. style = extend(extend({}, style), {
  51656. fill: stringify(colorArr, 'rgba')
  51657. });
  51658. }
  51659. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode); // FIXME: consider different series has items with the same name.
  51660. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  51661. // more than one pie series.
  51662. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  51663. legendDrawnMap.set(name, true);
  51664. }
  51665. }, this);
  51666. }
  51667. if ("development" !== 'production') {
  51668. if (!legendDrawnMap.get(name)) {
  51669. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  51670. }
  51671. }
  51672. }, this);
  51673. if (selector) {
  51674. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  51675. }
  51676. };
  51677. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  51678. var selectorGroup = this.getSelectorGroup();
  51679. each$7(selector, function createSelectorButton(selectorItem) {
  51680. var type = selectorItem.type;
  51681. var labelText = new ZRText({
  51682. style: {
  51683. x: 0,
  51684. y: 0,
  51685. align: 'center',
  51686. verticalAlign: 'middle'
  51687. },
  51688. onclick: function () {
  51689. api.dispatchAction({
  51690. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  51691. });
  51692. }
  51693. });
  51694. selectorGroup.add(labelText);
  51695. var labelModel = legendModel.getModel('selectorLabel');
  51696. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  51697. setLabelStyle(labelText, {
  51698. normal: labelModel,
  51699. emphasis: emphasisLabelModel
  51700. }, {
  51701. defaultText: selectorItem.title
  51702. });
  51703. enableHoverEmphasis(labelText);
  51704. });
  51705. };
  51706. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode) {
  51707. var drawType = seriesModel.visualDrawType;
  51708. var itemWidth = legendModel.get('itemWidth');
  51709. var itemHeight = legendModel.get('itemHeight');
  51710. var isSelected = legendModel.isSelected(name);
  51711. var iconRotate = legendItemModel.get('symbolRotate');
  51712. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  51713. var legendIconType = legendItemModel.get('icon');
  51714. legendIcon = legendIconType || legendIcon || 'roundRect';
  51715. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected);
  51716. var itemGroup = new Group$1();
  51717. var textStyleModel = legendItemModel.getModel('textStyle');
  51718. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  51719. // Series has specific way to define legend icon
  51720. itemGroup.add(seriesModel.getLegendIcon({
  51721. itemWidth: itemWidth,
  51722. itemHeight: itemHeight,
  51723. icon: legendIcon,
  51724. iconRotate: iconRotate,
  51725. itemStyle: style.itemStyle,
  51726. lineStyle: style.lineStyle,
  51727. symbolKeepAspect: symbolKeepAspect
  51728. }));
  51729. } else {
  51730. // Use default legend icon policy for most series
  51731. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  51732. itemGroup.add(getDefaultLegendIcon({
  51733. itemWidth: itemWidth,
  51734. itemHeight: itemHeight,
  51735. icon: legendIcon,
  51736. iconRotate: rotate,
  51737. itemStyle: style.itemStyle,
  51738. lineStyle: style.lineStyle,
  51739. symbolKeepAspect: symbolKeepAspect
  51740. }));
  51741. }
  51742. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  51743. var textAlign = itemAlign;
  51744. var formatter = legendModel.get('formatter');
  51745. var content = name;
  51746. if (isString(formatter) && formatter) {
  51747. content = formatter.replace('{name}', name != null ? name : '');
  51748. } else if (isFunction(formatter)) {
  51749. content = formatter(name);
  51750. }
  51751. var inactiveColor = legendItemModel.get('inactiveColor');
  51752. itemGroup.add(new ZRText({
  51753. style: createTextStyle(textStyleModel, {
  51754. text: content,
  51755. x: textX,
  51756. y: itemHeight / 2,
  51757. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  51758. align: textAlign,
  51759. verticalAlign: 'middle'
  51760. })
  51761. })); // Add a invisible rect to increase the area of mouse hover
  51762. var hitRect = new Rect({
  51763. shape: itemGroup.getBoundingRect(),
  51764. invisible: true
  51765. });
  51766. var tooltipModel = legendItemModel.getModel('tooltip');
  51767. if (tooltipModel.get('show')) {
  51768. setTooltipConfig({
  51769. el: hitRect,
  51770. componentModel: legendModel,
  51771. itemName: name,
  51772. itemTooltipOption: tooltipModel.option
  51773. });
  51774. }
  51775. itemGroup.add(hitRect);
  51776. itemGroup.eachChild(function (child) {
  51777. child.silent = true;
  51778. });
  51779. hitRect.silent = !selectMode;
  51780. this.getContentGroup().add(itemGroup);
  51781. enableHoverEmphasis(itemGroup); // @ts-ignore
  51782. itemGroup.__legendDataIndex = dataIndex;
  51783. return itemGroup;
  51784. };
  51785. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  51786. var contentGroup = this.getContentGroup();
  51787. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  51788. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  51789. var contentRect = contentGroup.getBoundingRect();
  51790. var contentPos = [-contentRect.x, -contentRect.y];
  51791. selectorGroup.markRedraw();
  51792. contentGroup.markRedraw();
  51793. if (selector) {
  51794. // Place buttons in selectorGroup
  51795. box( // Buttons in selectorGroup always layout horizontally
  51796. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  51797. var selectorRect = selectorGroup.getBoundingRect();
  51798. var selectorPos = [-selectorRect.x, -selectorRect.y];
  51799. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  51800. var orientIdx = legendModel.getOrient().index;
  51801. var wh = orientIdx === 0 ? 'width' : 'height';
  51802. var hw = orientIdx === 0 ? 'height' : 'width';
  51803. var yx = orientIdx === 0 ? 'y' : 'x';
  51804. if (selectorPosition === 'end') {
  51805. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  51806. } else {
  51807. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  51808. } //Always align selector to content as 'middle'
  51809. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  51810. selectorGroup.x = selectorPos[0];
  51811. selectorGroup.y = selectorPos[1];
  51812. contentGroup.x = contentPos[0];
  51813. contentGroup.y = contentPos[1];
  51814. var mainRect = {
  51815. x: 0,
  51816. y: 0
  51817. };
  51818. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  51819. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  51820. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  51821. return mainRect;
  51822. } else {
  51823. contentGroup.x = contentPos[0];
  51824. contentGroup.y = contentPos[1];
  51825. return this.group.getBoundingRect();
  51826. }
  51827. };
  51828. /**
  51829. * @protected
  51830. */
  51831. LegendView.prototype.remove = function () {
  51832. this.getContentGroup().removeAll();
  51833. this._isFirstRender = true;
  51834. };
  51835. LegendView.type = 'legend.plain';
  51836. return LegendView;
  51837. }(ComponentView);
  51838. function getLegendStyle(iconType, legendModel, lineVisualStyle, itemVisualStyle, drawType, isSelected) {
  51839. /**
  51840. * Use series style if is inherit;
  51841. * elsewise, use legend style
  51842. */
  51843. function handleCommonProps(style, visualStyle) {
  51844. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  51845. if (style.lineWidth === 'auto') {
  51846. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  51847. }
  51848. each$7(style, function (propVal, propName) {
  51849. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  51850. });
  51851. } // itemStyle
  51852. var legendItemModel = legendModel.getModel('itemStyle');
  51853. var itemStyle = legendItemModel.getItemStyle();
  51854. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  51855. itemStyle.decal = itemVisualStyle.decal;
  51856. if (itemStyle.fill === 'inherit') {
  51857. /**
  51858. * Series with visualDrawType as 'stroke' should have
  51859. * series stroke as legend fill
  51860. */
  51861. itemStyle.fill = itemVisualStyle[drawType];
  51862. }
  51863. if (itemStyle.stroke === 'inherit') {
  51864. /**
  51865. * icon type with "emptyXXX" should use fill color
  51866. * in visual style
  51867. */
  51868. itemStyle.stroke = itemVisualStyle[iconBrushType];
  51869. }
  51870. if (itemStyle.opacity === 'inherit') {
  51871. /**
  51872. * Use lineStyle.opacity if drawType is stroke
  51873. */
  51874. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  51875. }
  51876. handleCommonProps(itemStyle, itemVisualStyle); // lineStyle
  51877. var legendLineModel = legendModel.getModel('lineStyle');
  51878. var lineStyle = legendLineModel.getLineStyle();
  51879. handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color
  51880. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  51881. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  51882. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  51883. if (!isSelected) {
  51884. var borderWidth = legendModel.get('inactiveBorderWidth');
  51885. /**
  51886. * Since stroke is set to be inactiveBorderColor, it may occur that
  51887. * there is no border in series but border in legend, so we need to
  51888. * use border only when series has border if is set to be auto
  51889. */
  51890. var visualHasBorder = itemStyle[iconBrushType];
  51891. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  51892. itemStyle.fill = legendModel.get('inactiveColor');
  51893. itemStyle.stroke = legendModel.get('inactiveBorderColor');
  51894. lineStyle.stroke = legendLineModel.get('inactiveColor');
  51895. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  51896. }
  51897. return {
  51898. itemStyle: itemStyle,
  51899. lineStyle: lineStyle
  51900. };
  51901. }
  51902. function getDefaultLegendIcon(opt) {
  51903. var symboType = opt.icon || 'roundRect';
  51904. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  51905. icon.setStyle(opt.itemStyle);
  51906. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  51907. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  51908. if (symboType.indexOf('empty') > -1) {
  51909. icon.style.stroke = icon.style.fill;
  51910. icon.style.fill = '#fff';
  51911. icon.style.lineWidth = 2;
  51912. }
  51913. return icon;
  51914. }
  51915. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  51916. // downplay before unselect
  51917. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  51918. api.dispatchAction({
  51919. type: 'legendToggleSelect',
  51920. name: seriesName != null ? seriesName : dataName
  51921. }); // highlight after select
  51922. // TODO higlight immediately may cause animation loss.
  51923. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  51924. }
  51925. function isUseHoverLayer(api) {
  51926. var list = api.getZr().storage.getDisplayList();
  51927. var emphasisState;
  51928. var i = 0;
  51929. var len = list.length;
  51930. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  51931. i++;
  51932. }
  51933. return emphasisState && emphasisState.hoverLayer;
  51934. }
  51935. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  51936. // If element hover will move to a hoverLayer.
  51937. if (!isUseHoverLayer(api)) {
  51938. api.dispatchAction({
  51939. type: 'highlight',
  51940. seriesName: seriesName,
  51941. name: dataName,
  51942. excludeSeriesId: excludeSeriesId
  51943. });
  51944. }
  51945. }
  51946. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  51947. // If element hover will move to a hoverLayer.
  51948. if (!isUseHoverLayer(api)) {
  51949. api.dispatchAction({
  51950. type: 'downplay',
  51951. seriesName: seriesName,
  51952. name: dataName,
  51953. excludeSeriesId: excludeSeriesId
  51954. });
  51955. }
  51956. }
  51957. /*
  51958. * Licensed to the Apache Software Foundation (ASF) under one
  51959. * or more contributor license agreements. See the NOTICE file
  51960. * distributed with this work for additional information
  51961. * regarding copyright ownership. The ASF licenses this file
  51962. * to you under the Apache License, Version 2.0 (the
  51963. * "License"); you may not use this file except in compliance
  51964. * with the License. You may obtain a copy of the License at
  51965. *
  51966. * http://www.apache.org/licenses/LICENSE-2.0
  51967. *
  51968. * Unless required by applicable law or agreed to in writing,
  51969. * software distributed under the License is distributed on an
  51970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51971. * KIND, either express or implied. See the License for the
  51972. * specific language governing permissions and limitations
  51973. * under the License.
  51974. */
  51975. /**
  51976. * AUTO-GENERATED FILE. DO NOT MODIFY.
  51977. */
  51978. /*
  51979. * Licensed to the Apache Software Foundation (ASF) under one
  51980. * or more contributor license agreements. See the NOTICE file
  51981. * distributed with this work for additional information
  51982. * regarding copyright ownership. The ASF licenses this file
  51983. * to you under the Apache License, Version 2.0 (the
  51984. * "License"); you may not use this file except in compliance
  51985. * with the License. You may obtain a copy of the License at
  51986. *
  51987. * http://www.apache.org/licenses/LICENSE-2.0
  51988. *
  51989. * Unless required by applicable law or agreed to in writing,
  51990. * software distributed under the License is distributed on an
  51991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51992. * KIND, either express or implied. See the License for the
  51993. * specific language governing permissions and limitations
  51994. * under the License.
  51995. */
  51996. function legendFilter(ecModel) {
  51997. var legendModels = ecModel.findComponents({
  51998. mainType: 'legend'
  51999. });
  52000. if (legendModels && legendModels.length) {
  52001. ecModel.filterSeries(function (series) {
  52002. // If in any legend component the status is not selected.
  52003. // Because in legend series is assumed selected when it is not in the legend data.
  52004. for (var i = 0; i < legendModels.length; i++) {
  52005. if (!legendModels[i].isSelected(series.name)) {
  52006. return false;
  52007. }
  52008. }
  52009. return true;
  52010. });
  52011. }
  52012. }
  52013. function legendSelectActionHandler(methodName, payload, ecModel) {
  52014. var selectedMap = {};
  52015. var isToggleSelect = methodName === 'toggleSelected';
  52016. var isSelected; // Update all legend components
  52017. ecModel.eachComponent('legend', function (legendModel) {
  52018. if (isToggleSelect && isSelected != null) {
  52019. // Force other legend has same selected status
  52020. // Or the first is toggled to true and other are toggled to false
  52021. // In the case one legend has some item unSelected in option. And if other legend
  52022. // doesn't has the item, they will assume it is selected.
  52023. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  52024. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  52025. legendModel[methodName]();
  52026. } else {
  52027. legendModel[methodName](payload.name);
  52028. isSelected = legendModel.isSelected(payload.name);
  52029. }
  52030. var legendData = legendModel.getData();
  52031. each(legendData, function (model) {
  52032. var name = model.get('name'); // Wrap element
  52033. if (name === '\n' || name === '') {
  52034. return;
  52035. }
  52036. var isItemSelected = legendModel.isSelected(name);
  52037. if (selectedMap.hasOwnProperty(name)) {
  52038. // Unselected if any legend is unselected
  52039. selectedMap[name] = selectedMap[name] && isItemSelected;
  52040. } else {
  52041. selectedMap[name] = isItemSelected;
  52042. }
  52043. });
  52044. }); // Return the event explicitly
  52045. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  52046. selected: selectedMap
  52047. } : {
  52048. name: payload.name,
  52049. selected: selectedMap
  52050. };
  52051. }
  52052. function installLegendAction(registers) {
  52053. /**
  52054. * @event legendToggleSelect
  52055. * @type {Object}
  52056. * @property {string} type 'legendToggleSelect'
  52057. * @property {string} [from]
  52058. * @property {string} name Series name or data item name
  52059. */
  52060. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  52061. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  52062. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  52063. /**
  52064. * @event legendSelect
  52065. * @type {Object}
  52066. * @property {string} type 'legendSelect'
  52067. * @property {string} name Series name or data item name
  52068. */
  52069. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  52070. /**
  52071. * @event legendUnSelect
  52072. * @type {Object}
  52073. * @property {string} type 'legendUnSelect'
  52074. * @property {string} name Series name or data item name
  52075. */
  52076. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  52077. }
  52078. function install$h(registers) {
  52079. registers.registerComponentModel(LegendModel);
  52080. registers.registerComponentView(LegendView);
  52081. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  52082. registers.registerSubTypeDefaulter('legend', function () {
  52083. return 'plain';
  52084. });
  52085. installLegendAction(registers);
  52086. }
  52087. var ScrollableLegendModel =
  52088. /** @class */
  52089. function (_super) {
  52090. __extends(ScrollableLegendModel, _super);
  52091. function ScrollableLegendModel() {
  52092. var _this = _super !== null && _super.apply(this, arguments) || this;
  52093. _this.type = ScrollableLegendModel.type;
  52094. return _this;
  52095. }
  52096. /**
  52097. * @param {number} scrollDataIndex
  52098. */
  52099. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  52100. this.option.scrollDataIndex = scrollDataIndex;
  52101. };
  52102. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  52103. var inputPositionParams = getLayoutParams(option);
  52104. _super.prototype.init.call(this, option, parentModel, ecModel);
  52105. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  52106. };
  52107. /**
  52108. * @override
  52109. */
  52110. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  52111. _super.prototype.mergeOption.call(this, option, ecModel);
  52112. mergeAndNormalizeLayoutParams(this, this.option, option);
  52113. };
  52114. ScrollableLegendModel.type = 'legend.scroll';
  52115. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  52116. scrollDataIndex: 0,
  52117. pageButtonItemGap: 5,
  52118. pageButtonGap: null,
  52119. pageButtonPosition: 'end',
  52120. pageFormatter: '{current}/{total}',
  52121. pageIcons: {
  52122. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  52123. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  52124. },
  52125. pageIconColor: '#2f4554',
  52126. pageIconInactiveColor: '#aaa',
  52127. pageIconSize: 15,
  52128. pageTextStyle: {
  52129. color: '#333'
  52130. },
  52131. animationDurationUpdate: 800
  52132. });
  52133. return ScrollableLegendModel;
  52134. }(LegendModel);
  52135. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  52136. var orient = legendModel.getOrient();
  52137. var ignoreSize = [1, 1];
  52138. ignoreSize[orient.index] = 0;
  52139. mergeLayoutParam(target, raw, {
  52140. type: 'box',
  52141. ignoreSize: !!ignoreSize
  52142. });
  52143. }
  52144. var Group$2 = Group;
  52145. var WH = ['width', 'height'];
  52146. var XY = ['x', 'y'];
  52147. var ScrollableLegendView =
  52148. /** @class */
  52149. function (_super) {
  52150. __extends(ScrollableLegendView, _super);
  52151. function ScrollableLegendView() {
  52152. var _this = _super !== null && _super.apply(this, arguments) || this;
  52153. _this.type = ScrollableLegendView.type;
  52154. _this.newlineDisabled = true;
  52155. _this._currentIndex = 0;
  52156. return _this;
  52157. }
  52158. ScrollableLegendView.prototype.init = function () {
  52159. _super.prototype.init.call(this);
  52160. this.group.add(this._containerGroup = new Group$2());
  52161. this._containerGroup.add(this.getContentGroup());
  52162. this.group.add(this._controllerGroup = new Group$2());
  52163. };
  52164. /**
  52165. * @override
  52166. */
  52167. ScrollableLegendView.prototype.resetInner = function () {
  52168. _super.prototype.resetInner.call(this);
  52169. this._controllerGroup.removeAll();
  52170. this._containerGroup.removeClipPath();
  52171. this._containerGroup.__rectSize = null;
  52172. };
  52173. /**
  52174. * @override
  52175. */
  52176. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  52177. var self = this; // Render content items.
  52178. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  52179. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  52180. // e.g., '3/12345' should not overlap with the control arrow button.
  52181. var pageIconSize = legendModel.get('pageIconSize', true);
  52182. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  52183. createPageButton('pagePrev', 0);
  52184. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  52185. controllerGroup.add(new ZRText({
  52186. name: 'pageText',
  52187. style: {
  52188. // Placeholder to calculate a proper layout.
  52189. text: 'xx/xx',
  52190. fill: pageTextStyleModel.getTextColor(),
  52191. font: pageTextStyleModel.getFont(),
  52192. verticalAlign: 'middle',
  52193. align: 'center'
  52194. },
  52195. silent: true
  52196. }));
  52197. createPageButton('pageNext', 1);
  52198. function createPageButton(name, iconIdx) {
  52199. var pageDataIndexName = name + 'DataIndex';
  52200. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  52201. // Buttons will be created in each render, so we do not need
  52202. // to worry about avoiding using legendModel kept in scope.
  52203. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  52204. }, {
  52205. x: -pageIconSizeArr[0] / 2,
  52206. y: -pageIconSizeArr[1] / 2,
  52207. width: pageIconSizeArr[0],
  52208. height: pageIconSizeArr[1]
  52209. });
  52210. icon.name = name;
  52211. controllerGroup.add(icon);
  52212. }
  52213. };
  52214. /**
  52215. * @override
  52216. */
  52217. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  52218. var selectorGroup = this.getSelectorGroup();
  52219. var orientIdx = legendModel.getOrient().index;
  52220. var wh = WH[orientIdx];
  52221. var xy = XY[orientIdx];
  52222. var hw = WH[1 - orientIdx];
  52223. var yx = XY[1 - orientIdx];
  52224. selector && box( // Buttons in selectorGroup always layout horizontally
  52225. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  52226. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  52227. var selectorRect = selectorGroup.getBoundingRect();
  52228. var selectorPos = [-selectorRect.x, -selectorRect.y];
  52229. var processMaxSize = clone(maxSize);
  52230. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  52231. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  52232. if (selector) {
  52233. if (selectorPosition === 'end') {
  52234. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  52235. } else {
  52236. var offset = selectorRect[wh] + selectorButtonGap;
  52237. selectorPos[orientIdx] -= offset;
  52238. mainRect[xy] -= offset;
  52239. }
  52240. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  52241. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  52242. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  52243. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  52244. selectorGroup.x = selectorPos[0];
  52245. selectorGroup.y = selectorPos[1];
  52246. selectorGroup.markRedraw();
  52247. }
  52248. return mainRect;
  52249. };
  52250. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  52251. var contentGroup = this.getContentGroup();
  52252. var containerGroup = this._containerGroup;
  52253. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  52254. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  52255. box( // Buttons in controller are layout always horizontally.
  52256. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  52257. var contentRect = contentGroup.getBoundingRect();
  52258. var controllerRect = controllerGroup.getBoundingRect();
  52259. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  52260. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  52261. // If first rendering, `contentGroup.position` is [0, 0], which
  52262. // does not make sense and may cause unexepcted animation if adopted.
  52263. if (!isFirstRender) {
  52264. contentPos[orientIdx] = contentGroup[xy];
  52265. } // Layout container group based on 0.
  52266. var containerPos = [0, 0];
  52267. var controllerPos = [-controllerRect.x, -controllerRect.y];
  52268. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  52269. if (showController) {
  52270. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  52271. if (pageButtonPosition === 'end') {
  52272. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  52273. } // controller is on the left / top.
  52274. else {
  52275. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  52276. }
  52277. } // Always align controller to content as 'middle'.
  52278. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  52279. contentGroup.setPosition(contentPos);
  52280. containerGroup.setPosition(containerPos);
  52281. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  52282. // mainRect should not be calculated by `this.group.getBoundingRect()`
  52283. // for sake of the overflow.
  52284. var mainRect = {
  52285. x: 0,
  52286. y: 0
  52287. }; // Consider content may be overflow (should be clipped).
  52288. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  52289. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  52290. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  52291. containerGroup.__rectSize = maxSize[wh];
  52292. if (showController) {
  52293. var clipShape = {
  52294. x: 0,
  52295. y: 0
  52296. };
  52297. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  52298. clipShape[hw] = mainRect[hw];
  52299. containerGroup.setClipPath(new Rect({
  52300. shape: clipShape
  52301. })); // Consider content may be larger than container, container rect
  52302. // can not be obtained from `containerGroup.getBoundingRect()`.
  52303. containerGroup.__rectSize = clipShape[wh];
  52304. } else {
  52305. // Do not remove or ignore controller. Keep them set as placeholders.
  52306. controllerGroup.eachChild(function (child) {
  52307. child.attr({
  52308. invisible: true,
  52309. silent: true
  52310. });
  52311. });
  52312. } // Content translate animation.
  52313. var pageInfo = this._getPageInfo(legendModel);
  52314. pageInfo.pageIndex != null && updateProps(contentGroup, {
  52315. x: pageInfo.contentPosition[0],
  52316. y: pageInfo.contentPosition[1]
  52317. }, // When switch from "show controller" to "not show controller", view should be
  52318. // updated immediately without animation, otherwise causes weird effect.
  52319. showController ? legendModel : null);
  52320. this._updatePageInfoView(legendModel, pageInfo);
  52321. return mainRect;
  52322. };
  52323. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  52324. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  52325. scrollDataIndex != null && api.dispatchAction({
  52326. type: 'legendScroll',
  52327. scrollDataIndex: scrollDataIndex,
  52328. legendId: legendModel.id
  52329. });
  52330. };
  52331. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  52332. var controllerGroup = this._controllerGroup;
  52333. each(['pagePrev', 'pageNext'], function (name) {
  52334. var key = name + 'DataIndex';
  52335. var canJump = pageInfo[key] != null;
  52336. var icon = controllerGroup.childOfName(name);
  52337. if (icon) {
  52338. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  52339. icon.cursor = canJump ? 'pointer' : 'default';
  52340. }
  52341. });
  52342. var pageText = controllerGroup.childOfName('pageText');
  52343. var pageFormatter = legendModel.get('pageFormatter');
  52344. var pageIndex = pageInfo.pageIndex;
  52345. var current = pageIndex != null ? pageIndex + 1 : 0;
  52346. var total = pageInfo.pageCount;
  52347. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  52348. current: current,
  52349. total: total
  52350. }));
  52351. };
  52352. /**
  52353. * contentPosition: Array.<number>, null when data item not found.
  52354. * pageIndex: number, null when data item not found.
  52355. * pageCount: number, always be a number, can be 0.
  52356. * pagePrevDataIndex: number, null when no previous page.
  52357. * pageNextDataIndex: number, null when no next page.
  52358. * }
  52359. */
  52360. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  52361. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  52362. var contentGroup = this.getContentGroup();
  52363. var containerRectSize = this._containerGroup.__rectSize;
  52364. var orientIdx = legendModel.getOrient().index;
  52365. var wh = WH[orientIdx];
  52366. var xy = XY[orientIdx];
  52367. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  52368. var children = contentGroup.children();
  52369. var targetItem = children[targetItemIndex];
  52370. var itemCount = children.length;
  52371. var pCount = !itemCount ? 0 : 1;
  52372. var result = {
  52373. contentPosition: [contentGroup.x, contentGroup.y],
  52374. pageCount: pCount,
  52375. pageIndex: pCount - 1,
  52376. pagePrevDataIndex: null,
  52377. pageNextDataIndex: null
  52378. };
  52379. if (!targetItem) {
  52380. return result;
  52381. }
  52382. var targetItemInfo = getItemInfo(targetItem);
  52383. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  52384. // (1) Always align based on the left/top most item.
  52385. // (2) It is user-friendly that the last item shown in the
  52386. // current window is shown at the begining of next window.
  52387. // Otherwise if half of the last item is cut by the window,
  52388. // it will have no chance to display entirely.
  52389. // (3) Consider that item size probably be different, we
  52390. // have calculate pageIndex by size rather than item index,
  52391. // and we can not get page index directly by division.
  52392. // (4) The window is to narrow to contain more than
  52393. // one item, we should make sure that the page can be fliped.
  52394. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  52395. currItemInfo = getItemInfo(children[i]);
  52396. if ( // Half of the last item is out of the window.
  52397. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  52398. // can be started at the current item or the last item.
  52399. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  52400. if (winEndItemInfo.i > winStartItemInfo.i) {
  52401. winStartItemInfo = winEndItemInfo;
  52402. } else {
  52403. // e.g., when page size is smaller than item size.
  52404. winStartItemInfo = currItemInfo;
  52405. }
  52406. if (winStartItemInfo) {
  52407. if (result.pageNextDataIndex == null) {
  52408. result.pageNextDataIndex = winStartItemInfo.i;
  52409. }
  52410. ++result.pageCount;
  52411. }
  52412. }
  52413. winEndItemInfo = currItemInfo;
  52414. }
  52415. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  52416. currItemInfo = getItemInfo(children[i]);
  52417. if ( // If the the end item does not intersect with the window started
  52418. // from the current item, a page can be settled.
  52419. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  52420. winStartItemInfo.i < winEndItemInfo.i) {
  52421. winEndItemInfo = winStartItemInfo;
  52422. if (result.pagePrevDataIndex == null) {
  52423. result.pagePrevDataIndex = winStartItemInfo.i;
  52424. }
  52425. ++result.pageCount;
  52426. ++result.pageIndex;
  52427. }
  52428. winStartItemInfo = currItemInfo;
  52429. }
  52430. return result;
  52431. function getItemInfo(el) {
  52432. if (el) {
  52433. var itemRect = el.getBoundingRect();
  52434. var start = itemRect[xy] + el[xy];
  52435. return {
  52436. s: start,
  52437. e: start + itemRect[wh],
  52438. i: el.__legendDataIndex
  52439. };
  52440. }
  52441. }
  52442. function intersect(itemInfo, winStart) {
  52443. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  52444. }
  52445. };
  52446. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  52447. if (!this._showController) {
  52448. return 0;
  52449. }
  52450. var index;
  52451. var contentGroup = this.getContentGroup();
  52452. var defaultIndex;
  52453. contentGroup.eachChild(function (child, idx) {
  52454. var legendDataIdx = child.__legendDataIndex; // FIXME
  52455. // If the given targetDataIndex (from model) is illegal,
  52456. // we use defaultIndex. But the index on the legend model and
  52457. // action payload is still illegal. That case will not be
  52458. // changed until some scenario requires.
  52459. if (defaultIndex == null && legendDataIdx != null) {
  52460. defaultIndex = idx;
  52461. }
  52462. if (legendDataIdx === targetDataIndex) {
  52463. index = idx;
  52464. }
  52465. });
  52466. return index != null ? index : defaultIndex;
  52467. };
  52468. ScrollableLegendView.type = 'legend.scroll';
  52469. return ScrollableLegendView;
  52470. }(LegendView);
  52471. /*
  52472. * Licensed to the Apache Software Foundation (ASF) under one
  52473. * or more contributor license agreements. See the NOTICE file
  52474. * distributed with this work for additional information
  52475. * regarding copyright ownership. The ASF licenses this file
  52476. * to you under the Apache License, Version 2.0 (the
  52477. * "License"); you may not use this file except in compliance
  52478. * with the License. You may obtain a copy of the License at
  52479. *
  52480. * http://www.apache.org/licenses/LICENSE-2.0
  52481. *
  52482. * Unless required by applicable law or agreed to in writing,
  52483. * software distributed under the License is distributed on an
  52484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52485. * KIND, either express or implied. See the License for the
  52486. * specific language governing permissions and limitations
  52487. * under the License.
  52488. */
  52489. /**
  52490. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52491. */
  52492. /*
  52493. * Licensed to the Apache Software Foundation (ASF) under one
  52494. * or more contributor license agreements. See the NOTICE file
  52495. * distributed with this work for additional information
  52496. * regarding copyright ownership. The ASF licenses this file
  52497. * to you under the Apache License, Version 2.0 (the
  52498. * "License"); you may not use this file except in compliance
  52499. * with the License. You may obtain a copy of the License at
  52500. *
  52501. * http://www.apache.org/licenses/LICENSE-2.0
  52502. *
  52503. * Unless required by applicable law or agreed to in writing,
  52504. * software distributed under the License is distributed on an
  52505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52506. * KIND, either express or implied. See the License for the
  52507. * specific language governing permissions and limitations
  52508. * under the License.
  52509. */
  52510. function installScrollableLegendAction(registers) {
  52511. /**
  52512. * @event legendScroll
  52513. * @type {Object}
  52514. * @property {string} type 'legendScroll'
  52515. * @property {string} scrollDataIndex
  52516. */
  52517. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  52518. var scrollDataIndex = payload.scrollDataIndex;
  52519. scrollDataIndex != null && ecModel.eachComponent({
  52520. mainType: 'legend',
  52521. subType: 'scroll',
  52522. query: payload
  52523. }, function (legendModel) {
  52524. legendModel.setScrollDataIndex(scrollDataIndex);
  52525. });
  52526. });
  52527. }
  52528. function install$i(registers) {
  52529. use(install$h);
  52530. registers.registerComponentModel(ScrollableLegendModel);
  52531. registers.registerComponentView(ScrollableLegendView);
  52532. installScrollableLegendAction(registers);
  52533. }
  52534. function install$j(registers) {
  52535. use(install$h);
  52536. use(install$i);
  52537. }
  52538. var InsideZoomModel =
  52539. /** @class */
  52540. function (_super) {
  52541. __extends(InsideZoomModel, _super);
  52542. function InsideZoomModel() {
  52543. var _this = _super !== null && _super.apply(this, arguments) || this;
  52544. _this.type = InsideZoomModel.type;
  52545. return _this;
  52546. }
  52547. InsideZoomModel.type = 'dataZoom.inside';
  52548. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  52549. disabled: false,
  52550. zoomLock: false,
  52551. zoomOnMouseWheel: true,
  52552. moveOnMouseMove: true,
  52553. moveOnMouseWheel: false,
  52554. preventDefaultMouseMove: true
  52555. });
  52556. return InsideZoomModel;
  52557. }(DataZoomModel);
  52558. var RoamController =
  52559. /** @class */
  52560. function (_super) {
  52561. __extends(RoamController, _super);
  52562. function RoamController(zr) {
  52563. var _this = _super.call(this) || this;
  52564. _this._zr = zr; // Avoid two roamController bind the same handler
  52565. var mousedownHandler = bind(_this._mousedownHandler, _this);
  52566. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  52567. var mouseupHandler = bind(_this._mouseupHandler, _this);
  52568. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  52569. var pinchHandler = bind(_this._pinchHandler, _this);
  52570. /**
  52571. * Notice: only enable needed types. For example, if 'zoom'
  52572. * is not needed, 'zoom' should not be enabled, otherwise
  52573. * default mousewheel behaviour (scroll page) will be disabled.
  52574. */
  52575. _this.enable = function (controlType, opt) {
  52576. // Disable previous first
  52577. this.disable();
  52578. this._opt = defaults(clone(opt) || {}, {
  52579. zoomOnMouseWheel: true,
  52580. moveOnMouseMove: true,
  52581. // By default, wheel do not trigger move.
  52582. moveOnMouseWheel: false,
  52583. preventDefaultMouseMove: true
  52584. });
  52585. if (controlType == null) {
  52586. controlType = true;
  52587. }
  52588. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  52589. zr.on('mousedown', mousedownHandler);
  52590. zr.on('mousemove', mousemoveHandler);
  52591. zr.on('mouseup', mouseupHandler);
  52592. }
  52593. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  52594. zr.on('mousewheel', mousewheelHandler);
  52595. zr.on('pinch', pinchHandler);
  52596. }
  52597. };
  52598. _this.disable = function () {
  52599. zr.off('mousedown', mousedownHandler);
  52600. zr.off('mousemove', mousemoveHandler);
  52601. zr.off('mouseup', mouseupHandler);
  52602. zr.off('mousewheel', mousewheelHandler);
  52603. zr.off('pinch', pinchHandler);
  52604. };
  52605. return _this;
  52606. }
  52607. RoamController.prototype.isDragging = function () {
  52608. return this._dragging;
  52609. };
  52610. RoamController.prototype.isPinching = function () {
  52611. return this._pinching;
  52612. };
  52613. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  52614. this.pointerChecker = pointerChecker;
  52615. };
  52616. RoamController.prototype.dispose = function () {
  52617. this.disable();
  52618. };
  52619. RoamController.prototype._mousedownHandler = function (e) {
  52620. if (isMiddleOrRightButtonOnMouseUpDown(e) || e.target && e.target.draggable) {
  52621. return;
  52622. }
  52623. var x = e.offsetX;
  52624. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  52625. // Mouse can be out of target when mouse moving.
  52626. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  52627. this._x = x;
  52628. this._y = y;
  52629. this._dragging = true;
  52630. }
  52631. };
  52632. RoamController.prototype._mousemoveHandler = function (e) {
  52633. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  52634. return;
  52635. }
  52636. var x = e.offsetX;
  52637. var y = e.offsetY;
  52638. var oldX = this._x;
  52639. var oldY = this._y;
  52640. var dx = x - oldX;
  52641. var dy = y - oldY;
  52642. this._x = x;
  52643. this._y = y;
  52644. this._opt.preventDefaultMouseMove && stop(e.event);
  52645. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  52646. dx: dx,
  52647. dy: dy,
  52648. oldX: oldX,
  52649. oldY: oldY,
  52650. newX: x,
  52651. newY: y,
  52652. isAvailableBehavior: null
  52653. });
  52654. };
  52655. RoamController.prototype._mouseupHandler = function (e) {
  52656. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  52657. this._dragging = false;
  52658. }
  52659. };
  52660. RoamController.prototype._mousewheelHandler = function (e) {
  52661. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  52662. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  52663. var wheelDelta = e.wheelDelta;
  52664. var absWheelDeltaDelta = Math.abs(wheelDelta);
  52665. var originX = e.offsetX;
  52666. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  52667. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  52668. return;
  52669. } // If both `shouldZoom` and `shouldMove` is true, trigger
  52670. // their event both, and the final behavior is determined
  52671. // by event listener themselves.
  52672. if (shouldZoom) {
  52673. // Convenience:
  52674. // Mac and VM Windows on Mac: scroll up: zoom out.
  52675. // Windows: scroll up: zoom in.
  52676. // FIXME: Should do more test in different environment.
  52677. // wheelDelta is too complicated in difference nvironment
  52678. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  52679. // although it has been normallized by zrender.
  52680. // wheelDelta of mouse wheel is bigger than touch pad.
  52681. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  52682. var scale = wheelDelta > 0 ? factor : 1 / factor;
  52683. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  52684. scale: scale,
  52685. originX: originX,
  52686. originY: originY,
  52687. isAvailableBehavior: null
  52688. });
  52689. }
  52690. if (shouldMove) {
  52691. // FIXME: Should do more test in different environment.
  52692. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  52693. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  52694. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  52695. scrollDelta: scrollDelta,
  52696. originX: originX,
  52697. originY: originY,
  52698. isAvailableBehavior: null
  52699. });
  52700. }
  52701. };
  52702. RoamController.prototype._pinchHandler = function (e) {
  52703. if (isTaken(this._zr, 'globalPan')) {
  52704. return;
  52705. }
  52706. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  52707. checkPointerAndTrigger(this, 'zoom', null, e, {
  52708. scale: scale,
  52709. originX: e.pinchX,
  52710. originY: e.pinchY,
  52711. isAvailableBehavior: null
  52712. });
  52713. };
  52714. return RoamController;
  52715. }(Eventful);
  52716. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  52717. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  52718. // When mouse is out of roamController rect,
  52719. // default befavoius should not be be disabled, otherwise
  52720. // page sliding is disabled, contrary to expectation.
  52721. stop(e.event);
  52722. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  52723. }
  52724. }
  52725. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  52726. // Also provide behavior checker for event listener, for some case that
  52727. // multiple components share one listener.
  52728. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  52729. controller.trigger(eventName, contollerEvent);
  52730. } // settings: {
  52731. // zoomOnMouseWheel
  52732. // moveOnMouseMove
  52733. // moveOnMouseWheel
  52734. // }
  52735. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  52736. function isAvailableBehavior(behaviorToCheck, e, settings) {
  52737. var setting = settings[behaviorToCheck];
  52738. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  52739. }
  52740. var inner$g = makeInner();
  52741. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  52742. inner$g(api).coordSysRecordMap.each(function (coordSysRecord) {
  52743. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  52744. if (dzInfo) {
  52745. dzInfo.getRange = getRange;
  52746. }
  52747. });
  52748. }
  52749. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  52750. var coordSysRecordMap = inner$g(api).coordSysRecordMap;
  52751. var coordSysKeyArr = coordSysRecordMap.keys();
  52752. for (var i = 0; i < coordSysKeyArr.length; i++) {
  52753. var coordSysKey = coordSysKeyArr[i];
  52754. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  52755. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  52756. if (dataZoomInfoMap) {
  52757. var dzUid = dataZoomModel.uid;
  52758. var dzInfo = dataZoomInfoMap.get(dzUid);
  52759. if (dzInfo) {
  52760. dataZoomInfoMap.removeKey(dzUid);
  52761. if (!dataZoomInfoMap.keys().length) {
  52762. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  52763. }
  52764. }
  52765. }
  52766. }
  52767. }
  52768. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  52769. if (coordSysRecord) {
  52770. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  52771. var controller = coordSysRecord.controller;
  52772. controller && controller.dispose();
  52773. }
  52774. }
  52775. function createCoordSysRecord(api, coordSysModel) {
  52776. // These init props will never change after record created.
  52777. var coordSysRecord = {
  52778. model: coordSysModel,
  52779. containsPoint: curry(containsPoint, coordSysModel),
  52780. dispatchAction: curry(dispatchAction, api),
  52781. dataZoomInfoMap: null,
  52782. controller: null
  52783. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  52784. // because coordSysRecord not completed yet.
  52785. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  52786. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  52787. controller.on(eventName, function (event) {
  52788. var batch = [];
  52789. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  52790. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  52791. // moveOnMouseWheel, ...) enabled.
  52792. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  52793. return;
  52794. }
  52795. var method = (dzInfo.getRange || {})[eventName];
  52796. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  52797. !dzInfo.model.get('disabled', true) && range && batch.push({
  52798. dataZoomId: dzInfo.model.id,
  52799. start: range[0],
  52800. end: range[1]
  52801. });
  52802. });
  52803. batch.length && coordSysRecord.dispatchAction(batch);
  52804. });
  52805. });
  52806. return coordSysRecord;
  52807. }
  52808. /**
  52809. * This action will be throttled.
  52810. */
  52811. function dispatchAction(api, batch) {
  52812. if (!api.isDisposed()) {
  52813. api.dispatchAction({
  52814. type: 'dataZoom',
  52815. animation: {
  52816. easing: 'cubicOut',
  52817. duration: 100
  52818. },
  52819. batch: batch
  52820. });
  52821. }
  52822. }
  52823. function containsPoint(coordSysModel, e, x, y) {
  52824. return coordSysModel.coordinateSystem.containPoint([x, y]);
  52825. }
  52826. /**
  52827. * Merge roamController settings when multiple dataZooms share one roamController.
  52828. */
  52829. function mergeControllerParams(dataZoomInfoMap) {
  52830. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  52831. // as string, it is probably revert to reserved word by compress tool. See #7411.
  52832. var prefix = 'type_';
  52833. var typePriority = {
  52834. 'type_true': 2,
  52835. 'type_move': 1,
  52836. 'type_false': 0,
  52837. 'type_undefined': -1
  52838. };
  52839. var preventDefaultMouseMove = true;
  52840. dataZoomInfoMap.each(function (dataZoomInfo) {
  52841. var dataZoomModel = dataZoomInfo.model;
  52842. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  52843. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  52844. controlType = oneType;
  52845. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  52846. // users may be confused why it does not work when multiple insideZooms exist.
  52847. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  52848. });
  52849. return {
  52850. controlType: controlType,
  52851. opt: {
  52852. // RoamController will enable all of these functionalities,
  52853. // and the final behavior is determined by its event listener
  52854. // provided by each inside zoom.
  52855. zoomOnMouseWheel: true,
  52856. moveOnMouseMove: true,
  52857. moveOnMouseWheel: true,
  52858. preventDefaultMouseMove: !!preventDefaultMouseMove
  52859. }
  52860. };
  52861. }
  52862. function installDataZoomRoamProcessor(registers) {
  52863. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  52864. var apiInner = inner$g(api);
  52865. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  52866. coordSysRecordMap.each(function (coordSysRecord) {
  52867. // `coordSysRecordMap` always exists (becuase it hold the `roam controller`, which should
  52868. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  52869. coordSysRecord.dataZoomInfoMap = null;
  52870. });
  52871. ecModel.eachComponent({
  52872. mainType: 'dataZoom',
  52873. subType: 'inside'
  52874. }, function (dataZoomModel) {
  52875. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  52876. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  52877. var coordSysUid = dzCoordSysInfo.model.uid;
  52878. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  52879. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  52880. dataZoomInfoMap.set(dataZoomModel.uid, {
  52881. dzReferCoordSysInfo: dzCoordSysInfo,
  52882. model: dataZoomModel,
  52883. getRange: null
  52884. });
  52885. });
  52886. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  52887. // (2) Clear coord sys if not refered by any dataZoom.
  52888. coordSysRecordMap.each(function (coordSysRecord) {
  52889. var controller = coordSysRecord.controller;
  52890. var firstDzInfo;
  52891. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  52892. if (dataZoomInfoMap) {
  52893. var firstDzKey = dataZoomInfoMap.keys()[0];
  52894. if (firstDzKey != null) {
  52895. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  52896. }
  52897. }
  52898. if (!firstDzInfo) {
  52899. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  52900. return;
  52901. }
  52902. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  52903. controller.enable(controllerParams.controlType, controllerParams.opt);
  52904. controller.setPointerChecker(coordSysRecord.containsPoint);
  52905. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  52906. });
  52907. });
  52908. }
  52909. var InsideZoomView =
  52910. /** @class */
  52911. function (_super) {
  52912. __extends(InsideZoomView, _super);
  52913. function InsideZoomView() {
  52914. var _this = _super !== null && _super.apply(this, arguments) || this;
  52915. _this.type = 'dataZoom.inside';
  52916. return _this;
  52917. }
  52918. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  52919. _super.prototype.render.apply(this, arguments);
  52920. if (dataZoomModel.noTarget()) {
  52921. this._clear();
  52922. return;
  52923. } // Hence the `throttle` util ensures to preserve command order,
  52924. // here simply updating range all the time will not cause missing
  52925. // any of the the roam change.
  52926. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  52927. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  52928. pan: bind(getRangeHandlers.pan, this),
  52929. zoom: bind(getRangeHandlers.zoom, this),
  52930. scrollMove: bind(getRangeHandlers.scrollMove, this)
  52931. });
  52932. };
  52933. InsideZoomView.prototype.dispose = function () {
  52934. this._clear();
  52935. _super.prototype.dispose.apply(this, arguments);
  52936. };
  52937. InsideZoomView.prototype._clear = function () {
  52938. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  52939. this.range = null;
  52940. };
  52941. InsideZoomView.type = 'dataZoom.inside';
  52942. return InsideZoomView;
  52943. }(DataZoomView);
  52944. var getRangeHandlers = {
  52945. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  52946. var lastRange = this.range;
  52947. var range = lastRange.slice(); // Calculate transform by the first axis.
  52948. var axisModel = coordSysInfo.axisModels[0];
  52949. if (!axisModel) {
  52950. return;
  52951. }
  52952. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  52953. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  52954. var scale = Math.max(1 / e.scale, 0);
  52955. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  52956. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  52957. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  52958. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  52959. this.range = range;
  52960. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  52961. return range;
  52962. }
  52963. },
  52964. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  52965. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  52966. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  52967. }),
  52968. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  52969. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  52970. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  52971. })
  52972. };
  52973. function makeMover(getPercentDelta) {
  52974. return function (coordSysInfo, coordSysMainType, controller, e) {
  52975. var lastRange = this.range;
  52976. var range = lastRange.slice(); // Calculate transform by the first axis.
  52977. var axisModel = coordSysInfo.axisModels[0];
  52978. if (!axisModel) {
  52979. return;
  52980. }
  52981. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  52982. sliderMove(percentDelta, range, [0, 100], 'all');
  52983. this.range = range;
  52984. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  52985. return range;
  52986. }
  52987. };
  52988. }
  52989. var getDirectionInfo = {
  52990. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  52991. var axis = axisModel.axis;
  52992. var ret = {};
  52993. var rect = coordSysInfo.model.coordinateSystem.getRect();
  52994. oldPoint = oldPoint || [0, 0];
  52995. if (axis.dim === 'x') {
  52996. ret.pixel = newPoint[0] - oldPoint[0];
  52997. ret.pixelLength = rect.width;
  52998. ret.pixelStart = rect.x;
  52999. ret.signal = axis.inverse ? 1 : -1;
  53000. } else {
  53001. // axis.dim === 'y'
  53002. ret.pixel = newPoint[1] - oldPoint[1];
  53003. ret.pixelLength = rect.height;
  53004. ret.pixelStart = rect.y;
  53005. ret.signal = axis.inverse ? -1 : 1;
  53006. }
  53007. return ret;
  53008. },
  53009. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  53010. var axis = axisModel.axis;
  53011. var ret = {};
  53012. var polar = coordSysInfo.model.coordinateSystem;
  53013. var radiusExtent = polar.getRadiusAxis().getExtent();
  53014. var angleExtent = polar.getAngleAxis().getExtent();
  53015. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  53016. newPoint = polar.pointToCoord(newPoint);
  53017. if (axisModel.mainType === 'radiusAxis') {
  53018. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  53019. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  53020. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  53021. ret.pixelStart = radiusExtent[0];
  53022. ret.signal = axis.inverse ? 1 : -1;
  53023. } else {
  53024. // 'angleAxis'
  53025. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  53026. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  53027. ret.pixelLength = angleExtent[1] - angleExtent[0];
  53028. ret.pixelStart = angleExtent[0];
  53029. ret.signal = axis.inverse ? -1 : 1;
  53030. }
  53031. return ret;
  53032. },
  53033. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  53034. var axis = axisModel.axis;
  53035. var rect = coordSysInfo.model.coordinateSystem.getRect();
  53036. var ret = {};
  53037. oldPoint = oldPoint || [0, 0];
  53038. if (axis.orient === 'horizontal') {
  53039. ret.pixel = newPoint[0] - oldPoint[0];
  53040. ret.pixelLength = rect.width;
  53041. ret.pixelStart = rect.x;
  53042. ret.signal = axis.inverse ? 1 : -1;
  53043. } else {
  53044. // 'vertical'
  53045. ret.pixel = newPoint[1] - oldPoint[1];
  53046. ret.pixelLength = rect.height;
  53047. ret.pixelStart = rect.y;
  53048. ret.signal = axis.inverse ? -1 : 1;
  53049. }
  53050. return ret;
  53051. }
  53052. };
  53053. function install$k(registers) {
  53054. installCommon(registers);
  53055. registers.registerComponentModel(InsideZoomModel);
  53056. registers.registerComponentView(InsideZoomView);
  53057. installDataZoomRoamProcessor(registers);
  53058. }
  53059. var SliderZoomModel =
  53060. /** @class */
  53061. function (_super) {
  53062. __extends(SliderZoomModel, _super);
  53063. function SliderZoomModel() {
  53064. var _this = _super !== null && _super.apply(this, arguments) || this;
  53065. _this.type = SliderZoomModel.type;
  53066. return _this;
  53067. }
  53068. SliderZoomModel.type = 'dataZoom.slider';
  53069. SliderZoomModel.layoutMode = 'box';
  53070. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  53071. show: true,
  53072. // deault value can only be drived in view stage.
  53073. right: 'ph',
  53074. top: 'ph',
  53075. width: 'ph',
  53076. height: 'ph',
  53077. left: null,
  53078. bottom: null,
  53079. borderColor: '#d2dbee',
  53080. borderRadius: 3,
  53081. backgroundColor: 'rgba(47,69,84,0)',
  53082. // dataBackgroundColor: '#ddd',
  53083. dataBackground: {
  53084. lineStyle: {
  53085. color: '#d2dbee',
  53086. width: 0.5
  53087. },
  53088. areaStyle: {
  53089. color: '#d2dbee',
  53090. opacity: 0.2
  53091. }
  53092. },
  53093. selectedDataBackground: {
  53094. lineStyle: {
  53095. color: '#8fb0f7',
  53096. width: 0.5
  53097. },
  53098. areaStyle: {
  53099. color: '#8fb0f7',
  53100. opacity: 0.2
  53101. }
  53102. },
  53103. // Color of selected window.
  53104. fillerColor: 'rgba(135,175,274,0.2)',
  53105. 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',
  53106. // Percent of the slider height
  53107. handleSize: '100%',
  53108. handleStyle: {
  53109. color: '#fff',
  53110. borderColor: '#ACB8D1'
  53111. },
  53112. moveHandleSize: 7,
  53113. 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',
  53114. moveHandleStyle: {
  53115. color: '#D2DBEE',
  53116. opacity: 0.7
  53117. },
  53118. showDetail: true,
  53119. showDataShadow: 'auto',
  53120. realtime: true,
  53121. zoomLock: false,
  53122. textStyle: {
  53123. color: '#6E7079'
  53124. },
  53125. brushSelect: true,
  53126. brushStyle: {
  53127. color: 'rgba(135,175,274,0.15)'
  53128. },
  53129. emphasis: {
  53130. handleStyle: {
  53131. borderColor: '#8FB0F7'
  53132. },
  53133. moveHandleStyle: {
  53134. color: '#8FB0F7'
  53135. }
  53136. }
  53137. });
  53138. return SliderZoomModel;
  53139. }(DataZoomModel);
  53140. var Rect$1 = Rect; // Constants
  53141. var DEFAULT_LOCATION_EDGE_GAP = 7;
  53142. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  53143. var DEFAULT_FILLER_SIZE = 30;
  53144. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  53145. var HORIZONTAL = 'horizontal';
  53146. var VERTICAL = 'vertical';
  53147. var LABEL_GAP = 5;
  53148. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  53149. var REALTIME_ANIMATION_CONFIG = {
  53150. easing: 'cubicOut',
  53151. duration: 100,
  53152. delay: 0
  53153. };
  53154. var SliderZoomView =
  53155. /** @class */
  53156. function (_super) {
  53157. __extends(SliderZoomView, _super);
  53158. function SliderZoomView() {
  53159. var _this = _super !== null && _super.apply(this, arguments) || this;
  53160. _this.type = SliderZoomView.type;
  53161. _this._displayables = {};
  53162. return _this;
  53163. }
  53164. SliderZoomView.prototype.init = function (ecModel, api) {
  53165. this.api = api; // A unique handler for each dataZoom component
  53166. this._onBrush = bind(this._onBrush, this);
  53167. this._onBrushEnd = bind(this._onBrushEnd, this);
  53168. };
  53169. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  53170. _super.prototype.render.apply(this, arguments);
  53171. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  53172. this._orient = dataZoomModel.getOrient();
  53173. if (dataZoomModel.get('show') === false) {
  53174. this.group.removeAll();
  53175. return;
  53176. }
  53177. if (dataZoomModel.noTarget()) {
  53178. this._clear();
  53179. this.group.removeAll();
  53180. return;
  53181. } // Notice: this._resetInterval() should not be executed when payload.type
  53182. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  53183. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  53184. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  53185. this._buildView();
  53186. }
  53187. this._updateView();
  53188. };
  53189. SliderZoomView.prototype.dispose = function () {
  53190. this._clear();
  53191. _super.prototype.dispose.apply(this, arguments);
  53192. };
  53193. SliderZoomView.prototype._clear = function () {
  53194. clear(this, '_dispatchZoomAction');
  53195. var zr = this.api.getZr();
  53196. zr.off('mousemove', this._onBrush);
  53197. zr.off('mouseup', this._onBrushEnd);
  53198. };
  53199. SliderZoomView.prototype._buildView = function () {
  53200. var thisGroup = this.group;
  53201. thisGroup.removeAll();
  53202. this._brushing = false;
  53203. this._displayables.brushRect = null;
  53204. this._resetLocation();
  53205. this._resetInterval();
  53206. var barGroup = this._displayables.sliderGroup = new Group();
  53207. this._renderBackground();
  53208. this._renderHandle();
  53209. this._renderDataShadow();
  53210. thisGroup.add(barGroup);
  53211. this._positionGroup();
  53212. };
  53213. SliderZoomView.prototype._resetLocation = function () {
  53214. var dataZoomModel = this.dataZoomModel;
  53215. var api = this.api;
  53216. var showMoveHandle = dataZoomModel.get('brushSelect');
  53217. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  53218. // auto-adapt according to target grid.
  53219. var coordRect = this._findCoordRect();
  53220. var ecSize = {
  53221. width: api.getWidth(),
  53222. height: api.getHeight()
  53223. }; // Default align by coordinate system rect.
  53224. var positionInfo = this._orient === HORIZONTAL ? {
  53225. // Why using 'right', because right should be used in vertical,
  53226. // and it is better to be consistent for dealing with position param merge.
  53227. right: ecSize.width - coordRect.x - coordRect.width,
  53228. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  53229. width: coordRect.width,
  53230. height: DEFAULT_FILLER_SIZE
  53231. } : {
  53232. right: DEFAULT_LOCATION_EDGE_GAP,
  53233. top: coordRect.y,
  53234. width: DEFAULT_FILLER_SIZE,
  53235. height: coordRect.height
  53236. }; // Do not write back to option and replace value 'ph', because
  53237. // the 'ph' value should be recalculated when resize.
  53238. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  53239. each(['right', 'top', 'width', 'height'], function (name) {
  53240. if (layoutParams[name] === 'ph') {
  53241. layoutParams[name] = positionInfo[name];
  53242. }
  53243. });
  53244. var layoutRect = getLayoutRect(layoutParams, ecSize);
  53245. this._location = {
  53246. x: layoutRect.x,
  53247. y: layoutRect.y
  53248. };
  53249. this._size = [layoutRect.width, layoutRect.height];
  53250. this._orient === VERTICAL && this._size.reverse();
  53251. };
  53252. SliderZoomView.prototype._positionGroup = function () {
  53253. var thisGroup = this.group;
  53254. var location = this._location;
  53255. var orient = this._orient; // Just use the first axis to determine mapping.
  53256. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  53257. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  53258. var sliderGroup = this._displayables.sliderGroup;
  53259. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  53260. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  53261. scaleY: otherAxisInverse ? 1 : -1,
  53262. scaleX: 1
  53263. } : orient === HORIZONTAL && inverse ? {
  53264. scaleY: otherAxisInverse ? 1 : -1,
  53265. scaleX: -1
  53266. } : orient === VERTICAL && !inverse ? {
  53267. scaleY: otherAxisInverse ? -1 : 1,
  53268. scaleX: 1,
  53269. rotation: Math.PI / 2
  53270. } // Dont use Math.PI, considering shadow direction.
  53271. : {
  53272. scaleY: otherAxisInverse ? -1 : 1,
  53273. scaleX: -1,
  53274. rotation: Math.PI / 2
  53275. }); // Position barGroup
  53276. var rect = thisGroup.getBoundingRect([sliderGroup]);
  53277. thisGroup.x = location.x - rect.x;
  53278. thisGroup.y = location.y - rect.y;
  53279. thisGroup.markRedraw();
  53280. };
  53281. SliderZoomView.prototype._getViewExtent = function () {
  53282. return [0, this._size[0]];
  53283. };
  53284. SliderZoomView.prototype._renderBackground = function () {
  53285. var dataZoomModel = this.dataZoomModel;
  53286. var size = this._size;
  53287. var barGroup = this._displayables.sliderGroup;
  53288. var brushSelect = dataZoomModel.get('brushSelect');
  53289. barGroup.add(new Rect$1({
  53290. silent: true,
  53291. shape: {
  53292. x: 0,
  53293. y: 0,
  53294. width: size[0],
  53295. height: size[1]
  53296. },
  53297. style: {
  53298. fill: dataZoomModel.get('backgroundColor')
  53299. },
  53300. z2: -40
  53301. })); // Click panel, over shadow, below handles.
  53302. var clickPanel = new Rect$1({
  53303. shape: {
  53304. x: 0,
  53305. y: 0,
  53306. width: size[0],
  53307. height: size[1]
  53308. },
  53309. style: {
  53310. fill: 'transparent'
  53311. },
  53312. z2: 0,
  53313. onclick: bind(this._onClickPanel, this)
  53314. });
  53315. var zr = this.api.getZr();
  53316. if (brushSelect) {
  53317. clickPanel.on('mousedown', this._onBrushStart, this);
  53318. clickPanel.cursor = 'crosshair';
  53319. zr.on('mousemove', this._onBrush);
  53320. zr.on('mouseup', this._onBrushEnd);
  53321. } else {
  53322. zr.off('mousemove', this._onBrush);
  53323. zr.off('mouseup', this._onBrushEnd);
  53324. }
  53325. barGroup.add(clickPanel);
  53326. };
  53327. SliderZoomView.prototype._renderDataShadow = function () {
  53328. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  53329. this._displayables.dataShadowSegs = [];
  53330. if (!info) {
  53331. return;
  53332. }
  53333. var size = this._size;
  53334. var oldSize = this._shadowSize || [];
  53335. var seriesModel = info.series;
  53336. var data = seriesModel.getRawData();
  53337. var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
  53338. : info.otherDim;
  53339. if (otherDim == null) {
  53340. return;
  53341. }
  53342. var polygonPts = this._shadowPolygonPts;
  53343. var polylinePts = this._shadowPolylinePts; // Not re-render if data doesn't change.
  53344. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  53345. var otherDataExtent_1 = data.getDataExtent(otherDim); // Nice extent.
  53346. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  53347. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  53348. var otherShadowExtent_1 = [0, size[1]];
  53349. var thisShadowExtent = [0, size[0]];
  53350. var areaPoints_1 = [[size[0], 0], [0, 0]];
  53351. var linePoints_1 = [];
  53352. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  53353. var thisCoord_1 = 0; // Optimize for large data shadow
  53354. var stride_1 = Math.round(data.count() / size[0]);
  53355. var lastIsEmpty_1;
  53356. data.each([otherDim], function (value, index) {
  53357. if (stride_1 > 0 && index % stride_1) {
  53358. thisCoord_1 += step_1;
  53359. return;
  53360. } // FIXME
  53361. // Should consider axis.min/axis.max when drawing dataShadow.
  53362. // FIXME
  53363. // 应该使用统一的空判断?还是在list里进行空判断?
  53364. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  53365. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true); // Attempt to draw data shadow precisely when there are empty value.
  53366. if (isEmpty && !lastIsEmpty_1 && index) {
  53367. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  53368. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  53369. } else if (!isEmpty && lastIsEmpty_1) {
  53370. areaPoints_1.push([thisCoord_1, 0]);
  53371. linePoints_1.push([thisCoord_1, 0]);
  53372. }
  53373. areaPoints_1.push([thisCoord_1, otherCoord]);
  53374. linePoints_1.push([thisCoord_1, otherCoord]);
  53375. thisCoord_1 += step_1;
  53376. lastIsEmpty_1 = isEmpty;
  53377. });
  53378. polygonPts = this._shadowPolygonPts = areaPoints_1;
  53379. polylinePts = this._shadowPolylinePts = linePoints_1;
  53380. }
  53381. this._shadowData = data;
  53382. this._shadowDim = otherDim;
  53383. this._shadowSize = [size[0], size[1]];
  53384. var dataZoomModel = this.dataZoomModel;
  53385. function createDataShadowGroup(isSelectedArea) {
  53386. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  53387. var group = new Group();
  53388. var polygon = new Polygon({
  53389. shape: {
  53390. points: polygonPts
  53391. },
  53392. segmentIgnoreThreshold: 1,
  53393. style: model.getModel('areaStyle').getAreaStyle(),
  53394. silent: true,
  53395. z2: -20
  53396. });
  53397. var polyline = new Polyline({
  53398. shape: {
  53399. points: polylinePts
  53400. },
  53401. segmentIgnoreThreshold: 1,
  53402. style: model.getModel('lineStyle').getLineStyle(),
  53403. silent: true,
  53404. z2: -19
  53405. });
  53406. group.add(polygon);
  53407. group.add(polyline);
  53408. return group;
  53409. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  53410. for (var i = 0; i < 3; i++) {
  53411. var group = createDataShadowGroup(i === 1);
  53412. this._displayables.sliderGroup.add(group);
  53413. this._displayables.dataShadowSegs.push(group);
  53414. }
  53415. };
  53416. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  53417. var dataZoomModel = this.dataZoomModel;
  53418. var showDataShadow = dataZoomModel.get('showDataShadow');
  53419. if (showDataShadow === false) {
  53420. return;
  53421. } // Find a representative series.
  53422. var result;
  53423. var ecModel = this.ecModel;
  53424. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  53425. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  53426. each(seriesModels, function (seriesModel) {
  53427. if (result) {
  53428. return;
  53429. }
  53430. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  53431. return;
  53432. }
  53433. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  53434. var otherDim = getOtherDim(axisDim);
  53435. var otherAxisInverse;
  53436. var coordSys = seriesModel.coordinateSystem;
  53437. if (otherDim != null && coordSys.getOtherAxis) {
  53438. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  53439. }
  53440. otherDim = seriesModel.getData().mapDimension(otherDim);
  53441. result = {
  53442. thisAxis: thisAxis,
  53443. series: seriesModel,
  53444. thisDim: axisDim,
  53445. otherDim: otherDim,
  53446. otherAxisInverse: otherAxisInverse
  53447. };
  53448. }, this);
  53449. }, this);
  53450. return result;
  53451. };
  53452. SliderZoomView.prototype._renderHandle = function () {
  53453. var thisGroup = this.group;
  53454. var displayables = this._displayables;
  53455. var handles = displayables.handles = [null, null];
  53456. var handleLabels = displayables.handleLabels = [null, null];
  53457. var sliderGroup = this._displayables.sliderGroup;
  53458. var size = this._size;
  53459. var dataZoomModel = this.dataZoomModel;
  53460. var api = this.api;
  53461. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  53462. var brushSelect = dataZoomModel.get('brushSelect');
  53463. var filler = displayables.filler = new Rect$1({
  53464. silent: brushSelect,
  53465. style: {
  53466. fill: dataZoomModel.get('fillerColor')
  53467. },
  53468. textConfig: {
  53469. position: 'inside'
  53470. }
  53471. });
  53472. sliderGroup.add(filler); // Frame border.
  53473. sliderGroup.add(new Rect$1({
  53474. silent: true,
  53475. subPixelOptimize: true,
  53476. shape: {
  53477. x: 0,
  53478. y: 0,
  53479. width: size[0],
  53480. height: size[1],
  53481. r: borderRadius
  53482. },
  53483. style: {
  53484. stroke: dataZoomModel.get('dataBackgroundColor') // deprecated option
  53485. || dataZoomModel.get('borderColor'),
  53486. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  53487. fill: 'rgba(0,0,0,0)'
  53488. }
  53489. })); // Left and right handle to resize
  53490. each([0, 1], function (handleIndex) {
  53491. var iconStr = dataZoomModel.get('handleIcon');
  53492. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  53493. // Compatitable with the old icon parsers. Which can use a path string without path://
  53494. iconStr = 'path://' + iconStr;
  53495. if ("development" !== 'production') {
  53496. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  53497. }
  53498. }
  53499. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  53500. path.attr({
  53501. cursor: getCursor(this._orient),
  53502. draggable: true,
  53503. drift: bind(this._onDragMove, this, handleIndex),
  53504. ondragend: bind(this._onDragEnd, this),
  53505. onmouseover: bind(this._showDataInfo, this, true),
  53506. onmouseout: bind(this._showDataInfo, this, false),
  53507. z2: 5
  53508. });
  53509. var bRect = path.getBoundingRect();
  53510. var handleSize = dataZoomModel.get('handleSize');
  53511. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  53512. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  53513. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  53514. path.style.strokeNoScale = true;
  53515. path.rectHover = true;
  53516. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  53517. enableHoverEmphasis(path);
  53518. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  53519. // Compatitable with previous version
  53520. if (handleColor != null) {
  53521. path.style.fill = handleColor;
  53522. }
  53523. sliderGroup.add(handles[handleIndex] = path);
  53524. var textStyleModel = dataZoomModel.getModel('textStyle');
  53525. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  53526. silent: true,
  53527. invisible: true,
  53528. style: createTextStyle(textStyleModel, {
  53529. x: 0,
  53530. y: 0,
  53531. text: '',
  53532. verticalAlign: 'middle',
  53533. align: 'center',
  53534. fill: textStyleModel.getTextColor(),
  53535. font: textStyleModel.getFont()
  53536. }),
  53537. z2: 10
  53538. }));
  53539. }, this); // Handle to move. Only visible when brushSelect is set true.
  53540. var actualMoveZone = filler;
  53541. if (brushSelect) {
  53542. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  53543. var moveHandle_1 = displayables.moveHandle = new Rect({
  53544. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  53545. silent: true,
  53546. shape: {
  53547. r: [0, 0, 2, 2],
  53548. y: size[1] - 0.5,
  53549. height: moveHandleHeight
  53550. }
  53551. });
  53552. var iconSize = moveHandleHeight * 0.8;
  53553. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  53554. moveHandleIcon.silent = true;
  53555. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  53556. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  53557. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  53558. actualMoveZone = displayables.moveZone = new Rect({
  53559. invisible: true,
  53560. shape: {
  53561. y: size[1] - moveZoneExpandSize,
  53562. height: moveHandleHeight + moveZoneExpandSize
  53563. }
  53564. });
  53565. actualMoveZone.on('mouseover', function () {
  53566. api.enterEmphasis(moveHandle_1);
  53567. }).on('mouseout', function () {
  53568. api.leaveEmphasis(moveHandle_1);
  53569. });
  53570. sliderGroup.add(moveHandle_1);
  53571. sliderGroup.add(moveHandleIcon);
  53572. sliderGroup.add(actualMoveZone);
  53573. }
  53574. actualMoveZone.attr({
  53575. draggable: true,
  53576. cursor: getCursor(this._orient),
  53577. drift: bind(this._onDragMove, this, 'all'),
  53578. ondragstart: bind(this._showDataInfo, this, true),
  53579. ondragend: bind(this._onDragEnd, this),
  53580. onmouseover: bind(this._showDataInfo, this, true),
  53581. onmouseout: bind(this._showDataInfo, this, false)
  53582. });
  53583. };
  53584. SliderZoomView.prototype._resetInterval = function () {
  53585. var range = this._range = this.dataZoomModel.getPercentRange();
  53586. var viewExtent = this._getViewExtent();
  53587. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  53588. };
  53589. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  53590. var dataZoomModel = this.dataZoomModel;
  53591. var handleEnds = this._handleEnds;
  53592. var viewExtend = this._getViewExtent();
  53593. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  53594. var percentExtent = [0, 100];
  53595. 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);
  53596. var lastRange = this._range;
  53597. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  53598. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  53599. };
  53600. SliderZoomView.prototype._updateView = function (nonRealtime) {
  53601. var displaybles = this._displayables;
  53602. var handleEnds = this._handleEnds;
  53603. var handleInterval = asc(handleEnds.slice());
  53604. var size = this._size;
  53605. each([0, 1], function (handleIndex) {
  53606. // Handles
  53607. var handle = displaybles.handles[handleIndex];
  53608. var handleHeight = this._handleHeight;
  53609. handle.attr({
  53610. scaleX: handleHeight / 2,
  53611. scaleY: handleHeight / 2,
  53612. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  53613. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  53614. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  53615. y: size[1] / 2 - handleHeight / 2
  53616. });
  53617. }, this); // Filler
  53618. displaybles.filler.setShape({
  53619. x: handleInterval[0],
  53620. y: 0,
  53621. width: handleInterval[1] - handleInterval[0],
  53622. height: size[1]
  53623. });
  53624. var viewExtent = {
  53625. x: handleInterval[0],
  53626. width: handleInterval[1] - handleInterval[0]
  53627. }; // Move handle
  53628. if (displaybles.moveHandle) {
  53629. displaybles.moveHandle.setShape(viewExtent);
  53630. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  53631. displaybles.moveZone.getBoundingRect();
  53632. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  53633. } // update clip path of shadow.
  53634. var dataShadowSegs = displaybles.dataShadowSegs;
  53635. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  53636. for (var i = 0; i < dataShadowSegs.length; i++) {
  53637. var segGroup = dataShadowSegs[i];
  53638. var clipPath = segGroup.getClipPath();
  53639. if (!clipPath) {
  53640. clipPath = new Rect();
  53641. segGroup.setClipPath(clipPath);
  53642. }
  53643. clipPath.setShape({
  53644. x: segIntervals[i],
  53645. y: 0,
  53646. width: segIntervals[i + 1] - segIntervals[i],
  53647. height: size[1]
  53648. });
  53649. }
  53650. this._updateDataInfo(nonRealtime);
  53651. };
  53652. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  53653. var dataZoomModel = this.dataZoomModel;
  53654. var displaybles = this._displayables;
  53655. var handleLabels = displaybles.handleLabels;
  53656. var orient = this._orient;
  53657. var labelTexts = ['', '']; // FIXME
  53658. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  53659. if (dataZoomModel.get('showDetail')) {
  53660. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  53661. if (axisProxy) {
  53662. var axis = axisProxy.getAxisModel().axis;
  53663. var range = this._range;
  53664. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  53665. ? axisProxy.calculateDataWindow({
  53666. start: range[0],
  53667. end: range[1]
  53668. }).valueWindow : axisProxy.getDataValueWindow();
  53669. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  53670. }
  53671. }
  53672. var orderedHandleEnds = asc(this._handleEnds.slice());
  53673. setLabel.call(this, 0);
  53674. setLabel.call(this, 1);
  53675. function setLabel(handleIndex) {
  53676. // Label
  53677. // Text should not transform by barGroup.
  53678. // Ignore handlers transform
  53679. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  53680. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  53681. var offset = this._handleWidth / 2 + LABEL_GAP;
  53682. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  53683. handleLabels[handleIndex].setStyle({
  53684. x: textPoint[0],
  53685. y: textPoint[1],
  53686. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  53687. align: orient === HORIZONTAL ? direction : 'center',
  53688. text: labelTexts[handleIndex]
  53689. });
  53690. }
  53691. };
  53692. SliderZoomView.prototype._formatLabel = function (value, axis) {
  53693. var dataZoomModel = this.dataZoomModel;
  53694. var labelFormatter = dataZoomModel.get('labelFormatter');
  53695. var labelPrecision = dataZoomModel.get('labelPrecision');
  53696. if (labelPrecision == null || labelPrecision === 'auto') {
  53697. labelPrecision = axis.getPixelPrecision();
  53698. }
  53699. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  53700. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  53701. value: Math.round(value)
  53702. }) // param of toFixed should less then 20.
  53703. : value.toFixed(Math.min(labelPrecision, 20));
  53704. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  53705. };
  53706. /**
  53707. * @param showOrHide true: show, false: hide
  53708. */
  53709. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  53710. // Always show when drgging.
  53711. showOrHide = this._dragging || showOrHide;
  53712. var displayables = this._displayables;
  53713. var handleLabels = displayables.handleLabels;
  53714. handleLabels[0].attr('invisible', !showOrHide);
  53715. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  53716. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  53717. };
  53718. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  53719. this._dragging = true; // For mobile device, prevent screen slider on the button.
  53720. stop(event.event); // Transform dx, dy to bar coordination.
  53721. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  53722. var vertex = applyTransform$1([dx, dy], barTransform, true);
  53723. var changed = this._updateInterval(handleIndex, vertex[0]);
  53724. var realtime = this.dataZoomModel.get('realtime');
  53725. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  53726. // which cause bad visual effect when progressive enabled.
  53727. changed && realtime && this._dispatchZoomAction(true);
  53728. };
  53729. SliderZoomView.prototype._onDragEnd = function () {
  53730. this._dragging = false;
  53731. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  53732. // drag end will cause the whole view rerender, which is unnecessary.
  53733. var realtime = this.dataZoomModel.get('realtime');
  53734. !realtime && this._dispatchZoomAction(false);
  53735. };
  53736. SliderZoomView.prototype._onClickPanel = function (e) {
  53737. var size = this._size;
  53738. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  53739. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  53740. return;
  53741. }
  53742. var handleEnds = this._handleEnds;
  53743. var center = (handleEnds[0] + handleEnds[1]) / 2;
  53744. var changed = this._updateInterval('all', localPoint[0] - center);
  53745. this._updateView();
  53746. changed && this._dispatchZoomAction(false);
  53747. };
  53748. SliderZoomView.prototype._onBrushStart = function (e) {
  53749. var x = e.offsetX;
  53750. var y = e.offsetY;
  53751. this._brushStart = new Point(x, y);
  53752. this._brushing = true;
  53753. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  53754. };
  53755. SliderZoomView.prototype._onBrushEnd = function (e) {
  53756. if (!this._brushing) {
  53757. return;
  53758. }
  53759. var brushRect = this._displayables.brushRect;
  53760. this._brushing = false;
  53761. if (!brushRect) {
  53762. return;
  53763. }
  53764. brushRect.attr('ignore', true);
  53765. var brushShape = brushRect.shape;
  53766. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  53767. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  53768. // Will treat it as a click
  53769. return;
  53770. }
  53771. var viewExtend = this._getViewExtent();
  53772. var percentExtent = [0, 100];
  53773. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  53774. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  53775. this._updateView();
  53776. this._dispatchZoomAction(false);
  53777. };
  53778. SliderZoomView.prototype._onBrush = function (e) {
  53779. if (this._brushing) {
  53780. // For mobile device, prevent screen slider on the button.
  53781. stop(e.event);
  53782. this._updateBrushRect(e.offsetX, e.offsetY);
  53783. }
  53784. };
  53785. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  53786. var displayables = this._displayables;
  53787. var dataZoomModel = this.dataZoomModel;
  53788. var brushRect = displayables.brushRect;
  53789. if (!brushRect) {
  53790. brushRect = displayables.brushRect = new Rect$1({
  53791. silent: true,
  53792. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  53793. });
  53794. displayables.sliderGroup.add(brushRect);
  53795. }
  53796. brushRect.attr('ignore', false);
  53797. var brushStart = this._brushStart;
  53798. var sliderGroup = this._displayables.sliderGroup;
  53799. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  53800. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  53801. var size = this._size;
  53802. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  53803. brushRect.setShape({
  53804. x: startPoint[0],
  53805. y: 0,
  53806. width: endPoint[0] - startPoint[0],
  53807. height: size[1]
  53808. });
  53809. };
  53810. /**
  53811. * This action will be throttled.
  53812. */
  53813. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  53814. var range = this._range;
  53815. this.api.dispatchAction({
  53816. type: 'dataZoom',
  53817. from: this.uid,
  53818. dataZoomId: this.dataZoomModel.id,
  53819. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  53820. start: range[0],
  53821. end: range[1]
  53822. });
  53823. };
  53824. SliderZoomView.prototype._findCoordRect = function () {
  53825. // Find the grid coresponding to the first axis referred by dataZoom.
  53826. var rect;
  53827. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  53828. if (!rect && coordSysInfoList.length) {
  53829. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  53830. rect = coordSys.getRect && coordSys.getRect();
  53831. }
  53832. if (!rect) {
  53833. var width = this.api.getWidth();
  53834. var height = this.api.getHeight();
  53835. rect = {
  53836. x: width * 0.2,
  53837. y: height * 0.2,
  53838. width: width * 0.6,
  53839. height: height * 0.6
  53840. };
  53841. }
  53842. return rect;
  53843. };
  53844. SliderZoomView.type = 'dataZoom.slider';
  53845. return SliderZoomView;
  53846. }(DataZoomView);
  53847. function getOtherDim(thisDim) {
  53848. // FIXME
  53849. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  53850. var map = {
  53851. x: 'y',
  53852. y: 'x',
  53853. radius: 'angle',
  53854. angle: 'radius'
  53855. };
  53856. return map[thisDim];
  53857. }
  53858. function getCursor(orient) {
  53859. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  53860. }
  53861. function install$l(registers) {
  53862. registers.registerComponentModel(SliderZoomModel);
  53863. registers.registerComponentView(SliderZoomView);
  53864. installCommon(registers);
  53865. }
  53866. function install$m(registers) {
  53867. use(install$k);
  53868. use(install$l); // Do not install './dataZoomSelect',
  53869. // since it only work for toolbox dataZoom.
  53870. }
  53871. var DEFAULT_OPTION = {
  53872. label: {
  53873. enabled: true
  53874. },
  53875. decal: {
  53876. show: false
  53877. }
  53878. };
  53879. var inner$h = makeInner();
  53880. var decalPaletteScope = {};
  53881. function ariaVisual(ecModel, api) {
  53882. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  53883. if (!ariaModel.get('enabled')) {
  53884. return;
  53885. }
  53886. var defaultOption = clone(DEFAULT_OPTION);
  53887. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  53888. merge(ariaModel.option, defaultOption, false);
  53889. setDecal();
  53890. setLabel();
  53891. function setDecal() {
  53892. var decalModel = ariaModel.getModel('decal');
  53893. var useDecal = decalModel.get('show');
  53894. if (useDecal) {
  53895. // Each type of series use one scope.
  53896. // Pie and funnel are using diferrent scopes
  53897. var paletteScopeGroupByType_1 = createHashMap();
  53898. ecModel.eachSeries(function (seriesModel) {
  53899. if (seriesModel.isColorBySeries()) {
  53900. return;
  53901. }
  53902. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  53903. if (!decalScope) {
  53904. decalScope = {};
  53905. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  53906. }
  53907. inner$h(seriesModel).scope = decalScope;
  53908. });
  53909. ecModel.eachRawSeries(function (seriesModel) {
  53910. if (ecModel.isSeriesFiltered(seriesModel)) {
  53911. return;
  53912. }
  53913. if (isFunction(seriesModel.enableAriaDecal)) {
  53914. // Let series define how to use decal palette on data
  53915. seriesModel.enableAriaDecal();
  53916. return;
  53917. }
  53918. var data = seriesModel.getData();
  53919. if (!seriesModel.isColorBySeries()) {
  53920. var dataAll_1 = seriesModel.getRawData();
  53921. var idxMap_1 = {};
  53922. var decalScope_1 = inner$h(seriesModel).scope;
  53923. data.each(function (idx) {
  53924. var rawIdx = data.getRawIndex(idx);
  53925. idxMap_1[rawIdx] = idx;
  53926. });
  53927. var dataCount_1 = dataAll_1.count();
  53928. dataAll_1.each(function (rawIdx) {
  53929. var idx = idxMap_1[rawIdx];
  53930. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  53931. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  53932. var specifiedDecal = data.getItemVisual(idx, 'decal');
  53933. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  53934. });
  53935. } else {
  53936. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  53937. var specifiedDecal = data.getVisual('decal');
  53938. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  53939. }
  53940. function mergeDecal(specifiedDecal, paletteDecal) {
  53941. // Merge decal from palette to decal from itemStyle.
  53942. // User do not need to specify all of the decal props.
  53943. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  53944. resultDecal.dirty = true;
  53945. return resultDecal;
  53946. }
  53947. });
  53948. }
  53949. }
  53950. function setLabel() {
  53951. var labelLocale = ecModel.getLocaleModel().get('aria');
  53952. var labelModel = ariaModel.getModel('label');
  53953. labelModel.option = defaults(labelModel.option, labelLocale);
  53954. if (!labelModel.get('enabled')) {
  53955. return;
  53956. }
  53957. var dom = api.getZr().dom;
  53958. if (labelModel.get('description')) {
  53959. dom.setAttribute('aria-label', labelModel.get('description'));
  53960. return;
  53961. }
  53962. var seriesCnt = ecModel.getSeriesCount();
  53963. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  53964. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  53965. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  53966. var ariaLabel;
  53967. if (seriesCnt < 1) {
  53968. // No series, no aria label
  53969. return;
  53970. } else {
  53971. var title = getTitle();
  53972. if (title) {
  53973. var withTitle = labelModel.get(['general', 'withTitle']);
  53974. ariaLabel = replace(withTitle, {
  53975. title: title
  53976. });
  53977. } else {
  53978. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  53979. }
  53980. var seriesLabels_1 = [];
  53981. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  53982. ariaLabel += replace(prefix, {
  53983. seriesCount: seriesCnt
  53984. });
  53985. ecModel.eachSeries(function (seriesModel, idx) {
  53986. if (idx < displaySeriesCnt) {
  53987. var seriesLabel = void 0;
  53988. var seriesName = seriesModel.get('name');
  53989. var withName = seriesName ? 'withName' : 'withoutName';
  53990. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  53991. seriesLabel = replace(seriesLabel, {
  53992. seriesId: seriesModel.seriesIndex,
  53993. seriesName: seriesModel.get('name'),
  53994. seriesType: getSeriesTypeName(seriesModel.subType)
  53995. });
  53996. var data = seriesModel.getData();
  53997. if (data.count() > maxDataCnt) {
  53998. // Show part of data
  53999. var partialLabel = labelModel.get(['data', 'partialData']);
  54000. seriesLabel += replace(partialLabel, {
  54001. displayCnt: maxDataCnt
  54002. });
  54003. } else {
  54004. seriesLabel += labelModel.get(['data', 'allData']);
  54005. }
  54006. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  54007. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  54008. var dataLabels = [];
  54009. for (var i = 0; i < data.count(); i++) {
  54010. if (i < maxDataCnt) {
  54011. var name_1 = data.getName(i);
  54012. var value = data.getValues(i);
  54013. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  54014. dataLabels.push(replace(dataLabel, {
  54015. name: name_1,
  54016. value: value.join(middleSeparator_1)
  54017. }));
  54018. }
  54019. }
  54020. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  54021. seriesLabels_1.push(seriesLabel);
  54022. }
  54023. });
  54024. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  54025. var middleSeparator = separatorModel.get('middle');
  54026. var endSeparator = separatorModel.get('end');
  54027. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  54028. dom.setAttribute('aria-label', ariaLabel);
  54029. }
  54030. }
  54031. function replace(str, keyValues) {
  54032. if (!isString(str)) {
  54033. return str;
  54034. }
  54035. var result = str;
  54036. each(keyValues, function (value, key) {
  54037. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  54038. });
  54039. return result;
  54040. }
  54041. function getTitle() {
  54042. var title = ecModel.get('title');
  54043. if (title && title.length) {
  54044. title = title[0];
  54045. }
  54046. return title && title.text;
  54047. }
  54048. function getSeriesTypeName(type) {
  54049. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  54050. }
  54051. }
  54052. function ariaPreprocessor(option) {
  54053. if (!option || !option.aria) {
  54054. return;
  54055. }
  54056. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  54057. if (aria.show != null) {
  54058. aria.enabled = aria.show;
  54059. }
  54060. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  54061. each(['description', 'general', 'series', 'data'], function (name) {
  54062. if (aria[name] != null) {
  54063. aria.label[name] = aria[name];
  54064. }
  54065. });
  54066. }
  54067. function install$n(registers) {
  54068. registers.registerPreprocessor(ariaPreprocessor);
  54069. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  54070. }
  54071. var DatasetModel =
  54072. /** @class */
  54073. function (_super) {
  54074. __extends(DatasetModel, _super);
  54075. function DatasetModel() {
  54076. var _this = _super !== null && _super.apply(this, arguments) || this;
  54077. _this.type = 'dataset';
  54078. return _this;
  54079. }
  54080. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  54081. _super.prototype.init.call(this, option, parentModel, ecModel);
  54082. this._sourceManager = new SourceManager(this);
  54083. disableTransformOptionMerge(this);
  54084. };
  54085. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  54086. _super.prototype.mergeOption.call(this, newOption, ecModel);
  54087. disableTransformOptionMerge(this);
  54088. };
  54089. DatasetModel.prototype.optionUpdated = function () {
  54090. this._sourceManager.dirty();
  54091. };
  54092. DatasetModel.prototype.getSourceManager = function () {
  54093. return this._sourceManager;
  54094. };
  54095. DatasetModel.type = 'dataset';
  54096. DatasetModel.defaultOption = {
  54097. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  54098. };
  54099. return DatasetModel;
  54100. }(ComponentModel);
  54101. var DatasetView =
  54102. /** @class */
  54103. function (_super) {
  54104. __extends(DatasetView, _super);
  54105. function DatasetView() {
  54106. var _this = _super !== null && _super.apply(this, arguments) || this;
  54107. _this.type = 'dataset';
  54108. return _this;
  54109. }
  54110. DatasetView.type = 'dataset';
  54111. return DatasetView;
  54112. }(ComponentView);
  54113. function install$o(registers) {
  54114. registers.registerComponentModel(DatasetModel);
  54115. registers.registerComponentView(DatasetView);
  54116. }
  54117. use([install$1]);
  54118. use([install]);
  54119. use([install$2, install$3, install$4, install$6]);
  54120. 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]);
  54121. exports.Axis = Axis;
  54122. exports.ChartView = ChartView;
  54123. exports.ComponentModel = ComponentModel;
  54124. exports.ComponentView = ComponentView;
  54125. exports.List = SeriesData;
  54126. exports.Model = Model;
  54127. exports.PRIORITY = PRIORITY;
  54128. exports.SeriesModel = SeriesModel;
  54129. exports.color = color;
  54130. exports.connect = connect;
  54131. exports.dataTool = dataTool;
  54132. exports.dependencies = dependencies;
  54133. exports.disConnect = disConnect;
  54134. exports.disconnect = disconnect;
  54135. exports.dispose = dispose$1;
  54136. exports.env = env;
  54137. exports.extendChartView = extendChartView;
  54138. exports.extendComponentModel = extendComponentModel;
  54139. exports.extendComponentView = extendComponentView;
  54140. exports.extendSeriesModel = extendSeriesModel;
  54141. exports.format = format$1;
  54142. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  54143. exports.getInstanceByDom = getInstanceByDom;
  54144. exports.getInstanceById = getInstanceById;
  54145. exports.getMap = getMap;
  54146. exports.graphic = graphic$1;
  54147. exports.helper = helper;
  54148. exports.init = init$1;
  54149. exports.innerDrawElementOnCanvas = brushSingle;
  54150. exports.matrix = matrix;
  54151. exports.number = number;
  54152. exports.parseGeoJSON = parseGeoJSON;
  54153. exports.parseGeoJson = parseGeoJSON;
  54154. exports.registerAction = registerAction;
  54155. exports.registerCoordinateSystem = registerCoordinateSystem;
  54156. exports.registerLayout = registerLayout;
  54157. exports.registerLoading = registerLoading;
  54158. exports.registerLocale = registerLocale;
  54159. exports.registerMap = registerMap;
  54160. exports.registerPostInit = registerPostInit;
  54161. exports.registerPostUpdate = registerPostUpdate;
  54162. exports.registerPreprocessor = registerPreprocessor;
  54163. exports.registerProcessor = registerProcessor;
  54164. exports.registerTheme = registerTheme;
  54165. exports.registerTransform = registerTransform;
  54166. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  54167. exports.registerVisual = registerVisual;
  54168. exports.setCanvasCreator = setCanvasCreator;
  54169. exports.setPlatformAPI = setPlatformAPI;
  54170. exports.throttle = throttle;
  54171. exports.time = time;
  54172. exports.use = use;
  54173. exports.util = util$1;
  54174. exports.vector = vector;
  54175. exports.version = version$1;
  54176. exports.zrUtil = util;
  54177. exports.zrender = zrender;
  54178. Object.defineProperty(exports, '__esModule', { value: true });
  54179. })));
  54180. //# sourceMappingURL=echarts.common.js.map